]> asedeno.scripts.mit.edu Git - linux.git/blob - drivers/gpu/drm/i915/intel_display.c
b83c238faee18c921242241eb81842af3680f0e6
[linux.git] / drivers / gpu / drm / i915 / intel_display.c
1 /*
2  * Copyright © 2006-2007 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *      Eric Anholt <eric@anholt.net>
25  */
26
27 #include <linux/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/reservation.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 "i915_drv.h"
48 #include "i915_gem_clflush.h"
49 #include "i915_trace.h"
50 #include "intel_acpi.h"
51 #include "intel_atomic.h"
52 #include "intel_atomic_plane.h"
53 #include "intel_color.h"
54 #include "intel_cdclk.h"
55 #include "intel_crt.h"
56 #include "intel_ddi.h"
57 #include "intel_dp.h"
58 #include "intel_drv.h"
59 #include "intel_dsi.h"
60 #include "intel_dvo.h"
61 #include "intel_fbc.h"
62 #include "intel_fbdev.h"
63 #include "intel_fifo_underrun.h"
64 #include "intel_frontbuffer.h"
65 #include "intel_gmbus.h"
66 #include "intel_hdcp.h"
67 #include "intel_hdmi.h"
68 #include "intel_hotplug.h"
69 #include "intel_lvds.h"
70 #include "intel_overlay.h"
71 #include "intel_pipe_crc.h"
72 #include "intel_pm.h"
73 #include "intel_psr.h"
74 #include "intel_quirks.h"
75 #include "intel_sdvo.h"
76 #include "intel_sideband.h"
77 #include "intel_sprite.h"
78 #include "intel_tv.h"
79 #include "intel_vdsc.h"
80
81 /* Primary plane formats for gen <= 3 */
82 static const u32 i8xx_primary_formats[] = {
83         DRM_FORMAT_C8,
84         DRM_FORMAT_RGB565,
85         DRM_FORMAT_XRGB1555,
86         DRM_FORMAT_XRGB8888,
87 };
88
89 /* Primary plane formats for gen >= 4 */
90 static const u32 i965_primary_formats[] = {
91         DRM_FORMAT_C8,
92         DRM_FORMAT_RGB565,
93         DRM_FORMAT_XRGB8888,
94         DRM_FORMAT_XBGR8888,
95         DRM_FORMAT_XRGB2101010,
96         DRM_FORMAT_XBGR2101010,
97 };
98
99 static const u64 i9xx_format_modifiers[] = {
100         I915_FORMAT_MOD_X_TILED,
101         DRM_FORMAT_MOD_LINEAR,
102         DRM_FORMAT_MOD_INVALID
103 };
104
105 /* Cursor formats */
106 static const u32 intel_cursor_formats[] = {
107         DRM_FORMAT_ARGB8888,
108 };
109
110 static const u64 cursor_format_modifiers[] = {
111         DRM_FORMAT_MOD_LINEAR,
112         DRM_FORMAT_MOD_INVALID
113 };
114
115 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
116                                 struct intel_crtc_state *pipe_config);
117 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
118                                    struct intel_crtc_state *pipe_config);
119
120 static int intel_framebuffer_init(struct intel_framebuffer *ifb,
121                                   struct drm_i915_gem_object *obj,
122                                   struct drm_mode_fb_cmd2 *mode_cmd);
123 static void intel_set_pipe_timings(const struct intel_crtc_state *crtc_state);
124 static void intel_set_pipe_src_size(const struct intel_crtc_state *crtc_state);
125 static void intel_cpu_transcoder_set_m_n(const struct intel_crtc_state *crtc_state,
126                                          const struct intel_link_m_n *m_n,
127                                          const struct intel_link_m_n *m2_n2);
128 static void i9xx_set_pipeconf(const struct intel_crtc_state *crtc_state);
129 static void ironlake_set_pipeconf(const struct intel_crtc_state *crtc_state);
130 static void haswell_set_pipeconf(const struct intel_crtc_state *crtc_state);
131 static void bdw_set_pipemisc(const struct intel_crtc_state *crtc_state);
132 static void vlv_prepare_pll(struct intel_crtc *crtc,
133                             const struct intel_crtc_state *pipe_config);
134 static void chv_prepare_pll(struct intel_crtc *crtc,
135                             const struct intel_crtc_state *pipe_config);
136 static void intel_begin_crtc_commit(struct intel_atomic_state *, struct intel_crtc *);
137 static void intel_finish_crtc_commit(struct intel_atomic_state *, struct intel_crtc *);
138 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
139                                     struct intel_crtc_state *crtc_state);
140 static void skylake_pfit_enable(const struct intel_crtc_state *crtc_state);
141 static void ironlake_pfit_disable(const struct intel_crtc_state *old_crtc_state);
142 static void ironlake_pfit_enable(const struct intel_crtc_state *crtc_state);
143 static void intel_modeset_setup_hw_state(struct drm_device *dev,
144                                          struct drm_modeset_acquire_ctx *ctx);
145 static void intel_pre_disable_primary_noatomic(struct drm_crtc *crtc);
146
147 struct intel_limit {
148         struct {
149                 int min, max;
150         } dot, vco, n, m, m1, m2, p, p1;
151
152         struct {
153                 int dot_limit;
154                 int p2_slow, p2_fast;
155         } p2;
156 };
157
158 /* returns HPLL frequency in kHz */
159 int vlv_get_hpll_vco(struct drm_i915_private *dev_priv)
160 {
161         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
162
163         /* Obtain SKU information */
164         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
165                 CCK_FUSE_HPLL_FREQ_MASK;
166
167         return vco_freq[hpll_freq] * 1000;
168 }
169
170 int vlv_get_cck_clock(struct drm_i915_private *dev_priv,
171                       const char *name, u32 reg, int ref_freq)
172 {
173         u32 val;
174         int divider;
175
176         val = vlv_cck_read(dev_priv, reg);
177         divider = val & CCK_FREQUENCY_VALUES;
178
179         WARN((val & CCK_FREQUENCY_STATUS) !=
180              (divider << CCK_FREQUENCY_STATUS_SHIFT),
181              "%s change in progress\n", name);
182
183         return DIV_ROUND_CLOSEST(ref_freq << 1, divider + 1);
184 }
185
186 int vlv_get_cck_clock_hpll(struct drm_i915_private *dev_priv,
187                            const char *name, u32 reg)
188 {
189         int hpll;
190
191         vlv_cck_get(dev_priv);
192
193         if (dev_priv->hpll_freq == 0)
194                 dev_priv->hpll_freq = vlv_get_hpll_vco(dev_priv);
195
196         hpll = vlv_get_cck_clock(dev_priv, name, reg, dev_priv->hpll_freq);
197
198         vlv_cck_put(dev_priv);
199
200         return hpll;
201 }
202
203 static void intel_update_czclk(struct drm_i915_private *dev_priv)
204 {
205         if (!(IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)))
206                 return;
207
208         dev_priv->czclk_freq = vlv_get_cck_clock_hpll(dev_priv, "czclk",
209                                                       CCK_CZ_CLOCK_CONTROL);
210
211         DRM_DEBUG_DRIVER("CZ clock rate: %d kHz\n", dev_priv->czclk_freq);
212 }
213
214 static inline u32 /* units of 100MHz */
215 intel_fdi_link_freq(struct drm_i915_private *dev_priv,
216                     const struct intel_crtc_state *pipe_config)
217 {
218         if (HAS_DDI(dev_priv))
219                 return pipe_config->port_clock; /* SPLL */
220         else
221                 return dev_priv->fdi_pll_freq;
222 }
223
224 static const struct intel_limit intel_limits_i8xx_dac = {
225         .dot = { .min = 25000, .max = 350000 },
226         .vco = { .min = 908000, .max = 1512000 },
227         .n = { .min = 2, .max = 16 },
228         .m = { .min = 96, .max = 140 },
229         .m1 = { .min = 18, .max = 26 },
230         .m2 = { .min = 6, .max = 16 },
231         .p = { .min = 4, .max = 128 },
232         .p1 = { .min = 2, .max = 33 },
233         .p2 = { .dot_limit = 165000,
234                 .p2_slow = 4, .p2_fast = 2 },
235 };
236
237 static const struct intel_limit intel_limits_i8xx_dvo = {
238         .dot = { .min = 25000, .max = 350000 },
239         .vco = { .min = 908000, .max = 1512000 },
240         .n = { .min = 2, .max = 16 },
241         .m = { .min = 96, .max = 140 },
242         .m1 = { .min = 18, .max = 26 },
243         .m2 = { .min = 6, .max = 16 },
244         .p = { .min = 4, .max = 128 },
245         .p1 = { .min = 2, .max = 33 },
246         .p2 = { .dot_limit = 165000,
247                 .p2_slow = 4, .p2_fast = 4 },
248 };
249
250 static const struct intel_limit intel_limits_i8xx_lvds = {
251         .dot = { .min = 25000, .max = 350000 },
252         .vco = { .min = 908000, .max = 1512000 },
253         .n = { .min = 2, .max = 16 },
254         .m = { .min = 96, .max = 140 },
255         .m1 = { .min = 18, .max = 26 },
256         .m2 = { .min = 6, .max = 16 },
257         .p = { .min = 4, .max = 128 },
258         .p1 = { .min = 1, .max = 6 },
259         .p2 = { .dot_limit = 165000,
260                 .p2_slow = 14, .p2_fast = 7 },
261 };
262
263 static const struct intel_limit intel_limits_i9xx_sdvo = {
264         .dot = { .min = 20000, .max = 400000 },
265         .vco = { .min = 1400000, .max = 2800000 },
266         .n = { .min = 1, .max = 6 },
267         .m = { .min = 70, .max = 120 },
268         .m1 = { .min = 8, .max = 18 },
269         .m2 = { .min = 3, .max = 7 },
270         .p = { .min = 5, .max = 80 },
271         .p1 = { .min = 1, .max = 8 },
272         .p2 = { .dot_limit = 200000,
273                 .p2_slow = 10, .p2_fast = 5 },
274 };
275
276 static const struct intel_limit intel_limits_i9xx_lvds = {
277         .dot = { .min = 20000, .max = 400000 },
278         .vco = { .min = 1400000, .max = 2800000 },
279         .n = { .min = 1, .max = 6 },
280         .m = { .min = 70, .max = 120 },
281         .m1 = { .min = 8, .max = 18 },
282         .m2 = { .min = 3, .max = 7 },
283         .p = { .min = 7, .max = 98 },
284         .p1 = { .min = 1, .max = 8 },
285         .p2 = { .dot_limit = 112000,
286                 .p2_slow = 14, .p2_fast = 7 },
287 };
288
289
290 static const struct intel_limit intel_limits_g4x_sdvo = {
291         .dot = { .min = 25000, .max = 270000 },
292         .vco = { .min = 1750000, .max = 3500000},
293         .n = { .min = 1, .max = 4 },
294         .m = { .min = 104, .max = 138 },
295         .m1 = { .min = 17, .max = 23 },
296         .m2 = { .min = 5, .max = 11 },
297         .p = { .min = 10, .max = 30 },
298         .p1 = { .min = 1, .max = 3},
299         .p2 = { .dot_limit = 270000,
300                 .p2_slow = 10,
301                 .p2_fast = 10
302         },
303 };
304
305 static const struct intel_limit intel_limits_g4x_hdmi = {
306         .dot = { .min = 22000, .max = 400000 },
307         .vco = { .min = 1750000, .max = 3500000},
308         .n = { .min = 1, .max = 4 },
309         .m = { .min = 104, .max = 138 },
310         .m1 = { .min = 16, .max = 23 },
311         .m2 = { .min = 5, .max = 11 },
312         .p = { .min = 5, .max = 80 },
313         .p1 = { .min = 1, .max = 8},
314         .p2 = { .dot_limit = 165000,
315                 .p2_slow = 10, .p2_fast = 5 },
316 };
317
318 static const struct intel_limit intel_limits_g4x_single_channel_lvds = {
319         .dot = { .min = 20000, .max = 115000 },
320         .vco = { .min = 1750000, .max = 3500000 },
321         .n = { .min = 1, .max = 3 },
322         .m = { .min = 104, .max = 138 },
323         .m1 = { .min = 17, .max = 23 },
324         .m2 = { .min = 5, .max = 11 },
325         .p = { .min = 28, .max = 112 },
326         .p1 = { .min = 2, .max = 8 },
327         .p2 = { .dot_limit = 0,
328                 .p2_slow = 14, .p2_fast = 14
329         },
330 };
331
332 static const struct intel_limit intel_limits_g4x_dual_channel_lvds = {
333         .dot = { .min = 80000, .max = 224000 },
334         .vco = { .min = 1750000, .max = 3500000 },
335         .n = { .min = 1, .max = 3 },
336         .m = { .min = 104, .max = 138 },
337         .m1 = { .min = 17, .max = 23 },
338         .m2 = { .min = 5, .max = 11 },
339         .p = { .min = 14, .max = 42 },
340         .p1 = { .min = 2, .max = 6 },
341         .p2 = { .dot_limit = 0,
342                 .p2_slow = 7, .p2_fast = 7
343         },
344 };
345
346 static const struct intel_limit intel_limits_pineview_sdvo = {
347         .dot = { .min = 20000, .max = 400000},
348         .vco = { .min = 1700000, .max = 3500000 },
349         /* Pineview's Ncounter is a ring counter */
350         .n = { .min = 3, .max = 6 },
351         .m = { .min = 2, .max = 256 },
352         /* Pineview only has one combined m divider, which we treat as m2. */
353         .m1 = { .min = 0, .max = 0 },
354         .m2 = { .min = 0, .max = 254 },
355         .p = { .min = 5, .max = 80 },
356         .p1 = { .min = 1, .max = 8 },
357         .p2 = { .dot_limit = 200000,
358                 .p2_slow = 10, .p2_fast = 5 },
359 };
360
361 static const struct intel_limit intel_limits_pineview_lvds = {
362         .dot = { .min = 20000, .max = 400000 },
363         .vco = { .min = 1700000, .max = 3500000 },
364         .n = { .min = 3, .max = 6 },
365         .m = { .min = 2, .max = 256 },
366         .m1 = { .min = 0, .max = 0 },
367         .m2 = { .min = 0, .max = 254 },
368         .p = { .min = 7, .max = 112 },
369         .p1 = { .min = 1, .max = 8 },
370         .p2 = { .dot_limit = 112000,
371                 .p2_slow = 14, .p2_fast = 14 },
372 };
373
374 /* Ironlake / Sandybridge
375  *
376  * We calculate clock using (register_value + 2) for N/M1/M2, so here
377  * the range value for them is (actual_value - 2).
378  */
379 static const struct intel_limit intel_limits_ironlake_dac = {
380         .dot = { .min = 25000, .max = 350000 },
381         .vco = { .min = 1760000, .max = 3510000 },
382         .n = { .min = 1, .max = 5 },
383         .m = { .min = 79, .max = 127 },
384         .m1 = { .min = 12, .max = 22 },
385         .m2 = { .min = 5, .max = 9 },
386         .p = { .min = 5, .max = 80 },
387         .p1 = { .min = 1, .max = 8 },
388         .p2 = { .dot_limit = 225000,
389                 .p2_slow = 10, .p2_fast = 5 },
390 };
391
392 static const struct intel_limit intel_limits_ironlake_single_lvds = {
393         .dot = { .min = 25000, .max = 350000 },
394         .vco = { .min = 1760000, .max = 3510000 },
395         .n = { .min = 1, .max = 3 },
396         .m = { .min = 79, .max = 118 },
397         .m1 = { .min = 12, .max = 22 },
398         .m2 = { .min = 5, .max = 9 },
399         .p = { .min = 28, .max = 112 },
400         .p1 = { .min = 2, .max = 8 },
401         .p2 = { .dot_limit = 225000,
402                 .p2_slow = 14, .p2_fast = 14 },
403 };
404
405 static const struct intel_limit intel_limits_ironlake_dual_lvds = {
406         .dot = { .min = 25000, .max = 350000 },
407         .vco = { .min = 1760000, .max = 3510000 },
408         .n = { .min = 1, .max = 3 },
409         .m = { .min = 79, .max = 127 },
410         .m1 = { .min = 12, .max = 22 },
411         .m2 = { .min = 5, .max = 9 },
412         .p = { .min = 14, .max = 56 },
413         .p1 = { .min = 2, .max = 8 },
414         .p2 = { .dot_limit = 225000,
415                 .p2_slow = 7, .p2_fast = 7 },
416 };
417
418 /* LVDS 100mhz refclk limits. */
419 static const struct intel_limit intel_limits_ironlake_single_lvds_100m = {
420         .dot = { .min = 25000, .max = 350000 },
421         .vco = { .min = 1760000, .max = 3510000 },
422         .n = { .min = 1, .max = 2 },
423         .m = { .min = 79, .max = 126 },
424         .m1 = { .min = 12, .max = 22 },
425         .m2 = { .min = 5, .max = 9 },
426         .p = { .min = 28, .max = 112 },
427         .p1 = { .min = 2, .max = 8 },
428         .p2 = { .dot_limit = 225000,
429                 .p2_slow = 14, .p2_fast = 14 },
430 };
431
432 static const struct intel_limit intel_limits_ironlake_dual_lvds_100m = {
433         .dot = { .min = 25000, .max = 350000 },
434         .vco = { .min = 1760000, .max = 3510000 },
435         .n = { .min = 1, .max = 3 },
436         .m = { .min = 79, .max = 126 },
437         .m1 = { .min = 12, .max = 22 },
438         .m2 = { .min = 5, .max = 9 },
439         .p = { .min = 14, .max = 42 },
440         .p1 = { .min = 2, .max = 6 },
441         .p2 = { .dot_limit = 225000,
442                 .p2_slow = 7, .p2_fast = 7 },
443 };
444
445 static const struct intel_limit intel_limits_vlv = {
446          /*
447           * These are the data rate limits (measured in fast clocks)
448           * since those are the strictest limits we have. The fast
449           * clock and actual rate limits are more relaxed, so checking
450           * them would make no difference.
451           */
452         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
453         .vco = { .min = 4000000, .max = 6000000 },
454         .n = { .min = 1, .max = 7 },
455         .m1 = { .min = 2, .max = 3 },
456         .m2 = { .min = 11, .max = 156 },
457         .p1 = { .min = 2, .max = 3 },
458         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
459 };
460
461 static const struct intel_limit intel_limits_chv = {
462         /*
463          * These are the data rate limits (measured in fast clocks)
464          * since those are the strictest limits we have.  The fast
465          * clock and actual rate limits are more relaxed, so checking
466          * them would make no difference.
467          */
468         .dot = { .min = 25000 * 5, .max = 540000 * 5},
469         .vco = { .min = 4800000, .max = 6480000 },
470         .n = { .min = 1, .max = 1 },
471         .m1 = { .min = 2, .max = 2 },
472         .m2 = { .min = 24 << 22, .max = 175 << 22 },
473         .p1 = { .min = 2, .max = 4 },
474         .p2 = { .p2_slow = 1, .p2_fast = 14 },
475 };
476
477 static const struct intel_limit intel_limits_bxt = {
478         /* FIXME: find real dot limits */
479         .dot = { .min = 0, .max = INT_MAX },
480         .vco = { .min = 4800000, .max = 6700000 },
481         .n = { .min = 1, .max = 1 },
482         .m1 = { .min = 2, .max = 2 },
483         /* FIXME: find real m2 limits */
484         .m2 = { .min = 2 << 22, .max = 255 << 22 },
485         .p1 = { .min = 2, .max = 4 },
486         .p2 = { .p2_slow = 1, .p2_fast = 20 },
487 };
488
489 /* WA Display #0827: Gen9:all */
490 static void
491 skl_wa_827(struct drm_i915_private *dev_priv, int pipe, bool enable)
492 {
493         if (enable)
494                 I915_WRITE(CLKGATE_DIS_PSL(pipe),
495                            I915_READ(CLKGATE_DIS_PSL(pipe)) |
496                            DUPS1_GATING_DIS | DUPS2_GATING_DIS);
497         else
498                 I915_WRITE(CLKGATE_DIS_PSL(pipe),
499                            I915_READ(CLKGATE_DIS_PSL(pipe)) &
500                            ~(DUPS1_GATING_DIS | DUPS2_GATING_DIS));
501 }
502
503 /* Wa_2006604312:icl */
504 static void
505 icl_wa_scalerclkgating(struct drm_i915_private *dev_priv, enum pipe pipe,
506                        bool enable)
507 {
508         if (enable)
509                 I915_WRITE(CLKGATE_DIS_PSL(pipe),
510                            I915_READ(CLKGATE_DIS_PSL(pipe)) | DPFR_GATING_DIS);
511         else
512                 I915_WRITE(CLKGATE_DIS_PSL(pipe),
513                            I915_READ(CLKGATE_DIS_PSL(pipe)) & ~DPFR_GATING_DIS);
514 }
515
516 static bool
517 needs_modeset(const struct drm_crtc_state *state)
518 {
519         return drm_atomic_crtc_needs_modeset(state);
520 }
521
522 /*
523  * Platform specific helpers to calculate the port PLL loopback- (clock.m),
524  * and post-divider (clock.p) values, pre- (clock.vco) and post-divided fast
525  * (clock.dot) clock rates. This fast dot clock is fed to the port's IO logic.
526  * The helpers' return value is the rate of the clock that is fed to the
527  * display engine's pipe which can be the above fast dot clock rate or a
528  * divided-down version of it.
529  */
530 /* m1 is reserved as 0 in Pineview, n is a ring counter */
531 static int pnv_calc_dpll_params(int refclk, struct dpll *clock)
532 {
533         clock->m = clock->m2 + 2;
534         clock->p = clock->p1 * clock->p2;
535         if (WARN_ON(clock->n == 0 || clock->p == 0))
536                 return 0;
537         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
538         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
539
540         return clock->dot;
541 }
542
543 static u32 i9xx_dpll_compute_m(struct dpll *dpll)
544 {
545         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
546 }
547
548 static int i9xx_calc_dpll_params(int refclk, struct dpll *clock)
549 {
550         clock->m = i9xx_dpll_compute_m(clock);
551         clock->p = clock->p1 * clock->p2;
552         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
553                 return 0;
554         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
555         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
556
557         return clock->dot;
558 }
559
560 static int vlv_calc_dpll_params(int refclk, struct dpll *clock)
561 {
562         clock->m = clock->m1 * clock->m2;
563         clock->p = clock->p1 * clock->p2;
564         if (WARN_ON(clock->n == 0 || clock->p == 0))
565                 return 0;
566         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
567         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
568
569         return clock->dot / 5;
570 }
571
572 int chv_calc_dpll_params(int refclk, struct dpll *clock)
573 {
574         clock->m = clock->m1 * clock->m2;
575         clock->p = clock->p1 * clock->p2;
576         if (WARN_ON(clock->n == 0 || clock->p == 0))
577                 return 0;
578         clock->vco = DIV_ROUND_CLOSEST_ULL((u64)refclk * clock->m,
579                                            clock->n << 22);
580         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
581
582         return clock->dot / 5;
583 }
584
585 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
586
587 /*
588  * Returns whether the given set of divisors are valid for a given refclk with
589  * the given connectors.
590  */
591 static bool intel_PLL_is_valid(struct drm_i915_private *dev_priv,
592                                const struct intel_limit *limit,
593                                const struct dpll *clock)
594 {
595         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
596                 INTELPllInvalid("n out of range\n");
597         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
598                 INTELPllInvalid("p1 out of range\n");
599         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
600                 INTELPllInvalid("m2 out of range\n");
601         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
602                 INTELPllInvalid("m1 out of range\n");
603
604         if (!IS_PINEVIEW(dev_priv) && !IS_VALLEYVIEW(dev_priv) &&
605             !IS_CHERRYVIEW(dev_priv) && !IS_GEN9_LP(dev_priv))
606                 if (clock->m1 <= clock->m2)
607                         INTELPllInvalid("m1 <= m2\n");
608
609         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
610             !IS_GEN9_LP(dev_priv)) {
611                 if (clock->p < limit->p.min || limit->p.max < clock->p)
612                         INTELPllInvalid("p out of range\n");
613                 if (clock->m < limit->m.min || limit->m.max < clock->m)
614                         INTELPllInvalid("m out of range\n");
615         }
616
617         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
618                 INTELPllInvalid("vco out of range\n");
619         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
620          * connector, etc., rather than just a single range.
621          */
622         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
623                 INTELPllInvalid("dot out of range\n");
624
625         return true;
626 }
627
628 static int
629 i9xx_select_p2_div(const struct intel_limit *limit,
630                    const struct intel_crtc_state *crtc_state,
631                    int target)
632 {
633         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
634
635         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
636                 /*
637                  * For LVDS just rely on its current settings for dual-channel.
638                  * We haven't figured out how to reliably set up different
639                  * single/dual channel state, if we even can.
640                  */
641                 if (intel_is_dual_link_lvds(dev_priv))
642                         return limit->p2.p2_fast;
643                 else
644                         return limit->p2.p2_slow;
645         } else {
646                 if (target < limit->p2.dot_limit)
647                         return limit->p2.p2_slow;
648                 else
649                         return limit->p2.p2_fast;
650         }
651 }
652
653 /*
654  * Returns a set of divisors for the desired target clock with the given
655  * refclk, or FALSE.  The returned values represent the clock equation:
656  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
657  *
658  * Target and reference clocks are specified in kHz.
659  *
660  * If match_clock is provided, then best_clock P divider must match the P
661  * divider from @match_clock used for LVDS downclocking.
662  */
663 static bool
664 i9xx_find_best_dpll(const struct intel_limit *limit,
665                     struct intel_crtc_state *crtc_state,
666                     int target, int refclk, struct dpll *match_clock,
667                     struct dpll *best_clock)
668 {
669         struct drm_device *dev = crtc_state->base.crtc->dev;
670         struct dpll clock;
671         int err = target;
672
673         memset(best_clock, 0, sizeof(*best_clock));
674
675         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
676
677         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
678              clock.m1++) {
679                 for (clock.m2 = limit->m2.min;
680                      clock.m2 <= limit->m2.max; clock.m2++) {
681                         if (clock.m2 >= clock.m1)
682                                 break;
683                         for (clock.n = limit->n.min;
684                              clock.n <= limit->n.max; clock.n++) {
685                                 for (clock.p1 = limit->p1.min;
686                                         clock.p1 <= limit->p1.max; clock.p1++) {
687                                         int this_err;
688
689                                         i9xx_calc_dpll_params(refclk, &clock);
690                                         if (!intel_PLL_is_valid(to_i915(dev),
691                                                                 limit,
692                                                                 &clock))
693                                                 continue;
694                                         if (match_clock &&
695                                             clock.p != match_clock->p)
696                                                 continue;
697
698                                         this_err = abs(clock.dot - target);
699                                         if (this_err < err) {
700                                                 *best_clock = clock;
701                                                 err = this_err;
702                                         }
703                                 }
704                         }
705                 }
706         }
707
708         return (err != target);
709 }
710
711 /*
712  * Returns a set of divisors for the desired target clock with the given
713  * refclk, or FALSE.  The returned values represent the clock equation:
714  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
715  *
716  * Target and reference clocks are specified in kHz.
717  *
718  * If match_clock is provided, then best_clock P divider must match the P
719  * divider from @match_clock used for LVDS downclocking.
720  */
721 static bool
722 pnv_find_best_dpll(const struct intel_limit *limit,
723                    struct intel_crtc_state *crtc_state,
724                    int target, int refclk, struct dpll *match_clock,
725                    struct dpll *best_clock)
726 {
727         struct drm_device *dev = crtc_state->base.crtc->dev;
728         struct dpll clock;
729         int err = target;
730
731         memset(best_clock, 0, sizeof(*best_clock));
732
733         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
734
735         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
736              clock.m1++) {
737                 for (clock.m2 = limit->m2.min;
738                      clock.m2 <= limit->m2.max; clock.m2++) {
739                         for (clock.n = limit->n.min;
740                              clock.n <= limit->n.max; clock.n++) {
741                                 for (clock.p1 = limit->p1.min;
742                                         clock.p1 <= limit->p1.max; clock.p1++) {
743                                         int this_err;
744
745                                         pnv_calc_dpll_params(refclk, &clock);
746                                         if (!intel_PLL_is_valid(to_i915(dev),
747                                                                 limit,
748                                                                 &clock))
749                                                 continue;
750                                         if (match_clock &&
751                                             clock.p != match_clock->p)
752                                                 continue;
753
754                                         this_err = abs(clock.dot - target);
755                                         if (this_err < err) {
756                                                 *best_clock = clock;
757                                                 err = this_err;
758                                         }
759                                 }
760                         }
761                 }
762         }
763
764         return (err != target);
765 }
766
767 /*
768  * Returns a set of divisors for the desired target clock with the given
769  * refclk, or FALSE.  The returned values represent the clock equation:
770  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
771  *
772  * Target and reference clocks are specified in kHz.
773  *
774  * If match_clock is provided, then best_clock P divider must match the P
775  * divider from @match_clock used for LVDS downclocking.
776  */
777 static bool
778 g4x_find_best_dpll(const struct intel_limit *limit,
779                    struct intel_crtc_state *crtc_state,
780                    int target, int refclk, struct dpll *match_clock,
781                    struct dpll *best_clock)
782 {
783         struct drm_device *dev = crtc_state->base.crtc->dev;
784         struct dpll clock;
785         int max_n;
786         bool found = false;
787         /* approximately equals target * 0.00585 */
788         int err_most = (target >> 8) + (target >> 9);
789
790         memset(best_clock, 0, sizeof(*best_clock));
791
792         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
793
794         max_n = limit->n.max;
795         /* based on hardware requirement, prefer smaller n to precision */
796         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
797                 /* based on hardware requirement, prefere larger m1,m2 */
798                 for (clock.m1 = limit->m1.max;
799                      clock.m1 >= limit->m1.min; clock.m1--) {
800                         for (clock.m2 = limit->m2.max;
801                              clock.m2 >= limit->m2.min; clock.m2--) {
802                                 for (clock.p1 = limit->p1.max;
803                                      clock.p1 >= limit->p1.min; clock.p1--) {
804                                         int this_err;
805
806                                         i9xx_calc_dpll_params(refclk, &clock);
807                                         if (!intel_PLL_is_valid(to_i915(dev),
808                                                                 limit,
809                                                                 &clock))
810                                                 continue;
811
812                                         this_err = abs(clock.dot - target);
813                                         if (this_err < err_most) {
814                                                 *best_clock = clock;
815                                                 err_most = this_err;
816                                                 max_n = clock.n;
817                                                 found = true;
818                                         }
819                                 }
820                         }
821                 }
822         }
823         return found;
824 }
825
826 /*
827  * Check if the calculated PLL configuration is more optimal compared to the
828  * best configuration and error found so far. Return the calculated error.
829  */
830 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
831                                const struct dpll *calculated_clock,
832                                const struct dpll *best_clock,
833                                unsigned int best_error_ppm,
834                                unsigned int *error_ppm)
835 {
836         /*
837          * For CHV ignore the error and consider only the P value.
838          * Prefer a bigger P value based on HW requirements.
839          */
840         if (IS_CHERRYVIEW(to_i915(dev))) {
841                 *error_ppm = 0;
842
843                 return calculated_clock->p > best_clock->p;
844         }
845
846         if (WARN_ON_ONCE(!target_freq))
847                 return false;
848
849         *error_ppm = div_u64(1000000ULL *
850                                 abs(target_freq - calculated_clock->dot),
851                              target_freq);
852         /*
853          * Prefer a better P value over a better (smaller) error if the error
854          * is small. Ensure this preference for future configurations too by
855          * setting the error to 0.
856          */
857         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
858                 *error_ppm = 0;
859
860                 return true;
861         }
862
863         return *error_ppm + 10 < best_error_ppm;
864 }
865
866 /*
867  * Returns a set of divisors for the desired target clock with the given
868  * refclk, or FALSE.  The returned values represent the clock equation:
869  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
870  */
871 static bool
872 vlv_find_best_dpll(const struct intel_limit *limit,
873                    struct intel_crtc_state *crtc_state,
874                    int target, int refclk, struct dpll *match_clock,
875                    struct dpll *best_clock)
876 {
877         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
878         struct drm_device *dev = crtc->base.dev;
879         struct dpll clock;
880         unsigned int bestppm = 1000000;
881         /* min update 19.2 MHz */
882         int max_n = min(limit->n.max, refclk / 19200);
883         bool found = false;
884
885         target *= 5; /* fast clock */
886
887         memset(best_clock, 0, sizeof(*best_clock));
888
889         /* based on hardware requirement, prefer smaller n to precision */
890         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
891                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
892                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
893                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
894                                 clock.p = clock.p1 * clock.p2;
895                                 /* based on hardware requirement, prefer bigger m1,m2 values */
896                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
897                                         unsigned int ppm;
898
899                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
900                                                                      refclk * clock.m1);
901
902                                         vlv_calc_dpll_params(refclk, &clock);
903
904                                         if (!intel_PLL_is_valid(to_i915(dev),
905                                                                 limit,
906                                                                 &clock))
907                                                 continue;
908
909                                         if (!vlv_PLL_is_optimal(dev, target,
910                                                                 &clock,
911                                                                 best_clock,
912                                                                 bestppm, &ppm))
913                                                 continue;
914
915                                         *best_clock = clock;
916                                         bestppm = ppm;
917                                         found = true;
918                                 }
919                         }
920                 }
921         }
922
923         return found;
924 }
925
926 /*
927  * Returns a set of divisors for the desired target clock with the given
928  * refclk, or FALSE.  The returned values represent the clock equation:
929  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
930  */
931 static bool
932 chv_find_best_dpll(const struct intel_limit *limit,
933                    struct intel_crtc_state *crtc_state,
934                    int target, int refclk, struct dpll *match_clock,
935                    struct dpll *best_clock)
936 {
937         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
938         struct drm_device *dev = crtc->base.dev;
939         unsigned int best_error_ppm;
940         struct dpll clock;
941         u64 m2;
942         int found = false;
943
944         memset(best_clock, 0, sizeof(*best_clock));
945         best_error_ppm = 1000000;
946
947         /*
948          * Based on hardware doc, the n always set to 1, and m1 always
949          * set to 2.  If requires to support 200Mhz refclk, we need to
950          * revisit this because n may not 1 anymore.
951          */
952         clock.n = 1, clock.m1 = 2;
953         target *= 5;    /* fast clock */
954
955         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
956                 for (clock.p2 = limit->p2.p2_fast;
957                                 clock.p2 >= limit->p2.p2_slow;
958                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
959                         unsigned int error_ppm;
960
961                         clock.p = clock.p1 * clock.p2;
962
963                         m2 = DIV_ROUND_CLOSEST_ULL(((u64)target * clock.p *
964                                         clock.n) << 22, refclk * clock.m1);
965
966                         if (m2 > INT_MAX/clock.m1)
967                                 continue;
968
969                         clock.m2 = m2;
970
971                         chv_calc_dpll_params(refclk, &clock);
972
973                         if (!intel_PLL_is_valid(to_i915(dev), limit, &clock))
974                                 continue;
975
976                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
977                                                 best_error_ppm, &error_ppm))
978                                 continue;
979
980                         *best_clock = clock;
981                         best_error_ppm = error_ppm;
982                         found = true;
983                 }
984         }
985
986         return found;
987 }
988
989 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state,
990                         struct dpll *best_clock)
991 {
992         int refclk = 100000;
993         const struct intel_limit *limit = &intel_limits_bxt;
994
995         return chv_find_best_dpll(limit, crtc_state,
996                                   crtc_state->port_clock, refclk,
997                                   NULL, best_clock);
998 }
999
1000 bool intel_crtc_active(struct intel_crtc *crtc)
1001 {
1002         /* Be paranoid as we can arrive here with only partial
1003          * state retrieved from the hardware during setup.
1004          *
1005          * We can ditch the adjusted_mode.crtc_clock check as soon
1006          * as Haswell has gained clock readout/fastboot support.
1007          *
1008          * We can ditch the crtc->primary->state->fb check as soon as we can
1009          * properly reconstruct framebuffers.
1010          *
1011          * FIXME: The intel_crtc->active here should be switched to
1012          * crtc->state->active once we have proper CRTC states wired up
1013          * for atomic.
1014          */
1015         return crtc->active && crtc->base.primary->state->fb &&
1016                 crtc->config->base.adjusted_mode.crtc_clock;
1017 }
1018
1019 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
1020                                              enum pipe pipe)
1021 {
1022         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
1023
1024         return crtc->config->cpu_transcoder;
1025 }
1026
1027 static bool pipe_scanline_is_moving(struct drm_i915_private *dev_priv,
1028                                     enum pipe pipe)
1029 {
1030         i915_reg_t reg = PIPEDSL(pipe);
1031         u32 line1, line2;
1032         u32 line_mask;
1033
1034         if (IS_GEN(dev_priv, 2))
1035                 line_mask = DSL_LINEMASK_GEN2;
1036         else
1037                 line_mask = DSL_LINEMASK_GEN3;
1038
1039         line1 = I915_READ(reg) & line_mask;
1040         msleep(5);
1041         line2 = I915_READ(reg) & line_mask;
1042
1043         return line1 != line2;
1044 }
1045
1046 static void wait_for_pipe_scanline_moving(struct intel_crtc *crtc, bool state)
1047 {
1048         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1049         enum pipe pipe = crtc->pipe;
1050
1051         /* Wait for the display line to settle/start moving */
1052         if (wait_for(pipe_scanline_is_moving(dev_priv, pipe) == state, 100))
1053                 DRM_ERROR("pipe %c scanline %s wait timed out\n",
1054                           pipe_name(pipe), onoff(state));
1055 }
1056
1057 static void intel_wait_for_pipe_scanline_stopped(struct intel_crtc *crtc)
1058 {
1059         wait_for_pipe_scanline_moving(crtc, false);
1060 }
1061
1062 static void intel_wait_for_pipe_scanline_moving(struct intel_crtc *crtc)
1063 {
1064         wait_for_pipe_scanline_moving(crtc, true);
1065 }
1066
1067 static void
1068 intel_wait_for_pipe_off(const struct intel_crtc_state *old_crtc_state)
1069 {
1070         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
1071         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1072
1073         if (INTEL_GEN(dev_priv) >= 4) {
1074                 enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
1075                 i915_reg_t reg = PIPECONF(cpu_transcoder);
1076
1077                 /* Wait for the Pipe State to go off */
1078                 if (intel_wait_for_register(&dev_priv->uncore,
1079                                             reg, I965_PIPECONF_ACTIVE, 0,
1080                                             100))
1081                         WARN(1, "pipe_off wait timed out\n");
1082         } else {
1083                 intel_wait_for_pipe_scanline_stopped(crtc);
1084         }
1085 }
1086
1087 /* Only for pre-ILK configs */
1088 void assert_pll(struct drm_i915_private *dev_priv,
1089                 enum pipe pipe, bool state)
1090 {
1091         u32 val;
1092         bool cur_state;
1093
1094         val = I915_READ(DPLL(pipe));
1095         cur_state = !!(val & DPLL_VCO_ENABLE);
1096         I915_STATE_WARN(cur_state != state,
1097              "PLL state assertion failure (expected %s, current %s)\n",
1098                         onoff(state), onoff(cur_state));
1099 }
1100
1101 /* XXX: the dsi pll is shared between MIPI DSI ports */
1102 void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1103 {
1104         u32 val;
1105         bool cur_state;
1106
1107         vlv_cck_get(dev_priv);
1108         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1109         vlv_cck_put(dev_priv);
1110
1111         cur_state = val & DSI_PLL_VCO_EN;
1112         I915_STATE_WARN(cur_state != state,
1113              "DSI PLL state assertion failure (expected %s, current %s)\n",
1114                         onoff(state), onoff(cur_state));
1115 }
1116
1117 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1118                           enum pipe pipe, bool state)
1119 {
1120         bool cur_state;
1121         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1122                                                                       pipe);
1123
1124         if (HAS_DDI(dev_priv)) {
1125                 /* DDI does not have a specific FDI_TX register */
1126                 u32 val = I915_READ(TRANS_DDI_FUNC_CTL(cpu_transcoder));
1127                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1128         } else {
1129                 u32 val = I915_READ(FDI_TX_CTL(pipe));
1130                 cur_state = !!(val & FDI_TX_ENABLE);
1131         }
1132         I915_STATE_WARN(cur_state != state,
1133              "FDI TX state assertion failure (expected %s, current %s)\n",
1134                         onoff(state), onoff(cur_state));
1135 }
1136 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1137 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1138
1139 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1140                           enum pipe pipe, bool state)
1141 {
1142         u32 val;
1143         bool cur_state;
1144
1145         val = I915_READ(FDI_RX_CTL(pipe));
1146         cur_state = !!(val & FDI_RX_ENABLE);
1147         I915_STATE_WARN(cur_state != state,
1148              "FDI RX state assertion failure (expected %s, current %s)\n",
1149                         onoff(state), onoff(cur_state));
1150 }
1151 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1152 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1153
1154 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1155                                       enum pipe pipe)
1156 {
1157         u32 val;
1158
1159         /* ILK FDI PLL is always enabled */
1160         if (IS_GEN(dev_priv, 5))
1161                 return;
1162
1163         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1164         if (HAS_DDI(dev_priv))
1165                 return;
1166
1167         val = I915_READ(FDI_TX_CTL(pipe));
1168         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1169 }
1170
1171 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1172                        enum pipe pipe, bool state)
1173 {
1174         u32 val;
1175         bool cur_state;
1176
1177         val = I915_READ(FDI_RX_CTL(pipe));
1178         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1179         I915_STATE_WARN(cur_state != state,
1180              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1181                         onoff(state), onoff(cur_state));
1182 }
1183
1184 void assert_panel_unlocked(struct drm_i915_private *dev_priv, enum pipe pipe)
1185 {
1186         i915_reg_t pp_reg;
1187         u32 val;
1188         enum pipe panel_pipe = INVALID_PIPE;
1189         bool locked = true;
1190
1191         if (WARN_ON(HAS_DDI(dev_priv)))
1192                 return;
1193
1194         if (HAS_PCH_SPLIT(dev_priv)) {
1195                 u32 port_sel;
1196
1197                 pp_reg = PP_CONTROL(0);
1198                 port_sel = I915_READ(PP_ON_DELAYS(0)) & PANEL_PORT_SELECT_MASK;
1199
1200                 switch (port_sel) {
1201                 case PANEL_PORT_SELECT_LVDS:
1202                         intel_lvds_port_enabled(dev_priv, PCH_LVDS, &panel_pipe);
1203                         break;
1204                 case PANEL_PORT_SELECT_DPA:
1205                         intel_dp_port_enabled(dev_priv, DP_A, PORT_A, &panel_pipe);
1206                         break;
1207                 case PANEL_PORT_SELECT_DPC:
1208                         intel_dp_port_enabled(dev_priv, PCH_DP_C, PORT_C, &panel_pipe);
1209                         break;
1210                 case PANEL_PORT_SELECT_DPD:
1211                         intel_dp_port_enabled(dev_priv, PCH_DP_D, PORT_D, &panel_pipe);
1212                         break;
1213                 default:
1214                         MISSING_CASE(port_sel);
1215                         break;
1216                 }
1217         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
1218                 /* presumably write lock depends on pipe, not port select */
1219                 pp_reg = PP_CONTROL(pipe);
1220                 panel_pipe = pipe;
1221         } else {
1222                 u32 port_sel;
1223
1224                 pp_reg = PP_CONTROL(0);
1225                 port_sel = I915_READ(PP_ON_DELAYS(0)) & PANEL_PORT_SELECT_MASK;
1226
1227                 WARN_ON(port_sel != PANEL_PORT_SELECT_LVDS);
1228                 intel_lvds_port_enabled(dev_priv, LVDS, &panel_pipe);
1229         }
1230
1231         val = I915_READ(pp_reg);
1232         if (!(val & PANEL_POWER_ON) ||
1233             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1234                 locked = false;
1235
1236         I915_STATE_WARN(panel_pipe == pipe && locked,
1237              "panel assertion failure, pipe %c regs locked\n",
1238              pipe_name(pipe));
1239 }
1240
1241 void assert_pipe(struct drm_i915_private *dev_priv,
1242                  enum pipe pipe, bool state)
1243 {
1244         bool cur_state;
1245         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1246                                                                       pipe);
1247         enum intel_display_power_domain power_domain;
1248         intel_wakeref_t wakeref;
1249
1250         /* we keep both pipes enabled on 830 */
1251         if (IS_I830(dev_priv))
1252                 state = true;
1253
1254         power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
1255         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
1256         if (wakeref) {
1257                 u32 val = I915_READ(PIPECONF(cpu_transcoder));
1258                 cur_state = !!(val & PIPECONF_ENABLE);
1259
1260                 intel_display_power_put(dev_priv, power_domain, wakeref);
1261         } else {
1262                 cur_state = false;
1263         }
1264
1265         I915_STATE_WARN(cur_state != state,
1266              "pipe %c assertion failure (expected %s, current %s)\n",
1267                         pipe_name(pipe), onoff(state), onoff(cur_state));
1268 }
1269
1270 static void assert_plane(struct intel_plane *plane, bool state)
1271 {
1272         enum pipe pipe;
1273         bool cur_state;
1274
1275         cur_state = plane->get_hw_state(plane, &pipe);
1276
1277         I915_STATE_WARN(cur_state != state,
1278                         "%s assertion failure (expected %s, current %s)\n",
1279                         plane->base.name, onoff(state), onoff(cur_state));
1280 }
1281
1282 #define assert_plane_enabled(p) assert_plane(p, true)
1283 #define assert_plane_disabled(p) assert_plane(p, false)
1284
1285 static void assert_planes_disabled(struct intel_crtc *crtc)
1286 {
1287         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1288         struct intel_plane *plane;
1289
1290         for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, plane)
1291                 assert_plane_disabled(plane);
1292 }
1293
1294 static void assert_vblank_disabled(struct drm_crtc *crtc)
1295 {
1296         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1297                 drm_crtc_vblank_put(crtc);
1298 }
1299
1300 void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1301                                     enum pipe pipe)
1302 {
1303         u32 val;
1304         bool enabled;
1305
1306         val = I915_READ(PCH_TRANSCONF(pipe));
1307         enabled = !!(val & TRANS_ENABLE);
1308         I915_STATE_WARN(enabled,
1309              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1310              pipe_name(pipe));
1311 }
1312
1313 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1314                                    enum pipe pipe, enum port port,
1315                                    i915_reg_t dp_reg)
1316 {
1317         enum pipe port_pipe;
1318         bool state;
1319
1320         state = intel_dp_port_enabled(dev_priv, dp_reg, port, &port_pipe);
1321
1322         I915_STATE_WARN(state && port_pipe == pipe,
1323                         "PCH DP %c enabled on transcoder %c, should be disabled\n",
1324                         port_name(port), pipe_name(pipe));
1325
1326         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && !state && port_pipe == PIPE_B,
1327                         "IBX PCH DP %c still using transcoder B\n",
1328                         port_name(port));
1329 }
1330
1331 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1332                                      enum pipe pipe, enum port port,
1333                                      i915_reg_t hdmi_reg)
1334 {
1335         enum pipe port_pipe;
1336         bool state;
1337
1338         state = intel_sdvo_port_enabled(dev_priv, hdmi_reg, &port_pipe);
1339
1340         I915_STATE_WARN(state && port_pipe == pipe,
1341                         "PCH HDMI %c enabled on transcoder %c, should be disabled\n",
1342                         port_name(port), pipe_name(pipe));
1343
1344         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && !state && port_pipe == PIPE_B,
1345                         "IBX PCH HDMI %c still using transcoder B\n",
1346                         port_name(port));
1347 }
1348
1349 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1350                                       enum pipe pipe)
1351 {
1352         enum pipe port_pipe;
1353
1354         assert_pch_dp_disabled(dev_priv, pipe, PORT_B, PCH_DP_B);
1355         assert_pch_dp_disabled(dev_priv, pipe, PORT_C, PCH_DP_C);
1356         assert_pch_dp_disabled(dev_priv, pipe, PORT_D, PCH_DP_D);
1357
1358         I915_STATE_WARN(intel_crt_port_enabled(dev_priv, PCH_ADPA, &port_pipe) &&
1359                         port_pipe == pipe,
1360                         "PCH VGA enabled on transcoder %c, should be disabled\n",
1361                         pipe_name(pipe));
1362
1363         I915_STATE_WARN(intel_lvds_port_enabled(dev_priv, PCH_LVDS, &port_pipe) &&
1364                         port_pipe == pipe,
1365                         "PCH LVDS enabled on transcoder %c, should be disabled\n",
1366                         pipe_name(pipe));
1367
1368         /* PCH SDVOB multiplex with HDMIB */
1369         assert_pch_hdmi_disabled(dev_priv, pipe, PORT_B, PCH_HDMIB);
1370         assert_pch_hdmi_disabled(dev_priv, pipe, PORT_C, PCH_HDMIC);
1371         assert_pch_hdmi_disabled(dev_priv, pipe, PORT_D, PCH_HDMID);
1372 }
1373
1374 static void _vlv_enable_pll(struct intel_crtc *crtc,
1375                             const struct intel_crtc_state *pipe_config)
1376 {
1377         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1378         enum pipe pipe = crtc->pipe;
1379
1380         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1381         POSTING_READ(DPLL(pipe));
1382         udelay(150);
1383
1384         if (intel_wait_for_register(&dev_priv->uncore,
1385                                     DPLL(pipe),
1386                                     DPLL_LOCK_VLV,
1387                                     DPLL_LOCK_VLV,
1388                                     1))
1389                 DRM_ERROR("DPLL %d failed to lock\n", pipe);
1390 }
1391
1392 static void vlv_enable_pll(struct intel_crtc *crtc,
1393                            const struct intel_crtc_state *pipe_config)
1394 {
1395         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1396         enum pipe pipe = crtc->pipe;
1397
1398         assert_pipe_disabled(dev_priv, pipe);
1399
1400         /* PLL is protected by panel, make sure we can write it */
1401         assert_panel_unlocked(dev_priv, pipe);
1402
1403         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1404                 _vlv_enable_pll(crtc, pipe_config);
1405
1406         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1407         POSTING_READ(DPLL_MD(pipe));
1408 }
1409
1410
1411 static void _chv_enable_pll(struct intel_crtc *crtc,
1412                             const struct intel_crtc_state *pipe_config)
1413 {
1414         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1415         enum pipe pipe = crtc->pipe;
1416         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1417         u32 tmp;
1418
1419         vlv_dpio_get(dev_priv);
1420
1421         /* Enable back the 10bit clock to display controller */
1422         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1423         tmp |= DPIO_DCLKP_EN;
1424         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1425
1426         vlv_dpio_put(dev_priv);
1427
1428         /*
1429          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1430          */
1431         udelay(1);
1432
1433         /* Enable PLL */
1434         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1435
1436         /* Check PLL is locked */
1437         if (intel_wait_for_register(&dev_priv->uncore,
1438                                     DPLL(pipe), DPLL_LOCK_VLV, DPLL_LOCK_VLV,
1439                                     1))
1440                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1441 }
1442
1443 static void chv_enable_pll(struct intel_crtc *crtc,
1444                            const struct intel_crtc_state *pipe_config)
1445 {
1446         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1447         enum pipe pipe = crtc->pipe;
1448
1449         assert_pipe_disabled(dev_priv, pipe);
1450
1451         /* PLL is protected by panel, make sure we can write it */
1452         assert_panel_unlocked(dev_priv, pipe);
1453
1454         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1455                 _chv_enable_pll(crtc, pipe_config);
1456
1457         if (pipe != PIPE_A) {
1458                 /*
1459                  * WaPixelRepeatModeFixForC0:chv
1460                  *
1461                  * DPLLCMD is AWOL. Use chicken bits to propagate
1462                  * the value from DPLLBMD to either pipe B or C.
1463                  */
1464                 I915_WRITE(CBR4_VLV, CBR_DPLLBMD_PIPE(pipe));
1465                 I915_WRITE(DPLL_MD(PIPE_B), pipe_config->dpll_hw_state.dpll_md);
1466                 I915_WRITE(CBR4_VLV, 0);
1467                 dev_priv->chv_dpll_md[pipe] = pipe_config->dpll_hw_state.dpll_md;
1468
1469                 /*
1470                  * DPLLB VGA mode also seems to cause problems.
1471                  * We should always have it disabled.
1472                  */
1473                 WARN_ON((I915_READ(DPLL(PIPE_B)) & DPLL_VGA_MODE_DIS) == 0);
1474         } else {
1475                 I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1476                 POSTING_READ(DPLL_MD(pipe));
1477         }
1478 }
1479
1480 static bool i9xx_has_pps(struct drm_i915_private *dev_priv)
1481 {
1482         if (IS_I830(dev_priv))
1483                 return false;
1484
1485         return IS_PINEVIEW(dev_priv) || IS_MOBILE(dev_priv);
1486 }
1487
1488 static void i9xx_enable_pll(struct intel_crtc *crtc,
1489                             const struct intel_crtc_state *crtc_state)
1490 {
1491         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1492         i915_reg_t reg = DPLL(crtc->pipe);
1493         u32 dpll = crtc_state->dpll_hw_state.dpll;
1494         int i;
1495
1496         assert_pipe_disabled(dev_priv, crtc->pipe);
1497
1498         /* PLL is protected by panel, make sure we can write it */
1499         if (i9xx_has_pps(dev_priv))
1500                 assert_panel_unlocked(dev_priv, crtc->pipe);
1501
1502         /*
1503          * Apparently we need to have VGA mode enabled prior to changing
1504          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
1505          * dividers, even though the register value does change.
1506          */
1507         I915_WRITE(reg, dpll & ~DPLL_VGA_MODE_DIS);
1508         I915_WRITE(reg, dpll);
1509
1510         /* Wait for the clocks to stabilize. */
1511         POSTING_READ(reg);
1512         udelay(150);
1513
1514         if (INTEL_GEN(dev_priv) >= 4) {
1515                 I915_WRITE(DPLL_MD(crtc->pipe),
1516                            crtc_state->dpll_hw_state.dpll_md);
1517         } else {
1518                 /* The pixel multiplier can only be updated once the
1519                  * DPLL is enabled and the clocks are stable.
1520                  *
1521                  * So write it again.
1522                  */
1523                 I915_WRITE(reg, dpll);
1524         }
1525
1526         /* We do this three times for luck */
1527         for (i = 0; i < 3; i++) {
1528                 I915_WRITE(reg, dpll);
1529                 POSTING_READ(reg);
1530                 udelay(150); /* wait for warmup */
1531         }
1532 }
1533
1534 static void i9xx_disable_pll(const struct intel_crtc_state *crtc_state)
1535 {
1536         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
1537         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1538         enum pipe pipe = crtc->pipe;
1539
1540         /* Don't disable pipe or pipe PLLs if needed */
1541         if (IS_I830(dev_priv))
1542                 return;
1543
1544         /* Make sure the pipe isn't still relying on us */
1545         assert_pipe_disabled(dev_priv, pipe);
1546
1547         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1548         POSTING_READ(DPLL(pipe));
1549 }
1550
1551 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1552 {
1553         u32 val;
1554
1555         /* Make sure the pipe isn't still relying on us */
1556         assert_pipe_disabled(dev_priv, pipe);
1557
1558         val = DPLL_INTEGRATED_REF_CLK_VLV |
1559                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1560         if (pipe != PIPE_A)
1561                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1562
1563         I915_WRITE(DPLL(pipe), val);
1564         POSTING_READ(DPLL(pipe));
1565 }
1566
1567 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1568 {
1569         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1570         u32 val;
1571
1572         /* Make sure the pipe isn't still relying on us */
1573         assert_pipe_disabled(dev_priv, pipe);
1574
1575         val = DPLL_SSC_REF_CLK_CHV |
1576                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1577         if (pipe != PIPE_A)
1578                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1579
1580         I915_WRITE(DPLL(pipe), val);
1581         POSTING_READ(DPLL(pipe));
1582
1583         vlv_dpio_get(dev_priv);
1584
1585         /* Disable 10bit clock to display controller */
1586         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1587         val &= ~DPIO_DCLKP_EN;
1588         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1589
1590         vlv_dpio_put(dev_priv);
1591 }
1592
1593 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1594                          struct intel_digital_port *dport,
1595                          unsigned int expected_mask)
1596 {
1597         u32 port_mask;
1598         i915_reg_t dpll_reg;
1599
1600         switch (dport->base.port) {
1601         case PORT_B:
1602                 port_mask = DPLL_PORTB_READY_MASK;
1603                 dpll_reg = DPLL(0);
1604                 break;
1605         case PORT_C:
1606                 port_mask = DPLL_PORTC_READY_MASK;
1607                 dpll_reg = DPLL(0);
1608                 expected_mask <<= 4;
1609                 break;
1610         case PORT_D:
1611                 port_mask = DPLL_PORTD_READY_MASK;
1612                 dpll_reg = DPIO_PHY_STATUS;
1613                 break;
1614         default:
1615                 BUG();
1616         }
1617
1618         if (intel_wait_for_register(&dev_priv->uncore,
1619                                     dpll_reg, port_mask, expected_mask,
1620                                     1000))
1621                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1622                      port_name(dport->base.port),
1623                      I915_READ(dpll_reg) & port_mask, expected_mask);
1624 }
1625
1626 static void ironlake_enable_pch_transcoder(const struct intel_crtc_state *crtc_state)
1627 {
1628         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
1629         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1630         enum pipe pipe = crtc->pipe;
1631         i915_reg_t reg;
1632         u32 val, pipeconf_val;
1633
1634         /* Make sure PCH DPLL is enabled */
1635         assert_shared_dpll_enabled(dev_priv, crtc_state->shared_dpll);
1636
1637         /* FDI must be feeding us bits for PCH ports */
1638         assert_fdi_tx_enabled(dev_priv, pipe);
1639         assert_fdi_rx_enabled(dev_priv, pipe);
1640
1641         if (HAS_PCH_CPT(dev_priv)) {
1642                 /* Workaround: Set the timing override bit before enabling the
1643                  * pch transcoder. */
1644                 reg = TRANS_CHICKEN2(pipe);
1645                 val = I915_READ(reg);
1646                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1647                 I915_WRITE(reg, val);
1648         }
1649
1650         reg = PCH_TRANSCONF(pipe);
1651         val = I915_READ(reg);
1652         pipeconf_val = I915_READ(PIPECONF(pipe));
1653
1654         if (HAS_PCH_IBX(dev_priv)) {
1655                 /*
1656                  * Make the BPC in transcoder be consistent with
1657                  * that in pipeconf reg. For HDMI we must use 8bpc
1658                  * here for both 8bpc and 12bpc.
1659                  */
1660                 val &= ~PIPECONF_BPC_MASK;
1661                 if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
1662                         val |= PIPECONF_8BPC;
1663                 else
1664                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1665         }
1666
1667         val &= ~TRANS_INTERLACE_MASK;
1668         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK) {
1669                 if (HAS_PCH_IBX(dev_priv) &&
1670                     intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO))
1671                         val |= TRANS_LEGACY_INTERLACED_ILK;
1672                 else
1673                         val |= TRANS_INTERLACED;
1674         } else {
1675                 val |= TRANS_PROGRESSIVE;
1676         }
1677
1678         I915_WRITE(reg, val | TRANS_ENABLE);
1679         if (intel_wait_for_register(&dev_priv->uncore,
1680                                     reg, TRANS_STATE_ENABLE, TRANS_STATE_ENABLE,
1681                                     100))
1682                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1683 }
1684
1685 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1686                                       enum transcoder cpu_transcoder)
1687 {
1688         u32 val, pipeconf_val;
1689
1690         /* FDI must be feeding us bits for PCH ports */
1691         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1692         assert_fdi_rx_enabled(dev_priv, PIPE_A);
1693
1694         /* Workaround: set timing override bit. */
1695         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1696         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1697         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1698
1699         val = TRANS_ENABLE;
1700         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1701
1702         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1703             PIPECONF_INTERLACED_ILK)
1704                 val |= TRANS_INTERLACED;
1705         else
1706                 val |= TRANS_PROGRESSIVE;
1707
1708         I915_WRITE(LPT_TRANSCONF, val);
1709         if (intel_wait_for_register(&dev_priv->uncore,
1710                                     LPT_TRANSCONF,
1711                                     TRANS_STATE_ENABLE,
1712                                     TRANS_STATE_ENABLE,
1713                                     100))
1714                 DRM_ERROR("Failed to enable PCH transcoder\n");
1715 }
1716
1717 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1718                                             enum pipe pipe)
1719 {
1720         i915_reg_t reg;
1721         u32 val;
1722
1723         /* FDI relies on the transcoder */
1724         assert_fdi_tx_disabled(dev_priv, pipe);
1725         assert_fdi_rx_disabled(dev_priv, pipe);
1726
1727         /* Ports must be off as well */
1728         assert_pch_ports_disabled(dev_priv, pipe);
1729
1730         reg = PCH_TRANSCONF(pipe);
1731         val = I915_READ(reg);
1732         val &= ~TRANS_ENABLE;
1733         I915_WRITE(reg, val);
1734         /* wait for PCH transcoder off, transcoder state */
1735         if (intel_wait_for_register(&dev_priv->uncore,
1736                                     reg, TRANS_STATE_ENABLE, 0,
1737                                     50))
1738                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1739
1740         if (HAS_PCH_CPT(dev_priv)) {
1741                 /* Workaround: Clear the timing override chicken bit again. */
1742                 reg = TRANS_CHICKEN2(pipe);
1743                 val = I915_READ(reg);
1744                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1745                 I915_WRITE(reg, val);
1746         }
1747 }
1748
1749 void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1750 {
1751         u32 val;
1752
1753         val = I915_READ(LPT_TRANSCONF);
1754         val &= ~TRANS_ENABLE;
1755         I915_WRITE(LPT_TRANSCONF, val);
1756         /* wait for PCH transcoder off, transcoder state */
1757         if (intel_wait_for_register(&dev_priv->uncore,
1758                                     LPT_TRANSCONF, TRANS_STATE_ENABLE, 0,
1759                                     50))
1760                 DRM_ERROR("Failed to disable PCH transcoder\n");
1761
1762         /* Workaround: clear timing override bit. */
1763         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1764         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1765         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1766 }
1767
1768 enum pipe intel_crtc_pch_transcoder(struct intel_crtc *crtc)
1769 {
1770         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1771
1772         if (HAS_PCH_LPT(dev_priv))
1773                 return PIPE_A;
1774         else
1775                 return crtc->pipe;
1776 }
1777
1778 static u32 intel_crtc_max_vblank_count(const struct intel_crtc_state *crtc_state)
1779 {
1780         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
1781
1782         /*
1783          * On i965gm the hardware frame counter reads
1784          * zero when the TV encoder is enabled :(
1785          */
1786         if (IS_I965GM(dev_priv) &&
1787             (crtc_state->output_types & BIT(INTEL_OUTPUT_TVOUT)))
1788                 return 0;
1789
1790         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
1791                 return 0xffffffff; /* full 32 bit counter */
1792         else if (INTEL_GEN(dev_priv) >= 3)
1793                 return 0xffffff; /* only 24 bits of frame count */
1794         else
1795                 return 0; /* Gen2 doesn't have a hardware frame counter */
1796 }
1797
1798 static void intel_crtc_vblank_on(const struct intel_crtc_state *crtc_state)
1799 {
1800         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
1801
1802         drm_crtc_set_max_vblank_count(&crtc->base,
1803                                       intel_crtc_max_vblank_count(crtc_state));
1804         drm_crtc_vblank_on(&crtc->base);
1805 }
1806
1807 static void intel_enable_pipe(const struct intel_crtc_state *new_crtc_state)
1808 {
1809         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
1810         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1811         enum transcoder cpu_transcoder = new_crtc_state->cpu_transcoder;
1812         enum pipe pipe = crtc->pipe;
1813         i915_reg_t reg;
1814         u32 val;
1815
1816         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
1817
1818         assert_planes_disabled(crtc);
1819
1820         /*
1821          * A pipe without a PLL won't actually be able to drive bits from
1822          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
1823          * need the check.
1824          */
1825         if (HAS_GMCH(dev_priv)) {
1826                 if (intel_crtc_has_type(new_crtc_state, INTEL_OUTPUT_DSI))
1827                         assert_dsi_pll_enabled(dev_priv);
1828                 else
1829                         assert_pll_enabled(dev_priv, pipe);
1830         } else {
1831                 if (new_crtc_state->has_pch_encoder) {
1832                         /* if driving the PCH, we need FDI enabled */
1833                         assert_fdi_rx_pll_enabled(dev_priv,
1834                                                   intel_crtc_pch_transcoder(crtc));
1835                         assert_fdi_tx_pll_enabled(dev_priv,
1836                                                   (enum pipe) cpu_transcoder);
1837                 }
1838                 /* FIXME: assert CPU port conditions for SNB+ */
1839         }
1840
1841         trace_intel_pipe_enable(dev_priv, pipe);
1842
1843         reg = PIPECONF(cpu_transcoder);
1844         val = I915_READ(reg);
1845         if (val & PIPECONF_ENABLE) {
1846                 /* we keep both pipes enabled on 830 */
1847                 WARN_ON(!IS_I830(dev_priv));
1848                 return;
1849         }
1850
1851         I915_WRITE(reg, val | PIPECONF_ENABLE);
1852         POSTING_READ(reg);
1853
1854         /*
1855          * Until the pipe starts PIPEDSL reads will return a stale value,
1856          * which causes an apparent vblank timestamp jump when PIPEDSL
1857          * resets to its proper value. That also messes up the frame count
1858          * when it's derived from the timestamps. So let's wait for the
1859          * pipe to start properly before we call drm_crtc_vblank_on()
1860          */
1861         if (intel_crtc_max_vblank_count(new_crtc_state) == 0)
1862                 intel_wait_for_pipe_scanline_moving(crtc);
1863 }
1864
1865 static void intel_disable_pipe(const struct intel_crtc_state *old_crtc_state)
1866 {
1867         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
1868         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1869         enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
1870         enum pipe pipe = crtc->pipe;
1871         i915_reg_t reg;
1872         u32 val;
1873
1874         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
1875
1876         /*
1877          * Make sure planes won't keep trying to pump pixels to us,
1878          * or we might hang the display.
1879          */
1880         assert_planes_disabled(crtc);
1881
1882         trace_intel_pipe_disable(dev_priv, pipe);
1883
1884         reg = PIPECONF(cpu_transcoder);
1885         val = I915_READ(reg);
1886         if ((val & PIPECONF_ENABLE) == 0)
1887                 return;
1888
1889         /*
1890          * Double wide has implications for planes
1891          * so best keep it disabled when not needed.
1892          */
1893         if (old_crtc_state->double_wide)
1894                 val &= ~PIPECONF_DOUBLE_WIDE;
1895
1896         /* Don't disable pipe or pipe PLLs if needed */
1897         if (!IS_I830(dev_priv))
1898                 val &= ~PIPECONF_ENABLE;
1899
1900         I915_WRITE(reg, val);
1901         if ((val & PIPECONF_ENABLE) == 0)
1902                 intel_wait_for_pipe_off(old_crtc_state);
1903 }
1904
1905 static unsigned int intel_tile_size(const struct drm_i915_private *dev_priv)
1906 {
1907         return IS_GEN(dev_priv, 2) ? 2048 : 4096;
1908 }
1909
1910 static unsigned int
1911 intel_tile_width_bytes(const struct drm_framebuffer *fb, int color_plane)
1912 {
1913         struct drm_i915_private *dev_priv = to_i915(fb->dev);
1914         unsigned int cpp = fb->format->cpp[color_plane];
1915
1916         switch (fb->modifier) {
1917         case DRM_FORMAT_MOD_LINEAR:
1918                 return cpp;
1919         case I915_FORMAT_MOD_X_TILED:
1920                 if (IS_GEN(dev_priv, 2))
1921                         return 128;
1922                 else
1923                         return 512;
1924         case I915_FORMAT_MOD_Y_TILED_CCS:
1925                 if (color_plane == 1)
1926                         return 128;
1927                 /* fall through */
1928         case I915_FORMAT_MOD_Y_TILED:
1929                 if (IS_GEN(dev_priv, 2) || HAS_128_BYTE_Y_TILING(dev_priv))
1930                         return 128;
1931                 else
1932                         return 512;
1933         case I915_FORMAT_MOD_Yf_TILED_CCS:
1934                 if (color_plane == 1)
1935                         return 128;
1936                 /* fall through */
1937         case I915_FORMAT_MOD_Yf_TILED:
1938                 switch (cpp) {
1939                 case 1:
1940                         return 64;
1941                 case 2:
1942                 case 4:
1943                         return 128;
1944                 case 8:
1945                 case 16:
1946                         return 256;
1947                 default:
1948                         MISSING_CASE(cpp);
1949                         return cpp;
1950                 }
1951                 break;
1952         default:
1953                 MISSING_CASE(fb->modifier);
1954                 return cpp;
1955         }
1956 }
1957
1958 static unsigned int
1959 intel_tile_height(const struct drm_framebuffer *fb, int color_plane)
1960 {
1961         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
1962                 return 1;
1963         else
1964                 return intel_tile_size(to_i915(fb->dev)) /
1965                         intel_tile_width_bytes(fb, color_plane);
1966 }
1967
1968 /* Return the tile dimensions in pixel units */
1969 static void intel_tile_dims(const struct drm_framebuffer *fb, int color_plane,
1970                             unsigned int *tile_width,
1971                             unsigned int *tile_height)
1972 {
1973         unsigned int tile_width_bytes = intel_tile_width_bytes(fb, color_plane);
1974         unsigned int cpp = fb->format->cpp[color_plane];
1975
1976         *tile_width = tile_width_bytes / cpp;
1977         *tile_height = intel_tile_size(to_i915(fb->dev)) / tile_width_bytes;
1978 }
1979
1980 unsigned int
1981 intel_fb_align_height(const struct drm_framebuffer *fb,
1982                       int color_plane, unsigned int height)
1983 {
1984         unsigned int tile_height = intel_tile_height(fb, color_plane);
1985
1986         return ALIGN(height, tile_height);
1987 }
1988
1989 unsigned int intel_rotation_info_size(const struct intel_rotation_info *rot_info)
1990 {
1991         unsigned int size = 0;
1992         int i;
1993
1994         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
1995                 size += rot_info->plane[i].width * rot_info->plane[i].height;
1996
1997         return size;
1998 }
1999
2000 static void
2001 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view,
2002                         const struct drm_framebuffer *fb,
2003                         unsigned int rotation)
2004 {
2005         view->type = I915_GGTT_VIEW_NORMAL;
2006         if (drm_rotation_90_or_270(rotation)) {
2007                 view->type = I915_GGTT_VIEW_ROTATED;
2008                 view->rotated = to_intel_framebuffer(fb)->rot_info;
2009         }
2010 }
2011
2012 static unsigned int intel_cursor_alignment(const struct drm_i915_private *dev_priv)
2013 {
2014         if (IS_I830(dev_priv))
2015                 return 16 * 1024;
2016         else if (IS_I85X(dev_priv))
2017                 return 256;
2018         else if (IS_I845G(dev_priv) || IS_I865G(dev_priv))
2019                 return 32;
2020         else
2021                 return 4 * 1024;
2022 }
2023
2024 static unsigned int intel_linear_alignment(const struct drm_i915_private *dev_priv)
2025 {
2026         if (INTEL_GEN(dev_priv) >= 9)
2027                 return 256 * 1024;
2028         else if (IS_I965G(dev_priv) || IS_I965GM(dev_priv) ||
2029                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
2030                 return 128 * 1024;
2031         else if (INTEL_GEN(dev_priv) >= 4)
2032                 return 4 * 1024;
2033         else
2034                 return 0;
2035 }
2036
2037 static unsigned int intel_surf_alignment(const struct drm_framebuffer *fb,
2038                                          int color_plane)
2039 {
2040         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2041
2042         /* AUX_DIST needs only 4K alignment */
2043         if (color_plane == 1)
2044                 return 4096;
2045
2046         switch (fb->modifier) {
2047         case DRM_FORMAT_MOD_LINEAR:
2048                 return intel_linear_alignment(dev_priv);
2049         case I915_FORMAT_MOD_X_TILED:
2050                 if (INTEL_GEN(dev_priv) >= 9)
2051                         return 256 * 1024;
2052                 return 0;
2053         case I915_FORMAT_MOD_Y_TILED_CCS:
2054         case I915_FORMAT_MOD_Yf_TILED_CCS:
2055         case I915_FORMAT_MOD_Y_TILED:
2056         case I915_FORMAT_MOD_Yf_TILED:
2057                 return 1 * 1024 * 1024;
2058         default:
2059                 MISSING_CASE(fb->modifier);
2060                 return 0;
2061         }
2062 }
2063
2064 static bool intel_plane_uses_fence(const struct intel_plane_state *plane_state)
2065 {
2066         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2067         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
2068
2069         return INTEL_GEN(dev_priv) < 4 || plane->has_fbc;
2070 }
2071
2072 struct i915_vma *
2073 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb,
2074                            const struct i915_ggtt_view *view,
2075                            bool uses_fence,
2076                            unsigned long *out_flags)
2077 {
2078         struct drm_device *dev = fb->dev;
2079         struct drm_i915_private *dev_priv = to_i915(dev);
2080         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2081         intel_wakeref_t wakeref;
2082         struct i915_vma *vma;
2083         unsigned int pinctl;
2084         u32 alignment;
2085
2086         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2087
2088         alignment = intel_surf_alignment(fb, 0);
2089
2090         /* Note that the w/a also requires 64 PTE of padding following the
2091          * bo. We currently fill all unused PTE with the shadow page and so
2092          * we should always have valid PTE following the scanout preventing
2093          * the VT-d warning.
2094          */
2095         if (intel_scanout_needs_vtd_wa(dev_priv) && alignment < 256 * 1024)
2096                 alignment = 256 * 1024;
2097
2098         /*
2099          * Global gtt pte registers are special registers which actually forward
2100          * writes to a chunk of system memory. Which means that there is no risk
2101          * that the register values disappear as soon as we call
2102          * intel_runtime_pm_put(), so it is correct to wrap only the
2103          * pin/unpin/fence and not more.
2104          */
2105         wakeref = intel_runtime_pm_get(dev_priv);
2106
2107         atomic_inc(&dev_priv->gpu_error.pending_fb_pin);
2108
2109         pinctl = 0;
2110
2111         /* Valleyview is definitely limited to scanning out the first
2112          * 512MiB. Lets presume this behaviour was inherited from the
2113          * g4x display engine and that all earlier gen are similarly
2114          * limited. Testing suggests that it is a little more
2115          * complicated than this. For example, Cherryview appears quite
2116          * happy to scanout from anywhere within its global aperture.
2117          */
2118         if (HAS_GMCH(dev_priv))
2119                 pinctl |= PIN_MAPPABLE;
2120
2121         vma = i915_gem_object_pin_to_display_plane(obj,
2122                                                    alignment, view, pinctl);
2123         if (IS_ERR(vma))
2124                 goto err;
2125
2126         if (uses_fence && i915_vma_is_map_and_fenceable(vma)) {
2127                 int ret;
2128
2129                 /* Install a fence for tiled scan-out. Pre-i965 always needs a
2130                  * fence, whereas 965+ only requires a fence if using
2131                  * framebuffer compression.  For simplicity, we always, when
2132                  * possible, install a fence as the cost is not that onerous.
2133                  *
2134                  * If we fail to fence the tiled scanout, then either the
2135                  * modeset will reject the change (which is highly unlikely as
2136                  * the affected systems, all but one, do not have unmappable
2137                  * space) or we will not be able to enable full powersaving
2138                  * techniques (also likely not to apply due to various limits
2139                  * FBC and the like impose on the size of the buffer, which
2140                  * presumably we violated anyway with this unmappable buffer).
2141                  * Anyway, it is presumably better to stumble onwards with
2142                  * something and try to run the system in a "less than optimal"
2143                  * mode that matches the user configuration.
2144                  */
2145                 ret = i915_vma_pin_fence(vma);
2146                 if (ret != 0 && INTEL_GEN(dev_priv) < 4) {
2147                         i915_gem_object_unpin_from_display_plane(vma);
2148                         vma = ERR_PTR(ret);
2149                         goto err;
2150                 }
2151
2152                 if (ret == 0 && vma->fence)
2153                         *out_flags |= PLANE_HAS_FENCE;
2154         }
2155
2156         i915_vma_get(vma);
2157 err:
2158         atomic_dec(&dev_priv->gpu_error.pending_fb_pin);
2159
2160         intel_runtime_pm_put(dev_priv, 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         if (flags & PLANE_HAS_FENCE)
2169                 i915_vma_unpin_fence(vma);
2170         i915_gem_object_unpin_from_display_plane(vma);
2171         i915_vma_put(vma);
2172 }
2173
2174 static int intel_fb_pitch(const struct drm_framebuffer *fb, int color_plane,
2175                           unsigned int rotation)
2176 {
2177         if (drm_rotation_90_or_270(rotation))
2178                 return to_intel_framebuffer(fb)->rotated[color_plane].pitch;
2179         else
2180                 return fb->pitches[color_plane];
2181 }
2182
2183 /*
2184  * Convert the x/y offsets into a linear offset.
2185  * Only valid with 0/180 degree rotation, which is fine since linear
2186  * offset is only used with linear buffers on pre-hsw and tiled buffers
2187  * with gen2/3, and 90/270 degree rotations isn't supported on any of them.
2188  */
2189 u32 intel_fb_xy_to_linear(int x, int y,
2190                           const struct intel_plane_state *state,
2191                           int color_plane)
2192 {
2193         const struct drm_framebuffer *fb = state->base.fb;
2194         unsigned int cpp = fb->format->cpp[color_plane];
2195         unsigned int pitch = state->color_plane[color_plane].stride;
2196
2197         return y * pitch + x * cpp;
2198 }
2199
2200 /*
2201  * Add the x/y offsets derived from fb->offsets[] to the user
2202  * specified plane src x/y offsets. The resulting x/y offsets
2203  * specify the start of scanout from the beginning of the gtt mapping.
2204  */
2205 void intel_add_fb_offsets(int *x, int *y,
2206                           const struct intel_plane_state *state,
2207                           int color_plane)
2208
2209 {
2210         const struct intel_framebuffer *intel_fb = to_intel_framebuffer(state->base.fb);
2211         unsigned int rotation = state->base.rotation;
2212
2213         if (drm_rotation_90_or_270(rotation)) {
2214                 *x += intel_fb->rotated[color_plane].x;
2215                 *y += intel_fb->rotated[color_plane].y;
2216         } else {
2217                 *x += intel_fb->normal[color_plane].x;
2218                 *y += intel_fb->normal[color_plane].y;
2219         }
2220 }
2221
2222 static u32 intel_adjust_tile_offset(int *x, int *y,
2223                                     unsigned int tile_width,
2224                                     unsigned int tile_height,
2225                                     unsigned int tile_size,
2226                                     unsigned int pitch_tiles,
2227                                     u32 old_offset,
2228                                     u32 new_offset)
2229 {
2230         unsigned int pitch_pixels = pitch_tiles * tile_width;
2231         unsigned int tiles;
2232
2233         WARN_ON(old_offset & (tile_size - 1));
2234         WARN_ON(new_offset & (tile_size - 1));
2235         WARN_ON(new_offset > old_offset);
2236
2237         tiles = (old_offset - new_offset) / tile_size;
2238
2239         *y += tiles / pitch_tiles * tile_height;
2240         *x += tiles % pitch_tiles * tile_width;
2241
2242         /* minimize x in case it got needlessly big */
2243         *y += *x / pitch_pixels * tile_height;
2244         *x %= pitch_pixels;
2245
2246         return new_offset;
2247 }
2248
2249 static bool is_surface_linear(u64 modifier, int color_plane)
2250 {
2251         return modifier == DRM_FORMAT_MOD_LINEAR;
2252 }
2253
2254 static u32 intel_adjust_aligned_offset(int *x, int *y,
2255                                        const struct drm_framebuffer *fb,
2256                                        int color_plane,
2257                                        unsigned int rotation,
2258                                        unsigned int pitch,
2259                                        u32 old_offset, u32 new_offset)
2260 {
2261         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2262         unsigned int cpp = fb->format->cpp[color_plane];
2263
2264         WARN_ON(new_offset > old_offset);
2265
2266         if (!is_surface_linear(fb->modifier, color_plane)) {
2267                 unsigned int tile_size, tile_width, tile_height;
2268                 unsigned int pitch_tiles;
2269
2270                 tile_size = intel_tile_size(dev_priv);
2271                 intel_tile_dims(fb, color_plane, &tile_width, &tile_height);
2272
2273                 if (drm_rotation_90_or_270(rotation)) {
2274                         pitch_tiles = pitch / tile_height;
2275                         swap(tile_width, tile_height);
2276                 } else {
2277                         pitch_tiles = pitch / (tile_width * cpp);
2278                 }
2279
2280                 intel_adjust_tile_offset(x, y, tile_width, tile_height,
2281                                          tile_size, pitch_tiles,
2282                                          old_offset, new_offset);
2283         } else {
2284                 old_offset += *y * pitch + *x * cpp;
2285
2286                 *y = (old_offset - new_offset) / pitch;
2287                 *x = ((old_offset - new_offset) - *y * pitch) / cpp;
2288         }
2289
2290         return new_offset;
2291 }
2292
2293 /*
2294  * Adjust the tile offset by moving the difference into
2295  * the x/y offsets.
2296  */
2297 static u32 intel_plane_adjust_aligned_offset(int *x, int *y,
2298                                              const struct intel_plane_state *state,
2299                                              int color_plane,
2300                                              u32 old_offset, u32 new_offset)
2301 {
2302         return intel_adjust_aligned_offset(x, y, state->base.fb, color_plane,
2303                                            state->base.rotation,
2304                                            state->color_plane[color_plane].stride,
2305                                            old_offset, new_offset);
2306 }
2307
2308 /*
2309  * Computes the aligned offset to the base tile and adjusts
2310  * x, y. bytes per pixel is assumed to be a power-of-two.
2311  *
2312  * In the 90/270 rotated case, x and y are assumed
2313  * to be already rotated to match the rotated GTT view, and
2314  * pitch is the tile_height aligned framebuffer height.
2315  *
2316  * This function is used when computing the derived information
2317  * under intel_framebuffer, so using any of that information
2318  * here is not allowed. Anything under drm_framebuffer can be
2319  * used. This is why the user has to pass in the pitch since it
2320  * is specified in the rotated orientation.
2321  */
2322 static u32 intel_compute_aligned_offset(struct drm_i915_private *dev_priv,
2323                                         int *x, int *y,
2324                                         const struct drm_framebuffer *fb,
2325                                         int color_plane,
2326                                         unsigned int pitch,
2327                                         unsigned int rotation,
2328                                         u32 alignment)
2329 {
2330         unsigned int cpp = fb->format->cpp[color_plane];
2331         u32 offset, offset_aligned;
2332
2333         if (alignment)
2334                 alignment--;
2335
2336         if (!is_surface_linear(fb->modifier, color_plane)) {
2337                 unsigned int tile_size, tile_width, tile_height;
2338                 unsigned int tile_rows, tiles, pitch_tiles;
2339
2340                 tile_size = intel_tile_size(dev_priv);
2341                 intel_tile_dims(fb, color_plane, &tile_width, &tile_height);
2342
2343                 if (drm_rotation_90_or_270(rotation)) {
2344                         pitch_tiles = pitch / tile_height;
2345                         swap(tile_width, tile_height);
2346                 } else {
2347                         pitch_tiles = pitch / (tile_width * cpp);
2348                 }
2349
2350                 tile_rows = *y / tile_height;
2351                 *y %= tile_height;
2352
2353                 tiles = *x / tile_width;
2354                 *x %= tile_width;
2355
2356                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2357                 offset_aligned = offset & ~alignment;
2358
2359                 intel_adjust_tile_offset(x, y, tile_width, tile_height,
2360                                          tile_size, pitch_tiles,
2361                                          offset, offset_aligned);
2362         } else {
2363                 offset = *y * pitch + *x * cpp;
2364                 offset_aligned = offset & ~alignment;
2365
2366                 *y = (offset & alignment) / pitch;
2367                 *x = ((offset & alignment) - *y * pitch) / cpp;
2368         }
2369
2370         return offset_aligned;
2371 }
2372
2373 static u32 intel_plane_compute_aligned_offset(int *x, int *y,
2374                                               const struct intel_plane_state *state,
2375                                               int color_plane)
2376 {
2377         struct intel_plane *intel_plane = to_intel_plane(state->base.plane);
2378         struct drm_i915_private *dev_priv = to_i915(intel_plane->base.dev);
2379         const struct drm_framebuffer *fb = state->base.fb;
2380         unsigned int rotation = state->base.rotation;
2381         int pitch = state->color_plane[color_plane].stride;
2382         u32 alignment;
2383
2384         if (intel_plane->id == PLANE_CURSOR)
2385                 alignment = intel_cursor_alignment(dev_priv);
2386         else
2387                 alignment = intel_surf_alignment(fb, color_plane);
2388
2389         return intel_compute_aligned_offset(dev_priv, x, y, fb, color_plane,
2390                                             pitch, rotation, alignment);
2391 }
2392
2393 /* Convert the fb->offset[] into x/y offsets */
2394 static int intel_fb_offset_to_xy(int *x, int *y,
2395                                  const struct drm_framebuffer *fb,
2396                                  int color_plane)
2397 {
2398         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2399         unsigned int height;
2400
2401         if (fb->modifier != DRM_FORMAT_MOD_LINEAR &&
2402             fb->offsets[color_plane] % intel_tile_size(dev_priv)) {
2403                 DRM_DEBUG_KMS("Misaligned offset 0x%08x for color plane %d\n",
2404                               fb->offsets[color_plane], color_plane);
2405                 return -EINVAL;
2406         }
2407
2408         height = drm_framebuffer_plane_height(fb->height, fb, color_plane);
2409         height = ALIGN(height, intel_tile_height(fb, color_plane));
2410
2411         /* Catch potential overflows early */
2412         if (add_overflows_t(u32, mul_u32_u32(height, fb->pitches[color_plane]),
2413                             fb->offsets[color_plane])) {
2414                 DRM_DEBUG_KMS("Bad offset 0x%08x or pitch %d for color plane %d\n",
2415                               fb->offsets[color_plane], fb->pitches[color_plane],
2416                               color_plane);
2417                 return -ERANGE;
2418         }
2419
2420         *x = 0;
2421         *y = 0;
2422
2423         intel_adjust_aligned_offset(x, y,
2424                                     fb, color_plane, DRM_MODE_ROTATE_0,
2425                                     fb->pitches[color_plane],
2426                                     fb->offsets[color_plane], 0);
2427
2428         return 0;
2429 }
2430
2431 static unsigned int intel_fb_modifier_to_tiling(u64 fb_modifier)
2432 {
2433         switch (fb_modifier) {
2434         case I915_FORMAT_MOD_X_TILED:
2435                 return I915_TILING_X;
2436         case I915_FORMAT_MOD_Y_TILED:
2437         case I915_FORMAT_MOD_Y_TILED_CCS:
2438                 return I915_TILING_Y;
2439         default:
2440                 return I915_TILING_NONE;
2441         }
2442 }
2443
2444 /*
2445  * From the Sky Lake PRM:
2446  * "The Color Control Surface (CCS) contains the compression status of
2447  *  the cache-line pairs. The compression state of the cache-line pair
2448  *  is specified by 2 bits in the CCS. Each CCS cache-line represents
2449  *  an area on the main surface of 16 x16 sets of 128 byte Y-tiled
2450  *  cache-line-pairs. CCS is always Y tiled."
2451  *
2452  * Since cache line pairs refers to horizontally adjacent cache lines,
2453  * each cache line in the CCS corresponds to an area of 32x16 cache
2454  * lines on the main surface. Since each pixel is 4 bytes, this gives
2455  * us a ratio of one byte in the CCS for each 8x16 pixels in the
2456  * main surface.
2457  */
2458 static const struct drm_format_info ccs_formats[] = {
2459         { .format = DRM_FORMAT_XRGB8888, .depth = 24, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2460         { .format = DRM_FORMAT_XBGR8888, .depth = 24, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2461         { .format = DRM_FORMAT_ARGB8888, .depth = 32, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2462         { .format = DRM_FORMAT_ABGR8888, .depth = 32, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2463 };
2464
2465 static const struct drm_format_info *
2466 lookup_format_info(const struct drm_format_info formats[],
2467                    int num_formats, u32 format)
2468 {
2469         int i;
2470
2471         for (i = 0; i < num_formats; i++) {
2472                 if (formats[i].format == format)
2473                         return &formats[i];
2474         }
2475
2476         return NULL;
2477 }
2478
2479 static const struct drm_format_info *
2480 intel_get_format_info(const struct drm_mode_fb_cmd2 *cmd)
2481 {
2482         switch (cmd->modifier[0]) {
2483         case I915_FORMAT_MOD_Y_TILED_CCS:
2484         case I915_FORMAT_MOD_Yf_TILED_CCS:
2485                 return lookup_format_info(ccs_formats,
2486                                           ARRAY_SIZE(ccs_formats),
2487                                           cmd->pixel_format);
2488         default:
2489                 return NULL;
2490         }
2491 }
2492
2493 bool is_ccs_modifier(u64 modifier)
2494 {
2495         return modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
2496                modifier == I915_FORMAT_MOD_Yf_TILED_CCS;
2497 }
2498
2499 static int
2500 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2501                    struct drm_framebuffer *fb)
2502 {
2503         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
2504         struct intel_rotation_info *rot_info = &intel_fb->rot_info;
2505         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2506         u32 gtt_offset_rotated = 0;
2507         unsigned int max_size = 0;
2508         int i, num_planes = fb->format->num_planes;
2509         unsigned int tile_size = intel_tile_size(dev_priv);
2510
2511         for (i = 0; i < num_planes; i++) {
2512                 unsigned int width, height;
2513                 unsigned int cpp, size;
2514                 u32 offset;
2515                 int x, y;
2516                 int ret;
2517
2518                 cpp = fb->format->cpp[i];
2519                 width = drm_framebuffer_plane_width(fb->width, fb, i);
2520                 height = drm_framebuffer_plane_height(fb->height, fb, i);
2521
2522                 ret = intel_fb_offset_to_xy(&x, &y, fb, i);
2523                 if (ret) {
2524                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2525                                       i, fb->offsets[i]);
2526                         return ret;
2527                 }
2528
2529                 if (is_ccs_modifier(fb->modifier) && i == 1) {
2530                         int hsub = fb->format->hsub;
2531                         int vsub = fb->format->vsub;
2532                         int tile_width, tile_height;
2533                         int main_x, main_y;
2534                         int ccs_x, ccs_y;
2535
2536                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2537                         tile_width *= hsub;
2538                         tile_height *= vsub;
2539
2540                         ccs_x = (x * hsub) % tile_width;
2541                         ccs_y = (y * vsub) % tile_height;
2542                         main_x = intel_fb->normal[0].x % tile_width;
2543                         main_y = intel_fb->normal[0].y % tile_height;
2544
2545                         /*
2546                          * CCS doesn't have its own x/y offset register, so the intra CCS tile
2547                          * x/y offsets must match between CCS and the main surface.
2548                          */
2549                         if (main_x != ccs_x || main_y != ccs_y) {
2550                                 DRM_DEBUG_KMS("Bad CCS x/y (main %d,%d ccs %d,%d) full (main %d,%d ccs %d,%d)\n",
2551                                               main_x, main_y,
2552                                               ccs_x, ccs_y,
2553                                               intel_fb->normal[0].x,
2554                                               intel_fb->normal[0].y,
2555                                               x, y);
2556                                 return -EINVAL;
2557                         }
2558                 }
2559
2560                 /*
2561                  * The fence (if used) is aligned to the start of the object
2562                  * so having the framebuffer wrap around across the edge of the
2563                  * fenced region doesn't really work. We have no API to configure
2564                  * the fence start offset within the object (nor could we probably
2565                  * on gen2/3). So it's just easier if we just require that the
2566                  * fb layout agrees with the fence layout. We already check that the
2567                  * fb stride matches the fence stride elsewhere.
2568                  */
2569                 if (i == 0 && i915_gem_object_is_tiled(obj) &&
2570                     (x + width) * cpp > fb->pitches[i]) {
2571                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2572                                       i, fb->offsets[i]);
2573                         return -EINVAL;
2574                 }
2575
2576                 /*
2577                  * First pixel of the framebuffer from
2578                  * the start of the normal gtt mapping.
2579                  */
2580                 intel_fb->normal[i].x = x;
2581                 intel_fb->normal[i].y = y;
2582
2583                 offset = intel_compute_aligned_offset(dev_priv, &x, &y, fb, i,
2584                                                       fb->pitches[i],
2585                                                       DRM_MODE_ROTATE_0,
2586                                                       tile_size);
2587                 offset /= tile_size;
2588
2589                 if (!is_surface_linear(fb->modifier, i)) {
2590                         unsigned int tile_width, tile_height;
2591                         unsigned int pitch_tiles;
2592                         struct drm_rect r;
2593
2594                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2595
2596                         rot_info->plane[i].offset = offset;
2597                         rot_info->plane[i].stride = DIV_ROUND_UP(fb->pitches[i], tile_width * cpp);
2598                         rot_info->plane[i].width = DIV_ROUND_UP(x + width, tile_width);
2599                         rot_info->plane[i].height = DIV_ROUND_UP(y + height, tile_height);
2600
2601                         intel_fb->rotated[i].pitch =
2602                                 rot_info->plane[i].height * tile_height;
2603
2604                         /* how many tiles does this plane need */
2605                         size = rot_info->plane[i].stride * rot_info->plane[i].height;
2606                         /*
2607                          * If the plane isn't horizontally tile aligned,
2608                          * we need one more tile.
2609                          */
2610                         if (x != 0)
2611                                 size++;
2612
2613                         /* rotate the x/y offsets to match the GTT view */
2614                         r.x1 = x;
2615                         r.y1 = y;
2616                         r.x2 = x + width;
2617                         r.y2 = y + height;
2618                         drm_rect_rotate(&r,
2619                                         rot_info->plane[i].width * tile_width,
2620                                         rot_info->plane[i].height * tile_height,
2621                                         DRM_MODE_ROTATE_270);
2622                         x = r.x1;
2623                         y = r.y1;
2624
2625                         /* rotate the tile dimensions to match the GTT view */
2626                         pitch_tiles = intel_fb->rotated[i].pitch / tile_height;
2627                         swap(tile_width, tile_height);
2628
2629                         /*
2630                          * We only keep the x/y offsets, so push all of the
2631                          * gtt offset into the x/y offsets.
2632                          */
2633                         intel_adjust_tile_offset(&x, &y,
2634                                                  tile_width, tile_height,
2635                                                  tile_size, pitch_tiles,
2636                                                  gtt_offset_rotated * tile_size, 0);
2637
2638                         gtt_offset_rotated += rot_info->plane[i].width * rot_info->plane[i].height;
2639
2640                         /*
2641                          * First pixel of the framebuffer from
2642                          * the start of the rotated gtt mapping.
2643                          */
2644                         intel_fb->rotated[i].x = x;
2645                         intel_fb->rotated[i].y = y;
2646                 } else {
2647                         size = DIV_ROUND_UP((y + height) * fb->pitches[i] +
2648                                             x * cpp, tile_size);
2649                 }
2650
2651                 /* how many tiles in total needed in the bo */
2652                 max_size = max(max_size, offset + size);
2653         }
2654
2655         if (mul_u32_u32(max_size, tile_size) > obj->base.size) {
2656                 DRM_DEBUG_KMS("fb too big for bo (need %llu bytes, have %zu bytes)\n",
2657                               mul_u32_u32(max_size, tile_size), obj->base.size);
2658                 return -EINVAL;
2659         }
2660
2661         return 0;
2662 }
2663
2664 static int i9xx_format_to_fourcc(int format)
2665 {
2666         switch (format) {
2667         case DISPPLANE_8BPP:
2668                 return DRM_FORMAT_C8;
2669         case DISPPLANE_BGRX555:
2670                 return DRM_FORMAT_XRGB1555;
2671         case DISPPLANE_BGRX565:
2672                 return DRM_FORMAT_RGB565;
2673         default:
2674         case DISPPLANE_BGRX888:
2675                 return DRM_FORMAT_XRGB8888;
2676         case DISPPLANE_RGBX888:
2677                 return DRM_FORMAT_XBGR8888;
2678         case DISPPLANE_BGRX101010:
2679                 return DRM_FORMAT_XRGB2101010;
2680         case DISPPLANE_RGBX101010:
2681                 return DRM_FORMAT_XBGR2101010;
2682         }
2683 }
2684
2685 int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2686 {
2687         switch (format) {
2688         case PLANE_CTL_FORMAT_RGB_565:
2689                 return DRM_FORMAT_RGB565;
2690         case PLANE_CTL_FORMAT_NV12:
2691                 return DRM_FORMAT_NV12;
2692         case PLANE_CTL_FORMAT_P010:
2693                 return DRM_FORMAT_P010;
2694         case PLANE_CTL_FORMAT_P012:
2695                 return DRM_FORMAT_P012;
2696         case PLANE_CTL_FORMAT_P016:
2697                 return DRM_FORMAT_P016;
2698         case PLANE_CTL_FORMAT_Y210:
2699                 return DRM_FORMAT_Y210;
2700         case PLANE_CTL_FORMAT_Y212:
2701                 return DRM_FORMAT_Y212;
2702         case PLANE_CTL_FORMAT_Y216:
2703                 return DRM_FORMAT_Y216;
2704         case PLANE_CTL_FORMAT_Y410:
2705                 return DRM_FORMAT_XVYU2101010;
2706         case PLANE_CTL_FORMAT_Y412:
2707                 return DRM_FORMAT_XVYU12_16161616;
2708         case PLANE_CTL_FORMAT_Y416:
2709                 return DRM_FORMAT_XVYU16161616;
2710         default:
2711         case PLANE_CTL_FORMAT_XRGB_8888:
2712                 if (rgb_order) {
2713                         if (alpha)
2714                                 return DRM_FORMAT_ABGR8888;
2715                         else
2716                                 return DRM_FORMAT_XBGR8888;
2717                 } else {
2718                         if (alpha)
2719                                 return DRM_FORMAT_ARGB8888;
2720                         else
2721                                 return DRM_FORMAT_XRGB8888;
2722                 }
2723         case PLANE_CTL_FORMAT_XRGB_2101010:
2724                 if (rgb_order)
2725                         return DRM_FORMAT_XBGR2101010;
2726                 else
2727                         return DRM_FORMAT_XRGB2101010;
2728         case PLANE_CTL_FORMAT_XRGB_16161616F:
2729                 if (rgb_order) {
2730                         if (alpha)
2731                                 return DRM_FORMAT_ABGR16161616F;
2732                         else
2733                                 return DRM_FORMAT_XBGR16161616F;
2734                 } else {
2735                         if (alpha)
2736                                 return DRM_FORMAT_ARGB16161616F;
2737                         else
2738                                 return DRM_FORMAT_XRGB16161616F;
2739                 }
2740         }
2741 }
2742
2743 static bool
2744 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2745                               struct intel_initial_plane_config *plane_config)
2746 {
2747         struct drm_device *dev = crtc->base.dev;
2748         struct drm_i915_private *dev_priv = to_i915(dev);
2749         struct drm_i915_gem_object *obj = NULL;
2750         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2751         struct drm_framebuffer *fb = &plane_config->fb->base;
2752         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2753         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2754                                     PAGE_SIZE);
2755
2756         size_aligned -= base_aligned;
2757
2758         if (plane_config->size == 0)
2759                 return false;
2760
2761         /* If the FB is too big, just don't use it since fbdev is not very
2762          * important and we should probably use that space with FBC or other
2763          * features. */
2764         if (size_aligned * 2 > dev_priv->stolen_usable_size)
2765                 return false;
2766
2767         switch (fb->modifier) {
2768         case DRM_FORMAT_MOD_LINEAR:
2769         case I915_FORMAT_MOD_X_TILED:
2770         case I915_FORMAT_MOD_Y_TILED:
2771                 break;
2772         default:
2773                 DRM_DEBUG_DRIVER("Unsupported modifier for initial FB: 0x%llx\n",
2774                                  fb->modifier);
2775                 return false;
2776         }
2777
2778         mutex_lock(&dev->struct_mutex);
2779         obj = i915_gem_object_create_stolen_for_preallocated(dev_priv,
2780                                                              base_aligned,
2781                                                              base_aligned,
2782                                                              size_aligned);
2783         mutex_unlock(&dev->struct_mutex);
2784         if (!obj)
2785                 return false;
2786
2787         switch (plane_config->tiling) {
2788         case I915_TILING_NONE:
2789                 break;
2790         case I915_TILING_X:
2791         case I915_TILING_Y:
2792                 obj->tiling_and_stride = fb->pitches[0] | plane_config->tiling;
2793                 break;
2794         default:
2795                 MISSING_CASE(plane_config->tiling);
2796                 return false;
2797         }
2798
2799         mode_cmd.pixel_format = fb->format->format;
2800         mode_cmd.width = fb->width;
2801         mode_cmd.height = fb->height;
2802         mode_cmd.pitches[0] = fb->pitches[0];
2803         mode_cmd.modifier[0] = fb->modifier;
2804         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2805
2806         if (intel_framebuffer_init(to_intel_framebuffer(fb), obj, &mode_cmd)) {
2807                 DRM_DEBUG_KMS("intel fb init failed\n");
2808                 goto out_unref_obj;
2809         }
2810
2811
2812         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2813         return true;
2814
2815 out_unref_obj:
2816         i915_gem_object_put(obj);
2817         return false;
2818 }
2819
2820 static void
2821 intel_set_plane_visible(struct intel_crtc_state *crtc_state,
2822                         struct intel_plane_state *plane_state,
2823                         bool visible)
2824 {
2825         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2826
2827         plane_state->base.visible = visible;
2828
2829         if (visible)
2830                 crtc_state->base.plane_mask |= drm_plane_mask(&plane->base);
2831         else
2832                 crtc_state->base.plane_mask &= ~drm_plane_mask(&plane->base);
2833 }
2834
2835 static void fixup_active_planes(struct intel_crtc_state *crtc_state)
2836 {
2837         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
2838         struct drm_plane *plane;
2839
2840         /*
2841          * Active_planes aliases if multiple "primary" or cursor planes
2842          * have been used on the same (or wrong) pipe. plane_mask uses
2843          * unique ids, hence we can use that to reconstruct active_planes.
2844          */
2845         crtc_state->active_planes = 0;
2846
2847         drm_for_each_plane_mask(plane, &dev_priv->drm,
2848                                 crtc_state->base.plane_mask)
2849                 crtc_state->active_planes |= BIT(to_intel_plane(plane)->id);
2850 }
2851
2852 static void intel_plane_disable_noatomic(struct intel_crtc *crtc,
2853                                          struct intel_plane *plane)
2854 {
2855         struct intel_crtc_state *crtc_state =
2856                 to_intel_crtc_state(crtc->base.state);
2857         struct intel_plane_state *plane_state =
2858                 to_intel_plane_state(plane->base.state);
2859
2860         DRM_DEBUG_KMS("Disabling [PLANE:%d:%s] on [CRTC:%d:%s]\n",
2861                       plane->base.base.id, plane->base.name,
2862                       crtc->base.base.id, crtc->base.name);
2863
2864         intel_set_plane_visible(crtc_state, plane_state, false);
2865         fixup_active_planes(crtc_state);
2866
2867         if (plane->id == PLANE_PRIMARY)
2868                 intel_pre_disable_primary_noatomic(&crtc->base);
2869
2870         intel_disable_plane(plane, crtc_state);
2871 }
2872
2873 static void
2874 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2875                              struct intel_initial_plane_config *plane_config)
2876 {
2877         struct drm_device *dev = intel_crtc->base.dev;
2878         struct drm_i915_private *dev_priv = to_i915(dev);
2879         struct drm_crtc *c;
2880         struct drm_i915_gem_object *obj;
2881         struct drm_plane *primary = intel_crtc->base.primary;
2882         struct drm_plane_state *plane_state = primary->state;
2883         struct intel_plane *intel_plane = to_intel_plane(primary);
2884         struct intel_plane_state *intel_state =
2885                 to_intel_plane_state(plane_state);
2886         struct drm_framebuffer *fb;
2887
2888         if (!plane_config->fb)
2889                 return;
2890
2891         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2892                 fb = &plane_config->fb->base;
2893                 goto valid_fb;
2894         }
2895
2896         kfree(plane_config->fb);
2897
2898         /*
2899          * Failed to alloc the obj, check to see if we should share
2900          * an fb with another CRTC instead
2901          */
2902         for_each_crtc(dev, c) {
2903                 struct intel_plane_state *state;
2904
2905                 if (c == &intel_crtc->base)
2906                         continue;
2907
2908                 if (!to_intel_crtc(c)->active)
2909                         continue;
2910
2911                 state = to_intel_plane_state(c->primary->state);
2912                 if (!state->vma)
2913                         continue;
2914
2915                 if (intel_plane_ggtt_offset(state) == plane_config->base) {
2916                         fb = state->base.fb;
2917                         drm_framebuffer_get(fb);
2918                         goto valid_fb;
2919                 }
2920         }
2921
2922         /*
2923          * We've failed to reconstruct the BIOS FB.  Current display state
2924          * indicates that the primary plane is visible, but has a NULL FB,
2925          * which will lead to problems later if we don't fix it up.  The
2926          * simplest solution is to just disable the primary plane now and
2927          * pretend the BIOS never had it enabled.
2928          */
2929         intel_plane_disable_noatomic(intel_crtc, intel_plane);
2930
2931         return;
2932
2933 valid_fb:
2934         intel_state->base.rotation = plane_config->rotation;
2935         intel_fill_fb_ggtt_view(&intel_state->view, fb,
2936                                 intel_state->base.rotation);
2937         intel_state->color_plane[0].stride =
2938                 intel_fb_pitch(fb, 0, intel_state->base.rotation);
2939
2940         mutex_lock(&dev->struct_mutex);
2941         intel_state->vma =
2942                 intel_pin_and_fence_fb_obj(fb,
2943                                            &intel_state->view,
2944                                            intel_plane_uses_fence(intel_state),
2945                                            &intel_state->flags);
2946         mutex_unlock(&dev->struct_mutex);
2947         if (IS_ERR(intel_state->vma)) {
2948                 DRM_ERROR("failed to pin boot fb on pipe %d: %li\n",
2949                           intel_crtc->pipe, PTR_ERR(intel_state->vma));
2950
2951                 intel_state->vma = NULL;
2952                 drm_framebuffer_put(fb);
2953                 return;
2954         }
2955
2956         obj = intel_fb_obj(fb);
2957         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
2958
2959         plane_state->src_x = 0;
2960         plane_state->src_y = 0;
2961         plane_state->src_w = fb->width << 16;
2962         plane_state->src_h = fb->height << 16;
2963
2964         plane_state->crtc_x = 0;
2965         plane_state->crtc_y = 0;
2966         plane_state->crtc_w = fb->width;
2967         plane_state->crtc_h = fb->height;
2968
2969         intel_state->base.src = drm_plane_state_src(plane_state);
2970         intel_state->base.dst = drm_plane_state_dest(plane_state);
2971
2972         if (i915_gem_object_is_tiled(obj))
2973                 dev_priv->preserve_bios_swizzle = true;
2974
2975         plane_state->fb = fb;
2976         plane_state->crtc = &intel_crtc->base;
2977
2978         atomic_or(to_intel_plane(primary)->frontbuffer_bit,
2979                   &obj->frontbuffer_bits);
2980 }
2981
2982 static int skl_max_plane_width(const struct drm_framebuffer *fb,
2983                                int color_plane,
2984                                unsigned int rotation)
2985 {
2986         int cpp = fb->format->cpp[color_plane];
2987
2988         switch (fb->modifier) {
2989         case DRM_FORMAT_MOD_LINEAR:
2990         case I915_FORMAT_MOD_X_TILED:
2991                 return 4096;
2992         case I915_FORMAT_MOD_Y_TILED_CCS:
2993         case I915_FORMAT_MOD_Yf_TILED_CCS:
2994                 /* FIXME AUX plane? */
2995         case I915_FORMAT_MOD_Y_TILED:
2996         case I915_FORMAT_MOD_Yf_TILED:
2997                 if (cpp == 8)
2998                         return 2048;
2999                 else
3000                         return 4096;
3001         default:
3002                 MISSING_CASE(fb->modifier);
3003                 return 2048;
3004         }
3005 }
3006
3007 static int glk_max_plane_width(const struct drm_framebuffer *fb,
3008                                int color_plane,
3009                                unsigned int rotation)
3010 {
3011         int cpp = fb->format->cpp[color_plane];
3012
3013         switch (fb->modifier) {
3014         case DRM_FORMAT_MOD_LINEAR:
3015         case I915_FORMAT_MOD_X_TILED:
3016                 if (cpp == 8)
3017                         return 4096;
3018                 else
3019                         return 5120;
3020         case I915_FORMAT_MOD_Y_TILED_CCS:
3021         case I915_FORMAT_MOD_Yf_TILED_CCS:
3022                 /* FIXME AUX plane? */
3023         case I915_FORMAT_MOD_Y_TILED:
3024         case I915_FORMAT_MOD_Yf_TILED:
3025                 if (cpp == 8)
3026                         return 2048;
3027                 else
3028                         return 5120;
3029         default:
3030                 MISSING_CASE(fb->modifier);
3031                 return 2048;
3032         }
3033 }
3034
3035 static int icl_max_plane_width(const struct drm_framebuffer *fb,
3036                                int color_plane,
3037                                unsigned int rotation)
3038 {
3039         return 5120;
3040 }
3041
3042 static bool skl_check_main_ccs_coordinates(struct intel_plane_state *plane_state,
3043                                            int main_x, int main_y, u32 main_offset)
3044 {
3045         const struct drm_framebuffer *fb = plane_state->base.fb;
3046         int hsub = fb->format->hsub;
3047         int vsub = fb->format->vsub;
3048         int aux_x = plane_state->color_plane[1].x;
3049         int aux_y = plane_state->color_plane[1].y;
3050         u32 aux_offset = plane_state->color_plane[1].offset;
3051         u32 alignment = intel_surf_alignment(fb, 1);
3052
3053         while (aux_offset >= main_offset && aux_y <= main_y) {
3054                 int x, y;
3055
3056                 if (aux_x == main_x && aux_y == main_y)
3057                         break;
3058
3059                 if (aux_offset == 0)
3060                         break;
3061
3062                 x = aux_x / hsub;
3063                 y = aux_y / vsub;
3064                 aux_offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 1,
3065                                                                aux_offset, aux_offset - alignment);
3066                 aux_x = x * hsub + aux_x % hsub;
3067                 aux_y = y * vsub + aux_y % vsub;
3068         }
3069
3070         if (aux_x != main_x || aux_y != main_y)
3071                 return false;
3072
3073         plane_state->color_plane[1].offset = aux_offset;
3074         plane_state->color_plane[1].x = aux_x;
3075         plane_state->color_plane[1].y = aux_y;
3076
3077         return true;
3078 }
3079
3080 static int skl_check_main_surface(struct intel_plane_state *plane_state)
3081 {
3082         struct drm_i915_private *dev_priv = to_i915(plane_state->base.plane->dev);
3083         const struct drm_framebuffer *fb = plane_state->base.fb;
3084         unsigned int rotation = plane_state->base.rotation;
3085         int x = plane_state->base.src.x1 >> 16;
3086         int y = plane_state->base.src.y1 >> 16;
3087         int w = drm_rect_width(&plane_state->base.src) >> 16;
3088         int h = drm_rect_height(&plane_state->base.src) >> 16;
3089         int max_width;
3090         int max_height = 4096;
3091         u32 alignment, offset, aux_offset = plane_state->color_plane[1].offset;
3092
3093         if (INTEL_GEN(dev_priv) >= 11)
3094                 max_width = icl_max_plane_width(fb, 0, rotation);
3095         else if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv))
3096                 max_width = glk_max_plane_width(fb, 0, rotation);
3097         else
3098                 max_width = skl_max_plane_width(fb, 0, rotation);
3099
3100         if (w > max_width || h > max_height) {
3101                 DRM_DEBUG_KMS("requested Y/RGB source size %dx%d too big (limit %dx%d)\n",
3102                               w, h, max_width, max_height);
3103                 return -EINVAL;
3104         }
3105
3106         intel_add_fb_offsets(&x, &y, plane_state, 0);
3107         offset = intel_plane_compute_aligned_offset(&x, &y, plane_state, 0);
3108         alignment = intel_surf_alignment(fb, 0);
3109
3110         /*
3111          * AUX surface offset is specified as the distance from the
3112          * main surface offset, and it must be non-negative. Make
3113          * sure that is what we will get.
3114          */
3115         if (offset > aux_offset)
3116                 offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 0,
3117                                                            offset, aux_offset & ~(alignment - 1));
3118
3119         /*
3120          * When using an X-tiled surface, the plane blows up
3121          * if the x offset + width exceed the stride.
3122          *
3123          * TODO: linear and Y-tiled seem fine, Yf untested,
3124          */
3125         if (fb->modifier == I915_FORMAT_MOD_X_TILED) {
3126                 int cpp = fb->format->cpp[0];
3127
3128                 while ((x + w) * cpp > plane_state->color_plane[0].stride) {
3129                         if (offset == 0) {
3130                                 DRM_DEBUG_KMS("Unable to find suitable display surface offset due to X-tiling\n");
3131                                 return -EINVAL;
3132                         }
3133
3134                         offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 0,
3135                                                                    offset, offset - alignment);
3136                 }
3137         }
3138
3139         /*
3140          * CCS AUX surface doesn't have its own x/y offsets, we must make sure
3141          * they match with the main surface x/y offsets.
3142          */
3143         if (is_ccs_modifier(fb->modifier)) {
3144                 while (!skl_check_main_ccs_coordinates(plane_state, x, y, offset)) {
3145                         if (offset == 0)
3146                                 break;
3147
3148                         offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 0,
3149                                                                    offset, offset - alignment);
3150                 }
3151
3152                 if (x != plane_state->color_plane[1].x || y != plane_state->color_plane[1].y) {
3153                         DRM_DEBUG_KMS("Unable to find suitable display surface offset due to CCS\n");
3154                         return -EINVAL;
3155                 }
3156         }
3157
3158         plane_state->color_plane[0].offset = offset;
3159         plane_state->color_plane[0].x = x;
3160         plane_state->color_plane[0].y = y;
3161
3162         return 0;
3163 }
3164
3165 static int skl_check_nv12_aux_surface(struct intel_plane_state *plane_state)
3166 {
3167         const struct drm_framebuffer *fb = plane_state->base.fb;
3168         unsigned int rotation = plane_state->base.rotation;
3169         int max_width = skl_max_plane_width(fb, 1, rotation);
3170         int max_height = 4096;
3171         int x = plane_state->base.src.x1 >> 17;
3172         int y = plane_state->base.src.y1 >> 17;
3173         int w = drm_rect_width(&plane_state->base.src) >> 17;
3174         int h = drm_rect_height(&plane_state->base.src) >> 17;
3175         u32 offset;
3176
3177         intel_add_fb_offsets(&x, &y, plane_state, 1);
3178         offset = intel_plane_compute_aligned_offset(&x, &y, plane_state, 1);
3179
3180         /* FIXME not quite sure how/if these apply to the chroma plane */
3181         if (w > max_width || h > max_height) {
3182                 DRM_DEBUG_KMS("CbCr source size %dx%d too big (limit %dx%d)\n",
3183                               w, h, max_width, max_height);
3184                 return -EINVAL;
3185         }
3186
3187         plane_state->color_plane[1].offset = offset;
3188         plane_state->color_plane[1].x = x;
3189         plane_state->color_plane[1].y = y;
3190
3191         return 0;
3192 }
3193
3194 static int skl_check_ccs_aux_surface(struct intel_plane_state *plane_state)
3195 {
3196         const struct drm_framebuffer *fb = plane_state->base.fb;
3197         int src_x = plane_state->base.src.x1 >> 16;
3198         int src_y = plane_state->base.src.y1 >> 16;
3199         int hsub = fb->format->hsub;
3200         int vsub = fb->format->vsub;
3201         int x = src_x / hsub;
3202         int y = src_y / vsub;
3203         u32 offset;
3204
3205         intel_add_fb_offsets(&x, &y, plane_state, 1);
3206         offset = intel_plane_compute_aligned_offset(&x, &y, plane_state, 1);
3207
3208         plane_state->color_plane[1].offset = offset;
3209         plane_state->color_plane[1].x = x * hsub + src_x % hsub;
3210         plane_state->color_plane[1].y = y * vsub + src_y % vsub;
3211
3212         return 0;
3213 }
3214
3215 int skl_check_plane_surface(struct intel_plane_state *plane_state)
3216 {
3217         const struct drm_framebuffer *fb = plane_state->base.fb;
3218         unsigned int rotation = plane_state->base.rotation;
3219         int ret;
3220
3221         intel_fill_fb_ggtt_view(&plane_state->view, fb, rotation);
3222         plane_state->color_plane[0].stride = intel_fb_pitch(fb, 0, rotation);
3223         plane_state->color_plane[1].stride = intel_fb_pitch(fb, 1, rotation);
3224
3225         ret = intel_plane_check_stride(plane_state);
3226         if (ret)
3227                 return ret;
3228
3229         if (!plane_state->base.visible)
3230                 return 0;
3231
3232         /* Rotate src coordinates to match rotated GTT view */
3233         if (drm_rotation_90_or_270(rotation))
3234                 drm_rect_rotate(&plane_state->base.src,
3235                                 fb->width << 16, fb->height << 16,
3236                                 DRM_MODE_ROTATE_270);
3237
3238         /*
3239          * Handle the AUX surface first since
3240          * the main surface setup depends on it.
3241          */
3242         if (is_planar_yuv_format(fb->format->format)) {
3243                 ret = skl_check_nv12_aux_surface(plane_state);
3244                 if (ret)
3245                         return ret;
3246         } else if (is_ccs_modifier(fb->modifier)) {
3247                 ret = skl_check_ccs_aux_surface(plane_state);
3248                 if (ret)
3249                         return ret;
3250         } else {
3251                 plane_state->color_plane[1].offset = ~0xfff;
3252                 plane_state->color_plane[1].x = 0;
3253                 plane_state->color_plane[1].y = 0;
3254         }
3255
3256         ret = skl_check_main_surface(plane_state);
3257         if (ret)
3258                 return ret;
3259
3260         return 0;
3261 }
3262
3263 unsigned int
3264 i9xx_plane_max_stride(struct intel_plane *plane,
3265                       u32 pixel_format, u64 modifier,
3266                       unsigned int rotation)
3267 {
3268         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3269
3270         if (!HAS_GMCH(dev_priv)) {
3271                 return 32*1024;
3272         } else if (INTEL_GEN(dev_priv) >= 4) {
3273                 if (modifier == I915_FORMAT_MOD_X_TILED)
3274                         return 16*1024;
3275                 else
3276                         return 32*1024;
3277         } else if (INTEL_GEN(dev_priv) >= 3) {
3278                 if (modifier == I915_FORMAT_MOD_X_TILED)
3279                         return 8*1024;
3280                 else
3281                         return 16*1024;
3282         } else {
3283                 if (plane->i9xx_plane == PLANE_C)
3284                         return 4*1024;
3285                 else
3286                         return 8*1024;
3287         }
3288 }
3289
3290 static u32 i9xx_plane_ctl_crtc(const struct intel_crtc_state *crtc_state)
3291 {
3292         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
3293         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
3294         u32 dspcntr = 0;
3295
3296         if (crtc_state->gamma_enable)
3297                 dspcntr |= DISPPLANE_GAMMA_ENABLE;
3298
3299         if (crtc_state->csc_enable)
3300                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
3301
3302         if (INTEL_GEN(dev_priv) < 5)
3303                 dspcntr |= DISPPLANE_SEL_PIPE(crtc->pipe);
3304
3305         return dspcntr;
3306 }
3307
3308 static u32 i9xx_plane_ctl(const struct intel_crtc_state *crtc_state,
3309                           const struct intel_plane_state *plane_state)
3310 {
3311         struct drm_i915_private *dev_priv =
3312                 to_i915(plane_state->base.plane->dev);
3313         const struct drm_framebuffer *fb = plane_state->base.fb;
3314         unsigned int rotation = plane_state->base.rotation;
3315         u32 dspcntr;
3316
3317         dspcntr = DISPLAY_PLANE_ENABLE;
3318
3319         if (IS_G4X(dev_priv) || IS_GEN(dev_priv, 5) ||
3320             IS_GEN(dev_priv, 6) || IS_IVYBRIDGE(dev_priv))
3321                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
3322
3323         switch (fb->format->format) {
3324         case DRM_FORMAT_C8:
3325                 dspcntr |= DISPPLANE_8BPP;
3326                 break;
3327         case DRM_FORMAT_XRGB1555:
3328                 dspcntr |= DISPPLANE_BGRX555;
3329                 break;
3330         case DRM_FORMAT_RGB565:
3331                 dspcntr |= DISPPLANE_BGRX565;
3332                 break;
3333         case DRM_FORMAT_XRGB8888:
3334                 dspcntr |= DISPPLANE_BGRX888;
3335                 break;
3336         case DRM_FORMAT_XBGR8888:
3337                 dspcntr |= DISPPLANE_RGBX888;
3338                 break;
3339         case DRM_FORMAT_XRGB2101010:
3340                 dspcntr |= DISPPLANE_BGRX101010;
3341                 break;
3342         case DRM_FORMAT_XBGR2101010:
3343                 dspcntr |= DISPPLANE_RGBX101010;
3344                 break;
3345         default:
3346                 MISSING_CASE(fb->format->format);
3347                 return 0;
3348         }
3349
3350         if (INTEL_GEN(dev_priv) >= 4 &&
3351             fb->modifier == I915_FORMAT_MOD_X_TILED)
3352                 dspcntr |= DISPPLANE_TILED;
3353
3354         if (rotation & DRM_MODE_ROTATE_180)
3355                 dspcntr |= DISPPLANE_ROTATE_180;
3356
3357         if (rotation & DRM_MODE_REFLECT_X)
3358                 dspcntr |= DISPPLANE_MIRROR;
3359
3360         return dspcntr;
3361 }
3362
3363 int i9xx_check_plane_surface(struct intel_plane_state *plane_state)
3364 {
3365         struct drm_i915_private *dev_priv =
3366                 to_i915(plane_state->base.plane->dev);
3367         const struct drm_framebuffer *fb = plane_state->base.fb;
3368         unsigned int rotation = plane_state->base.rotation;
3369         int src_x = plane_state->base.src.x1 >> 16;
3370         int src_y = plane_state->base.src.y1 >> 16;
3371         u32 offset;
3372         int ret;
3373
3374         intel_fill_fb_ggtt_view(&plane_state->view, fb, rotation);
3375         plane_state->color_plane[0].stride = intel_fb_pitch(fb, 0, rotation);
3376
3377         ret = intel_plane_check_stride(plane_state);
3378         if (ret)
3379                 return ret;
3380
3381         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
3382
3383         if (INTEL_GEN(dev_priv) >= 4)
3384                 offset = intel_plane_compute_aligned_offset(&src_x, &src_y,
3385                                                             plane_state, 0);
3386         else
3387                 offset = 0;
3388
3389         /* HSW/BDW do this automagically in hardware */
3390         if (!IS_HASWELL(dev_priv) && !IS_BROADWELL(dev_priv)) {
3391                 int src_w = drm_rect_width(&plane_state->base.src) >> 16;
3392                 int src_h = drm_rect_height(&plane_state->base.src) >> 16;
3393
3394                 if (rotation & DRM_MODE_ROTATE_180) {
3395                         src_x += src_w - 1;
3396                         src_y += src_h - 1;
3397                 } else if (rotation & DRM_MODE_REFLECT_X) {
3398                         src_x += src_w - 1;
3399                 }
3400         }
3401
3402         plane_state->color_plane[0].offset = offset;
3403         plane_state->color_plane[0].x = src_x;
3404         plane_state->color_plane[0].y = src_y;
3405
3406         return 0;
3407 }
3408
3409 static int
3410 i9xx_plane_check(struct intel_crtc_state *crtc_state,
3411                  struct intel_plane_state *plane_state)
3412 {
3413         int ret;
3414
3415         ret = chv_plane_check_rotation(plane_state);
3416         if (ret)
3417                 return ret;
3418
3419         ret = drm_atomic_helper_check_plane_state(&plane_state->base,
3420                                                   &crtc_state->base,
3421                                                   DRM_PLANE_HELPER_NO_SCALING,
3422                                                   DRM_PLANE_HELPER_NO_SCALING,
3423                                                   false, true);
3424         if (ret)
3425                 return ret;
3426
3427         if (!plane_state->base.visible)
3428                 return 0;
3429
3430         ret = intel_plane_check_src_coordinates(plane_state);
3431         if (ret)
3432                 return ret;
3433
3434         ret = i9xx_check_plane_surface(plane_state);
3435         if (ret)
3436                 return ret;
3437
3438         plane_state->ctl = i9xx_plane_ctl(crtc_state, plane_state);
3439
3440         return 0;
3441 }
3442
3443 static void i9xx_update_plane(struct intel_plane *plane,
3444                               const struct intel_crtc_state *crtc_state,
3445                               const struct intel_plane_state *plane_state)
3446 {
3447         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3448         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3449         u32 linear_offset;
3450         int x = plane_state->color_plane[0].x;
3451         int y = plane_state->color_plane[0].y;
3452         unsigned long irqflags;
3453         u32 dspaddr_offset;
3454         u32 dspcntr;
3455
3456         dspcntr = plane_state->ctl | i9xx_plane_ctl_crtc(crtc_state);
3457
3458         linear_offset = intel_fb_xy_to_linear(x, y, plane_state, 0);
3459
3460         if (INTEL_GEN(dev_priv) >= 4)
3461                 dspaddr_offset = plane_state->color_plane[0].offset;
3462         else
3463                 dspaddr_offset = linear_offset;
3464
3465         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3466
3467         I915_WRITE_FW(DSPSTRIDE(i9xx_plane), plane_state->color_plane[0].stride);
3468
3469         if (INTEL_GEN(dev_priv) < 4) {
3470                 /* pipesrc and dspsize control the size that is scaled from,
3471                  * which should always be the user's requested size.
3472                  */
3473                 I915_WRITE_FW(DSPPOS(i9xx_plane), 0);
3474                 I915_WRITE_FW(DSPSIZE(i9xx_plane),
3475                               ((crtc_state->pipe_src_h - 1) << 16) |
3476                               (crtc_state->pipe_src_w - 1));
3477         } else if (IS_CHERRYVIEW(dev_priv) && i9xx_plane == PLANE_B) {
3478                 I915_WRITE_FW(PRIMPOS(i9xx_plane), 0);
3479                 I915_WRITE_FW(PRIMSIZE(i9xx_plane),
3480                               ((crtc_state->pipe_src_h - 1) << 16) |
3481                               (crtc_state->pipe_src_w - 1));
3482                 I915_WRITE_FW(PRIMCNSTALPHA(i9xx_plane), 0);
3483         }
3484
3485         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
3486                 I915_WRITE_FW(DSPOFFSET(i9xx_plane), (y << 16) | x);
3487         } else if (INTEL_GEN(dev_priv) >= 4) {
3488                 I915_WRITE_FW(DSPLINOFF(i9xx_plane), linear_offset);
3489                 I915_WRITE_FW(DSPTILEOFF(i9xx_plane), (y << 16) | x);
3490         }
3491
3492         /*
3493          * The control register self-arms if the plane was previously
3494          * disabled. Try to make the plane enable atomic by writing
3495          * the control register just before the surface register.
3496          */
3497         I915_WRITE_FW(DSPCNTR(i9xx_plane), dspcntr);
3498         if (INTEL_GEN(dev_priv) >= 4)
3499                 I915_WRITE_FW(DSPSURF(i9xx_plane),
3500                               intel_plane_ggtt_offset(plane_state) +
3501                               dspaddr_offset);
3502         else
3503                 I915_WRITE_FW(DSPADDR(i9xx_plane),
3504                               intel_plane_ggtt_offset(plane_state) +
3505                               dspaddr_offset);
3506
3507         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3508 }
3509
3510 static void i9xx_disable_plane(struct intel_plane *plane,
3511                                const struct intel_crtc_state *crtc_state)
3512 {
3513         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3514         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3515         unsigned long irqflags;
3516         u32 dspcntr;
3517
3518         /*
3519          * DSPCNTR pipe gamma enable on g4x+ and pipe csc
3520          * enable on ilk+ affect the pipe bottom color as
3521          * well, so we must configure them even if the plane
3522          * is disabled.
3523          *
3524          * On pre-g4x there is no way to gamma correct the
3525          * pipe bottom color but we'll keep on doing this
3526          * anyway so that the crtc state readout works correctly.
3527          */
3528         dspcntr = i9xx_plane_ctl_crtc(crtc_state);
3529
3530         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3531
3532         I915_WRITE_FW(DSPCNTR(i9xx_plane), dspcntr);
3533         if (INTEL_GEN(dev_priv) >= 4)
3534                 I915_WRITE_FW(DSPSURF(i9xx_plane), 0);
3535         else
3536                 I915_WRITE_FW(DSPADDR(i9xx_plane), 0);
3537
3538         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3539 }
3540
3541 static bool i9xx_plane_get_hw_state(struct intel_plane *plane,
3542                                     enum pipe *pipe)
3543 {
3544         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3545         enum intel_display_power_domain power_domain;
3546         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3547         intel_wakeref_t wakeref;
3548         bool ret;
3549         u32 val;
3550
3551         /*
3552          * Not 100% correct for planes that can move between pipes,
3553          * but that's only the case for gen2-4 which don't have any
3554          * display power wells.
3555          */
3556         power_domain = POWER_DOMAIN_PIPE(plane->pipe);
3557         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
3558         if (!wakeref)
3559                 return false;
3560
3561         val = I915_READ(DSPCNTR(i9xx_plane));
3562
3563         ret = val & DISPLAY_PLANE_ENABLE;
3564
3565         if (INTEL_GEN(dev_priv) >= 5)
3566                 *pipe = plane->pipe;
3567         else
3568                 *pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
3569                         DISPPLANE_SEL_PIPE_SHIFT;
3570
3571         intel_display_power_put(dev_priv, power_domain, wakeref);
3572
3573         return ret;
3574 }
3575
3576 static u32
3577 intel_fb_stride_alignment(const struct drm_framebuffer *fb, int color_plane)
3578 {
3579         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
3580                 return 64;
3581         else
3582                 return intel_tile_width_bytes(fb, color_plane);
3583 }
3584
3585 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
3586 {
3587         struct drm_device *dev = intel_crtc->base.dev;
3588         struct drm_i915_private *dev_priv = to_i915(dev);
3589
3590         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
3591         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
3592         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
3593 }
3594
3595 /*
3596  * This function detaches (aka. unbinds) unused scalers in hardware
3597  */
3598 static void skl_detach_scalers(const struct intel_crtc_state *crtc_state)
3599 {
3600         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
3601         const struct intel_crtc_scaler_state *scaler_state =
3602                 &crtc_state->scaler_state;
3603         int i;
3604
3605         /* loop through and disable scalers that aren't in use */
3606         for (i = 0; i < intel_crtc->num_scalers; i++) {
3607                 if (!scaler_state->scalers[i].in_use)
3608                         skl_detach_scaler(intel_crtc, i);
3609         }
3610 }
3611
3612 static unsigned int skl_plane_stride_mult(const struct drm_framebuffer *fb,
3613                                           int color_plane, unsigned int rotation)
3614 {
3615         /*
3616          * The stride is either expressed as a multiple of 64 bytes chunks for
3617          * linear buffers or in number of tiles for tiled buffers.
3618          */
3619         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
3620                 return 64;
3621         else if (drm_rotation_90_or_270(rotation))
3622                 return intel_tile_height(fb, color_plane);
3623         else
3624                 return intel_tile_width_bytes(fb, color_plane);
3625 }
3626
3627 u32 skl_plane_stride(const struct intel_plane_state *plane_state,
3628                      int color_plane)
3629 {
3630         const struct drm_framebuffer *fb = plane_state->base.fb;
3631         unsigned int rotation = plane_state->base.rotation;
3632         u32 stride = plane_state->color_plane[color_plane].stride;
3633
3634         if (color_plane >= fb->format->num_planes)
3635                 return 0;
3636
3637         return stride / skl_plane_stride_mult(fb, color_plane, rotation);
3638 }
3639
3640 static u32 skl_plane_ctl_format(u32 pixel_format)
3641 {
3642         switch (pixel_format) {
3643         case DRM_FORMAT_C8:
3644                 return PLANE_CTL_FORMAT_INDEXED;
3645         case DRM_FORMAT_RGB565:
3646                 return PLANE_CTL_FORMAT_RGB_565;
3647         case DRM_FORMAT_XBGR8888:
3648         case DRM_FORMAT_ABGR8888:
3649                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
3650         case DRM_FORMAT_XRGB8888:
3651         case DRM_FORMAT_ARGB8888:
3652                 return PLANE_CTL_FORMAT_XRGB_8888;
3653         case DRM_FORMAT_XRGB2101010:
3654                 return PLANE_CTL_FORMAT_XRGB_2101010;
3655         case DRM_FORMAT_XBGR2101010:
3656                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
3657         case DRM_FORMAT_XBGR16161616F:
3658         case DRM_FORMAT_ABGR16161616F:
3659                 return PLANE_CTL_FORMAT_XRGB_16161616F | PLANE_CTL_ORDER_RGBX;
3660         case DRM_FORMAT_XRGB16161616F:
3661         case DRM_FORMAT_ARGB16161616F:
3662                 return PLANE_CTL_FORMAT_XRGB_16161616F;
3663         case DRM_FORMAT_YUYV:
3664                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
3665         case DRM_FORMAT_YVYU:
3666                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
3667         case DRM_FORMAT_UYVY:
3668                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
3669         case DRM_FORMAT_VYUY:
3670                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
3671         case DRM_FORMAT_NV12:
3672                 return PLANE_CTL_FORMAT_NV12;
3673         case DRM_FORMAT_P010:
3674                 return PLANE_CTL_FORMAT_P010;
3675         case DRM_FORMAT_P012:
3676                 return PLANE_CTL_FORMAT_P012;
3677         case DRM_FORMAT_P016:
3678                 return PLANE_CTL_FORMAT_P016;
3679         case DRM_FORMAT_Y210:
3680                 return PLANE_CTL_FORMAT_Y210;
3681         case DRM_FORMAT_Y212:
3682                 return PLANE_CTL_FORMAT_Y212;
3683         case DRM_FORMAT_Y216:
3684                 return PLANE_CTL_FORMAT_Y216;
3685         case DRM_FORMAT_XVYU2101010:
3686                 return PLANE_CTL_FORMAT_Y410;
3687         case DRM_FORMAT_XVYU12_16161616:
3688                 return PLANE_CTL_FORMAT_Y412;
3689         case DRM_FORMAT_XVYU16161616:
3690                 return PLANE_CTL_FORMAT_Y416;
3691         default:
3692                 MISSING_CASE(pixel_format);
3693         }
3694
3695         return 0;
3696 }
3697
3698 static u32 skl_plane_ctl_alpha(const struct intel_plane_state *plane_state)
3699 {
3700         if (!plane_state->base.fb->format->has_alpha)
3701                 return PLANE_CTL_ALPHA_DISABLE;
3702
3703         switch (plane_state->base.pixel_blend_mode) {
3704         case DRM_MODE_BLEND_PIXEL_NONE:
3705                 return PLANE_CTL_ALPHA_DISABLE;
3706         case DRM_MODE_BLEND_PREMULTI:
3707                 return PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3708         case DRM_MODE_BLEND_COVERAGE:
3709                 return PLANE_CTL_ALPHA_HW_PREMULTIPLY;
3710         default:
3711                 MISSING_CASE(plane_state->base.pixel_blend_mode);
3712                 return PLANE_CTL_ALPHA_DISABLE;
3713         }
3714 }
3715
3716 static u32 glk_plane_color_ctl_alpha(const struct intel_plane_state *plane_state)
3717 {
3718         if (!plane_state->base.fb->format->has_alpha)
3719                 return PLANE_COLOR_ALPHA_DISABLE;
3720
3721         switch (plane_state->base.pixel_blend_mode) {
3722         case DRM_MODE_BLEND_PIXEL_NONE:
3723                 return PLANE_COLOR_ALPHA_DISABLE;
3724         case DRM_MODE_BLEND_PREMULTI:
3725                 return PLANE_COLOR_ALPHA_SW_PREMULTIPLY;
3726         case DRM_MODE_BLEND_COVERAGE:
3727                 return PLANE_COLOR_ALPHA_HW_PREMULTIPLY;
3728         default:
3729                 MISSING_CASE(plane_state->base.pixel_blend_mode);
3730                 return PLANE_COLOR_ALPHA_DISABLE;
3731         }
3732 }
3733
3734 static u32 skl_plane_ctl_tiling(u64 fb_modifier)
3735 {
3736         switch (fb_modifier) {
3737         case DRM_FORMAT_MOD_LINEAR:
3738                 break;
3739         case I915_FORMAT_MOD_X_TILED:
3740                 return PLANE_CTL_TILED_X;
3741         case I915_FORMAT_MOD_Y_TILED:
3742                 return PLANE_CTL_TILED_Y;
3743         case I915_FORMAT_MOD_Y_TILED_CCS:
3744                 return PLANE_CTL_TILED_Y | PLANE_CTL_RENDER_DECOMPRESSION_ENABLE;
3745         case I915_FORMAT_MOD_Yf_TILED:
3746                 return PLANE_CTL_TILED_YF;
3747         case I915_FORMAT_MOD_Yf_TILED_CCS:
3748                 return PLANE_CTL_TILED_YF | PLANE_CTL_RENDER_DECOMPRESSION_ENABLE;
3749         default:
3750                 MISSING_CASE(fb_modifier);
3751         }
3752
3753         return 0;
3754 }
3755
3756 static u32 skl_plane_ctl_rotate(unsigned int rotate)
3757 {
3758         switch (rotate) {
3759         case DRM_MODE_ROTATE_0:
3760                 break;
3761         /*
3762          * DRM_MODE_ROTATE_ is counter clockwise to stay compatible with Xrandr
3763          * while i915 HW rotation is clockwise, thats why this swapping.
3764          */
3765         case DRM_MODE_ROTATE_90:
3766                 return PLANE_CTL_ROTATE_270;
3767         case DRM_MODE_ROTATE_180:
3768                 return PLANE_CTL_ROTATE_180;
3769         case DRM_MODE_ROTATE_270:
3770                 return PLANE_CTL_ROTATE_90;
3771         default:
3772                 MISSING_CASE(rotate);
3773         }
3774
3775         return 0;
3776 }
3777
3778 static u32 cnl_plane_ctl_flip(unsigned int reflect)
3779 {
3780         switch (reflect) {
3781         case 0:
3782                 break;
3783         case DRM_MODE_REFLECT_X:
3784                 return PLANE_CTL_FLIP_HORIZONTAL;
3785         case DRM_MODE_REFLECT_Y:
3786         default:
3787                 MISSING_CASE(reflect);
3788         }
3789
3790         return 0;
3791 }
3792
3793 u32 skl_plane_ctl_crtc(const struct intel_crtc_state *crtc_state)
3794 {
3795         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
3796         u32 plane_ctl = 0;
3797
3798         if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv))
3799                 return plane_ctl;
3800
3801         if (crtc_state->gamma_enable)
3802                 plane_ctl |= PLANE_CTL_PIPE_GAMMA_ENABLE;
3803
3804         if (crtc_state->csc_enable)
3805                 plane_ctl |= PLANE_CTL_PIPE_CSC_ENABLE;
3806
3807         return plane_ctl;
3808 }
3809
3810 u32 skl_plane_ctl(const struct intel_crtc_state *crtc_state,
3811                   const struct intel_plane_state *plane_state)
3812 {
3813         struct drm_i915_private *dev_priv =
3814                 to_i915(plane_state->base.plane->dev);
3815         const struct drm_framebuffer *fb = plane_state->base.fb;
3816         unsigned int rotation = plane_state->base.rotation;
3817         const struct drm_intel_sprite_colorkey *key = &plane_state->ckey;
3818         u32 plane_ctl;
3819
3820         plane_ctl = PLANE_CTL_ENABLE;
3821
3822         if (INTEL_GEN(dev_priv) < 10 && !IS_GEMINILAKE(dev_priv)) {
3823                 plane_ctl |= skl_plane_ctl_alpha(plane_state);
3824                 plane_ctl |= PLANE_CTL_PLANE_GAMMA_DISABLE;
3825
3826                 if (plane_state->base.color_encoding == DRM_COLOR_YCBCR_BT709)
3827                         plane_ctl |= PLANE_CTL_YUV_TO_RGB_CSC_FORMAT_BT709;
3828
3829                 if (plane_state->base.color_range == DRM_COLOR_YCBCR_FULL_RANGE)
3830                         plane_ctl |= PLANE_CTL_YUV_RANGE_CORRECTION_DISABLE;
3831         }
3832
3833         plane_ctl |= skl_plane_ctl_format(fb->format->format);
3834         plane_ctl |= skl_plane_ctl_tiling(fb->modifier);
3835         plane_ctl |= skl_plane_ctl_rotate(rotation & DRM_MODE_ROTATE_MASK);
3836
3837         if (INTEL_GEN(dev_priv) >= 10)
3838                 plane_ctl |= cnl_plane_ctl_flip(rotation &
3839                                                 DRM_MODE_REFLECT_MASK);
3840
3841         if (key->flags & I915_SET_COLORKEY_DESTINATION)
3842                 plane_ctl |= PLANE_CTL_KEY_ENABLE_DESTINATION;
3843         else if (key->flags & I915_SET_COLORKEY_SOURCE)
3844                 plane_ctl |= PLANE_CTL_KEY_ENABLE_SOURCE;
3845
3846         return plane_ctl;
3847 }
3848
3849 u32 glk_plane_color_ctl_crtc(const struct intel_crtc_state *crtc_state)
3850 {
3851         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
3852         u32 plane_color_ctl = 0;
3853
3854         if (INTEL_GEN(dev_priv) >= 11)
3855                 return plane_color_ctl;
3856
3857         if (crtc_state->gamma_enable)
3858                 plane_color_ctl |= PLANE_COLOR_PIPE_GAMMA_ENABLE;
3859
3860         if (crtc_state->csc_enable)
3861                 plane_color_ctl |= PLANE_COLOR_PIPE_CSC_ENABLE;
3862
3863         return plane_color_ctl;
3864 }
3865
3866 u32 glk_plane_color_ctl(const struct intel_crtc_state *crtc_state,
3867                         const struct intel_plane_state *plane_state)
3868 {
3869         struct drm_i915_private *dev_priv =
3870                 to_i915(plane_state->base.plane->dev);
3871         const struct drm_framebuffer *fb = plane_state->base.fb;
3872         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
3873         u32 plane_color_ctl = 0;
3874
3875         plane_color_ctl |= PLANE_COLOR_PLANE_GAMMA_DISABLE;
3876         plane_color_ctl |= glk_plane_color_ctl_alpha(plane_state);
3877
3878         if (fb->format->is_yuv && !icl_is_hdr_plane(dev_priv, plane->id)) {
3879                 if (plane_state->base.color_encoding == DRM_COLOR_YCBCR_BT709)
3880                         plane_color_ctl |= PLANE_COLOR_CSC_MODE_YUV709_TO_RGB709;
3881                 else
3882                         plane_color_ctl |= PLANE_COLOR_CSC_MODE_YUV601_TO_RGB709;
3883
3884                 if (plane_state->base.color_range == DRM_COLOR_YCBCR_FULL_RANGE)
3885                         plane_color_ctl |= PLANE_COLOR_YUV_RANGE_CORRECTION_DISABLE;
3886         } else if (fb->format->is_yuv) {
3887                 plane_color_ctl |= PLANE_COLOR_INPUT_CSC_ENABLE;
3888         }
3889
3890         return plane_color_ctl;
3891 }
3892
3893 static int
3894 __intel_display_resume(struct drm_device *dev,
3895                        struct drm_atomic_state *state,
3896                        struct drm_modeset_acquire_ctx *ctx)
3897 {
3898         struct drm_crtc_state *crtc_state;
3899         struct drm_crtc *crtc;
3900         int i, ret;
3901
3902         intel_modeset_setup_hw_state(dev, ctx);
3903         i915_redisable_vga(to_i915(dev));
3904
3905         if (!state)
3906                 return 0;
3907
3908         /*
3909          * We've duplicated the state, pointers to the old state are invalid.
3910          *
3911          * Don't attempt to use the old state until we commit the duplicated state.
3912          */
3913         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
3914                 /*
3915                  * Force recalculation even if we restore
3916                  * current state. With fast modeset this may not result
3917                  * in a modeset when the state is compatible.
3918                  */
3919                 crtc_state->mode_changed = true;
3920         }
3921
3922         /* ignore any reset values/BIOS leftovers in the WM registers */
3923         if (!HAS_GMCH(to_i915(dev)))
3924                 to_intel_atomic_state(state)->skip_intermediate_wm = true;
3925
3926         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
3927
3928         WARN_ON(ret == -EDEADLK);
3929         return ret;
3930 }
3931
3932 static bool gpu_reset_clobbers_display(struct drm_i915_private *dev_priv)
3933 {
3934         return (INTEL_INFO(dev_priv)->gpu_reset_clobbers_display &&
3935                 intel_has_gpu_reset(dev_priv));
3936 }
3937
3938 void intel_prepare_reset(struct drm_i915_private *dev_priv)
3939 {
3940         struct drm_device *dev = &dev_priv->drm;
3941         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3942         struct drm_atomic_state *state;
3943         int ret;
3944
3945         /* reset doesn't touch the display */
3946         if (!i915_modparams.force_reset_modeset_test &&
3947             !gpu_reset_clobbers_display(dev_priv))
3948                 return;
3949
3950         /* We have a modeset vs reset deadlock, defensively unbreak it. */
3951         set_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
3952         wake_up_all(&dev_priv->gpu_error.wait_queue);
3953
3954         if (atomic_read(&dev_priv->gpu_error.pending_fb_pin)) {
3955                 DRM_DEBUG_KMS("Modeset potentially stuck, unbreaking through wedging\n");
3956                 i915_gem_set_wedged(dev_priv);
3957         }
3958
3959         /*
3960          * Need mode_config.mutex so that we don't
3961          * trample ongoing ->detect() and whatnot.
3962          */
3963         mutex_lock(&dev->mode_config.mutex);
3964         drm_modeset_acquire_init(ctx, 0);
3965         while (1) {
3966                 ret = drm_modeset_lock_all_ctx(dev, ctx);
3967                 if (ret != -EDEADLK)
3968                         break;
3969
3970                 drm_modeset_backoff(ctx);
3971         }
3972         /*
3973          * Disabling the crtcs gracefully seems nicer. Also the
3974          * g33 docs say we should at least disable all the planes.
3975          */
3976         state = drm_atomic_helper_duplicate_state(dev, ctx);
3977         if (IS_ERR(state)) {
3978                 ret = PTR_ERR(state);
3979                 DRM_ERROR("Duplicating state failed with %i\n", ret);
3980                 return;
3981         }
3982
3983         ret = drm_atomic_helper_disable_all(dev, ctx);
3984         if (ret) {
3985                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
3986                 drm_atomic_state_put(state);
3987                 return;
3988         }
3989
3990         dev_priv->modeset_restore_state = state;
3991         state->acquire_ctx = ctx;
3992 }
3993
3994 void intel_finish_reset(struct drm_i915_private *dev_priv)
3995 {
3996         struct drm_device *dev = &dev_priv->drm;
3997         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3998         struct drm_atomic_state *state;
3999         int ret;
4000
4001         /* reset doesn't touch the display */
4002         if (!test_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags))
4003                 return;
4004
4005         state = fetch_and_zero(&dev_priv->modeset_restore_state);
4006         if (!state)
4007                 goto unlock;
4008
4009         /* reset doesn't touch the display */
4010         if (!gpu_reset_clobbers_display(dev_priv)) {
4011                 /* for testing only restore the display */
4012                 ret = __intel_display_resume(dev, state, ctx);
4013                 if (ret)
4014                         DRM_ERROR("Restoring old state failed with %i\n", ret);
4015         } else {
4016                 /*
4017                  * The display has been reset as well,
4018                  * so need a full re-initialization.
4019                  */
4020                 intel_pps_unlock_regs_wa(dev_priv);
4021                 intel_modeset_init_hw(dev);
4022                 intel_init_clock_gating(dev_priv);
4023
4024                 spin_lock_irq(&dev_priv->irq_lock);
4025                 if (dev_priv->display.hpd_irq_setup)
4026                         dev_priv->display.hpd_irq_setup(dev_priv);
4027                 spin_unlock_irq(&dev_priv->irq_lock);
4028
4029                 ret = __intel_display_resume(dev, state, ctx);
4030                 if (ret)
4031                         DRM_ERROR("Restoring old state failed with %i\n", ret);
4032
4033                 intel_hpd_init(dev_priv);
4034         }
4035
4036         drm_atomic_state_put(state);
4037 unlock:
4038         drm_modeset_drop_locks(ctx);
4039         drm_modeset_acquire_fini(ctx);
4040         mutex_unlock(&dev->mode_config.mutex);
4041
4042         clear_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
4043 }
4044
4045 static void icl_set_pipe_chicken(struct intel_crtc *crtc)
4046 {
4047         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4048         enum pipe pipe = crtc->pipe;
4049         u32 tmp;
4050
4051         tmp = I915_READ(PIPE_CHICKEN(pipe));
4052
4053         /*
4054          * Display WA #1153: icl
4055          * enable hardware to bypass the alpha math
4056          * and rounding for per-pixel values 00 and 0xff
4057          */
4058         tmp |= PER_PIXEL_ALPHA_BYPASS_EN;
4059         /*
4060          * Display WA # 1605353570: icl
4061          * Set the pixel rounding bit to 1 for allowing
4062          * passthrough of Frame buffer pixels unmodified
4063          * across pipe
4064          */
4065         tmp |= PIXEL_ROUNDING_TRUNC_FB_PASSTHRU;
4066         I915_WRITE(PIPE_CHICKEN(pipe), tmp);
4067 }
4068
4069 static void intel_update_pipe_config(const struct intel_crtc_state *old_crtc_state,
4070                                      const struct intel_crtc_state *new_crtc_state)
4071 {
4072         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
4073         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4074
4075         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
4076         crtc->base.mode = new_crtc_state->base.mode;
4077
4078         /*
4079          * Update pipe size and adjust fitter if needed: the reason for this is
4080          * that in compute_mode_changes we check the native mode (not the pfit
4081          * mode) to see if we can flip rather than do a full mode set. In the
4082          * fastboot case, we'll flip, but if we don't update the pipesrc and
4083          * pfit state, we'll end up with a big fb scanned out into the wrong
4084          * sized surface.
4085          */
4086
4087         I915_WRITE(PIPESRC(crtc->pipe),
4088                    ((new_crtc_state->pipe_src_w - 1) << 16) |
4089                    (new_crtc_state->pipe_src_h - 1));
4090
4091         /* on skylake this is done by detaching scalers */
4092         if (INTEL_GEN(dev_priv) >= 9) {
4093                 skl_detach_scalers(new_crtc_state);
4094
4095                 if (new_crtc_state->pch_pfit.enabled)
4096                         skylake_pfit_enable(new_crtc_state);
4097         } else if (HAS_PCH_SPLIT(dev_priv)) {
4098                 if (new_crtc_state->pch_pfit.enabled)
4099                         ironlake_pfit_enable(new_crtc_state);
4100                 else if (old_crtc_state->pch_pfit.enabled)
4101                         ironlake_pfit_disable(old_crtc_state);
4102         }
4103
4104         if (INTEL_GEN(dev_priv) >= 11)
4105                 icl_set_pipe_chicken(crtc);
4106 }
4107
4108 static void intel_fdi_normal_train(struct intel_crtc *crtc)
4109 {
4110         struct drm_device *dev = crtc->base.dev;
4111         struct drm_i915_private *dev_priv = to_i915(dev);
4112         int pipe = crtc->pipe;
4113         i915_reg_t reg;
4114         u32 temp;
4115
4116         /* enable normal train */
4117         reg = FDI_TX_CTL(pipe);
4118         temp = I915_READ(reg);
4119         if (IS_IVYBRIDGE(dev_priv)) {
4120                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
4121                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
4122         } else {
4123                 temp &= ~FDI_LINK_TRAIN_NONE;
4124                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
4125         }
4126         I915_WRITE(reg, temp);
4127
4128         reg = FDI_RX_CTL(pipe);
4129         temp = I915_READ(reg);
4130         if (HAS_PCH_CPT(dev_priv)) {
4131                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4132                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
4133         } else {
4134                 temp &= ~FDI_LINK_TRAIN_NONE;
4135                 temp |= FDI_LINK_TRAIN_NONE;
4136         }
4137         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
4138
4139         /* wait one idle pattern time */
4140         POSTING_READ(reg);
4141         udelay(1000);
4142
4143         /* IVB wants error correction enabled */
4144         if (IS_IVYBRIDGE(dev_priv))
4145                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
4146                            FDI_FE_ERRC_ENABLE);
4147 }
4148
4149 /* The FDI link training functions for ILK/Ibexpeak. */
4150 static void ironlake_fdi_link_train(struct intel_crtc *crtc,
4151                                     const struct intel_crtc_state *crtc_state)
4152 {
4153         struct drm_device *dev = crtc->base.dev;
4154         struct drm_i915_private *dev_priv = to_i915(dev);
4155         int pipe = crtc->pipe;
4156         i915_reg_t reg;
4157         u32 temp, tries;
4158
4159         /* FDI needs bits from pipe first */
4160         assert_pipe_enabled(dev_priv, pipe);
4161
4162         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4163            for train result */
4164         reg = FDI_RX_IMR(pipe);
4165         temp = I915_READ(reg);
4166         temp &= ~FDI_RX_SYMBOL_LOCK;
4167         temp &= ~FDI_RX_BIT_LOCK;
4168         I915_WRITE(reg, temp);
4169         I915_READ(reg);
4170         udelay(150);
4171
4172         /* enable CPU FDI TX and PCH FDI RX */
4173         reg = FDI_TX_CTL(pipe);
4174         temp = I915_READ(reg);
4175         temp &= ~FDI_DP_PORT_WIDTH_MASK;
4176         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4177         temp &= ~FDI_LINK_TRAIN_NONE;
4178         temp |= FDI_LINK_TRAIN_PATTERN_1;
4179         I915_WRITE(reg, temp | FDI_TX_ENABLE);
4180
4181         reg = FDI_RX_CTL(pipe);
4182         temp = I915_READ(reg);
4183         temp &= ~FDI_LINK_TRAIN_NONE;
4184         temp |= FDI_LINK_TRAIN_PATTERN_1;
4185         I915_WRITE(reg, temp | FDI_RX_ENABLE);
4186
4187         POSTING_READ(reg);
4188         udelay(150);
4189
4190         /* Ironlake workaround, enable clock pointer after FDI enable*/
4191         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
4192         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
4193                    FDI_RX_PHASE_SYNC_POINTER_EN);
4194
4195         reg = FDI_RX_IIR(pipe);
4196         for (tries = 0; tries < 5; tries++) {
4197                 temp = I915_READ(reg);
4198                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4199
4200                 if ((temp & FDI_RX_BIT_LOCK)) {
4201                         DRM_DEBUG_KMS("FDI train 1 done.\n");
4202                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4203                         break;
4204                 }
4205         }
4206         if (tries == 5)
4207                 DRM_ERROR("FDI train 1 fail!\n");
4208
4209         /* Train 2 */
4210         reg = FDI_TX_CTL(pipe);
4211         temp = I915_READ(reg);
4212         temp &= ~FDI_LINK_TRAIN_NONE;
4213         temp |= FDI_LINK_TRAIN_PATTERN_2;
4214         I915_WRITE(reg, temp);
4215
4216         reg = FDI_RX_CTL(pipe);
4217         temp = I915_READ(reg);
4218         temp &= ~FDI_LINK_TRAIN_NONE;
4219         temp |= FDI_LINK_TRAIN_PATTERN_2;
4220         I915_WRITE(reg, temp);
4221
4222         POSTING_READ(reg);
4223         udelay(150);
4224
4225         reg = FDI_RX_IIR(pipe);
4226         for (tries = 0; tries < 5; tries++) {
4227                 temp = I915_READ(reg);
4228                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4229
4230                 if (temp & FDI_RX_SYMBOL_LOCK) {
4231                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4232                         DRM_DEBUG_KMS("FDI train 2 done.\n");
4233                         break;
4234                 }
4235         }
4236         if (tries == 5)
4237                 DRM_ERROR("FDI train 2 fail!\n");
4238
4239         DRM_DEBUG_KMS("FDI train done\n");
4240
4241 }
4242
4243 static const int snb_b_fdi_train_param[] = {
4244         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
4245         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
4246         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
4247         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
4248 };
4249
4250 /* The FDI link training functions for SNB/Cougarpoint. */
4251 static void gen6_fdi_link_train(struct intel_crtc *crtc,
4252                                 const struct intel_crtc_state *crtc_state)
4253 {
4254         struct drm_device *dev = crtc->base.dev;
4255         struct drm_i915_private *dev_priv = to_i915(dev);
4256         int pipe = crtc->pipe;
4257         i915_reg_t reg;
4258         u32 temp, i, retry;
4259
4260         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4261            for train result */
4262         reg = FDI_RX_IMR(pipe);
4263         temp = I915_READ(reg);
4264         temp &= ~FDI_RX_SYMBOL_LOCK;
4265         temp &= ~FDI_RX_BIT_LOCK;
4266         I915_WRITE(reg, temp);
4267
4268         POSTING_READ(reg);
4269         udelay(150);
4270
4271         /* enable CPU FDI TX and PCH FDI RX */
4272         reg = FDI_TX_CTL(pipe);
4273         temp = I915_READ(reg);
4274         temp &= ~FDI_DP_PORT_WIDTH_MASK;
4275         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4276         temp &= ~FDI_LINK_TRAIN_NONE;
4277         temp |= FDI_LINK_TRAIN_PATTERN_1;
4278         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4279         /* SNB-B */
4280         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
4281         I915_WRITE(reg, temp | FDI_TX_ENABLE);
4282
4283         I915_WRITE(FDI_RX_MISC(pipe),
4284                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4285
4286         reg = FDI_RX_CTL(pipe);
4287         temp = I915_READ(reg);
4288         if (HAS_PCH_CPT(dev_priv)) {
4289                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4290                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4291         } else {
4292                 temp &= ~FDI_LINK_TRAIN_NONE;
4293                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4294         }
4295         I915_WRITE(reg, temp | FDI_RX_ENABLE);
4296
4297         POSTING_READ(reg);
4298         udelay(150);
4299
4300         for (i = 0; i < 4; i++) {
4301                 reg = FDI_TX_CTL(pipe);
4302                 temp = I915_READ(reg);
4303                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4304                 temp |= snb_b_fdi_train_param[i];
4305                 I915_WRITE(reg, temp);
4306
4307                 POSTING_READ(reg);
4308                 udelay(500);
4309
4310                 for (retry = 0; retry < 5; retry++) {
4311                         reg = FDI_RX_IIR(pipe);
4312                         temp = I915_READ(reg);
4313                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4314                         if (temp & FDI_RX_BIT_LOCK) {
4315                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4316                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
4317                                 break;
4318                         }
4319                         udelay(50);
4320                 }
4321                 if (retry < 5)
4322                         break;
4323         }
4324         if (i == 4)
4325                 DRM_ERROR("FDI train 1 fail!\n");
4326
4327         /* Train 2 */
4328         reg = FDI_TX_CTL(pipe);
4329         temp = I915_READ(reg);
4330         temp &= ~FDI_LINK_TRAIN_NONE;
4331         temp |= FDI_LINK_TRAIN_PATTERN_2;
4332         if (IS_GEN(dev_priv, 6)) {
4333                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4334                 /* SNB-B */
4335                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
4336         }
4337         I915_WRITE(reg, temp);
4338
4339         reg = FDI_RX_CTL(pipe);
4340         temp = I915_READ(reg);
4341         if (HAS_PCH_CPT(dev_priv)) {
4342                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4343                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4344         } else {
4345                 temp &= ~FDI_LINK_TRAIN_NONE;
4346                 temp |= FDI_LINK_TRAIN_PATTERN_2;
4347         }
4348         I915_WRITE(reg, temp);
4349
4350         POSTING_READ(reg);
4351         udelay(150);
4352
4353         for (i = 0; i < 4; i++) {
4354                 reg = FDI_TX_CTL(pipe);
4355                 temp = I915_READ(reg);
4356                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4357                 temp |= snb_b_fdi_train_param[i];
4358                 I915_WRITE(reg, temp);
4359
4360                 POSTING_READ(reg);
4361                 udelay(500);
4362
4363                 for (retry = 0; retry < 5; retry++) {
4364                         reg = FDI_RX_IIR(pipe);
4365                         temp = I915_READ(reg);
4366                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4367                         if (temp & FDI_RX_SYMBOL_LOCK) {
4368                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4369                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
4370                                 break;
4371                         }
4372                         udelay(50);
4373                 }
4374                 if (retry < 5)
4375                         break;
4376         }
4377         if (i == 4)
4378                 DRM_ERROR("FDI train 2 fail!\n");
4379
4380         DRM_DEBUG_KMS("FDI train done.\n");
4381 }
4382
4383 /* Manual link training for Ivy Bridge A0 parts */
4384 static void ivb_manual_fdi_link_train(struct intel_crtc *crtc,
4385                                       const struct intel_crtc_state *crtc_state)
4386 {
4387         struct drm_device *dev = crtc->base.dev;
4388         struct drm_i915_private *dev_priv = to_i915(dev);
4389         int pipe = crtc->pipe;
4390         i915_reg_t reg;
4391         u32 temp, i, j;
4392
4393         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4394            for train result */
4395         reg = FDI_RX_IMR(pipe);
4396         temp = I915_READ(reg);
4397         temp &= ~FDI_RX_SYMBOL_LOCK;
4398         temp &= ~FDI_RX_BIT_LOCK;
4399         I915_WRITE(reg, temp);
4400
4401         POSTING_READ(reg);
4402         udelay(150);
4403
4404         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
4405                       I915_READ(FDI_RX_IIR(pipe)));
4406
4407         /* Try each vswing and preemphasis setting twice before moving on */
4408         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
4409                 /* disable first in case we need to retry */
4410                 reg = FDI_TX_CTL(pipe);
4411                 temp = I915_READ(reg);
4412                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
4413                 temp &= ~FDI_TX_ENABLE;
4414                 I915_WRITE(reg, temp);
4415
4416                 reg = FDI_RX_CTL(pipe);
4417                 temp = I915_READ(reg);
4418                 temp &= ~FDI_LINK_TRAIN_AUTO;
4419                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4420                 temp &= ~FDI_RX_ENABLE;
4421                 I915_WRITE(reg, temp);
4422
4423                 /* enable CPU FDI TX and PCH FDI RX */
4424                 reg = FDI_TX_CTL(pipe);
4425                 temp = I915_READ(reg);
4426                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
4427                 temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4428                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
4429                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4430                 temp |= snb_b_fdi_train_param[j/2];
4431                 temp |= FDI_COMPOSITE_SYNC;
4432                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
4433
4434                 I915_WRITE(FDI_RX_MISC(pipe),
4435                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4436
4437                 reg = FDI_RX_CTL(pipe);
4438                 temp = I915_READ(reg);
4439                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4440                 temp |= FDI_COMPOSITE_SYNC;
4441                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
4442
4443                 POSTING_READ(reg);
4444                 udelay(1); /* should be 0.5us */
4445
4446                 for (i = 0; i < 4; i++) {
4447                         reg = FDI_RX_IIR(pipe);
4448                         temp = I915_READ(reg);
4449                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4450
4451                         if (temp & FDI_RX_BIT_LOCK ||
4452                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
4453                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4454                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
4455                                               i);
4456                                 break;
4457                         }
4458                         udelay(1); /* should be 0.5us */
4459                 }
4460                 if (i == 4) {
4461                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
4462                         continue;
4463                 }
4464
4465                 /* Train 2 */
4466                 reg = FDI_TX_CTL(pipe);
4467                 temp = I915_READ(reg);
4468                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
4469                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
4470                 I915_WRITE(reg, temp);
4471
4472                 reg = FDI_RX_CTL(pipe);
4473                 temp = I915_READ(reg);
4474                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4475                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4476                 I915_WRITE(reg, temp);
4477
4478                 POSTING_READ(reg);
4479                 udelay(2); /* should be 1.5us */
4480
4481                 for (i = 0; i < 4; i++) {
4482                         reg = FDI_RX_IIR(pipe);
4483                         temp = I915_READ(reg);
4484                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4485
4486                         if (temp & FDI_RX_SYMBOL_LOCK ||
4487                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
4488                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4489                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
4490                                               i);
4491                                 goto train_done;
4492                         }
4493                         udelay(2); /* should be 1.5us */
4494                 }
4495                 if (i == 4)
4496                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
4497         }
4498
4499 train_done:
4500         DRM_DEBUG_KMS("FDI train done.\n");
4501 }
4502
4503 static void ironlake_fdi_pll_enable(const struct intel_crtc_state *crtc_state)
4504 {
4505         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
4506         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
4507         int pipe = intel_crtc->pipe;
4508         i915_reg_t reg;
4509         u32 temp;
4510
4511         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
4512         reg = FDI_RX_CTL(pipe);
4513         temp = I915_READ(reg);
4514         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
4515         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4516         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4517         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
4518
4519         POSTING_READ(reg);
4520         udelay(200);
4521
4522         /* Switch from Rawclk to PCDclk */
4523         temp = I915_READ(reg);
4524         I915_WRITE(reg, temp | FDI_PCDCLK);
4525
4526         POSTING_READ(reg);
4527         udelay(200);
4528
4529         /* Enable CPU FDI TX PLL, always on for Ironlake */
4530         reg = FDI_TX_CTL(pipe);
4531         temp = I915_READ(reg);
4532         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
4533                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
4534
4535                 POSTING_READ(reg);
4536                 udelay(100);
4537         }
4538 }
4539
4540 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
4541 {
4542         struct drm_device *dev = intel_crtc->base.dev;
4543         struct drm_i915_private *dev_priv = to_i915(dev);
4544         int pipe = intel_crtc->pipe;
4545         i915_reg_t reg;
4546         u32 temp;
4547
4548         /* Switch from PCDclk to Rawclk */
4549         reg = FDI_RX_CTL(pipe);
4550         temp = I915_READ(reg);
4551         I915_WRITE(reg, temp & ~FDI_PCDCLK);
4552
4553         /* Disable CPU FDI TX PLL */
4554         reg = FDI_TX_CTL(pipe);
4555         temp = I915_READ(reg);
4556         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
4557
4558         POSTING_READ(reg);
4559         udelay(100);
4560
4561         reg = FDI_RX_CTL(pipe);
4562         temp = I915_READ(reg);
4563         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
4564
4565         /* Wait for the clocks to turn off. */
4566         POSTING_READ(reg);
4567         udelay(100);
4568 }
4569
4570 static void ironlake_fdi_disable(struct drm_crtc *crtc)
4571 {
4572         struct drm_device *dev = crtc->dev;
4573         struct drm_i915_private *dev_priv = to_i915(dev);
4574         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4575         int pipe = intel_crtc->pipe;
4576         i915_reg_t reg;
4577         u32 temp;
4578
4579         /* disable CPU FDI tx and PCH FDI rx */
4580         reg = FDI_TX_CTL(pipe);
4581         temp = I915_READ(reg);
4582         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
4583         POSTING_READ(reg);
4584
4585         reg = FDI_RX_CTL(pipe);
4586         temp = I915_READ(reg);
4587         temp &= ~(0x7 << 16);
4588         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4589         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
4590
4591         POSTING_READ(reg);
4592         udelay(100);
4593
4594         /* Ironlake workaround, disable clock pointer after downing FDI */
4595         if (HAS_PCH_IBX(dev_priv))
4596                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
4597
4598         /* still set train pattern 1 */
4599         reg = FDI_TX_CTL(pipe);
4600         temp = I915_READ(reg);
4601         temp &= ~FDI_LINK_TRAIN_NONE;
4602         temp |= FDI_LINK_TRAIN_PATTERN_1;
4603         I915_WRITE(reg, temp);
4604
4605         reg = FDI_RX_CTL(pipe);
4606         temp = I915_READ(reg);
4607         if (HAS_PCH_CPT(dev_priv)) {
4608                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4609                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4610         } else {
4611                 temp &= ~FDI_LINK_TRAIN_NONE;
4612                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4613         }
4614         /* BPC in FDI rx is consistent with that in PIPECONF */
4615         temp &= ~(0x07 << 16);
4616         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4617         I915_WRITE(reg, temp);
4618
4619         POSTING_READ(reg);
4620         udelay(100);
4621 }
4622
4623 bool intel_has_pending_fb_unpin(struct drm_i915_private *dev_priv)
4624 {
4625         struct drm_crtc *crtc;
4626         bool cleanup_done;
4627
4628         drm_for_each_crtc(crtc, &dev_priv->drm) {
4629                 struct drm_crtc_commit *commit;
4630                 spin_lock(&crtc->commit_lock);
4631                 commit = list_first_entry_or_null(&crtc->commit_list,
4632                                                   struct drm_crtc_commit, commit_entry);
4633                 cleanup_done = commit ?
4634                         try_wait_for_completion(&commit->cleanup_done) : true;
4635                 spin_unlock(&crtc->commit_lock);
4636
4637                 if (cleanup_done)
4638                         continue;
4639
4640                 drm_crtc_wait_one_vblank(crtc);
4641
4642                 return true;
4643         }
4644
4645         return false;
4646 }
4647
4648 void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
4649 {
4650         u32 temp;
4651
4652         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
4653
4654         mutex_lock(&dev_priv->sb_lock);
4655
4656         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4657         temp |= SBI_SSCCTL_DISABLE;
4658         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4659
4660         mutex_unlock(&dev_priv->sb_lock);
4661 }
4662
4663 /* Program iCLKIP clock to the desired frequency */
4664 static void lpt_program_iclkip(const struct intel_crtc_state *crtc_state)
4665 {
4666         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4667         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4668         int clock = crtc_state->base.adjusted_mode.crtc_clock;
4669         u32 divsel, phaseinc, auxdiv, phasedir = 0;
4670         u32 temp;
4671
4672         lpt_disable_iclkip(dev_priv);
4673
4674         /* The iCLK virtual clock root frequency is in MHz,
4675          * but the adjusted_mode->crtc_clock in in KHz. To get the
4676          * divisors, it is necessary to divide one by another, so we
4677          * convert the virtual clock precision to KHz here for higher
4678          * precision.
4679          */
4680         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
4681                 u32 iclk_virtual_root_freq = 172800 * 1000;
4682                 u32 iclk_pi_range = 64;
4683                 u32 desired_divisor;
4684
4685                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4686                                                     clock << auxdiv);
4687                 divsel = (desired_divisor / iclk_pi_range) - 2;
4688                 phaseinc = desired_divisor % iclk_pi_range;
4689
4690                 /*
4691                  * Near 20MHz is a corner case which is
4692                  * out of range for the 7-bit divisor
4693                  */
4694                 if (divsel <= 0x7f)
4695                         break;
4696         }
4697
4698         /* This should not happen with any sane values */
4699         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
4700                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
4701         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
4702                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
4703
4704         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
4705                         clock,
4706                         auxdiv,
4707                         divsel,
4708                         phasedir,
4709                         phaseinc);
4710
4711         mutex_lock(&dev_priv->sb_lock);
4712
4713         /* Program SSCDIVINTPHASE6 */
4714         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4715         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
4716         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
4717         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
4718         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
4719         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
4720         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
4721         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
4722
4723         /* Program SSCAUXDIV */
4724         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4725         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
4726         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
4727         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
4728
4729         /* Enable modulator and associated divider */
4730         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4731         temp &= ~SBI_SSCCTL_DISABLE;
4732         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4733
4734         mutex_unlock(&dev_priv->sb_lock);
4735
4736         /* Wait for initialization time */
4737         udelay(24);
4738
4739         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
4740 }
4741
4742 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
4743 {
4744         u32 divsel, phaseinc, auxdiv;
4745         u32 iclk_virtual_root_freq = 172800 * 1000;
4746         u32 iclk_pi_range = 64;
4747         u32 desired_divisor;
4748         u32 temp;
4749
4750         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
4751                 return 0;
4752
4753         mutex_lock(&dev_priv->sb_lock);
4754
4755         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4756         if (temp & SBI_SSCCTL_DISABLE) {
4757                 mutex_unlock(&dev_priv->sb_lock);
4758                 return 0;
4759         }
4760
4761         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4762         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
4763                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
4764         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
4765                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
4766
4767         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4768         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
4769                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
4770
4771         mutex_unlock(&dev_priv->sb_lock);
4772
4773         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
4774
4775         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4776                                  desired_divisor << auxdiv);
4777 }
4778
4779 static void ironlake_pch_transcoder_set_timings(const struct intel_crtc_state *crtc_state,
4780                                                 enum pipe pch_transcoder)
4781 {
4782         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4783         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4784         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
4785
4786         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
4787                    I915_READ(HTOTAL(cpu_transcoder)));
4788         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4789                    I915_READ(HBLANK(cpu_transcoder)));
4790         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4791                    I915_READ(HSYNC(cpu_transcoder)));
4792
4793         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4794                    I915_READ(VTOTAL(cpu_transcoder)));
4795         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4796                    I915_READ(VBLANK(cpu_transcoder)));
4797         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4798                    I915_READ(VSYNC(cpu_transcoder)));
4799         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4800                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4801 }
4802
4803 static void cpt_set_fdi_bc_bifurcation(struct drm_i915_private *dev_priv, bool enable)
4804 {
4805         u32 temp;
4806
4807         temp = I915_READ(SOUTH_CHICKEN1);
4808         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4809                 return;
4810
4811         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4812         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4813
4814         temp &= ~FDI_BC_BIFURCATION_SELECT;
4815         if (enable)
4816                 temp |= FDI_BC_BIFURCATION_SELECT;
4817
4818         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4819         I915_WRITE(SOUTH_CHICKEN1, temp);
4820         POSTING_READ(SOUTH_CHICKEN1);
4821 }
4822
4823 static void ivybridge_update_fdi_bc_bifurcation(const struct intel_crtc_state *crtc_state)
4824 {
4825         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4826         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4827
4828         switch (crtc->pipe) {
4829         case PIPE_A:
4830                 break;
4831         case PIPE_B:
4832                 if (crtc_state->fdi_lanes > 2)
4833                         cpt_set_fdi_bc_bifurcation(dev_priv, false);
4834                 else
4835                         cpt_set_fdi_bc_bifurcation(dev_priv, true);
4836
4837                 break;
4838         case PIPE_C:
4839                 cpt_set_fdi_bc_bifurcation(dev_priv, true);
4840
4841                 break;
4842         default:
4843                 BUG();
4844         }
4845 }
4846
4847 /*
4848  * Finds the encoder associated with the given CRTC. This can only be
4849  * used when we know that the CRTC isn't feeding multiple encoders!
4850  */
4851 static struct intel_encoder *
4852 intel_get_crtc_new_encoder(const struct intel_atomic_state *state,
4853                            const struct intel_crtc_state *crtc_state)
4854 {
4855         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4856         const struct drm_connector_state *connector_state;
4857         const struct drm_connector *connector;
4858         struct intel_encoder *encoder = NULL;
4859         int num_encoders = 0;
4860         int i;
4861
4862         for_each_new_connector_in_state(&state->base, connector, connector_state, i) {
4863                 if (connector_state->crtc != &crtc->base)
4864                         continue;
4865
4866                 encoder = to_intel_encoder(connector_state->best_encoder);
4867                 num_encoders++;
4868         }
4869
4870         WARN(num_encoders != 1, "%d encoders for pipe %c\n",
4871              num_encoders, pipe_name(crtc->pipe));
4872
4873         return encoder;
4874 }
4875
4876 /*
4877  * Enable PCH resources required for PCH ports:
4878  *   - PCH PLLs
4879  *   - FDI training & RX/TX
4880  *   - update transcoder timings
4881  *   - DP transcoding bits
4882  *   - transcoder
4883  */
4884 static void ironlake_pch_enable(const struct intel_atomic_state *state,
4885                                 const struct intel_crtc_state *crtc_state)
4886 {
4887         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4888         struct drm_device *dev = crtc->base.dev;
4889         struct drm_i915_private *dev_priv = to_i915(dev);
4890         int pipe = crtc->pipe;
4891         u32 temp;
4892
4893         assert_pch_transcoder_disabled(dev_priv, pipe);
4894
4895         if (IS_IVYBRIDGE(dev_priv))
4896                 ivybridge_update_fdi_bc_bifurcation(crtc_state);
4897
4898         /* Write the TU size bits before fdi link training, so that error
4899          * detection works. */
4900         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4901                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4902
4903         /* For PCH output, training FDI link */
4904         dev_priv->display.fdi_link_train(crtc, crtc_state);
4905
4906         /* We need to program the right clock selection before writing the pixel
4907          * mutliplier into the DPLL. */
4908         if (HAS_PCH_CPT(dev_priv)) {
4909                 u32 sel;
4910
4911                 temp = I915_READ(PCH_DPLL_SEL);
4912                 temp |= TRANS_DPLL_ENABLE(pipe);
4913                 sel = TRANS_DPLLB_SEL(pipe);
4914                 if (crtc_state->shared_dpll ==
4915                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
4916                         temp |= sel;
4917                 else
4918                         temp &= ~sel;
4919                 I915_WRITE(PCH_DPLL_SEL, temp);
4920         }
4921
4922         /* XXX: pch pll's can be enabled any time before we enable the PCH
4923          * transcoder, and we actually should do this to not upset any PCH
4924          * transcoder that already use the clock when we share it.
4925          *
4926          * Note that enable_shared_dpll tries to do the right thing, but
4927          * get_shared_dpll unconditionally resets the pll - we need that to have
4928          * the right LVDS enable sequence. */
4929         intel_enable_shared_dpll(crtc_state);
4930
4931         /* set transcoder timing, panel must allow it */
4932         assert_panel_unlocked(dev_priv, pipe);
4933         ironlake_pch_transcoder_set_timings(crtc_state, pipe);
4934
4935         intel_fdi_normal_train(crtc);
4936
4937         /* For PCH DP, enable TRANS_DP_CTL */
4938         if (HAS_PCH_CPT(dev_priv) &&
4939             intel_crtc_has_dp_encoder(crtc_state)) {
4940                 const struct drm_display_mode *adjusted_mode =
4941                         &crtc_state->base.adjusted_mode;
4942                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4943                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4944                 enum port port;
4945
4946                 temp = I915_READ(reg);
4947                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4948                           TRANS_DP_SYNC_MASK |
4949                           TRANS_DP_BPC_MASK);
4950                 temp |= TRANS_DP_OUTPUT_ENABLE;
4951                 temp |= bpc << 9; /* same format but at 11:9 */
4952
4953                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4954                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4955                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4956                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4957
4958                 port = intel_get_crtc_new_encoder(state, crtc_state)->port;
4959                 WARN_ON(port < PORT_B || port > PORT_D);
4960                 temp |= TRANS_DP_PORT_SEL(port);
4961
4962                 I915_WRITE(reg, temp);
4963         }
4964
4965         ironlake_enable_pch_transcoder(crtc_state);
4966 }
4967
4968 static void lpt_pch_enable(const struct intel_atomic_state *state,
4969                            const struct intel_crtc_state *crtc_state)
4970 {
4971         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4972         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4973         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
4974
4975         assert_pch_transcoder_disabled(dev_priv, PIPE_A);
4976
4977         lpt_program_iclkip(crtc_state);
4978
4979         /* Set transcoder timing. */
4980         ironlake_pch_transcoder_set_timings(crtc_state, PIPE_A);
4981
4982         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4983 }
4984
4985 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4986 {
4987         struct drm_i915_private *dev_priv = to_i915(dev);
4988         i915_reg_t dslreg = PIPEDSL(pipe);
4989         u32 temp;
4990
4991         temp = I915_READ(dslreg);
4992         udelay(500);
4993         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4994                 if (wait_for(I915_READ(dslreg) != temp, 5))
4995                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4996         }
4997 }
4998
4999 /*
5000  * The hardware phase 0.0 refers to the center of the pixel.
5001  * We want to start from the top/left edge which is phase
5002  * -0.5. That matches how the hardware calculates the scaling
5003  * factors (from top-left of the first pixel to bottom-right
5004  * of the last pixel, as opposed to the pixel centers).
5005  *
5006  * For 4:2:0 subsampled chroma planes we obviously have to
5007  * adjust that so that the chroma sample position lands in
5008  * the right spot.
5009  *
5010  * Note that for packed YCbCr 4:2:2 formats there is no way to
5011  * control chroma siting. The hardware simply replicates the
5012  * chroma samples for both of the luma samples, and thus we don't
5013  * actually get the expected MPEG2 chroma siting convention :(
5014  * The same behaviour is observed on pre-SKL platforms as well.
5015  *
5016  * Theory behind the formula (note that we ignore sub-pixel
5017  * source coordinates):
5018  * s = source sample position
5019  * d = destination sample position
5020  *
5021  * Downscaling 4:1:
5022  * -0.5
5023  * | 0.0
5024  * | |     1.5 (initial phase)
5025  * | |     |
5026  * v v     v
5027  * | s | s | s | s |
5028  * |       d       |
5029  *
5030  * Upscaling 1:4:
5031  * -0.5
5032  * | -0.375 (initial phase)
5033  * | |     0.0
5034  * | |     |
5035  * v v     v
5036  * |       s       |
5037  * | d | d | d | d |
5038  */
5039 u16 skl_scaler_calc_phase(int sub, int scale, bool chroma_cosited)
5040 {
5041         int phase = -0x8000;
5042         u16 trip = 0;
5043
5044         if (chroma_cosited)
5045                 phase += (sub - 1) * 0x8000 / sub;
5046
5047         phase += scale / (2 * sub);
5048
5049         /*
5050          * Hardware initial phase limited to [-0.5:1.5].
5051          * Since the max hardware scale factor is 3.0, we
5052          * should never actually excdeed 1.0 here.
5053          */
5054         WARN_ON(phase < -0x8000 || phase > 0x18000);
5055
5056         if (phase < 0)
5057                 phase = 0x10000 + phase;
5058         else
5059                 trip = PS_PHASE_TRIP;
5060
5061         return ((phase >> 2) & PS_PHASE_MASK) | trip;
5062 }
5063
5064 #define SKL_MIN_SRC_W 8
5065 #define SKL_MAX_SRC_W 4096
5066 #define SKL_MIN_SRC_H 8
5067 #define SKL_MAX_SRC_H 4096
5068 #define SKL_MIN_DST_W 8
5069 #define SKL_MAX_DST_W 4096
5070 #define SKL_MIN_DST_H 8
5071 #define SKL_MAX_DST_H 4096
5072 #define ICL_MAX_SRC_W 5120
5073 #define ICL_MAX_SRC_H 4096
5074 #define ICL_MAX_DST_W 5120
5075 #define ICL_MAX_DST_H 4096
5076 #define SKL_MIN_YUV_420_SRC_W 16
5077 #define SKL_MIN_YUV_420_SRC_H 16
5078
5079 static int
5080 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
5081                   unsigned int scaler_user, int *scaler_id,
5082                   int src_w, int src_h, int dst_w, int dst_h,
5083                   const struct drm_format_info *format, bool need_scaler)
5084 {
5085         struct intel_crtc_scaler_state *scaler_state =
5086                 &crtc_state->scaler_state;
5087         struct intel_crtc *intel_crtc =
5088                 to_intel_crtc(crtc_state->base.crtc);
5089         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
5090         const struct drm_display_mode *adjusted_mode =
5091                 &crtc_state->base.adjusted_mode;
5092
5093         /*
5094          * Src coordinates are already rotated by 270 degrees for
5095          * the 90/270 degree plane rotation cases (to match the
5096          * GTT mapping), hence no need to account for rotation here.
5097          */
5098         if (src_w != dst_w || src_h != dst_h)
5099                 need_scaler = true;
5100
5101         /*
5102          * Scaling/fitting not supported in IF-ID mode in GEN9+
5103          * TODO: Interlace fetch mode doesn't support YUV420 planar formats.
5104          * Once NV12 is enabled, handle it here while allocating scaler
5105          * for NV12.
5106          */
5107         if (INTEL_GEN(dev_priv) >= 9 && crtc_state->base.enable &&
5108             need_scaler && adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
5109                 DRM_DEBUG_KMS("Pipe/Plane scaling not supported with IF-ID mode\n");
5110                 return -EINVAL;
5111         }
5112
5113         /*
5114          * if plane is being disabled or scaler is no more required or force detach
5115          *  - free scaler binded to this plane/crtc
5116          *  - in order to do this, update crtc->scaler_usage
5117          *
5118          * Here scaler state in crtc_state is set free so that
5119          * scaler can be assigned to other user. Actual register
5120          * update to free the scaler is done in plane/panel-fit programming.
5121          * For this purpose crtc/plane_state->scaler_id isn't reset here.
5122          */
5123         if (force_detach || !need_scaler) {
5124                 if (*scaler_id >= 0) {
5125                         scaler_state->scaler_users &= ~(1 << scaler_user);
5126                         scaler_state->scalers[*scaler_id].in_use = 0;
5127
5128                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
5129                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
5130                                 intel_crtc->pipe, scaler_user, *scaler_id,
5131                                 scaler_state->scaler_users);
5132                         *scaler_id = -1;
5133                 }
5134                 return 0;
5135         }
5136
5137         if (format && is_planar_yuv_format(format->format) &&
5138             (src_h < SKL_MIN_YUV_420_SRC_H || src_w < SKL_MIN_YUV_420_SRC_W)) {
5139                 DRM_DEBUG_KMS("Planar YUV: src dimensions not met\n");
5140                 return -EINVAL;
5141         }
5142
5143         /* range checks */
5144         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
5145             dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
5146             (INTEL_GEN(dev_priv) >= 11 &&
5147              (src_w > ICL_MAX_SRC_W || src_h > ICL_MAX_SRC_H ||
5148               dst_w > ICL_MAX_DST_W || dst_h > ICL_MAX_DST_H)) ||
5149             (INTEL_GEN(dev_priv) < 11 &&
5150              (src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
5151               dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H))) {
5152                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
5153                         "size is out of scaler range\n",
5154                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
5155                 return -EINVAL;
5156         }
5157
5158         /* mark this plane as a scaler user in crtc_state */
5159         scaler_state->scaler_users |= (1 << scaler_user);
5160         DRM_DEBUG_KMS("scaler_user index %u.%u: "
5161                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
5162                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
5163                 scaler_state->scaler_users);
5164
5165         return 0;
5166 }
5167
5168 /**
5169  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
5170  *
5171  * @state: crtc's scaler state
5172  *
5173  * Return
5174  *     0 - scaler_usage updated successfully
5175  *    error - requested scaling cannot be supported or other error condition
5176  */
5177 int skl_update_scaler_crtc(struct intel_crtc_state *state)
5178 {
5179         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
5180         bool need_scaler = false;
5181
5182         if (state->output_format == INTEL_OUTPUT_FORMAT_YCBCR420)
5183                 need_scaler = true;
5184
5185         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
5186                                  &state->scaler_state.scaler_id,
5187                                  state->pipe_src_w, state->pipe_src_h,
5188                                  adjusted_mode->crtc_hdisplay,
5189                                  adjusted_mode->crtc_vdisplay, NULL, need_scaler);
5190 }
5191
5192 /**
5193  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
5194  * @crtc_state: crtc's scaler state
5195  * @plane_state: atomic plane state to update
5196  *
5197  * Return
5198  *     0 - scaler_usage updated successfully
5199  *    error - requested scaling cannot be supported or other error condition
5200  */
5201 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
5202                                    struct intel_plane_state *plane_state)
5203 {
5204         struct intel_plane *intel_plane =
5205                 to_intel_plane(plane_state->base.plane);
5206         struct drm_i915_private *dev_priv = to_i915(intel_plane->base.dev);
5207         struct drm_framebuffer *fb = plane_state->base.fb;
5208         int ret;
5209         bool force_detach = !fb || !plane_state->base.visible;
5210         bool need_scaler = false;
5211
5212         /* Pre-gen11 and SDR planes always need a scaler for planar formats. */
5213         if (!icl_is_hdr_plane(dev_priv, intel_plane->id) &&
5214             fb && is_planar_yuv_format(fb->format->format))
5215                 need_scaler = true;
5216
5217         ret = skl_update_scaler(crtc_state, force_detach,
5218                                 drm_plane_index(&intel_plane->base),
5219                                 &plane_state->scaler_id,
5220                                 drm_rect_width(&plane_state->base.src) >> 16,
5221                                 drm_rect_height(&plane_state->base.src) >> 16,
5222                                 drm_rect_width(&plane_state->base.dst),
5223                                 drm_rect_height(&plane_state->base.dst),
5224                                 fb ? fb->format : NULL, need_scaler);
5225
5226         if (ret || plane_state->scaler_id < 0)
5227                 return ret;
5228
5229         /* check colorkey */
5230         if (plane_state->ckey.flags) {
5231                 DRM_DEBUG_KMS("[PLANE:%d:%s] scaling with color key not allowed",
5232                               intel_plane->base.base.id,
5233                               intel_plane->base.name);
5234                 return -EINVAL;
5235         }
5236
5237         /* Check src format */
5238         switch (fb->format->format) {
5239         case DRM_FORMAT_RGB565:
5240         case DRM_FORMAT_XBGR8888:
5241         case DRM_FORMAT_XRGB8888:
5242         case DRM_FORMAT_ABGR8888:
5243         case DRM_FORMAT_ARGB8888:
5244         case DRM_FORMAT_XRGB2101010:
5245         case DRM_FORMAT_XBGR2101010:
5246         case DRM_FORMAT_XBGR16161616F:
5247         case DRM_FORMAT_ABGR16161616F:
5248         case DRM_FORMAT_XRGB16161616F:
5249         case DRM_FORMAT_ARGB16161616F:
5250         case DRM_FORMAT_YUYV:
5251         case DRM_FORMAT_YVYU:
5252         case DRM_FORMAT_UYVY:
5253         case DRM_FORMAT_VYUY:
5254         case DRM_FORMAT_NV12:
5255         case DRM_FORMAT_P010:
5256         case DRM_FORMAT_P012:
5257         case DRM_FORMAT_P016:
5258         case DRM_FORMAT_Y210:
5259         case DRM_FORMAT_Y212:
5260         case DRM_FORMAT_Y216:
5261         case DRM_FORMAT_XVYU2101010:
5262         case DRM_FORMAT_XVYU12_16161616:
5263         case DRM_FORMAT_XVYU16161616:
5264                 break;
5265         default:
5266                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d unsupported scaling format 0x%x\n",
5267                               intel_plane->base.base.id, intel_plane->base.name,
5268                               fb->base.id, fb->format->format);
5269                 return -EINVAL;
5270         }
5271
5272         return 0;
5273 }
5274
5275 static void skylake_scaler_disable(struct intel_crtc *crtc)
5276 {
5277         int i;
5278
5279         for (i = 0; i < crtc->num_scalers; i++)
5280                 skl_detach_scaler(crtc, i);
5281 }
5282
5283 static void skylake_pfit_enable(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 pipe pipe = crtc->pipe;
5288         const struct intel_crtc_scaler_state *scaler_state =
5289                 &crtc_state->scaler_state;
5290
5291         if (crtc_state->pch_pfit.enabled) {
5292                 u16 uv_rgb_hphase, uv_rgb_vphase;
5293                 int pfit_w, pfit_h, hscale, vscale;
5294                 int id;
5295
5296                 if (WARN_ON(crtc_state->scaler_state.scaler_id < 0))
5297                         return;
5298
5299                 pfit_w = (crtc_state->pch_pfit.size >> 16) & 0xFFFF;
5300                 pfit_h = crtc_state->pch_pfit.size & 0xFFFF;
5301
5302                 hscale = (crtc_state->pipe_src_w << 16) / pfit_w;
5303                 vscale = (crtc_state->pipe_src_h << 16) / pfit_h;
5304
5305                 uv_rgb_hphase = skl_scaler_calc_phase(1, hscale, false);
5306                 uv_rgb_vphase = skl_scaler_calc_phase(1, vscale, false);
5307
5308                 id = scaler_state->scaler_id;
5309                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
5310                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
5311                 I915_WRITE_FW(SKL_PS_VPHASE(pipe, id),
5312                               PS_Y_PHASE(0) | PS_UV_RGB_PHASE(uv_rgb_vphase));
5313                 I915_WRITE_FW(SKL_PS_HPHASE(pipe, id),
5314                               PS_Y_PHASE(0) | PS_UV_RGB_PHASE(uv_rgb_hphase));
5315                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc_state->pch_pfit.pos);
5316                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc_state->pch_pfit.size);
5317         }
5318 }
5319
5320 static void ironlake_pfit_enable(const struct intel_crtc_state *crtc_state)
5321 {
5322         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5323         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5324         int pipe = crtc->pipe;
5325
5326         if (crtc_state->pch_pfit.enabled) {
5327                 /* Force use of hard-coded filter coefficients
5328                  * as some pre-programmed values are broken,
5329                  * e.g. x201.
5330                  */
5331                 if (IS_IVYBRIDGE(dev_priv) || IS_HASWELL(dev_priv))
5332                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
5333                                                  PF_PIPE_SEL_IVB(pipe));
5334                 else
5335                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
5336                 I915_WRITE(PF_WIN_POS(pipe), crtc_state->pch_pfit.pos);
5337                 I915_WRITE(PF_WIN_SZ(pipe), crtc_state->pch_pfit.size);
5338         }
5339 }
5340
5341 void hsw_enable_ips(const struct intel_crtc_state *crtc_state)
5342 {
5343         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5344         struct drm_device *dev = crtc->base.dev;
5345         struct drm_i915_private *dev_priv = to_i915(dev);
5346
5347         if (!crtc_state->ips_enabled)
5348                 return;
5349
5350         /*
5351          * We can only enable IPS after we enable a plane and wait for a vblank
5352          * This function is called from post_plane_update, which is run after
5353          * a vblank wait.
5354          */
5355         WARN_ON(!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)));
5356
5357         if (IS_BROADWELL(dev_priv)) {
5358                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL,
5359                                                 IPS_ENABLE | IPS_PCODE_CONTROL));
5360                 /* Quoting Art Runyan: "its not safe to expect any particular
5361                  * value in IPS_CTL bit 31 after enabling IPS through the
5362                  * mailbox." Moreover, the mailbox may return a bogus state,
5363                  * so we need to just enable it and continue on.
5364                  */
5365         } else {
5366                 I915_WRITE(IPS_CTL, IPS_ENABLE);
5367                 /* The bit only becomes 1 in the next vblank, so this wait here
5368                  * is essentially intel_wait_for_vblank. If we don't have this
5369                  * and don't wait for vblanks until the end of crtc_enable, then
5370                  * the HW state readout code will complain that the expected
5371                  * IPS_CTL value is not the one we read. */
5372                 if (intel_wait_for_register(&dev_priv->uncore,
5373                                             IPS_CTL, IPS_ENABLE, IPS_ENABLE,
5374                                             50))
5375                         DRM_ERROR("Timed out waiting for IPS enable\n");
5376         }
5377 }
5378
5379 void hsw_disable_ips(const struct intel_crtc_state *crtc_state)
5380 {
5381         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5382         struct drm_device *dev = crtc->base.dev;
5383         struct drm_i915_private *dev_priv = to_i915(dev);
5384
5385         if (!crtc_state->ips_enabled)
5386                 return;
5387
5388         if (IS_BROADWELL(dev_priv)) {
5389                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
5390                 /*
5391                  * Wait for PCODE to finish disabling IPS. The BSpec specified
5392                  * 42ms timeout value leads to occasional timeouts so use 100ms
5393                  * instead.
5394                  */
5395                 if (intel_wait_for_register(&dev_priv->uncore,
5396                                             IPS_CTL, IPS_ENABLE, 0,
5397                                             100))
5398                         DRM_ERROR("Timed out waiting for IPS disable\n");
5399         } else {
5400                 I915_WRITE(IPS_CTL, 0);
5401                 POSTING_READ(IPS_CTL);
5402         }
5403
5404         /* We need to wait for a vblank before we can disable the plane. */
5405         intel_wait_for_vblank(dev_priv, crtc->pipe);
5406 }
5407
5408 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
5409 {
5410         if (intel_crtc->overlay) {
5411                 struct drm_device *dev = intel_crtc->base.dev;
5412
5413                 mutex_lock(&dev->struct_mutex);
5414                 (void) intel_overlay_switch_off(intel_crtc->overlay);
5415                 mutex_unlock(&dev->struct_mutex);
5416         }
5417
5418         /* Let userspace switch the overlay on again. In most cases userspace
5419          * has to recompute where to put it anyway.
5420          */
5421 }
5422
5423 /**
5424  * intel_post_enable_primary - Perform operations after enabling primary plane
5425  * @crtc: the CRTC whose primary plane was just enabled
5426  * @new_crtc_state: the enabling state
5427  *
5428  * Performs potentially sleeping operations that must be done after the primary
5429  * plane is enabled, such as updating FBC and IPS.  Note that this may be
5430  * called due to an explicit primary plane update, or due to an implicit
5431  * re-enable that is caused when a sprite plane is updated to no longer
5432  * completely hide the primary plane.
5433  */
5434 static void
5435 intel_post_enable_primary(struct drm_crtc *crtc,
5436                           const struct intel_crtc_state *new_crtc_state)
5437 {
5438         struct drm_device *dev = crtc->dev;
5439         struct drm_i915_private *dev_priv = to_i915(dev);
5440         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5441         int pipe = intel_crtc->pipe;
5442
5443         /*
5444          * Gen2 reports pipe underruns whenever all planes are disabled.
5445          * So don't enable underrun reporting before at least some planes
5446          * are enabled.
5447          * FIXME: Need to fix the logic to work when we turn off all planes
5448          * but leave the pipe running.
5449          */
5450         if (IS_GEN(dev_priv, 2))
5451                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5452
5453         /* Underruns don't always raise interrupts, so check manually. */
5454         intel_check_cpu_fifo_underruns(dev_priv);
5455         intel_check_pch_fifo_underruns(dev_priv);
5456 }
5457
5458 /* FIXME get rid of this and use pre_plane_update */
5459 static void
5460 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
5461 {
5462         struct drm_device *dev = crtc->dev;
5463         struct drm_i915_private *dev_priv = to_i915(dev);
5464         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5465         int pipe = intel_crtc->pipe;
5466
5467         /*
5468          * Gen2 reports pipe underruns whenever all planes are disabled.
5469          * So disable underrun reporting before all the planes get disabled.
5470          */
5471         if (IS_GEN(dev_priv, 2))
5472                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5473
5474         hsw_disable_ips(to_intel_crtc_state(crtc->state));
5475
5476         /*
5477          * Vblank time updates from the shadow to live plane control register
5478          * are blocked if the memory self-refresh mode is active at that
5479          * moment. So to make sure the plane gets truly disabled, disable
5480          * first the self-refresh mode. The self-refresh enable bit in turn
5481          * will be checked/applied by the HW only at the next frame start
5482          * event which is after the vblank start event, so we need to have a
5483          * wait-for-vblank between disabling the plane and the pipe.
5484          */
5485         if (HAS_GMCH(dev_priv) &&
5486             intel_set_memory_cxsr(dev_priv, false))
5487                 intel_wait_for_vblank(dev_priv, pipe);
5488 }
5489
5490 static bool hsw_pre_update_disable_ips(const struct intel_crtc_state *old_crtc_state,
5491                                        const struct intel_crtc_state *new_crtc_state)
5492 {
5493         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
5494         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5495
5496         if (!old_crtc_state->ips_enabled)
5497                 return false;
5498
5499         if (needs_modeset(&new_crtc_state->base))
5500                 return true;
5501
5502         /*
5503          * Workaround : Do not read or write the pipe palette/gamma data while
5504          * GAMMA_MODE is configured for split gamma and IPS_CTL has IPS enabled.
5505          *
5506          * Disable IPS before we program the LUT.
5507          */
5508         if (IS_HASWELL(dev_priv) &&
5509             (new_crtc_state->base.color_mgmt_changed ||
5510              new_crtc_state->update_pipe) &&
5511             new_crtc_state->gamma_mode == GAMMA_MODE_MODE_SPLIT)
5512                 return true;
5513
5514         return !new_crtc_state->ips_enabled;
5515 }
5516
5517 static bool hsw_post_update_enable_ips(const struct intel_crtc_state *old_crtc_state,
5518                                        const struct intel_crtc_state *new_crtc_state)
5519 {
5520         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
5521         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5522
5523         if (!new_crtc_state->ips_enabled)
5524                 return false;
5525
5526         if (needs_modeset(&new_crtc_state->base))
5527                 return true;
5528
5529         /*
5530          * Workaround : Do not read or write the pipe palette/gamma data while
5531          * GAMMA_MODE is configured for split gamma and IPS_CTL has IPS enabled.
5532          *
5533          * Re-enable IPS after the LUT has been programmed.
5534          */
5535         if (IS_HASWELL(dev_priv) &&
5536             (new_crtc_state->base.color_mgmt_changed ||
5537              new_crtc_state->update_pipe) &&
5538             new_crtc_state->gamma_mode == GAMMA_MODE_MODE_SPLIT)
5539                 return true;
5540
5541         /*
5542          * We can't read out IPS on broadwell, assume the worst and
5543          * forcibly enable IPS on the first fastset.
5544          */
5545         if (new_crtc_state->update_pipe &&
5546             old_crtc_state->base.adjusted_mode.private_flags & I915_MODE_FLAG_INHERITED)
5547                 return true;
5548
5549         return !old_crtc_state->ips_enabled;
5550 }
5551
5552 static bool needs_nv12_wa(struct drm_i915_private *dev_priv,
5553                           const struct intel_crtc_state *crtc_state)
5554 {
5555         if (!crtc_state->nv12_planes)
5556                 return false;
5557
5558         /* WA Display #0827: Gen9:all */
5559         if (IS_GEN(dev_priv, 9) && !IS_GEMINILAKE(dev_priv))
5560                 return true;
5561
5562         return false;
5563 }
5564
5565 static bool needs_scalerclk_wa(struct drm_i915_private *dev_priv,
5566                                const struct intel_crtc_state *crtc_state)
5567 {
5568         /* Wa_2006604312:icl */
5569         if (crtc_state->scaler_state.scaler_users > 0 && IS_ICELAKE(dev_priv))
5570                 return true;
5571
5572         return false;
5573 }
5574
5575 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
5576 {
5577         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5578         struct drm_device *dev = crtc->base.dev;
5579         struct drm_i915_private *dev_priv = to_i915(dev);
5580         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5581         struct intel_crtc_state *pipe_config =
5582                 intel_atomic_get_new_crtc_state(to_intel_atomic_state(old_state),
5583                                                 crtc);
5584         struct drm_plane *primary = crtc->base.primary;
5585         struct drm_plane_state *old_primary_state =
5586                 drm_atomic_get_old_plane_state(old_state, primary);
5587
5588         intel_frontbuffer_flip(to_i915(crtc->base.dev), pipe_config->fb_bits);
5589
5590         if (pipe_config->update_wm_post && pipe_config->base.active)
5591                 intel_update_watermarks(crtc);
5592
5593         if (hsw_post_update_enable_ips(old_crtc_state, pipe_config))
5594                 hsw_enable_ips(pipe_config);
5595
5596         if (old_primary_state) {
5597                 struct drm_plane_state *new_primary_state =
5598                         drm_atomic_get_new_plane_state(old_state, primary);
5599
5600                 intel_fbc_post_update(crtc);
5601
5602                 if (new_primary_state->visible &&
5603                     (needs_modeset(&pipe_config->base) ||
5604                      !old_primary_state->visible))
5605                         intel_post_enable_primary(&crtc->base, pipe_config);
5606         }
5607
5608         if (needs_nv12_wa(dev_priv, old_crtc_state) &&
5609             !needs_nv12_wa(dev_priv, pipe_config))
5610                 skl_wa_827(dev_priv, crtc->pipe, false);
5611
5612         if (needs_scalerclk_wa(dev_priv, old_crtc_state) &&
5613             !needs_scalerclk_wa(dev_priv, pipe_config))
5614                 icl_wa_scalerclkgating(dev_priv, crtc->pipe, false);
5615 }
5616
5617 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state,
5618                                    struct intel_crtc_state *pipe_config)
5619 {
5620         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5621         struct drm_device *dev = crtc->base.dev;
5622         struct drm_i915_private *dev_priv = to_i915(dev);
5623         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5624         struct drm_plane *primary = crtc->base.primary;
5625         struct drm_plane_state *old_primary_state =
5626                 drm_atomic_get_old_plane_state(old_state, primary);
5627         bool modeset = needs_modeset(&pipe_config->base);
5628         struct intel_atomic_state *old_intel_state =
5629                 to_intel_atomic_state(old_state);
5630
5631         if (hsw_pre_update_disable_ips(old_crtc_state, pipe_config))
5632                 hsw_disable_ips(old_crtc_state);
5633
5634         if (old_primary_state) {
5635                 struct intel_plane_state *new_primary_state =
5636                         intel_atomic_get_new_plane_state(old_intel_state,
5637                                                          to_intel_plane(primary));
5638
5639                 intel_fbc_pre_update(crtc, pipe_config, new_primary_state);
5640                 /*
5641                  * Gen2 reports pipe underruns whenever all planes are disabled.
5642                  * So disable underrun reporting before all the planes get disabled.
5643                  */
5644                 if (IS_GEN(dev_priv, 2) && old_primary_state->visible &&
5645                     (modeset || !new_primary_state->base.visible))
5646                         intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, false);
5647         }
5648
5649         /* Display WA 827 */
5650         if (!needs_nv12_wa(dev_priv, old_crtc_state) &&
5651             needs_nv12_wa(dev_priv, pipe_config))
5652                 skl_wa_827(dev_priv, crtc->pipe, true);
5653
5654         /* Wa_2006604312:icl */
5655         if (!needs_scalerclk_wa(dev_priv, old_crtc_state) &&
5656             needs_scalerclk_wa(dev_priv, pipe_config))
5657                 icl_wa_scalerclkgating(dev_priv, crtc->pipe, true);
5658
5659         /*
5660          * Vblank time updates from the shadow to live plane control register
5661          * are blocked if the memory self-refresh mode is active at that
5662          * moment. So to make sure the plane gets truly disabled, disable
5663          * first the self-refresh mode. The self-refresh enable bit in turn
5664          * will be checked/applied by the HW only at the next frame start
5665          * event which is after the vblank start event, so we need to have a
5666          * wait-for-vblank between disabling the plane and the pipe.
5667          */
5668         if (HAS_GMCH(dev_priv) && old_crtc_state->base.active &&
5669             pipe_config->disable_cxsr && intel_set_memory_cxsr(dev_priv, false))
5670                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5671
5672         /*
5673          * IVB workaround: must disable low power watermarks for at least
5674          * one frame before enabling scaling.  LP watermarks can be re-enabled
5675          * when scaling is disabled.
5676          *
5677          * WaCxSRDisabledForSpriteScaling:ivb
5678          */
5679         if (pipe_config->disable_lp_wm && ilk_disable_lp_wm(dev) &&
5680             old_crtc_state->base.active)
5681                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5682
5683         /*
5684          * If we're doing a modeset, we're done.  No need to do any pre-vblank
5685          * watermark programming here.
5686          */
5687         if (needs_modeset(&pipe_config->base))
5688                 return;
5689
5690         /*
5691          * For platforms that support atomic watermarks, program the
5692          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
5693          * will be the intermediate values that are safe for both pre- and
5694          * post- vblank; when vblank happens, the 'active' values will be set
5695          * to the final 'target' values and we'll do this again to get the
5696          * optimal watermarks.  For gen9+ platforms, the values we program here
5697          * will be the final target values which will get automatically latched
5698          * at vblank time; no further programming will be necessary.
5699          *
5700          * If a platform hasn't been transitioned to atomic watermarks yet,
5701          * we'll continue to update watermarks the old way, if flags tell
5702          * us to.
5703          */
5704         if (dev_priv->display.initial_watermarks != NULL)
5705                 dev_priv->display.initial_watermarks(old_intel_state,
5706                                                      pipe_config);
5707         else if (pipe_config->update_wm_pre)
5708                 intel_update_watermarks(crtc);
5709 }
5710
5711 static void intel_crtc_disable_planes(struct intel_atomic_state *state,
5712                                       struct intel_crtc *crtc)
5713 {
5714         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5715         const struct intel_crtc_state *new_crtc_state =
5716                 intel_atomic_get_new_crtc_state(state, crtc);
5717         unsigned int update_mask = new_crtc_state->update_planes;
5718         const struct intel_plane_state *old_plane_state;
5719         struct intel_plane *plane;
5720         unsigned fb_bits = 0;
5721         int i;
5722
5723         intel_crtc_dpms_overlay_disable(crtc);
5724
5725         for_each_old_intel_plane_in_state(state, plane, old_plane_state, i) {
5726                 if (crtc->pipe != plane->pipe ||
5727                     !(update_mask & BIT(plane->id)))
5728                         continue;
5729
5730                 intel_disable_plane(plane, new_crtc_state);
5731
5732                 if (old_plane_state->base.visible)
5733                         fb_bits |= plane->frontbuffer_bit;
5734         }
5735
5736         intel_frontbuffer_flip(dev_priv, fb_bits);
5737 }
5738
5739 static void intel_encoders_pre_pll_enable(struct drm_crtc *crtc,
5740                                           struct intel_crtc_state *crtc_state,
5741                                           struct drm_atomic_state *old_state)
5742 {
5743         struct drm_connector_state *conn_state;
5744         struct drm_connector *conn;
5745         int i;
5746
5747         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5748                 struct intel_encoder *encoder =
5749                         to_intel_encoder(conn_state->best_encoder);
5750
5751                 if (conn_state->crtc != crtc)
5752                         continue;
5753
5754                 if (encoder->pre_pll_enable)
5755                         encoder->pre_pll_enable(encoder, crtc_state, conn_state);
5756         }
5757 }
5758
5759 static void intel_encoders_pre_enable(struct drm_crtc *crtc,
5760                                       struct intel_crtc_state *crtc_state,
5761                                       struct drm_atomic_state *old_state)
5762 {
5763         struct drm_connector_state *conn_state;
5764         struct drm_connector *conn;
5765         int i;
5766
5767         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5768                 struct intel_encoder *encoder =
5769                         to_intel_encoder(conn_state->best_encoder);
5770
5771                 if (conn_state->crtc != crtc)
5772                         continue;
5773
5774                 if (encoder->pre_enable)
5775                         encoder->pre_enable(encoder, crtc_state, conn_state);
5776         }
5777 }
5778
5779 static void intel_encoders_enable(struct drm_crtc *crtc,
5780                                   struct intel_crtc_state *crtc_state,
5781                                   struct drm_atomic_state *old_state)
5782 {
5783         struct drm_connector_state *conn_state;
5784         struct drm_connector *conn;
5785         int i;
5786
5787         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5788                 struct intel_encoder *encoder =
5789                         to_intel_encoder(conn_state->best_encoder);
5790
5791                 if (conn_state->crtc != crtc)
5792                         continue;
5793
5794                 if (encoder->enable)
5795                         encoder->enable(encoder, crtc_state, conn_state);
5796                 intel_opregion_notify_encoder(encoder, true);
5797         }
5798 }
5799
5800 static void intel_encoders_disable(struct drm_crtc *crtc,
5801                                    struct intel_crtc_state *old_crtc_state,
5802                                    struct drm_atomic_state *old_state)
5803 {
5804         struct drm_connector_state *old_conn_state;
5805         struct drm_connector *conn;
5806         int i;
5807
5808         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5809                 struct intel_encoder *encoder =
5810                         to_intel_encoder(old_conn_state->best_encoder);
5811
5812                 if (old_conn_state->crtc != crtc)
5813                         continue;
5814
5815                 intel_opregion_notify_encoder(encoder, false);
5816                 if (encoder->disable)
5817                         encoder->disable(encoder, old_crtc_state, old_conn_state);
5818         }
5819 }
5820
5821 static void intel_encoders_post_disable(struct drm_crtc *crtc,
5822                                         struct intel_crtc_state *old_crtc_state,
5823                                         struct drm_atomic_state *old_state)
5824 {
5825         struct drm_connector_state *old_conn_state;
5826         struct drm_connector *conn;
5827         int i;
5828
5829         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5830                 struct intel_encoder *encoder =
5831                         to_intel_encoder(old_conn_state->best_encoder);
5832
5833                 if (old_conn_state->crtc != crtc)
5834                         continue;
5835
5836                 if (encoder->post_disable)
5837                         encoder->post_disable(encoder, old_crtc_state, old_conn_state);
5838         }
5839 }
5840
5841 static void intel_encoders_post_pll_disable(struct drm_crtc *crtc,
5842                                             struct intel_crtc_state *old_crtc_state,
5843                                             struct drm_atomic_state *old_state)
5844 {
5845         struct drm_connector_state *old_conn_state;
5846         struct drm_connector *conn;
5847         int i;
5848
5849         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5850                 struct intel_encoder *encoder =
5851                         to_intel_encoder(old_conn_state->best_encoder);
5852
5853                 if (old_conn_state->crtc != crtc)
5854                         continue;
5855
5856                 if (encoder->post_pll_disable)
5857                         encoder->post_pll_disable(encoder, old_crtc_state, old_conn_state);
5858         }
5859 }
5860
5861 static void intel_encoders_update_pipe(struct drm_crtc *crtc,
5862                                        struct intel_crtc_state *crtc_state,
5863                                        struct drm_atomic_state *old_state)
5864 {
5865         struct drm_connector_state *conn_state;
5866         struct drm_connector *conn;
5867         int i;
5868
5869         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5870                 struct intel_encoder *encoder =
5871                         to_intel_encoder(conn_state->best_encoder);
5872
5873                 if (conn_state->crtc != crtc)
5874                         continue;
5875
5876                 if (encoder->update_pipe)
5877                         encoder->update_pipe(encoder, crtc_state, conn_state);
5878         }
5879 }
5880
5881 static void intel_disable_primary_plane(const struct intel_crtc_state *crtc_state)
5882 {
5883         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5884         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
5885
5886         plane->disable_plane(plane, crtc_state);
5887 }
5888
5889 static void ironlake_crtc_enable(struct intel_crtc_state *pipe_config,
5890                                  struct drm_atomic_state *old_state)
5891 {
5892         struct drm_crtc *crtc = pipe_config->base.crtc;
5893         struct drm_device *dev = crtc->dev;
5894         struct drm_i915_private *dev_priv = to_i915(dev);
5895         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5896         int pipe = intel_crtc->pipe;
5897         struct intel_atomic_state *old_intel_state =
5898                 to_intel_atomic_state(old_state);
5899
5900         if (WARN_ON(intel_crtc->active))
5901                 return;
5902
5903         /*
5904          * Sometimes spurious CPU pipe underruns happen during FDI
5905          * training, at least with VGA+HDMI cloning. Suppress them.
5906          *
5907          * On ILK we get an occasional spurious CPU pipe underruns
5908          * between eDP port A enable and vdd enable. Also PCH port
5909          * enable seems to result in the occasional CPU pipe underrun.
5910          *
5911          * Spurious PCH underruns also occur during PCH enabling.
5912          */
5913         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5914         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5915
5916         if (pipe_config->has_pch_encoder)
5917                 intel_prepare_shared_dpll(pipe_config);
5918
5919         if (intel_crtc_has_dp_encoder(pipe_config))
5920                 intel_dp_set_m_n(pipe_config, M1_N1);
5921
5922         intel_set_pipe_timings(pipe_config);
5923         intel_set_pipe_src_size(pipe_config);
5924
5925         if (pipe_config->has_pch_encoder) {
5926                 intel_cpu_transcoder_set_m_n(pipe_config,
5927                                              &pipe_config->fdi_m_n, NULL);
5928         }
5929
5930         ironlake_set_pipeconf(pipe_config);
5931
5932         intel_crtc->active = true;
5933
5934         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5935
5936         if (pipe_config->has_pch_encoder) {
5937                 /* Note: FDI PLL enabling _must_ be done before we enable the
5938                  * cpu pipes, hence this is separate from all the other fdi/pch
5939                  * enabling. */
5940                 ironlake_fdi_pll_enable(pipe_config);
5941         } else {
5942                 assert_fdi_tx_disabled(dev_priv, pipe);
5943                 assert_fdi_rx_disabled(dev_priv, pipe);
5944         }
5945
5946         ironlake_pfit_enable(pipe_config);
5947
5948         /*
5949          * On ILK+ LUT must be loaded before the pipe is running but with
5950          * clocks enabled
5951          */
5952         intel_color_load_luts(pipe_config);
5953         intel_color_commit(pipe_config);
5954         /* update DSPCNTR to configure gamma for pipe bottom color */
5955         intel_disable_primary_plane(pipe_config);
5956
5957         if (dev_priv->display.initial_watermarks != NULL)
5958                 dev_priv->display.initial_watermarks(old_intel_state, pipe_config);
5959         intel_enable_pipe(pipe_config);
5960
5961         if (pipe_config->has_pch_encoder)
5962                 ironlake_pch_enable(old_intel_state, pipe_config);
5963
5964         assert_vblank_disabled(crtc);
5965         intel_crtc_vblank_on(pipe_config);
5966
5967         intel_encoders_enable(crtc, pipe_config, old_state);
5968
5969         if (HAS_PCH_CPT(dev_priv))
5970                 cpt_verify_modeset(dev, intel_crtc->pipe);
5971
5972         /*
5973          * Must wait for vblank to avoid spurious PCH FIFO underruns.
5974          * And a second vblank wait is needed at least on ILK with
5975          * some interlaced HDMI modes. Let's do the double wait always
5976          * in case there are more corner cases we don't know about.
5977          */
5978         if (pipe_config->has_pch_encoder) {
5979                 intel_wait_for_vblank(dev_priv, pipe);
5980                 intel_wait_for_vblank(dev_priv, pipe);
5981         }
5982         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5983         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5984 }
5985
5986 /* IPS only exists on ULT machines and is tied to pipe A. */
5987 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
5988 {
5989         return HAS_IPS(to_i915(crtc->base.dev)) && crtc->pipe == PIPE_A;
5990 }
5991
5992 static void glk_pipe_scaler_clock_gating_wa(struct drm_i915_private *dev_priv,
5993                                             enum pipe pipe, bool apply)
5994 {
5995         u32 val = I915_READ(CLKGATE_DIS_PSL(pipe));
5996         u32 mask = DPF_GATING_DIS | DPF_RAM_GATING_DIS | DPFR_GATING_DIS;
5997
5998         if (apply)
5999                 val |= mask;
6000         else
6001                 val &= ~mask;
6002
6003         I915_WRITE(CLKGATE_DIS_PSL(pipe), val);
6004 }
6005
6006 static void icl_pipe_mbus_enable(struct intel_crtc *crtc)
6007 {
6008         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6009         enum pipe pipe = crtc->pipe;
6010         u32 val;
6011
6012         val = MBUS_DBOX_A_CREDIT(2);
6013         val |= MBUS_DBOX_BW_CREDIT(1);
6014         val |= MBUS_DBOX_B_CREDIT(8);
6015
6016         I915_WRITE(PIPE_MBUS_DBOX_CTL(pipe), val);
6017 }
6018
6019 static void haswell_crtc_enable(struct intel_crtc_state *pipe_config,
6020                                 struct drm_atomic_state *old_state)
6021 {
6022         struct drm_crtc *crtc = pipe_config->base.crtc;
6023         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6024         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6025         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
6026         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
6027         struct intel_atomic_state *old_intel_state =
6028                 to_intel_atomic_state(old_state);
6029         bool psl_clkgate_wa;
6030
6031         if (WARN_ON(intel_crtc->active))
6032                 return;
6033
6034         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
6035
6036         if (pipe_config->shared_dpll)
6037                 intel_enable_shared_dpll(pipe_config);
6038
6039         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6040
6041         if (intel_crtc_has_dp_encoder(pipe_config))
6042                 intel_dp_set_m_n(pipe_config, M1_N1);
6043
6044         if (!transcoder_is_dsi(cpu_transcoder))
6045                 intel_set_pipe_timings(pipe_config);
6046
6047         intel_set_pipe_src_size(pipe_config);
6048
6049         if (cpu_transcoder != TRANSCODER_EDP &&
6050             !transcoder_is_dsi(cpu_transcoder)) {
6051                 I915_WRITE(PIPE_MULT(cpu_transcoder),
6052                            pipe_config->pixel_multiplier - 1);
6053         }
6054
6055         if (pipe_config->has_pch_encoder) {
6056                 intel_cpu_transcoder_set_m_n(pipe_config,
6057                                              &pipe_config->fdi_m_n, NULL);
6058         }
6059
6060         if (!transcoder_is_dsi(cpu_transcoder))
6061                 haswell_set_pipeconf(pipe_config);
6062
6063         if (INTEL_GEN(dev_priv) >= 9 || IS_BROADWELL(dev_priv))
6064                 bdw_set_pipemisc(pipe_config);
6065
6066         intel_crtc->active = true;
6067
6068         /* Display WA #1180: WaDisableScalarClockGating: glk, cnl */
6069         psl_clkgate_wa = (IS_GEMINILAKE(dev_priv) || IS_CANNONLAKE(dev_priv)) &&
6070                          pipe_config->pch_pfit.enabled;
6071         if (psl_clkgate_wa)
6072                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, true);
6073
6074         if (INTEL_GEN(dev_priv) >= 9)
6075                 skylake_pfit_enable(pipe_config);
6076         else
6077                 ironlake_pfit_enable(pipe_config);
6078
6079         /*
6080          * On ILK+ LUT must be loaded before the pipe is running but with
6081          * clocks enabled
6082          */
6083         intel_color_load_luts(pipe_config);
6084         intel_color_commit(pipe_config);
6085         /* update DSPCNTR to configure gamma/csc for pipe bottom color */
6086         if (INTEL_GEN(dev_priv) < 9)
6087                 intel_disable_primary_plane(pipe_config);
6088
6089         if (INTEL_GEN(dev_priv) >= 11)
6090                 icl_set_pipe_chicken(intel_crtc);
6091
6092         intel_ddi_set_pipe_settings(pipe_config);
6093         if (!transcoder_is_dsi(cpu_transcoder))
6094                 intel_ddi_enable_transcoder_func(pipe_config);
6095
6096         if (dev_priv->display.initial_watermarks != NULL)
6097                 dev_priv->display.initial_watermarks(old_intel_state, pipe_config);
6098
6099         if (INTEL_GEN(dev_priv) >= 11)
6100                 icl_pipe_mbus_enable(intel_crtc);
6101
6102         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
6103         if (!transcoder_is_dsi(cpu_transcoder))
6104                 intel_enable_pipe(pipe_config);
6105
6106         if (pipe_config->has_pch_encoder)
6107                 lpt_pch_enable(old_intel_state, pipe_config);
6108
6109         if (intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DP_MST))
6110                 intel_ddi_set_vc_payload_alloc(pipe_config, true);
6111
6112         assert_vblank_disabled(crtc);
6113         intel_crtc_vblank_on(pipe_config);
6114
6115         intel_encoders_enable(crtc, pipe_config, old_state);
6116
6117         if (psl_clkgate_wa) {
6118                 intel_wait_for_vblank(dev_priv, pipe);
6119                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, false);
6120         }
6121
6122         /* If we change the relative order between pipe/planes enabling, we need
6123          * to change the workaround. */
6124         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
6125         if (IS_HASWELL(dev_priv) && hsw_workaround_pipe != INVALID_PIPE) {
6126                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
6127                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
6128         }
6129 }
6130
6131 static void ironlake_pfit_disable(const struct intel_crtc_state *old_crtc_state)
6132 {
6133         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
6134         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6135         enum pipe pipe = crtc->pipe;
6136
6137         /* To avoid upsetting the power well on haswell only disable the pfit if
6138          * it's in use. The hw state code will make sure we get this right. */
6139         if (old_crtc_state->pch_pfit.enabled) {
6140                 I915_WRITE(PF_CTL(pipe), 0);
6141                 I915_WRITE(PF_WIN_POS(pipe), 0);
6142                 I915_WRITE(PF_WIN_SZ(pipe), 0);
6143         }
6144 }
6145
6146 static void ironlake_crtc_disable(struct intel_crtc_state *old_crtc_state,
6147                                   struct drm_atomic_state *old_state)
6148 {
6149         struct drm_crtc *crtc = old_crtc_state->base.crtc;
6150         struct drm_device *dev = crtc->dev;
6151         struct drm_i915_private *dev_priv = to_i915(dev);
6152         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6153         int pipe = intel_crtc->pipe;
6154
6155         /*
6156          * Sometimes spurious CPU pipe underruns happen when the
6157          * pipe is already disabled, but FDI RX/TX is still enabled.
6158          * Happens at least with VGA+HDMI cloning. Suppress them.
6159          */
6160         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6161         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
6162
6163         intel_encoders_disable(crtc, old_crtc_state, old_state);
6164
6165         drm_crtc_vblank_off(crtc);
6166         assert_vblank_disabled(crtc);
6167
6168         intel_disable_pipe(old_crtc_state);
6169
6170         ironlake_pfit_disable(old_crtc_state);
6171
6172         if (old_crtc_state->has_pch_encoder)
6173                 ironlake_fdi_disable(crtc);
6174
6175         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
6176
6177         if (old_crtc_state->has_pch_encoder) {
6178                 ironlake_disable_pch_transcoder(dev_priv, pipe);
6179
6180                 if (HAS_PCH_CPT(dev_priv)) {
6181                         i915_reg_t reg;
6182                         u32 temp;
6183
6184                         /* disable TRANS_DP_CTL */
6185                         reg = TRANS_DP_CTL(pipe);
6186                         temp = I915_READ(reg);
6187                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
6188                                   TRANS_DP_PORT_SEL_MASK);
6189                         temp |= TRANS_DP_PORT_SEL_NONE;
6190                         I915_WRITE(reg, temp);
6191
6192                         /* disable DPLL_SEL */
6193                         temp = I915_READ(PCH_DPLL_SEL);
6194                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
6195                         I915_WRITE(PCH_DPLL_SEL, temp);
6196                 }
6197
6198                 ironlake_fdi_pll_disable(intel_crtc);
6199         }
6200
6201         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6202         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
6203 }
6204
6205 static void haswell_crtc_disable(struct intel_crtc_state *old_crtc_state,
6206                                  struct drm_atomic_state *old_state)
6207 {
6208         struct drm_crtc *crtc = old_crtc_state->base.crtc;
6209         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6210         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6211         enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
6212
6213         intel_encoders_disable(crtc, old_crtc_state, old_state);
6214
6215         drm_crtc_vblank_off(crtc);
6216         assert_vblank_disabled(crtc);
6217
6218         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
6219         if (!transcoder_is_dsi(cpu_transcoder))
6220                 intel_disable_pipe(old_crtc_state);
6221
6222         if (intel_crtc_has_type(old_crtc_state, INTEL_OUTPUT_DP_MST))
6223                 intel_ddi_set_vc_payload_alloc(old_crtc_state, false);
6224
6225         if (!transcoder_is_dsi(cpu_transcoder))
6226                 intel_ddi_disable_transcoder_func(old_crtc_state);
6227
6228         intel_dsc_disable(old_crtc_state);
6229
6230         if (INTEL_GEN(dev_priv) >= 9)
6231                 skylake_scaler_disable(intel_crtc);
6232         else
6233                 ironlake_pfit_disable(old_crtc_state);
6234
6235         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
6236
6237         intel_encoders_post_pll_disable(crtc, old_crtc_state, old_state);
6238 }
6239
6240 static void i9xx_pfit_enable(const struct intel_crtc_state *crtc_state)
6241 {
6242         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6243         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6244
6245         if (!crtc_state->gmch_pfit.control)
6246                 return;
6247
6248         /*
6249          * The panel fitter should only be adjusted whilst the pipe is disabled,
6250          * according to register description and PRM.
6251          */
6252         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
6253         assert_pipe_disabled(dev_priv, crtc->pipe);
6254
6255         I915_WRITE(PFIT_PGM_RATIOS, crtc_state->gmch_pfit.pgm_ratios);
6256         I915_WRITE(PFIT_CONTROL, crtc_state->gmch_pfit.control);
6257
6258         /* Border color in case we don't scale up to the full screen. Black by
6259          * default, change to something else for debugging. */
6260         I915_WRITE(BCLRPAT(crtc->pipe), 0);
6261 }
6262
6263 bool intel_port_is_combophy(struct drm_i915_private *dev_priv, enum port port)
6264 {
6265         if (port == PORT_NONE)
6266                 return false;
6267
6268         if (IS_ELKHARTLAKE(dev_priv))
6269                 return port <= PORT_C;
6270
6271         if (INTEL_GEN(dev_priv) >= 11)
6272                 return port <= PORT_B;
6273
6274         return false;
6275 }
6276
6277 bool intel_port_is_tc(struct drm_i915_private *dev_priv, enum port port)
6278 {
6279         if (INTEL_GEN(dev_priv) >= 11 && !IS_ELKHARTLAKE(dev_priv))
6280                 return port >= PORT_C && port <= PORT_F;
6281
6282         return false;
6283 }
6284
6285 enum tc_port intel_port_to_tc(struct drm_i915_private *dev_priv, enum port port)
6286 {
6287         if (!intel_port_is_tc(dev_priv, port))
6288                 return PORT_TC_NONE;
6289
6290         return port - PORT_C;
6291 }
6292
6293 enum intel_display_power_domain intel_port_to_power_domain(enum port port)
6294 {
6295         switch (port) {
6296         case PORT_A:
6297                 return POWER_DOMAIN_PORT_DDI_A_LANES;
6298         case PORT_B:
6299                 return POWER_DOMAIN_PORT_DDI_B_LANES;
6300         case PORT_C:
6301                 return POWER_DOMAIN_PORT_DDI_C_LANES;
6302         case PORT_D:
6303                 return POWER_DOMAIN_PORT_DDI_D_LANES;
6304         case PORT_E:
6305                 return POWER_DOMAIN_PORT_DDI_E_LANES;
6306         case PORT_F:
6307                 return POWER_DOMAIN_PORT_DDI_F_LANES;
6308         default:
6309                 MISSING_CASE(port);
6310                 return POWER_DOMAIN_PORT_OTHER;
6311         }
6312 }
6313
6314 enum intel_display_power_domain
6315 intel_aux_power_domain(struct intel_digital_port *dig_port)
6316 {
6317         switch (dig_port->aux_ch) {
6318         case AUX_CH_A:
6319                 return POWER_DOMAIN_AUX_A;
6320         case AUX_CH_B:
6321                 return POWER_DOMAIN_AUX_B;
6322         case AUX_CH_C:
6323                 return POWER_DOMAIN_AUX_C;
6324         case AUX_CH_D:
6325                 return POWER_DOMAIN_AUX_D;
6326         case AUX_CH_E:
6327                 return POWER_DOMAIN_AUX_E;
6328         case AUX_CH_F:
6329                 return POWER_DOMAIN_AUX_F;
6330         default:
6331                 MISSING_CASE(dig_port->aux_ch);
6332                 return POWER_DOMAIN_AUX_A;
6333         }
6334 }
6335
6336 static u64 get_crtc_power_domains(struct drm_crtc *crtc,
6337                                   struct intel_crtc_state *crtc_state)
6338 {
6339         struct drm_device *dev = crtc->dev;
6340         struct drm_i915_private *dev_priv = to_i915(dev);
6341         struct drm_encoder *encoder;
6342         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6343         enum pipe pipe = intel_crtc->pipe;
6344         u64 mask;
6345         enum transcoder transcoder = crtc_state->cpu_transcoder;
6346
6347         if (!crtc_state->base.active)
6348                 return 0;
6349
6350         mask = BIT_ULL(POWER_DOMAIN_PIPE(pipe));
6351         mask |= BIT_ULL(POWER_DOMAIN_TRANSCODER(transcoder));
6352         if (crtc_state->pch_pfit.enabled ||
6353             crtc_state->pch_pfit.force_thru)
6354                 mask |= BIT_ULL(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
6355
6356         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
6357                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6358
6359                 mask |= BIT_ULL(intel_encoder->power_domain);
6360         }
6361
6362         if (HAS_DDI(dev_priv) && crtc_state->has_audio)
6363                 mask |= BIT_ULL(POWER_DOMAIN_AUDIO);
6364
6365         if (crtc_state->shared_dpll)
6366                 mask |= BIT_ULL(POWER_DOMAIN_PLLS);
6367
6368         return mask;
6369 }
6370
6371 static u64
6372 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
6373                                struct intel_crtc_state *crtc_state)
6374 {
6375         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6376         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6377         enum intel_display_power_domain domain;
6378         u64 domains, new_domains, old_domains;
6379
6380         old_domains = intel_crtc->enabled_power_domains;
6381         intel_crtc->enabled_power_domains = new_domains =
6382                 get_crtc_power_domains(crtc, crtc_state);
6383
6384         domains = new_domains & ~old_domains;
6385
6386         for_each_power_domain(domain, domains)
6387                 intel_display_power_get(dev_priv, domain);
6388
6389         return old_domains & ~new_domains;
6390 }
6391
6392 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
6393                                       u64 domains)
6394 {
6395         enum intel_display_power_domain domain;
6396
6397         for_each_power_domain(domain, domains)
6398                 intel_display_power_put_unchecked(dev_priv, domain);
6399 }
6400
6401 static void valleyview_crtc_enable(struct intel_crtc_state *pipe_config,
6402                                    struct drm_atomic_state *old_state)
6403 {
6404         struct intel_atomic_state *old_intel_state =
6405                 to_intel_atomic_state(old_state);
6406         struct drm_crtc *crtc = pipe_config->base.crtc;
6407         struct drm_device *dev = crtc->dev;
6408         struct drm_i915_private *dev_priv = to_i915(dev);
6409         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6410         int pipe = intel_crtc->pipe;
6411
6412         if (WARN_ON(intel_crtc->active))
6413                 return;
6414
6415         if (intel_crtc_has_dp_encoder(pipe_config))
6416                 intel_dp_set_m_n(pipe_config, M1_N1);
6417
6418         intel_set_pipe_timings(pipe_config);
6419         intel_set_pipe_src_size(pipe_config);
6420
6421         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
6422                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6423                 I915_WRITE(CHV_CANVAS(pipe), 0);
6424         }
6425
6426         i9xx_set_pipeconf(pipe_config);
6427
6428         intel_crtc->active = true;
6429
6430         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6431
6432         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
6433
6434         if (IS_CHERRYVIEW(dev_priv)) {
6435                 chv_prepare_pll(intel_crtc, pipe_config);
6436                 chv_enable_pll(intel_crtc, pipe_config);
6437         } else {
6438                 vlv_prepare_pll(intel_crtc, pipe_config);
6439                 vlv_enable_pll(intel_crtc, pipe_config);
6440         }
6441
6442         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6443
6444         i9xx_pfit_enable(pipe_config);
6445
6446         intel_color_load_luts(pipe_config);
6447         intel_color_commit(pipe_config);
6448         /* update DSPCNTR to configure gamma for pipe bottom color */
6449         intel_disable_primary_plane(pipe_config);
6450
6451         dev_priv->display.initial_watermarks(old_intel_state,
6452                                              pipe_config);
6453         intel_enable_pipe(pipe_config);
6454
6455         assert_vblank_disabled(crtc);
6456         intel_crtc_vblank_on(pipe_config);
6457
6458         intel_encoders_enable(crtc, pipe_config, old_state);
6459 }
6460
6461 static void i9xx_set_pll_dividers(const struct intel_crtc_state *crtc_state)
6462 {
6463         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6464         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6465
6466         I915_WRITE(FP0(crtc->pipe), crtc_state->dpll_hw_state.fp0);
6467         I915_WRITE(FP1(crtc->pipe), crtc_state->dpll_hw_state.fp1);
6468 }
6469
6470 static void i9xx_crtc_enable(struct intel_crtc_state *pipe_config,
6471                              struct drm_atomic_state *old_state)
6472 {
6473         struct intel_atomic_state *old_intel_state =
6474                 to_intel_atomic_state(old_state);
6475         struct drm_crtc *crtc = pipe_config->base.crtc;
6476         struct drm_device *dev = crtc->dev;
6477         struct drm_i915_private *dev_priv = to_i915(dev);
6478         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6479         enum pipe pipe = intel_crtc->pipe;
6480
6481         if (WARN_ON(intel_crtc->active))
6482                 return;
6483
6484         i9xx_set_pll_dividers(pipe_config);
6485
6486         if (intel_crtc_has_dp_encoder(pipe_config))
6487                 intel_dp_set_m_n(pipe_config, M1_N1);
6488
6489         intel_set_pipe_timings(pipe_config);
6490         intel_set_pipe_src_size(pipe_config);
6491
6492         i9xx_set_pipeconf(pipe_config);
6493
6494         intel_crtc->active = true;
6495
6496         if (!IS_GEN(dev_priv, 2))
6497                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6498
6499         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6500
6501         i9xx_enable_pll(intel_crtc, pipe_config);
6502
6503         i9xx_pfit_enable(pipe_config);
6504
6505         intel_color_load_luts(pipe_config);
6506         intel_color_commit(pipe_config);
6507         /* update DSPCNTR to configure gamma for pipe bottom color */
6508         intel_disable_primary_plane(pipe_config);
6509
6510         if (dev_priv->display.initial_watermarks != NULL)
6511                 dev_priv->display.initial_watermarks(old_intel_state,
6512                                                      pipe_config);
6513         else
6514                 intel_update_watermarks(intel_crtc);
6515         intel_enable_pipe(pipe_config);
6516
6517         assert_vblank_disabled(crtc);
6518         intel_crtc_vblank_on(pipe_config);
6519
6520         intel_encoders_enable(crtc, pipe_config, old_state);
6521 }
6522
6523 static void i9xx_pfit_disable(const struct intel_crtc_state *old_crtc_state)
6524 {
6525         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
6526         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6527
6528         if (!old_crtc_state->gmch_pfit.control)
6529                 return;
6530
6531         assert_pipe_disabled(dev_priv, crtc->pipe);
6532
6533         DRM_DEBUG_KMS("disabling pfit, current: 0x%08x\n",
6534                       I915_READ(PFIT_CONTROL));
6535         I915_WRITE(PFIT_CONTROL, 0);
6536 }
6537
6538 static void i9xx_crtc_disable(struct intel_crtc_state *old_crtc_state,
6539                               struct drm_atomic_state *old_state)
6540 {
6541         struct drm_crtc *crtc = old_crtc_state->base.crtc;
6542         struct drm_device *dev = crtc->dev;
6543         struct drm_i915_private *dev_priv = to_i915(dev);
6544         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6545         int pipe = intel_crtc->pipe;
6546
6547         /*
6548          * On gen2 planes are double buffered but the pipe isn't, so we must
6549          * wait for planes to fully turn off before disabling the pipe.
6550          */
6551         if (IS_GEN(dev_priv, 2))
6552                 intel_wait_for_vblank(dev_priv, pipe);
6553
6554         intel_encoders_disable(crtc, old_crtc_state, old_state);
6555
6556         drm_crtc_vblank_off(crtc);
6557         assert_vblank_disabled(crtc);
6558
6559         intel_disable_pipe(old_crtc_state);
6560
6561         i9xx_pfit_disable(old_crtc_state);
6562
6563         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
6564
6565         if (!intel_crtc_has_type(old_crtc_state, INTEL_OUTPUT_DSI)) {
6566                 if (IS_CHERRYVIEW(dev_priv))
6567                         chv_disable_pll(dev_priv, pipe);
6568                 else if (IS_VALLEYVIEW(dev_priv))
6569                         vlv_disable_pll(dev_priv, pipe);
6570                 else
6571                         i9xx_disable_pll(old_crtc_state);
6572         }
6573
6574         intel_encoders_post_pll_disable(crtc, old_crtc_state, old_state);
6575
6576         if (!IS_GEN(dev_priv, 2))
6577                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6578
6579         if (!dev_priv->display.initial_watermarks)
6580                 intel_update_watermarks(intel_crtc);
6581
6582         /* clock the pipe down to 640x480@60 to potentially save power */
6583         if (IS_I830(dev_priv))
6584                 i830_enable_pipe(dev_priv, pipe);
6585 }
6586
6587 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc,
6588                                         struct drm_modeset_acquire_ctx *ctx)
6589 {
6590         struct intel_encoder *encoder;
6591         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6592         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6593         enum intel_display_power_domain domain;
6594         struct intel_plane *plane;
6595         u64 domains;
6596         struct drm_atomic_state *state;
6597         struct intel_crtc_state *crtc_state;
6598         int ret;
6599
6600         if (!intel_crtc->active)
6601                 return;
6602
6603         for_each_intel_plane_on_crtc(&dev_priv->drm, intel_crtc, plane) {
6604                 const struct intel_plane_state *plane_state =
6605                         to_intel_plane_state(plane->base.state);
6606
6607                 if (plane_state->base.visible)
6608                         intel_plane_disable_noatomic(intel_crtc, plane);
6609         }
6610
6611         state = drm_atomic_state_alloc(crtc->dev);
6612         if (!state) {
6613                 DRM_DEBUG_KMS("failed to disable [CRTC:%d:%s], out of memory",
6614                               crtc->base.id, crtc->name);
6615                 return;
6616         }
6617
6618         state->acquire_ctx = ctx;
6619
6620         /* Everything's already locked, -EDEADLK can't happen. */
6621         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
6622         ret = drm_atomic_add_affected_connectors(state, crtc);
6623
6624         WARN_ON(IS_ERR(crtc_state) || ret);
6625
6626         dev_priv->display.crtc_disable(crtc_state, state);
6627
6628         drm_atomic_state_put(state);
6629
6630         DRM_DEBUG_KMS("[CRTC:%d:%s] hw state adjusted, was enabled, now disabled\n",
6631                       crtc->base.id, crtc->name);
6632
6633         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
6634         crtc->state->active = false;
6635         intel_crtc->active = false;
6636         crtc->enabled = false;
6637         crtc->state->connector_mask = 0;
6638         crtc->state->encoder_mask = 0;
6639
6640         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
6641                 encoder->base.crtc = NULL;
6642
6643         intel_fbc_disable(intel_crtc);
6644         intel_update_watermarks(intel_crtc);
6645         intel_disable_shared_dpll(to_intel_crtc_state(crtc->state));
6646
6647         domains = intel_crtc->enabled_power_domains;
6648         for_each_power_domain(domain, domains)
6649                 intel_display_power_put_unchecked(dev_priv, domain);
6650         intel_crtc->enabled_power_domains = 0;
6651
6652         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6653         dev_priv->min_cdclk[intel_crtc->pipe] = 0;
6654         dev_priv->min_voltage_level[intel_crtc->pipe] = 0;
6655 }
6656
6657 /*
6658  * turn all crtc's off, but do not adjust state
6659  * This has to be paired with a call to intel_modeset_setup_hw_state.
6660  */
6661 int intel_display_suspend(struct drm_device *dev)
6662 {
6663         struct drm_i915_private *dev_priv = to_i915(dev);
6664         struct drm_atomic_state *state;
6665         int ret;
6666
6667         state = drm_atomic_helper_suspend(dev);
6668         ret = PTR_ERR_OR_ZERO(state);
6669         if (ret)
6670                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6671         else
6672                 dev_priv->modeset_restore_state = state;
6673         return ret;
6674 }
6675
6676 void intel_encoder_destroy(struct drm_encoder *encoder)
6677 {
6678         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6679
6680         drm_encoder_cleanup(encoder);
6681         kfree(intel_encoder);
6682 }
6683
6684 /* Cross check the actual hw state with our own modeset state tracking (and it's
6685  * internal consistency). */
6686 static void intel_connector_verify_state(struct drm_crtc_state *crtc_state,
6687                                          struct drm_connector_state *conn_state)
6688 {
6689         struct intel_connector *connector = to_intel_connector(conn_state->connector);
6690
6691         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6692                       connector->base.base.id,
6693                       connector->base.name);
6694
6695         if (connector->get_hw_state(connector)) {
6696                 struct intel_encoder *encoder = connector->encoder;
6697
6698                 I915_STATE_WARN(!crtc_state,
6699                          "connector enabled without attached crtc\n");
6700
6701                 if (!crtc_state)
6702                         return;
6703
6704                 I915_STATE_WARN(!crtc_state->active,
6705                       "connector is active, but attached crtc isn't\n");
6706
6707                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6708                         return;
6709
6710                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6711                         "atomic encoder doesn't match attached encoder\n");
6712
6713                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6714                         "attached encoder crtc differs from connector crtc\n");
6715         } else {
6716                 I915_STATE_WARN(crtc_state && crtc_state->active,
6717                         "attached crtc is active, but connector isn't\n");
6718                 I915_STATE_WARN(!crtc_state && conn_state->best_encoder,
6719                         "best encoder set without crtc!\n");
6720         }
6721 }
6722
6723 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6724 {
6725         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6726                 return crtc_state->fdi_lanes;
6727
6728         return 0;
6729 }
6730
6731 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6732                                      struct intel_crtc_state *pipe_config)
6733 {
6734         struct drm_i915_private *dev_priv = to_i915(dev);
6735         struct drm_atomic_state *state = pipe_config->base.state;
6736         struct intel_crtc *other_crtc;
6737         struct intel_crtc_state *other_crtc_state;
6738
6739         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6740                       pipe_name(pipe), pipe_config->fdi_lanes);
6741         if (pipe_config->fdi_lanes > 4) {
6742                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6743                               pipe_name(pipe), pipe_config->fdi_lanes);
6744                 return -EINVAL;
6745         }
6746
6747         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
6748                 if (pipe_config->fdi_lanes > 2) {
6749                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6750                                       pipe_config->fdi_lanes);
6751                         return -EINVAL;
6752                 } else {
6753                         return 0;
6754                 }
6755         }
6756
6757         if (INTEL_INFO(dev_priv)->num_pipes == 2)
6758                 return 0;
6759
6760         /* Ivybridge 3 pipe is really complicated */
6761         switch (pipe) {
6762         case PIPE_A:
6763                 return 0;
6764         case PIPE_B:
6765                 if (pipe_config->fdi_lanes <= 2)
6766                         return 0;
6767
6768                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_C);
6769                 other_crtc_state =
6770                         intel_atomic_get_crtc_state(state, other_crtc);
6771                 if (IS_ERR(other_crtc_state))
6772                         return PTR_ERR(other_crtc_state);
6773
6774                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6775                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6776                                       pipe_name(pipe), pipe_config->fdi_lanes);
6777                         return -EINVAL;
6778                 }
6779                 return 0;
6780         case PIPE_C:
6781                 if (pipe_config->fdi_lanes > 2) {
6782                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6783                                       pipe_name(pipe), pipe_config->fdi_lanes);
6784                         return -EINVAL;
6785                 }
6786
6787                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_B);
6788                 other_crtc_state =
6789                         intel_atomic_get_crtc_state(state, other_crtc);
6790                 if (IS_ERR(other_crtc_state))
6791                         return PTR_ERR(other_crtc_state);
6792
6793                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6794                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6795                         return -EINVAL;
6796                 }
6797                 return 0;
6798         default:
6799                 BUG();
6800         }
6801 }
6802
6803 #define RETRY 1
6804 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6805                                        struct intel_crtc_state *pipe_config)
6806 {
6807         struct drm_device *dev = intel_crtc->base.dev;
6808         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6809         int lane, link_bw, fdi_dotclock, ret;
6810         bool needs_recompute = false;
6811
6812 retry:
6813         /* FDI is a binary signal running at ~2.7GHz, encoding
6814          * each output octet as 10 bits. The actual frequency
6815          * is stored as a divider into a 100MHz clock, and the
6816          * mode pixel clock is stored in units of 1KHz.
6817          * Hence the bw of each lane in terms of the mode signal
6818          * is:
6819          */
6820         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
6821
6822         fdi_dotclock = adjusted_mode->crtc_clock;
6823
6824         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6825                                            pipe_config->pipe_bpp);
6826
6827         pipe_config->fdi_lanes = lane;
6828
6829         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6830                                link_bw, &pipe_config->fdi_m_n, false);
6831
6832         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
6833         if (ret == -EDEADLK)
6834                 return ret;
6835
6836         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6837                 pipe_config->pipe_bpp -= 2*3;
6838                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6839                               pipe_config->pipe_bpp);
6840                 needs_recompute = true;
6841                 pipe_config->bw_constrained = true;
6842
6843                 goto retry;
6844         }
6845
6846         if (needs_recompute)
6847                 return RETRY;
6848
6849         return ret;
6850 }
6851
6852 bool hsw_crtc_state_ips_capable(const struct intel_crtc_state *crtc_state)
6853 {
6854         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6855         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6856
6857         /* IPS only exists on ULT machines and is tied to pipe A. */
6858         if (!hsw_crtc_supports_ips(crtc))
6859                 return false;
6860
6861         if (!i915_modparams.enable_ips)
6862                 return false;
6863
6864         if (crtc_state->pipe_bpp > 24)
6865                 return false;
6866
6867         /*
6868          * We compare against max which means we must take
6869          * the increased cdclk requirement into account when
6870          * calculating the new cdclk.
6871          *
6872          * Should measure whether using a lower cdclk w/o IPS
6873          */
6874         if (IS_BROADWELL(dev_priv) &&
6875             crtc_state->pixel_rate > dev_priv->max_cdclk_freq * 95 / 100)
6876                 return false;
6877
6878         return true;
6879 }
6880
6881 static bool hsw_compute_ips_config(struct intel_crtc_state *crtc_state)
6882 {
6883         struct drm_i915_private *dev_priv =
6884                 to_i915(crtc_state->base.crtc->dev);
6885         struct intel_atomic_state *intel_state =
6886                 to_intel_atomic_state(crtc_state->base.state);
6887
6888         if (!hsw_crtc_state_ips_capable(crtc_state))
6889                 return false;
6890
6891         /*
6892          * When IPS gets enabled, the pipe CRC changes. Since IPS gets
6893          * enabled and disabled dynamically based on package C states,
6894          * user space can't make reliable use of the CRCs, so let's just
6895          * completely disable it.
6896          */
6897         if (crtc_state->crc_enabled)
6898                 return false;
6899
6900         /* IPS should be fine as long as at least one plane is enabled. */
6901         if (!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)))
6902                 return false;
6903
6904         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
6905         if (IS_BROADWELL(dev_priv) &&
6906             crtc_state->pixel_rate > intel_state->cdclk.logical.cdclk * 95 / 100)
6907                 return false;
6908
6909         return true;
6910 }
6911
6912 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
6913 {
6914         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6915
6916         /* GDG double wide on either pipe, otherwise pipe A only */
6917         return INTEL_GEN(dev_priv) < 4 &&
6918                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
6919 }
6920
6921 static u32 ilk_pipe_pixel_rate(const struct intel_crtc_state *pipe_config)
6922 {
6923         u32 pixel_rate;
6924
6925         pixel_rate = pipe_config->base.adjusted_mode.crtc_clock;
6926
6927         /*
6928          * We only use IF-ID interlacing. If we ever use
6929          * PF-ID we'll need to adjust the pixel_rate here.
6930          */
6931
6932         if (pipe_config->pch_pfit.enabled) {
6933                 u64 pipe_w, pipe_h, pfit_w, pfit_h;
6934                 u32 pfit_size = pipe_config->pch_pfit.size;
6935
6936                 pipe_w = pipe_config->pipe_src_w;
6937                 pipe_h = pipe_config->pipe_src_h;
6938
6939                 pfit_w = (pfit_size >> 16) & 0xFFFF;
6940                 pfit_h = pfit_size & 0xFFFF;
6941                 if (pipe_w < pfit_w)
6942                         pipe_w = pfit_w;
6943                 if (pipe_h < pfit_h)
6944                         pipe_h = pfit_h;
6945
6946                 if (WARN_ON(!pfit_w || !pfit_h))
6947                         return pixel_rate;
6948
6949                 pixel_rate = div_u64((u64)pixel_rate * pipe_w * pipe_h,
6950                                      pfit_w * pfit_h);
6951         }
6952
6953         return pixel_rate;
6954 }
6955
6956 static void intel_crtc_compute_pixel_rate(struct intel_crtc_state *crtc_state)
6957 {
6958         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
6959
6960         if (HAS_GMCH(dev_priv))
6961                 /* FIXME calculate proper pipe pixel rate for GMCH pfit */
6962                 crtc_state->pixel_rate =
6963                         crtc_state->base.adjusted_mode.crtc_clock;
6964         else
6965                 crtc_state->pixel_rate =
6966                         ilk_pipe_pixel_rate(crtc_state);
6967 }
6968
6969 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6970                                      struct intel_crtc_state *pipe_config)
6971 {
6972         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6973         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6974         int clock_limit = dev_priv->max_dotclk_freq;
6975
6976         if (INTEL_GEN(dev_priv) < 4) {
6977                 clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
6978
6979                 /*
6980                  * Enable double wide mode when the dot clock
6981                  * is > 90% of the (display) core speed.
6982                  */
6983                 if (intel_crtc_supports_double_wide(crtc) &&
6984                     adjusted_mode->crtc_clock > clock_limit) {
6985                         clock_limit = dev_priv->max_dotclk_freq;
6986                         pipe_config->double_wide = true;
6987                 }
6988         }
6989
6990         if (adjusted_mode->crtc_clock > clock_limit) {
6991                 DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
6992                               adjusted_mode->crtc_clock, clock_limit,
6993                               yesno(pipe_config->double_wide));
6994                 return -EINVAL;
6995         }
6996
6997         if ((pipe_config->output_format == INTEL_OUTPUT_FORMAT_YCBCR420 ||
6998              pipe_config->output_format == INTEL_OUTPUT_FORMAT_YCBCR444) &&
6999              pipe_config->base.ctm) {
7000                 /*
7001                  * There is only one pipe CSC unit per pipe, and we need that
7002                  * for output conversion from RGB->YCBCR. So if CTM is already
7003                  * applied we can't support YCBCR420 output.
7004                  */
7005                 DRM_DEBUG_KMS("YCBCR420 and CTM together are not possible\n");
7006                 return -EINVAL;
7007         }
7008
7009         /*
7010          * Pipe horizontal size must be even in:
7011          * - DVO ganged mode
7012          * - LVDS dual channel mode
7013          * - Double wide pipe
7014          */
7015         if (pipe_config->pipe_src_w & 1) {
7016                 if (pipe_config->double_wide) {
7017                         DRM_DEBUG_KMS("Odd pipe source width not supported with double wide pipe\n");
7018                         return -EINVAL;
7019                 }
7020
7021                 if (intel_crtc_has_type(pipe_config, INTEL_OUTPUT_LVDS) &&
7022                     intel_is_dual_link_lvds(dev_priv)) {
7023                         DRM_DEBUG_KMS("Odd pipe source width not supported with dual link LVDS\n");
7024                         return -EINVAL;
7025                 }
7026         }
7027
7028         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
7029          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
7030          */
7031         if ((INTEL_GEN(dev_priv) > 4 || IS_G4X(dev_priv)) &&
7032                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
7033                 return -EINVAL;
7034
7035         intel_crtc_compute_pixel_rate(pipe_config);
7036
7037         if (pipe_config->has_pch_encoder)
7038                 return ironlake_fdi_compute_config(crtc, pipe_config);
7039
7040         return 0;
7041 }
7042
7043 static void
7044 intel_reduce_m_n_ratio(u32 *num, u32 *den)
7045 {
7046         while (*num > DATA_LINK_M_N_MASK ||
7047                *den > DATA_LINK_M_N_MASK) {
7048                 *num >>= 1;
7049                 *den >>= 1;
7050         }
7051 }
7052
7053 static void compute_m_n(unsigned int m, unsigned int n,
7054                         u32 *ret_m, u32 *ret_n,
7055                         bool constant_n)
7056 {
7057         /*
7058          * Several DP dongles in particular seem to be fussy about
7059          * too large link M/N values. Give N value as 0x8000 that
7060          * should be acceptable by specific devices. 0x8000 is the
7061          * specified fixed N value for asynchronous clock mode,
7062          * which the devices expect also in synchronous clock mode.
7063          */
7064         if (constant_n)
7065                 *ret_n = 0x8000;
7066         else
7067                 *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
7068
7069         *ret_m = div_u64((u64)m * *ret_n, n);
7070         intel_reduce_m_n_ratio(ret_m, ret_n);
7071 }
7072
7073 void
7074 intel_link_compute_m_n(u16 bits_per_pixel, int nlanes,
7075                        int pixel_clock, int link_clock,
7076                        struct intel_link_m_n *m_n,
7077                        bool constant_n)
7078 {
7079         m_n->tu = 64;
7080
7081         compute_m_n(bits_per_pixel * pixel_clock,
7082                     link_clock * nlanes * 8,
7083                     &m_n->gmch_m, &m_n->gmch_n,
7084                     constant_n);
7085
7086         compute_m_n(pixel_clock, link_clock,
7087                     &m_n->link_m, &m_n->link_n,
7088                     constant_n);
7089 }
7090
7091 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
7092 {
7093         if (i915_modparams.panel_use_ssc >= 0)
7094                 return i915_modparams.panel_use_ssc != 0;
7095         return dev_priv->vbt.lvds_use_ssc
7096                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
7097 }
7098
7099 static u32 pnv_dpll_compute_fp(struct dpll *dpll)
7100 {
7101         return (1 << dpll->n) << 16 | dpll->m2;
7102 }
7103
7104 static u32 i9xx_dpll_compute_fp(struct dpll *dpll)
7105 {
7106         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
7107 }
7108
7109 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
7110                                      struct intel_crtc_state *crtc_state,
7111                                      struct dpll *reduced_clock)
7112 {
7113         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7114         u32 fp, fp2 = 0;
7115
7116         if (IS_PINEVIEW(dev_priv)) {
7117                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
7118                 if (reduced_clock)
7119                         fp2 = pnv_dpll_compute_fp(reduced_clock);
7120         } else {
7121                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
7122                 if (reduced_clock)
7123                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
7124         }
7125
7126         crtc_state->dpll_hw_state.fp0 = fp;
7127
7128         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7129             reduced_clock) {
7130                 crtc_state->dpll_hw_state.fp1 = fp2;
7131         } else {
7132                 crtc_state->dpll_hw_state.fp1 = fp;
7133         }
7134 }
7135
7136 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
7137                 pipe)
7138 {
7139         u32 reg_val;
7140
7141         /*
7142          * PLLB opamp always calibrates to max value of 0x3f, force enable it
7143          * and set it to a reasonable value instead.
7144          */
7145         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7146         reg_val &= 0xffffff00;
7147         reg_val |= 0x00000030;
7148         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7149
7150         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7151         reg_val &= 0x00ffffff;
7152         reg_val |= 0x8c000000;
7153         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7154
7155         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7156         reg_val &= 0xffffff00;
7157         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7158
7159         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7160         reg_val &= 0x00ffffff;
7161         reg_val |= 0xb0000000;
7162         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7163 }
7164
7165 static void intel_pch_transcoder_set_m_n(const struct intel_crtc_state *crtc_state,
7166                                          const struct intel_link_m_n *m_n)
7167 {
7168         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
7169         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7170         enum pipe pipe = crtc->pipe;
7171
7172         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7173         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
7174         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
7175         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
7176 }
7177
7178 static bool transcoder_has_m2_n2(struct drm_i915_private *dev_priv,
7179                                  enum transcoder transcoder)
7180 {
7181         if (IS_HASWELL(dev_priv))
7182                 return transcoder == TRANSCODER_EDP;
7183
7184         /*
7185          * Strictly speaking some registers are available before
7186          * gen7, but we only support DRRS on gen7+
7187          */
7188         return IS_GEN(dev_priv, 7) || IS_CHERRYVIEW(dev_priv);
7189 }
7190
7191 static void intel_cpu_transcoder_set_m_n(const struct intel_crtc_state *crtc_state,
7192                                          const struct intel_link_m_n *m_n,
7193                                          const struct intel_link_m_n *m2_n2)
7194 {
7195         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
7196         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7197         enum pipe pipe = crtc->pipe;
7198         enum transcoder transcoder = crtc_state->cpu_transcoder;
7199
7200         if (INTEL_GEN(dev_priv) >= 5) {
7201                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
7202                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
7203                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
7204                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
7205                 /*
7206                  *  M2_N2 registers are set only if DRRS is supported
7207                  * (to make sure the registers are not unnecessarily accessed).
7208                  */
7209                 if (m2_n2 && crtc_state->has_drrs &&
7210                     transcoder_has_m2_n2(dev_priv, transcoder)) {
7211                         I915_WRITE(PIPE_DATA_M2(transcoder),
7212                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
7213                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
7214                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
7215                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
7216                 }
7217         } else {
7218                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7219                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
7220                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
7221                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
7222         }
7223 }
7224
7225 void intel_dp_set_m_n(const struct intel_crtc_state *crtc_state, enum link_m_n_set m_n)
7226 {
7227         const struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
7228
7229         if (m_n == M1_N1) {
7230                 dp_m_n = &crtc_state->dp_m_n;
7231                 dp_m2_n2 = &crtc_state->dp_m2_n2;
7232         } else if (m_n == M2_N2) {
7233
7234                 /*
7235                  * M2_N2 registers are not supported. Hence m2_n2 divider value
7236                  * needs to be programmed into M1_N1.
7237                  */
7238                 dp_m_n = &crtc_state->dp_m2_n2;
7239         } else {
7240                 DRM_ERROR("Unsupported divider value\n");
7241                 return;
7242         }
7243
7244         if (crtc_state->has_pch_encoder)
7245                 intel_pch_transcoder_set_m_n(crtc_state, &crtc_state->dp_m_n);
7246         else
7247                 intel_cpu_transcoder_set_m_n(crtc_state, dp_m_n, dp_m2_n2);
7248 }
7249
7250 static void vlv_compute_dpll(struct intel_crtc *crtc,
7251                              struct intel_crtc_state *pipe_config)
7252 {
7253         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
7254                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7255         if (crtc->pipe != PIPE_A)
7256                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7257
7258         /* DPLL not used with DSI, but still need the rest set up */
7259         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
7260                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
7261                         DPLL_EXT_BUFFER_ENABLE_VLV;
7262
7263         pipe_config->dpll_hw_state.dpll_md =
7264                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7265 }
7266
7267 static void chv_compute_dpll(struct intel_crtc *crtc,
7268                              struct intel_crtc_state *pipe_config)
7269 {
7270         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
7271                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7272         if (crtc->pipe != PIPE_A)
7273                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7274
7275         /* DPLL not used with DSI, but still need the rest set up */
7276         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
7277                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE;
7278
7279         pipe_config->dpll_hw_state.dpll_md =
7280                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7281 }
7282
7283 static void vlv_prepare_pll(struct intel_crtc *crtc,
7284                             const struct intel_crtc_state *pipe_config)
7285 {
7286         struct drm_device *dev = crtc->base.dev;
7287         struct drm_i915_private *dev_priv = to_i915(dev);
7288         enum pipe pipe = crtc->pipe;
7289         u32 mdiv;
7290         u32 bestn, bestm1, bestm2, bestp1, bestp2;
7291         u32 coreclk, reg_val;
7292
7293         /* Enable Refclk */
7294         I915_WRITE(DPLL(pipe),
7295                    pipe_config->dpll_hw_state.dpll &
7296                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
7297
7298         /* No need to actually set up the DPLL with DSI */
7299         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7300                 return;
7301
7302         vlv_dpio_get(dev_priv);
7303
7304         bestn = pipe_config->dpll.n;
7305         bestm1 = pipe_config->dpll.m1;
7306         bestm2 = pipe_config->dpll.m2;
7307         bestp1 = pipe_config->dpll.p1;
7308         bestp2 = pipe_config->dpll.p2;
7309
7310         /* See eDP HDMI DPIO driver vbios notes doc */
7311
7312         /* PLL B needs special handling */
7313         if (pipe == PIPE_B)
7314                 vlv_pllb_recal_opamp(dev_priv, pipe);
7315
7316         /* Set up Tx target for periodic Rcomp update */
7317         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
7318
7319         /* Disable target IRef on PLL */
7320         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
7321         reg_val &= 0x00ffffff;
7322         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
7323
7324         /* Disable fast lock */
7325         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
7326
7327         /* Set idtafcrecal before PLL is enabled */
7328         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
7329         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
7330         mdiv |= ((bestn << DPIO_N_SHIFT));
7331         mdiv |= (1 << DPIO_K_SHIFT);
7332
7333         /*
7334          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
7335          * but we don't support that).
7336          * Note: don't use the DAC post divider as it seems unstable.
7337          */
7338         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
7339         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7340
7341         mdiv |= DPIO_ENABLE_CALIBRATION;
7342         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7343
7344         /* Set HBR and RBR LPF coefficients */
7345         if (pipe_config->port_clock == 162000 ||
7346             intel_crtc_has_type(pipe_config, INTEL_OUTPUT_ANALOG) ||
7347             intel_crtc_has_type(pipe_config, INTEL_OUTPUT_HDMI))
7348                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7349                                  0x009f0003);
7350         else
7351                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7352                                  0x00d0000f);
7353
7354         if (intel_crtc_has_dp_encoder(pipe_config)) {
7355                 /* Use SSC source */
7356                 if (pipe == PIPE_A)
7357                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7358                                          0x0df40000);
7359                 else
7360                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7361                                          0x0df70000);
7362         } else { /* HDMI or VGA */
7363                 /* Use bend source */
7364                 if (pipe == PIPE_A)
7365                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7366                                          0x0df70000);
7367                 else
7368                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7369                                          0x0df40000);
7370         }
7371
7372         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
7373         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
7374         if (intel_crtc_has_dp_encoder(pipe_config))
7375                 coreclk |= 0x01000000;
7376         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
7377
7378         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
7379
7380         vlv_dpio_put(dev_priv);
7381 }
7382
7383 static void chv_prepare_pll(struct intel_crtc *crtc,
7384                             const struct intel_crtc_state *pipe_config)
7385 {
7386         struct drm_device *dev = crtc->base.dev;
7387         struct drm_i915_private *dev_priv = to_i915(dev);
7388         enum pipe pipe = crtc->pipe;
7389         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7390         u32 loopfilter, tribuf_calcntr;
7391         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
7392         u32 dpio_val;
7393         int vco;
7394
7395         /* Enable Refclk and SSC */
7396         I915_WRITE(DPLL(pipe),
7397                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
7398
7399         /* No need to actually set up the DPLL with DSI */
7400         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7401                 return;
7402
7403         bestn = pipe_config->dpll.n;
7404         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
7405         bestm1 = pipe_config->dpll.m1;
7406         bestm2 = pipe_config->dpll.m2 >> 22;
7407         bestp1 = pipe_config->dpll.p1;
7408         bestp2 = pipe_config->dpll.p2;
7409         vco = pipe_config->dpll.vco;
7410         dpio_val = 0;
7411         loopfilter = 0;
7412
7413         vlv_dpio_get(dev_priv);
7414
7415         /* p1 and p2 divider */
7416         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
7417                         5 << DPIO_CHV_S1_DIV_SHIFT |
7418                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
7419                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
7420                         1 << DPIO_CHV_K_DIV_SHIFT);
7421
7422         /* Feedback post-divider - m2 */
7423         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
7424
7425         /* Feedback refclk divider - n and m1 */
7426         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
7427                         DPIO_CHV_M1_DIV_BY_2 |
7428                         1 << DPIO_CHV_N_DIV_SHIFT);
7429
7430         /* M2 fraction division */
7431         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
7432
7433         /* M2 fraction division enable */
7434         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7435         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
7436         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
7437         if (bestm2_frac)
7438                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
7439         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
7440
7441         /* Program digital lock detect threshold */
7442         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
7443         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
7444                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
7445         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
7446         if (!bestm2_frac)
7447                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
7448         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
7449
7450         /* Loop filter */
7451         if (vco == 5400000) {
7452                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
7453                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
7454                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
7455                 tribuf_calcntr = 0x9;
7456         } else if (vco <= 6200000) {
7457                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
7458                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
7459                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7460                 tribuf_calcntr = 0x9;
7461         } else if (vco <= 6480000) {
7462                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7463                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7464                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7465                 tribuf_calcntr = 0x8;
7466         } else {
7467                 /* Not supported. Apply the same limits as in the max case */
7468                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7469                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7470                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7471                 tribuf_calcntr = 0;
7472         }
7473         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
7474
7475         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
7476         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
7477         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
7478         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
7479
7480         /* AFC Recal */
7481         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
7482                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
7483                         DPIO_AFC_RECAL);
7484
7485         vlv_dpio_put(dev_priv);
7486 }
7487
7488 /**
7489  * vlv_force_pll_on - forcibly enable just the PLL
7490  * @dev_priv: i915 private structure
7491  * @pipe: pipe PLL to enable
7492  * @dpll: PLL configuration
7493  *
7494  * Enable the PLL for @pipe using the supplied @dpll config. To be used
7495  * in cases where we need the PLL enabled even when @pipe is not going to
7496  * be enabled.
7497  */
7498 int vlv_force_pll_on(struct drm_i915_private *dev_priv, enum pipe pipe,
7499                      const struct dpll *dpll)
7500 {
7501         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
7502         struct intel_crtc_state *pipe_config;
7503
7504         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
7505         if (!pipe_config)
7506                 return -ENOMEM;
7507
7508         pipe_config->base.crtc = &crtc->base;
7509         pipe_config->pixel_multiplier = 1;
7510         pipe_config->dpll = *dpll;
7511
7512         if (IS_CHERRYVIEW(dev_priv)) {
7513                 chv_compute_dpll(crtc, pipe_config);
7514                 chv_prepare_pll(crtc, pipe_config);
7515                 chv_enable_pll(crtc, pipe_config);
7516         } else {
7517                 vlv_compute_dpll(crtc, pipe_config);
7518                 vlv_prepare_pll(crtc, pipe_config);
7519                 vlv_enable_pll(crtc, pipe_config);
7520         }
7521
7522         kfree(pipe_config);
7523
7524         return 0;
7525 }
7526
7527 /**
7528  * vlv_force_pll_off - forcibly disable just the PLL
7529  * @dev_priv: i915 private structure
7530  * @pipe: pipe PLL to disable
7531  *
7532  * Disable the PLL for @pipe. To be used in cases where we need
7533  * the PLL enabled even when @pipe is not going to be enabled.
7534  */
7535 void vlv_force_pll_off(struct drm_i915_private *dev_priv, enum pipe pipe)
7536 {
7537         if (IS_CHERRYVIEW(dev_priv))
7538                 chv_disable_pll(dev_priv, pipe);
7539         else
7540                 vlv_disable_pll(dev_priv, pipe);
7541 }
7542
7543 static void i9xx_compute_dpll(struct intel_crtc *crtc,
7544                               struct intel_crtc_state *crtc_state,
7545                               struct dpll *reduced_clock)
7546 {
7547         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7548         u32 dpll;
7549         struct dpll *clock = &crtc_state->dpll;
7550
7551         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7552
7553         dpll = DPLL_VGA_MODE_DIS;
7554
7555         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
7556                 dpll |= DPLLB_MODE_LVDS;
7557         else
7558                 dpll |= DPLLB_MODE_DAC_SERIAL;
7559
7560         if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
7561             IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
7562                 dpll |= (crtc_state->pixel_multiplier - 1)
7563                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7564         }
7565
7566         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7567             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
7568                 dpll |= DPLL_SDVO_HIGH_SPEED;
7569
7570         if (intel_crtc_has_dp_encoder(crtc_state))
7571                 dpll |= DPLL_SDVO_HIGH_SPEED;
7572
7573         /* compute bitmask from p1 value */
7574         if (IS_PINEVIEW(dev_priv))
7575                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7576         else {
7577                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7578                 if (IS_G4X(dev_priv) && reduced_clock)
7579                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7580         }
7581         switch (clock->p2) {
7582         case 5:
7583                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7584                 break;
7585         case 7:
7586                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7587                 break;
7588         case 10:
7589                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7590                 break;
7591         case 14:
7592                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7593                 break;
7594         }
7595         if (INTEL_GEN(dev_priv) >= 4)
7596                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7597
7598         if (crtc_state->sdvo_tv_clock)
7599                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7600         else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7601                  intel_panel_use_ssc(dev_priv))
7602                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7603         else
7604                 dpll |= PLL_REF_INPUT_DREFCLK;
7605
7606         dpll |= DPLL_VCO_ENABLE;
7607         crtc_state->dpll_hw_state.dpll = dpll;
7608
7609         if (INTEL_GEN(dev_priv) >= 4) {
7610                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7611                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7612                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7613         }
7614 }
7615
7616 static void i8xx_compute_dpll(struct intel_crtc *crtc,
7617                               struct intel_crtc_state *crtc_state,
7618                               struct dpll *reduced_clock)
7619 {
7620         struct drm_device *dev = crtc->base.dev;
7621         struct drm_i915_private *dev_priv = to_i915(dev);
7622         u32 dpll;
7623         struct dpll *clock = &crtc_state->dpll;
7624
7625         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7626
7627         dpll = DPLL_VGA_MODE_DIS;
7628
7629         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7630                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7631         } else {
7632                 if (clock->p1 == 2)
7633                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7634                 else
7635                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7636                 if (clock->p2 == 4)
7637                         dpll |= PLL_P2_DIVIDE_BY_4;
7638         }
7639
7640         /*
7641          * Bspec:
7642          * "[Almador Errata}: For the correct operation of the muxed DVO pins
7643          *  (GDEVSELB/I2Cdata, GIRDBY/I2CClk) and (GFRAMEB/DVI_Data,
7644          *  GTRDYB/DVI_Clk): Bit 31 (DPLL VCO Enable) and Bit 30 (2X Clock
7645          *  Enable) must be set to “1” in both the DPLL A Control Register
7646          *  (06014h-06017h) and DPLL B Control Register (06018h-0601Bh)."
7647          *
7648          * For simplicity We simply keep both bits always enabled in
7649          * both DPLLS. The spec says we should disable the DVO 2X clock
7650          * when not needed, but this seems to work fine in practice.
7651          */
7652         if (IS_I830(dev_priv) ||
7653             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO))
7654                 dpll |= DPLL_DVO_2X_MODE;
7655
7656         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7657             intel_panel_use_ssc(dev_priv))
7658                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7659         else
7660                 dpll |= PLL_REF_INPUT_DREFCLK;
7661
7662         dpll |= DPLL_VCO_ENABLE;
7663         crtc_state->dpll_hw_state.dpll = dpll;
7664 }
7665
7666 static void intel_set_pipe_timings(const struct intel_crtc_state *crtc_state)
7667 {
7668         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
7669         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7670         enum pipe pipe = crtc->pipe;
7671         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
7672         const struct drm_display_mode *adjusted_mode = &crtc_state->base.adjusted_mode;
7673         u32 crtc_vtotal, crtc_vblank_end;
7674         int vsyncshift = 0;
7675
7676         /* We need to be careful not to changed the adjusted mode, for otherwise
7677          * the hw state checker will get angry at the mismatch. */
7678         crtc_vtotal = adjusted_mode->crtc_vtotal;
7679         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7680
7681         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7682                 /* the chip adds 2 halflines automatically */
7683                 crtc_vtotal -= 1;
7684                 crtc_vblank_end -= 1;
7685
7686                 if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO))
7687                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7688                 else
7689                         vsyncshift = adjusted_mode->crtc_hsync_start -
7690                                 adjusted_mode->crtc_htotal / 2;
7691                 if (vsyncshift < 0)
7692                         vsyncshift += adjusted_mode->crtc_htotal;
7693         }
7694
7695         if (INTEL_GEN(dev_priv) > 3)
7696                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7697
7698         I915_WRITE(HTOTAL(cpu_transcoder),
7699                    (adjusted_mode->crtc_hdisplay - 1) |
7700                    ((adjusted_mode->crtc_htotal - 1) << 16));
7701         I915_WRITE(HBLANK(cpu_transcoder),
7702                    (adjusted_mode->crtc_hblank_start - 1) |
7703                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7704         I915_WRITE(HSYNC(cpu_transcoder),
7705                    (adjusted_mode->crtc_hsync_start - 1) |
7706                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7707
7708         I915_WRITE(VTOTAL(cpu_transcoder),
7709                    (adjusted_mode->crtc_vdisplay - 1) |
7710                    ((crtc_vtotal - 1) << 16));
7711         I915_WRITE(VBLANK(cpu_transcoder),
7712                    (adjusted_mode->crtc_vblank_start - 1) |
7713                    ((crtc_vblank_end - 1) << 16));
7714         I915_WRITE(VSYNC(cpu_transcoder),
7715                    (adjusted_mode->crtc_vsync_start - 1) |
7716                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7717
7718         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7719          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7720          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7721          * bits. */
7722         if (IS_HASWELL(dev_priv) && cpu_transcoder == TRANSCODER_EDP &&
7723             (pipe == PIPE_B || pipe == PIPE_C))
7724                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7725
7726 }
7727
7728 static void intel_set_pipe_src_size(const struct intel_crtc_state *crtc_state)
7729 {
7730         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
7731         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7732         enum pipe pipe = crtc->pipe;
7733
7734         /* pipesrc controls the size that is scaled from, which should
7735          * always be the user's requested size.
7736          */
7737         I915_WRITE(PIPESRC(pipe),
7738                    ((crtc_state->pipe_src_w - 1) << 16) |
7739                    (crtc_state->pipe_src_h - 1));
7740 }
7741
7742 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7743                                    struct intel_crtc_state *pipe_config)
7744 {
7745         struct drm_device *dev = crtc->base.dev;
7746         struct drm_i915_private *dev_priv = to_i915(dev);
7747         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7748         u32 tmp;
7749
7750         tmp = I915_READ(HTOTAL(cpu_transcoder));
7751         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7752         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7753         tmp = I915_READ(HBLANK(cpu_transcoder));
7754         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7755         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7756         tmp = I915_READ(HSYNC(cpu_transcoder));
7757         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7758         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7759
7760         tmp = I915_READ(VTOTAL(cpu_transcoder));
7761         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7762         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7763         tmp = I915_READ(VBLANK(cpu_transcoder));
7764         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7765         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7766         tmp = I915_READ(VSYNC(cpu_transcoder));
7767         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7768         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7769
7770         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7771                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7772                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7773                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7774         }
7775 }
7776
7777 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
7778                                     struct intel_crtc_state *pipe_config)
7779 {
7780         struct drm_device *dev = crtc->base.dev;
7781         struct drm_i915_private *dev_priv = to_i915(dev);
7782         u32 tmp;
7783
7784         tmp = I915_READ(PIPESRC(crtc->pipe));
7785         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7786         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7787
7788         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7789         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7790 }
7791
7792 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7793                                  struct intel_crtc_state *pipe_config)
7794 {
7795         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7796         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7797         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7798         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7799
7800         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7801         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7802         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7803         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7804
7805         mode->flags = pipe_config->base.adjusted_mode.flags;
7806         mode->type = DRM_MODE_TYPE_DRIVER;
7807
7808         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7809
7810         mode->hsync = drm_mode_hsync(mode);
7811         mode->vrefresh = drm_mode_vrefresh(mode);
7812         drm_mode_set_name(mode);
7813 }
7814
7815 static void i9xx_set_pipeconf(const struct intel_crtc_state *crtc_state)
7816 {
7817         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
7818         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7819         u32 pipeconf;
7820
7821         pipeconf = 0;
7822
7823         /* we keep both pipes enabled on 830 */
7824         if (IS_I830(dev_priv))
7825                 pipeconf |= I915_READ(PIPECONF(crtc->pipe)) & PIPECONF_ENABLE;
7826
7827         if (crtc_state->double_wide)
7828                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7829
7830         /* only g4x and later have fancy bpc/dither controls */
7831         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7832             IS_CHERRYVIEW(dev_priv)) {
7833                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7834                 if (crtc_state->dither && crtc_state->pipe_bpp != 30)
7835                         pipeconf |= PIPECONF_DITHER_EN |
7836                                     PIPECONF_DITHER_TYPE_SP;
7837
7838                 switch (crtc_state->pipe_bpp) {
7839                 case 18:
7840                         pipeconf |= PIPECONF_6BPC;
7841                         break;
7842                 case 24:
7843                         pipeconf |= PIPECONF_8BPC;
7844                         break;
7845                 case 30:
7846                         pipeconf |= PIPECONF_10BPC;
7847                         break;
7848                 default:
7849                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7850                         BUG();
7851                 }
7852         }
7853
7854         if (crtc_state->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7855                 if (INTEL_GEN(dev_priv) < 4 ||
7856                     intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO))
7857                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7858                 else
7859                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7860         } else {
7861                 pipeconf |= PIPECONF_PROGRESSIVE;
7862         }
7863
7864         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7865              crtc_state->limited_color_range)
7866                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7867
7868         pipeconf |= PIPECONF_GAMMA_MODE(crtc_state->gamma_mode);
7869
7870         I915_WRITE(PIPECONF(crtc->pipe), pipeconf);
7871         POSTING_READ(PIPECONF(crtc->pipe));
7872 }
7873
7874 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
7875                                    struct intel_crtc_state *crtc_state)
7876 {
7877         struct drm_device *dev = crtc->base.dev;
7878         struct drm_i915_private *dev_priv = to_i915(dev);
7879         const struct intel_limit *limit;
7880         int refclk = 48000;
7881
7882         memset(&crtc_state->dpll_hw_state, 0,
7883                sizeof(crtc_state->dpll_hw_state));
7884
7885         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7886                 if (intel_panel_use_ssc(dev_priv)) {
7887                         refclk = dev_priv->vbt.lvds_ssc_freq;
7888                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7889                 }
7890
7891                 limit = &intel_limits_i8xx_lvds;
7892         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO)) {
7893                 limit = &intel_limits_i8xx_dvo;
7894         } else {
7895                 limit = &intel_limits_i8xx_dac;
7896         }
7897
7898         if (!crtc_state->clock_set &&
7899             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7900                                  refclk, NULL, &crtc_state->dpll)) {
7901                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7902                 return -EINVAL;
7903         }
7904
7905         i8xx_compute_dpll(crtc, crtc_state, NULL);
7906
7907         return 0;
7908 }
7909
7910 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
7911                                   struct intel_crtc_state *crtc_state)
7912 {
7913         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7914         const struct intel_limit *limit;
7915         int refclk = 96000;
7916
7917         memset(&crtc_state->dpll_hw_state, 0,
7918                sizeof(crtc_state->dpll_hw_state));
7919
7920         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7921                 if (intel_panel_use_ssc(dev_priv)) {
7922                         refclk = dev_priv->vbt.lvds_ssc_freq;
7923                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7924                 }
7925
7926                 if (intel_is_dual_link_lvds(dev_priv))
7927                         limit = &intel_limits_g4x_dual_channel_lvds;
7928                 else
7929                         limit = &intel_limits_g4x_single_channel_lvds;
7930         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI) ||
7931                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
7932                 limit = &intel_limits_g4x_hdmi;
7933         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO)) {
7934                 limit = &intel_limits_g4x_sdvo;
7935         } else {
7936                 /* The option is for other outputs */
7937                 limit = &intel_limits_i9xx_sdvo;
7938         }
7939
7940         if (!crtc_state->clock_set &&
7941             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7942                                 refclk, NULL, &crtc_state->dpll)) {
7943                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7944                 return -EINVAL;
7945         }
7946
7947         i9xx_compute_dpll(crtc, crtc_state, NULL);
7948
7949         return 0;
7950 }
7951
7952 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
7953                                   struct intel_crtc_state *crtc_state)
7954 {
7955         struct drm_device *dev = crtc->base.dev;
7956         struct drm_i915_private *dev_priv = to_i915(dev);
7957         const struct intel_limit *limit;
7958         int refclk = 96000;
7959
7960         memset(&crtc_state->dpll_hw_state, 0,
7961                sizeof(crtc_state->dpll_hw_state));
7962
7963         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7964                 if (intel_panel_use_ssc(dev_priv)) {
7965                         refclk = dev_priv->vbt.lvds_ssc_freq;
7966                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7967                 }
7968
7969                 limit = &intel_limits_pineview_lvds;
7970         } else {
7971                 limit = &intel_limits_pineview_sdvo;
7972         }
7973
7974         if (!crtc_state->clock_set &&
7975             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7976                                 refclk, NULL, &crtc_state->dpll)) {
7977                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7978                 return -EINVAL;
7979         }
7980
7981         i9xx_compute_dpll(crtc, crtc_state, NULL);
7982
7983         return 0;
7984 }
7985
7986 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7987                                    struct intel_crtc_state *crtc_state)
7988 {
7989         struct drm_device *dev = crtc->base.dev;
7990         struct drm_i915_private *dev_priv = to_i915(dev);
7991         const struct intel_limit *limit;
7992         int refclk = 96000;
7993
7994         memset(&crtc_state->dpll_hw_state, 0,
7995                sizeof(crtc_state->dpll_hw_state));
7996
7997         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7998                 if (intel_panel_use_ssc(dev_priv)) {
7999                         refclk = dev_priv->vbt.lvds_ssc_freq;
8000                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8001                 }
8002
8003                 limit = &intel_limits_i9xx_lvds;
8004         } else {
8005                 limit = &intel_limits_i9xx_sdvo;
8006         }
8007
8008         if (!crtc_state->clock_set &&
8009             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8010                                  refclk, NULL, &crtc_state->dpll)) {
8011                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8012                 return -EINVAL;
8013         }
8014
8015         i9xx_compute_dpll(crtc, crtc_state, NULL);
8016
8017         return 0;
8018 }
8019
8020 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
8021                                   struct intel_crtc_state *crtc_state)
8022 {
8023         int refclk = 100000;
8024         const struct intel_limit *limit = &intel_limits_chv;
8025
8026         memset(&crtc_state->dpll_hw_state, 0,
8027                sizeof(crtc_state->dpll_hw_state));
8028
8029         if (!crtc_state->clock_set &&
8030             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8031                                 refclk, NULL, &crtc_state->dpll)) {
8032                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8033                 return -EINVAL;
8034         }
8035
8036         chv_compute_dpll(crtc, crtc_state);
8037
8038         return 0;
8039 }
8040
8041 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
8042                                   struct intel_crtc_state *crtc_state)
8043 {
8044         int refclk = 100000;
8045         const struct intel_limit *limit = &intel_limits_vlv;
8046
8047         memset(&crtc_state->dpll_hw_state, 0,
8048                sizeof(crtc_state->dpll_hw_state));
8049
8050         if (!crtc_state->clock_set &&
8051             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8052                                 refclk, NULL, &crtc_state->dpll)) {
8053                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8054                 return -EINVAL;
8055         }
8056
8057         vlv_compute_dpll(crtc, crtc_state);
8058
8059         return 0;
8060 }
8061
8062 static bool i9xx_has_pfit(struct drm_i915_private *dev_priv)
8063 {
8064         if (IS_I830(dev_priv))
8065                 return false;
8066
8067         return INTEL_GEN(dev_priv) >= 4 ||
8068                 IS_PINEVIEW(dev_priv) || IS_MOBILE(dev_priv);
8069 }
8070
8071 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
8072                                  struct intel_crtc_state *pipe_config)
8073 {
8074         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8075         u32 tmp;
8076
8077         if (!i9xx_has_pfit(dev_priv))
8078                 return;
8079
8080         tmp = I915_READ(PFIT_CONTROL);
8081         if (!(tmp & PFIT_ENABLE))
8082                 return;
8083
8084         /* Check whether the pfit is attached to our pipe. */
8085         if (INTEL_GEN(dev_priv) < 4) {
8086                 if (crtc->pipe != PIPE_B)
8087                         return;
8088         } else {
8089                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
8090                         return;
8091         }
8092
8093         pipe_config->gmch_pfit.control = tmp;
8094         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
8095 }
8096
8097 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
8098                                struct intel_crtc_state *pipe_config)
8099 {
8100         struct drm_device *dev = crtc->base.dev;
8101         struct drm_i915_private *dev_priv = to_i915(dev);
8102         int pipe = pipe_config->cpu_transcoder;
8103         struct dpll clock;
8104         u32 mdiv;
8105         int refclk = 100000;
8106
8107         /* In case of DSI, DPLL will not be used */
8108         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
8109                 return;
8110
8111         vlv_dpio_get(dev_priv);
8112         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
8113         vlv_dpio_put(dev_priv);
8114
8115         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
8116         clock.m2 = mdiv & DPIO_M2DIV_MASK;
8117         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
8118         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
8119         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
8120
8121         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
8122 }
8123
8124 static void
8125 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
8126                               struct intel_initial_plane_config *plane_config)
8127 {
8128         struct drm_device *dev = crtc->base.dev;
8129         struct drm_i915_private *dev_priv = to_i915(dev);
8130         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
8131         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
8132         enum pipe pipe;
8133         u32 val, base, offset;
8134         int fourcc, pixel_format;
8135         unsigned int aligned_height;
8136         struct drm_framebuffer *fb;
8137         struct intel_framebuffer *intel_fb;
8138
8139         if (!plane->get_hw_state(plane, &pipe))
8140                 return;
8141
8142         WARN_ON(pipe != crtc->pipe);
8143
8144         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8145         if (!intel_fb) {
8146                 DRM_DEBUG_KMS("failed to alloc fb\n");
8147                 return;
8148         }
8149
8150         fb = &intel_fb->base;
8151
8152         fb->dev = dev;
8153
8154         val = I915_READ(DSPCNTR(i9xx_plane));
8155
8156         if (INTEL_GEN(dev_priv) >= 4) {
8157                 if (val & DISPPLANE_TILED) {
8158                         plane_config->tiling = I915_TILING_X;
8159                         fb->modifier = I915_FORMAT_MOD_X_TILED;
8160                 }
8161
8162                 if (val & DISPPLANE_ROTATE_180)
8163                         plane_config->rotation = DRM_MODE_ROTATE_180;
8164         }
8165
8166         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B &&
8167             val & DISPPLANE_MIRROR)
8168                 plane_config->rotation |= DRM_MODE_REFLECT_X;
8169
8170         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
8171         fourcc = i9xx_format_to_fourcc(pixel_format);
8172         fb->format = drm_format_info(fourcc);
8173
8174         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
8175                 offset = I915_READ(DSPOFFSET(i9xx_plane));
8176                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
8177         } else if (INTEL_GEN(dev_priv) >= 4) {
8178                 if (plane_config->tiling)
8179                         offset = I915_READ(DSPTILEOFF(i9xx_plane));
8180                 else
8181                         offset = I915_READ(DSPLINOFF(i9xx_plane));
8182                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
8183         } else {
8184                 base = I915_READ(DSPADDR(i9xx_plane));
8185         }
8186         plane_config->base = base;
8187
8188         val = I915_READ(PIPESRC(pipe));
8189         fb->width = ((val >> 16) & 0xfff) + 1;
8190         fb->height = ((val >> 0) & 0xfff) + 1;
8191
8192         val = I915_READ(DSPSTRIDE(i9xx_plane));
8193         fb->pitches[0] = val & 0xffffffc0;
8194
8195         aligned_height = intel_fb_align_height(fb, 0, fb->height);
8196
8197         plane_config->size = fb->pitches[0] * aligned_height;
8198
8199         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8200                       crtc->base.name, plane->base.name, fb->width, fb->height,
8201                       fb->format->cpp[0] * 8, base, fb->pitches[0],
8202                       plane_config->size);
8203
8204         plane_config->fb = intel_fb;
8205 }
8206
8207 static void chv_crtc_clock_get(struct intel_crtc *crtc,
8208                                struct intel_crtc_state *pipe_config)
8209 {
8210         struct drm_device *dev = crtc->base.dev;
8211         struct drm_i915_private *dev_priv = to_i915(dev);
8212         int pipe = pipe_config->cpu_transcoder;
8213         enum dpio_channel port = vlv_pipe_to_channel(pipe);
8214         struct dpll clock;
8215         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
8216         int refclk = 100000;
8217
8218         /* In case of DSI, DPLL will not be used */
8219         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
8220                 return;
8221
8222         vlv_dpio_get(dev_priv);
8223         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
8224         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
8225         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
8226         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
8227         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
8228         vlv_dpio_put(dev_priv);
8229
8230         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
8231         clock.m2 = (pll_dw0 & 0xff) << 22;
8232         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
8233                 clock.m2 |= pll_dw2 & 0x3fffff;
8234         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
8235         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
8236         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
8237
8238         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
8239 }
8240
8241 static void intel_get_crtc_ycbcr_config(struct intel_crtc *crtc,
8242                                         struct intel_crtc_state *pipe_config)
8243 {
8244         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8245         enum intel_output_format output = INTEL_OUTPUT_FORMAT_RGB;
8246
8247         pipe_config->lspcon_downsampling = false;
8248
8249         if (IS_BROADWELL(dev_priv) || INTEL_GEN(dev_priv) >= 9) {
8250                 u32 tmp = I915_READ(PIPEMISC(crtc->pipe));
8251
8252                 if (tmp & PIPEMISC_OUTPUT_COLORSPACE_YUV) {
8253                         bool ycbcr420_enabled = tmp & PIPEMISC_YUV420_ENABLE;
8254                         bool blend = tmp & PIPEMISC_YUV420_MODE_FULL_BLEND;
8255
8256                         if (ycbcr420_enabled) {
8257                                 /* We support 4:2:0 in full blend mode only */
8258                                 if (!blend)
8259                                         output = INTEL_OUTPUT_FORMAT_INVALID;
8260                                 else if (!(IS_GEMINILAKE(dev_priv) ||
8261                                            INTEL_GEN(dev_priv) >= 10))
8262                                         output = INTEL_OUTPUT_FORMAT_INVALID;
8263                                 else
8264                                         output = INTEL_OUTPUT_FORMAT_YCBCR420;
8265                         } else {
8266                                 /*
8267                                  * Currently there is no interface defined to
8268                                  * check user preference between RGB/YCBCR444
8269                                  * or YCBCR420. So the only possible case for
8270                                  * YCBCR444 usage is driving YCBCR420 output
8271                                  * with LSPCON, when pipe is configured for
8272                                  * YCBCR444 output and LSPCON takes care of
8273                                  * downsampling it.
8274                                  */
8275                                 pipe_config->lspcon_downsampling = true;
8276                                 output = INTEL_OUTPUT_FORMAT_YCBCR444;
8277                         }
8278                 }
8279         }
8280
8281         pipe_config->output_format = output;
8282 }
8283
8284 static void i9xx_get_pipe_color_config(struct intel_crtc_state *crtc_state)
8285 {
8286         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
8287         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
8288         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8289         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
8290         u32 tmp;
8291
8292         tmp = I915_READ(DSPCNTR(i9xx_plane));
8293
8294         if (tmp & DISPPLANE_GAMMA_ENABLE)
8295                 crtc_state->gamma_enable = true;
8296
8297         if (!HAS_GMCH(dev_priv) &&
8298             tmp & DISPPLANE_PIPE_CSC_ENABLE)
8299                 crtc_state->csc_enable = true;
8300 }
8301
8302 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
8303                                  struct intel_crtc_state *pipe_config)
8304 {
8305         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8306         enum intel_display_power_domain power_domain;
8307         intel_wakeref_t wakeref;
8308         u32 tmp;
8309         bool ret;
8310
8311         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8312         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
8313         if (!wakeref)
8314                 return false;
8315
8316         pipe_config->output_format = INTEL_OUTPUT_FORMAT_RGB;
8317         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8318         pipe_config->shared_dpll = NULL;
8319
8320         ret = false;
8321
8322         tmp = I915_READ(PIPECONF(crtc->pipe));
8323         if (!(tmp & PIPECONF_ENABLE))
8324                 goto out;
8325
8326         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
8327             IS_CHERRYVIEW(dev_priv)) {
8328                 switch (tmp & PIPECONF_BPC_MASK) {
8329                 case PIPECONF_6BPC:
8330                         pipe_config->pipe_bpp = 18;
8331                         break;
8332                 case PIPECONF_8BPC:
8333                         pipe_config->pipe_bpp = 24;
8334                         break;
8335                 case PIPECONF_10BPC:
8336                         pipe_config->pipe_bpp = 30;
8337                         break;
8338                 default:
8339                         break;
8340                 }
8341         }
8342
8343         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
8344             (tmp & PIPECONF_COLOR_RANGE_SELECT))
8345                 pipe_config->limited_color_range = true;
8346
8347         pipe_config->gamma_mode = (tmp & PIPECONF_GAMMA_MODE_MASK_I9XX) >>
8348                 PIPECONF_GAMMA_MODE_SHIFT;
8349
8350         if (IS_CHERRYVIEW(dev_priv))
8351                 pipe_config->cgm_mode = I915_READ(CGM_PIPE_MODE(crtc->pipe));
8352
8353         i9xx_get_pipe_color_config(pipe_config);
8354
8355         if (INTEL_GEN(dev_priv) < 4)
8356                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
8357
8358         intel_get_pipe_timings(crtc, pipe_config);
8359         intel_get_pipe_src_size(crtc, pipe_config);
8360
8361         i9xx_get_pfit_config(crtc, pipe_config);
8362
8363         if (INTEL_GEN(dev_priv) >= 4) {
8364                 /* No way to read it out on pipes B and C */
8365                 if (IS_CHERRYVIEW(dev_priv) && crtc->pipe != PIPE_A)
8366                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
8367                 else
8368                         tmp = I915_READ(DPLL_MD(crtc->pipe));
8369                 pipe_config->pixel_multiplier =
8370                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
8371                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
8372                 pipe_config->dpll_hw_state.dpll_md = tmp;
8373         } else if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
8374                    IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
8375                 tmp = I915_READ(DPLL(crtc->pipe));
8376                 pipe_config->pixel_multiplier =
8377                         ((tmp & SDVO_MULTIPLIER_MASK)
8378                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
8379         } else {
8380                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
8381                  * port and will be fixed up in the encoder->get_config
8382                  * function. */
8383                 pipe_config->pixel_multiplier = 1;
8384         }
8385         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
8386         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
8387                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
8388                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
8389         } else {
8390                 /* Mask out read-only status bits. */
8391                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
8392                                                      DPLL_PORTC_READY_MASK |
8393                                                      DPLL_PORTB_READY_MASK);
8394         }
8395
8396         if (IS_CHERRYVIEW(dev_priv))
8397                 chv_crtc_clock_get(crtc, pipe_config);
8398         else if (IS_VALLEYVIEW(dev_priv))
8399                 vlv_crtc_clock_get(crtc, pipe_config);
8400         else
8401                 i9xx_crtc_clock_get(crtc, pipe_config);
8402
8403         /*
8404          * Normally the dotclock is filled in by the encoder .get_config()
8405          * but in case the pipe is enabled w/o any ports we need a sane
8406          * default.
8407          */
8408         pipe_config->base.adjusted_mode.crtc_clock =
8409                 pipe_config->port_clock / pipe_config->pixel_multiplier;
8410
8411         ret = true;
8412
8413 out:
8414         intel_display_power_put(dev_priv, power_domain, wakeref);
8415
8416         return ret;
8417 }
8418
8419 static void ironlake_init_pch_refclk(struct drm_i915_private *dev_priv)
8420 {
8421         struct intel_encoder *encoder;
8422         int i;
8423         u32 val, final;
8424         bool has_lvds = false;
8425         bool has_cpu_edp = false;
8426         bool has_panel = false;
8427         bool has_ck505 = false;
8428         bool can_ssc = false;
8429         bool using_ssc_source = false;
8430
8431         /* We need to take the global config into account */
8432         for_each_intel_encoder(&dev_priv->drm, encoder) {
8433                 switch (encoder->type) {
8434                 case INTEL_OUTPUT_LVDS:
8435                         has_panel = true;
8436                         has_lvds = true;
8437                         break;
8438                 case INTEL_OUTPUT_EDP:
8439                         has_panel = true;
8440                         if (encoder->port == PORT_A)
8441                                 has_cpu_edp = true;
8442                         break;
8443                 default:
8444                         break;
8445                 }
8446         }
8447
8448         if (HAS_PCH_IBX(dev_priv)) {
8449                 has_ck505 = dev_priv->vbt.display_clock_mode;
8450                 can_ssc = has_ck505;
8451         } else {
8452                 has_ck505 = false;
8453                 can_ssc = true;
8454         }
8455
8456         /* Check if any DPLLs are using the SSC source */
8457         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
8458                 u32 temp = I915_READ(PCH_DPLL(i));
8459
8460                 if (!(temp & DPLL_VCO_ENABLE))
8461                         continue;
8462
8463                 if ((temp & PLL_REF_INPUT_MASK) ==
8464                     PLLB_REF_INPUT_SPREADSPECTRUMIN) {
8465                         using_ssc_source = true;
8466                         break;
8467                 }
8468         }
8469
8470         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d using_ssc_source %d\n",
8471                       has_panel, has_lvds, has_ck505, using_ssc_source);
8472
8473         /* Ironlake: try to setup display ref clock before DPLL
8474          * enabling. This is only under driver's control after
8475          * PCH B stepping, previous chipset stepping should be
8476          * ignoring this setting.
8477          */
8478         val = I915_READ(PCH_DREF_CONTROL);
8479
8480         /* As we must carefully and slowly disable/enable each source in turn,
8481          * compute the final state we want first and check if we need to
8482          * make any changes at all.
8483          */
8484         final = val;
8485         final &= ~DREF_NONSPREAD_SOURCE_MASK;
8486         if (has_ck505)
8487                 final |= DREF_NONSPREAD_CK505_ENABLE;
8488         else
8489                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
8490
8491         final &= ~DREF_SSC_SOURCE_MASK;
8492         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8493         final &= ~DREF_SSC1_ENABLE;
8494
8495         if (has_panel) {
8496                 final |= DREF_SSC_SOURCE_ENABLE;
8497
8498                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
8499                         final |= DREF_SSC1_ENABLE;
8500
8501                 if (has_cpu_edp) {
8502                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
8503                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8504                         else
8505                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8506                 } else
8507                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8508         } else if (using_ssc_source) {
8509                 final |= DREF_SSC_SOURCE_ENABLE;
8510                 final |= DREF_SSC1_ENABLE;
8511         }
8512
8513         if (final == val)
8514                 return;
8515
8516         /* Always enable nonspread source */
8517         val &= ~DREF_NONSPREAD_SOURCE_MASK;
8518
8519         if (has_ck505)
8520                 val |= DREF_NONSPREAD_CK505_ENABLE;
8521         else
8522                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
8523
8524         if (has_panel) {
8525                 val &= ~DREF_SSC_SOURCE_MASK;
8526                 val |= DREF_SSC_SOURCE_ENABLE;
8527
8528                 /* SSC must be turned on before enabling the CPU output  */
8529                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8530                         DRM_DEBUG_KMS("Using SSC on panel\n");
8531                         val |= DREF_SSC1_ENABLE;
8532                 } else
8533                         val &= ~DREF_SSC1_ENABLE;
8534
8535                 /* Get SSC going before enabling the outputs */
8536                 I915_WRITE(PCH_DREF_CONTROL, val);
8537                 POSTING_READ(PCH_DREF_CONTROL);
8538                 udelay(200);
8539
8540                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8541
8542                 /* Enable CPU source on CPU attached eDP */
8543                 if (has_cpu_edp) {
8544                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8545                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
8546                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8547                         } else
8548                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8549                 } else
8550                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8551
8552                 I915_WRITE(PCH_DREF_CONTROL, val);
8553                 POSTING_READ(PCH_DREF_CONTROL);
8554                 udelay(200);
8555         } else {
8556                 DRM_DEBUG_KMS("Disabling CPU source output\n");
8557
8558                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8559
8560                 /* Turn off CPU output */
8561                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8562
8563                 I915_WRITE(PCH_DREF_CONTROL, val);
8564                 POSTING_READ(PCH_DREF_CONTROL);
8565                 udelay(200);
8566
8567                 if (!using_ssc_source) {
8568                         DRM_DEBUG_KMS("Disabling SSC source\n");
8569
8570                         /* Turn off the SSC source */
8571                         val &= ~DREF_SSC_SOURCE_MASK;
8572                         val |= DREF_SSC_SOURCE_DISABLE;
8573
8574                         /* Turn off SSC1 */
8575                         val &= ~DREF_SSC1_ENABLE;
8576
8577                         I915_WRITE(PCH_DREF_CONTROL, val);
8578                         POSTING_READ(PCH_DREF_CONTROL);
8579                         udelay(200);
8580                 }
8581         }
8582
8583         BUG_ON(val != final);
8584 }
8585
8586 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
8587 {
8588         u32 tmp;
8589
8590         tmp = I915_READ(SOUTH_CHICKEN2);
8591         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
8592         I915_WRITE(SOUTH_CHICKEN2, tmp);
8593
8594         if (wait_for_us(I915_READ(SOUTH_CHICKEN2) &
8595                         FDI_MPHY_IOSFSB_RESET_STATUS, 100))
8596                 DRM_ERROR("FDI mPHY reset assert timeout\n");
8597
8598         tmp = I915_READ(SOUTH_CHICKEN2);
8599         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
8600         I915_WRITE(SOUTH_CHICKEN2, tmp);
8601
8602         if (wait_for_us((I915_READ(SOUTH_CHICKEN2) &
8603                          FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
8604                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
8605 }
8606
8607 /* WaMPhyProgramming:hsw */
8608 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
8609 {
8610         u32 tmp;
8611
8612         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
8613         tmp &= ~(0xFF << 24);
8614         tmp |= (0x12 << 24);
8615         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
8616
8617         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
8618         tmp |= (1 << 11);
8619         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
8620
8621         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
8622         tmp |= (1 << 11);
8623         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
8624
8625         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
8626         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8627         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
8628
8629         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
8630         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8631         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
8632
8633         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
8634         tmp &= ~(7 << 13);
8635         tmp |= (5 << 13);
8636         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
8637
8638         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
8639         tmp &= ~(7 << 13);
8640         tmp |= (5 << 13);
8641         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
8642
8643         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
8644         tmp &= ~0xFF;
8645         tmp |= 0x1C;
8646         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
8647
8648         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
8649         tmp &= ~0xFF;
8650         tmp |= 0x1C;
8651         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
8652
8653         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
8654         tmp &= ~(0xFF << 16);
8655         tmp |= (0x1C << 16);
8656         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
8657
8658         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
8659         tmp &= ~(0xFF << 16);
8660         tmp |= (0x1C << 16);
8661         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
8662
8663         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8664         tmp |= (1 << 27);
8665         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8666
8667         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8668         tmp |= (1 << 27);
8669         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8670
8671         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8672         tmp &= ~(0xF << 28);
8673         tmp |= (4 << 28);
8674         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8675
8676         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
8677         tmp &= ~(0xF << 28);
8678         tmp |= (4 << 28);
8679         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
8680 }
8681
8682 /* Implements 3 different sequences from BSpec chapter "Display iCLK
8683  * Programming" based on the parameters passed:
8684  * - Sequence to enable CLKOUT_DP
8685  * - Sequence to enable CLKOUT_DP without spread
8686  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
8687  */
8688 static void lpt_enable_clkout_dp(struct drm_i915_private *dev_priv,
8689                                  bool with_spread, bool with_fdi)
8690 {
8691         u32 reg, tmp;
8692
8693         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
8694                 with_spread = true;
8695         if (WARN(HAS_PCH_LPT_LP(dev_priv) &&
8696             with_fdi, "LP PCH doesn't have FDI\n"))
8697                 with_fdi = false;
8698
8699         mutex_lock(&dev_priv->sb_lock);
8700
8701         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8702         tmp &= ~SBI_SSCCTL_DISABLE;
8703         tmp |= SBI_SSCCTL_PATHALT;
8704         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8705
8706         udelay(24);
8707
8708         if (with_spread) {
8709                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8710                 tmp &= ~SBI_SSCCTL_PATHALT;
8711                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8712
8713                 if (with_fdi) {
8714                         lpt_reset_fdi_mphy(dev_priv);
8715                         lpt_program_fdi_mphy(dev_priv);
8716                 }
8717         }
8718
8719         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
8720         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8721         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8722         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8723
8724         mutex_unlock(&dev_priv->sb_lock);
8725 }
8726
8727 /* Sequence to disable CLKOUT_DP */
8728 static void lpt_disable_clkout_dp(struct drm_i915_private *dev_priv)
8729 {
8730         u32 reg, tmp;
8731
8732         mutex_lock(&dev_priv->sb_lock);
8733
8734         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
8735         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8736         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8737         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8738
8739         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8740         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8741                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8742                         tmp |= SBI_SSCCTL_PATHALT;
8743                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8744                         udelay(32);
8745                 }
8746                 tmp |= SBI_SSCCTL_DISABLE;
8747                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8748         }
8749
8750         mutex_unlock(&dev_priv->sb_lock);
8751 }
8752
8753 #define BEND_IDX(steps) ((50 + (steps)) / 5)
8754
8755 static const u16 sscdivintphase[] = {
8756         [BEND_IDX( 50)] = 0x3B23,
8757         [BEND_IDX( 45)] = 0x3B23,
8758         [BEND_IDX( 40)] = 0x3C23,
8759         [BEND_IDX( 35)] = 0x3C23,
8760         [BEND_IDX( 30)] = 0x3D23,
8761         [BEND_IDX( 25)] = 0x3D23,
8762         [BEND_IDX( 20)] = 0x3E23,
8763         [BEND_IDX( 15)] = 0x3E23,
8764         [BEND_IDX( 10)] = 0x3F23,
8765         [BEND_IDX(  5)] = 0x3F23,
8766         [BEND_IDX(  0)] = 0x0025,
8767         [BEND_IDX( -5)] = 0x0025,
8768         [BEND_IDX(-10)] = 0x0125,
8769         [BEND_IDX(-15)] = 0x0125,
8770         [BEND_IDX(-20)] = 0x0225,
8771         [BEND_IDX(-25)] = 0x0225,
8772         [BEND_IDX(-30)] = 0x0325,
8773         [BEND_IDX(-35)] = 0x0325,
8774         [BEND_IDX(-40)] = 0x0425,
8775         [BEND_IDX(-45)] = 0x0425,
8776         [BEND_IDX(-50)] = 0x0525,
8777 };
8778
8779 /*
8780  * Bend CLKOUT_DP
8781  * steps -50 to 50 inclusive, in steps of 5
8782  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
8783  * change in clock period = -(steps / 10) * 5.787 ps
8784  */
8785 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
8786 {
8787         u32 tmp;
8788         int idx = BEND_IDX(steps);
8789
8790         if (WARN_ON(steps % 5 != 0))
8791                 return;
8792
8793         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
8794                 return;
8795
8796         mutex_lock(&dev_priv->sb_lock);
8797
8798         if (steps % 10 != 0)
8799                 tmp = 0xAAAAAAAB;
8800         else
8801                 tmp = 0x00000000;
8802         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
8803
8804         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
8805         tmp &= 0xffff0000;
8806         tmp |= sscdivintphase[idx];
8807         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
8808
8809         mutex_unlock(&dev_priv->sb_lock);
8810 }
8811
8812 #undef BEND_IDX
8813
8814 static void lpt_init_pch_refclk(struct drm_i915_private *dev_priv)
8815 {
8816         struct intel_encoder *encoder;
8817         bool has_vga = false;
8818
8819         for_each_intel_encoder(&dev_priv->drm, encoder) {
8820                 switch (encoder->type) {
8821                 case INTEL_OUTPUT_ANALOG:
8822                         has_vga = true;
8823                         break;
8824                 default:
8825                         break;
8826                 }
8827         }
8828
8829         if (has_vga) {
8830                 lpt_bend_clkout_dp(dev_priv, 0);
8831                 lpt_enable_clkout_dp(dev_priv, true, true);
8832         } else {
8833                 lpt_disable_clkout_dp(dev_priv);
8834         }
8835 }
8836
8837 /*
8838  * Initialize reference clocks when the driver loads
8839  */
8840 void intel_init_pch_refclk(struct drm_i915_private *dev_priv)
8841 {
8842         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv))
8843                 ironlake_init_pch_refclk(dev_priv);
8844         else if (HAS_PCH_LPT(dev_priv))
8845                 lpt_init_pch_refclk(dev_priv);
8846 }
8847
8848 static void ironlake_set_pipeconf(const struct intel_crtc_state *crtc_state)
8849 {
8850         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
8851         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8852         enum pipe pipe = crtc->pipe;
8853         u32 val;
8854
8855         val = 0;
8856
8857         switch (crtc_state->pipe_bpp) {
8858         case 18:
8859                 val |= PIPECONF_6BPC;
8860                 break;
8861         case 24:
8862                 val |= PIPECONF_8BPC;
8863                 break;
8864         case 30:
8865                 val |= PIPECONF_10BPC;
8866                 break;
8867         case 36:
8868                 val |= PIPECONF_12BPC;
8869                 break;
8870         default:
8871                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8872                 BUG();
8873         }
8874
8875         if (crtc_state->dither)
8876                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8877
8878         if (crtc_state->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8879                 val |= PIPECONF_INTERLACED_ILK;
8880         else
8881                 val |= PIPECONF_PROGRESSIVE;
8882
8883         if (crtc_state->limited_color_range)
8884                 val |= PIPECONF_COLOR_RANGE_SELECT;
8885
8886         val |= PIPECONF_GAMMA_MODE(crtc_state->gamma_mode);
8887
8888         I915_WRITE(PIPECONF(pipe), val);
8889         POSTING_READ(PIPECONF(pipe));
8890 }
8891
8892 static void haswell_set_pipeconf(const struct intel_crtc_state *crtc_state)
8893 {
8894         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
8895         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8896         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
8897         u32 val = 0;
8898
8899         if (IS_HASWELL(dev_priv) && crtc_state->dither)
8900                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8901
8902         if (crtc_state->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8903                 val |= PIPECONF_INTERLACED_ILK;
8904         else
8905                 val |= PIPECONF_PROGRESSIVE;
8906
8907         I915_WRITE(PIPECONF(cpu_transcoder), val);
8908         POSTING_READ(PIPECONF(cpu_transcoder));
8909 }
8910
8911 static void bdw_set_pipemisc(const struct intel_crtc_state *crtc_state)
8912 {
8913         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
8914         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8915         u32 val = 0;
8916
8917         switch (crtc_state->pipe_bpp) {
8918         case 18:
8919                 val |= PIPEMISC_DITHER_6_BPC;
8920                 break;
8921         case 24:
8922                 val |= PIPEMISC_DITHER_8_BPC;
8923                 break;
8924         case 30:
8925                 val |= PIPEMISC_DITHER_10_BPC;
8926                 break;
8927         case 36:
8928                 val |= PIPEMISC_DITHER_12_BPC;
8929                 break;
8930         default:
8931                 MISSING_CASE(crtc_state->pipe_bpp);
8932                 break;
8933         }
8934
8935         if (crtc_state->dither)
8936                 val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8937
8938         if (crtc_state->output_format == INTEL_OUTPUT_FORMAT_YCBCR420 ||
8939             crtc_state->output_format == INTEL_OUTPUT_FORMAT_YCBCR444)
8940                 val |= PIPEMISC_OUTPUT_COLORSPACE_YUV;
8941
8942         if (crtc_state->output_format == INTEL_OUTPUT_FORMAT_YCBCR420)
8943                 val |= PIPEMISC_YUV420_ENABLE |
8944                         PIPEMISC_YUV420_MODE_FULL_BLEND;
8945
8946         if (INTEL_GEN(dev_priv) >= 11 &&
8947             (crtc_state->active_planes & ~(icl_hdr_plane_mask() |
8948                                            BIT(PLANE_CURSOR))) == 0)
8949                 val |= PIPEMISC_HDR_MODE_PRECISION;
8950
8951         I915_WRITE(PIPEMISC(crtc->pipe), val);
8952 }
8953
8954 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8955 {
8956         /*
8957          * Account for spread spectrum to avoid
8958          * oversubscribing the link. Max center spread
8959          * is 2.5%; use 5% for safety's sake.
8960          */
8961         u32 bps = target_clock * bpp * 21 / 20;
8962         return DIV_ROUND_UP(bps, link_bw * 8);
8963 }
8964
8965 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8966 {
8967         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8968 }
8969
8970 static void ironlake_compute_dpll(struct intel_crtc *crtc,
8971                                   struct intel_crtc_state *crtc_state,
8972                                   struct dpll *reduced_clock)
8973 {
8974         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8975         u32 dpll, fp, fp2;
8976         int factor;
8977
8978         /* Enable autotuning of the PLL clock (if permissible) */
8979         factor = 21;
8980         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8981                 if ((intel_panel_use_ssc(dev_priv) &&
8982                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8983                     (HAS_PCH_IBX(dev_priv) &&
8984                      intel_is_dual_link_lvds(dev_priv)))
8985                         factor = 25;
8986         } else if (crtc_state->sdvo_tv_clock) {
8987                 factor = 20;
8988         }
8989
8990         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8991
8992         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8993                 fp |= FP_CB_TUNE;
8994
8995         if (reduced_clock) {
8996                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
8997
8998                 if (reduced_clock->m < factor * reduced_clock->n)
8999                         fp2 |= FP_CB_TUNE;
9000         } else {
9001                 fp2 = fp;
9002         }
9003
9004         dpll = 0;
9005
9006         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
9007                 dpll |= DPLLB_MODE_LVDS;
9008         else
9009                 dpll |= DPLLB_MODE_DAC_SERIAL;
9010
9011         dpll |= (crtc_state->pixel_multiplier - 1)
9012                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
9013
9014         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
9015             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
9016                 dpll |= DPLL_SDVO_HIGH_SPEED;
9017
9018         if (intel_crtc_has_dp_encoder(crtc_state))
9019                 dpll |= DPLL_SDVO_HIGH_SPEED;
9020
9021         /*
9022          * The high speed IO clock is only really required for
9023          * SDVO/HDMI/DP, but we also enable it for CRT to make it
9024          * possible to share the DPLL between CRT and HDMI. Enabling
9025          * the clock needlessly does no real harm, except use up a
9026          * bit of power potentially.
9027          *
9028          * We'll limit this to IVB with 3 pipes, since it has only two
9029          * DPLLs and so DPLL sharing is the only way to get three pipes
9030          * driving PCH ports at the same time. On SNB we could do this,
9031          * and potentially avoid enabling the second DPLL, but it's not
9032          * clear if it''s a win or loss power wise. No point in doing
9033          * this on ILK at all since it has a fixed DPLL<->pipe mapping.
9034          */
9035         if (INTEL_INFO(dev_priv)->num_pipes == 3 &&
9036             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG))
9037                 dpll |= DPLL_SDVO_HIGH_SPEED;
9038
9039         /* compute bitmask from p1 value */
9040         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
9041         /* also FPA1 */
9042         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
9043
9044         switch (crtc_state->dpll.p2) {
9045         case 5:
9046                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
9047                 break;
9048         case 7:
9049                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
9050                 break;
9051         case 10:
9052                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
9053                 break;
9054         case 14:
9055                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
9056                 break;
9057         }
9058
9059         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
9060             intel_panel_use_ssc(dev_priv))
9061                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
9062         else
9063                 dpll |= PLL_REF_INPUT_DREFCLK;
9064
9065         dpll |= DPLL_VCO_ENABLE;
9066
9067         crtc_state->dpll_hw_state.dpll = dpll;
9068         crtc_state->dpll_hw_state.fp0 = fp;
9069         crtc_state->dpll_hw_state.fp1 = fp2;
9070 }
9071
9072 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
9073                                        struct intel_crtc_state *crtc_state)
9074 {
9075         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9076         const struct intel_limit *limit;
9077         int refclk = 120000;
9078
9079         memset(&crtc_state->dpll_hw_state, 0,
9080                sizeof(crtc_state->dpll_hw_state));
9081
9082         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
9083         if (!crtc_state->has_pch_encoder)
9084                 return 0;
9085
9086         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
9087                 if (intel_panel_use_ssc(dev_priv)) {
9088                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
9089                                       dev_priv->vbt.lvds_ssc_freq);
9090                         refclk = dev_priv->vbt.lvds_ssc_freq;
9091                 }
9092
9093                 if (intel_is_dual_link_lvds(dev_priv)) {
9094                         if (refclk == 100000)
9095                                 limit = &intel_limits_ironlake_dual_lvds_100m;
9096                         else
9097                                 limit = &intel_limits_ironlake_dual_lvds;
9098                 } else {
9099                         if (refclk == 100000)
9100                                 limit = &intel_limits_ironlake_single_lvds_100m;
9101                         else
9102                                 limit = &intel_limits_ironlake_single_lvds;
9103                 }
9104         } else {
9105                 limit = &intel_limits_ironlake_dac;
9106         }
9107
9108         if (!crtc_state->clock_set &&
9109             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
9110                                 refclk, NULL, &crtc_state->dpll)) {
9111                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
9112                 return -EINVAL;
9113         }
9114
9115         ironlake_compute_dpll(crtc, crtc_state, NULL);
9116
9117         if (!intel_get_shared_dpll(crtc_state, NULL)) {
9118                 DRM_DEBUG_KMS("failed to find PLL for pipe %c\n",
9119                               pipe_name(crtc->pipe));
9120                 return -EINVAL;
9121         }
9122
9123         return 0;
9124 }
9125
9126 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
9127                                          struct intel_link_m_n *m_n)
9128 {
9129         struct drm_device *dev = crtc->base.dev;
9130         struct drm_i915_private *dev_priv = to_i915(dev);
9131         enum pipe pipe = crtc->pipe;
9132
9133         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
9134         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
9135         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
9136                 & ~TU_SIZE_MASK;
9137         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
9138         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
9139                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9140 }
9141
9142 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
9143                                          enum transcoder transcoder,
9144                                          struct intel_link_m_n *m_n,
9145                                          struct intel_link_m_n *m2_n2)
9146 {
9147         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9148         enum pipe pipe = crtc->pipe;
9149
9150         if (INTEL_GEN(dev_priv) >= 5) {
9151                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
9152                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
9153                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
9154                         & ~TU_SIZE_MASK;
9155                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
9156                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
9157                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9158
9159                 if (m2_n2 && transcoder_has_m2_n2(dev_priv, transcoder)) {
9160                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
9161                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
9162                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
9163                                         & ~TU_SIZE_MASK;
9164                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
9165                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
9166                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9167                 }
9168         } else {
9169                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
9170                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
9171                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
9172                         & ~TU_SIZE_MASK;
9173                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
9174                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
9175                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9176         }
9177 }
9178
9179 void intel_dp_get_m_n(struct intel_crtc *crtc,
9180                       struct intel_crtc_state *pipe_config)
9181 {
9182         if (pipe_config->has_pch_encoder)
9183                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
9184         else
9185                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9186                                              &pipe_config->dp_m_n,
9187                                              &pipe_config->dp_m2_n2);
9188 }
9189
9190 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
9191                                         struct intel_crtc_state *pipe_config)
9192 {
9193         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9194                                      &pipe_config->fdi_m_n, NULL);
9195 }
9196
9197 static void skylake_get_pfit_config(struct intel_crtc *crtc,
9198                                     struct intel_crtc_state *pipe_config)
9199 {
9200         struct drm_device *dev = crtc->base.dev;
9201         struct drm_i915_private *dev_priv = to_i915(dev);
9202         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
9203         u32 ps_ctrl = 0;
9204         int id = -1;
9205         int i;
9206
9207         /* find scaler attached to this pipe */
9208         for (i = 0; i < crtc->num_scalers; i++) {
9209                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
9210                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
9211                         id = i;
9212                         pipe_config->pch_pfit.enabled = true;
9213                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
9214                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
9215                         scaler_state->scalers[i].in_use = true;
9216                         break;
9217                 }
9218         }
9219
9220         scaler_state->scaler_id = id;
9221         if (id >= 0) {
9222                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
9223         } else {
9224                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
9225         }
9226 }
9227
9228 static void
9229 skylake_get_initial_plane_config(struct intel_crtc *crtc,
9230                                  struct intel_initial_plane_config *plane_config)
9231 {
9232         struct drm_device *dev = crtc->base.dev;
9233         struct drm_i915_private *dev_priv = to_i915(dev);
9234         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
9235         enum plane_id plane_id = plane->id;
9236         enum pipe pipe;
9237         u32 val, base, offset, stride_mult, tiling, alpha;
9238         int fourcc, pixel_format;
9239         unsigned int aligned_height;
9240         struct drm_framebuffer *fb;
9241         struct intel_framebuffer *intel_fb;
9242
9243         if (!plane->get_hw_state(plane, &pipe))
9244                 return;
9245
9246         WARN_ON(pipe != crtc->pipe);
9247
9248         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9249         if (!intel_fb) {
9250                 DRM_DEBUG_KMS("failed to alloc fb\n");
9251                 return;
9252         }
9253
9254         fb = &intel_fb->base;
9255
9256         fb->dev = dev;
9257
9258         val = I915_READ(PLANE_CTL(pipe, plane_id));
9259
9260         if (INTEL_GEN(dev_priv) >= 11)
9261                 pixel_format = val & ICL_PLANE_CTL_FORMAT_MASK;
9262         else
9263                 pixel_format = val & PLANE_CTL_FORMAT_MASK;
9264
9265         if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv)) {
9266                 alpha = I915_READ(PLANE_COLOR_CTL(pipe, plane_id));
9267                 alpha &= PLANE_COLOR_ALPHA_MASK;
9268         } else {
9269                 alpha = val & PLANE_CTL_ALPHA_MASK;
9270         }
9271
9272         fourcc = skl_format_to_fourcc(pixel_format,
9273                                       val & PLANE_CTL_ORDER_RGBX, alpha);
9274         fb->format = drm_format_info(fourcc);
9275
9276         tiling = val & PLANE_CTL_TILED_MASK;
9277         switch (tiling) {
9278         case PLANE_CTL_TILED_LINEAR:
9279                 fb->modifier = DRM_FORMAT_MOD_LINEAR;
9280                 break;
9281         case PLANE_CTL_TILED_X:
9282                 plane_config->tiling = I915_TILING_X;
9283                 fb->modifier = I915_FORMAT_MOD_X_TILED;
9284                 break;
9285         case PLANE_CTL_TILED_Y:
9286                 plane_config->tiling = I915_TILING_Y;
9287                 if (val & PLANE_CTL_RENDER_DECOMPRESSION_ENABLE)
9288                         fb->modifier = I915_FORMAT_MOD_Y_TILED_CCS;
9289                 else
9290                         fb->modifier = I915_FORMAT_MOD_Y_TILED;
9291                 break;
9292         case PLANE_CTL_TILED_YF:
9293                 if (val & PLANE_CTL_RENDER_DECOMPRESSION_ENABLE)
9294                         fb->modifier = I915_FORMAT_MOD_Yf_TILED_CCS;
9295                 else
9296                         fb->modifier = I915_FORMAT_MOD_Yf_TILED;
9297                 break;
9298         default:
9299                 MISSING_CASE(tiling);
9300                 goto error;
9301         }
9302
9303         /*
9304          * DRM_MODE_ROTATE_ is counter clockwise to stay compatible with Xrandr
9305          * while i915 HW rotation is clockwise, thats why this swapping.
9306          */
9307         switch (val & PLANE_CTL_ROTATE_MASK) {
9308         case PLANE_CTL_ROTATE_0:
9309                 plane_config->rotation = DRM_MODE_ROTATE_0;
9310                 break;
9311         case PLANE_CTL_ROTATE_90:
9312                 plane_config->rotation = DRM_MODE_ROTATE_270;
9313                 break;
9314         case PLANE_CTL_ROTATE_180:
9315                 plane_config->rotation = DRM_MODE_ROTATE_180;
9316                 break;
9317         case PLANE_CTL_ROTATE_270:
9318                 plane_config->rotation = DRM_MODE_ROTATE_90;
9319                 break;
9320         }
9321
9322         if (INTEL_GEN(dev_priv) >= 10 &&
9323             val & PLANE_CTL_FLIP_HORIZONTAL)
9324                 plane_config->rotation |= DRM_MODE_REFLECT_X;
9325
9326         base = I915_READ(PLANE_SURF(pipe, plane_id)) & 0xfffff000;
9327         plane_config->base = base;
9328
9329         offset = I915_READ(PLANE_OFFSET(pipe, plane_id));
9330
9331         val = I915_READ(PLANE_SIZE(pipe, plane_id));
9332         fb->height = ((val >> 16) & 0xfff) + 1;
9333         fb->width = ((val >> 0) & 0x1fff) + 1;
9334
9335         val = I915_READ(PLANE_STRIDE(pipe, plane_id));
9336         stride_mult = skl_plane_stride_mult(fb, 0, DRM_MODE_ROTATE_0);
9337         fb->pitches[0] = (val & 0x3ff) * stride_mult;
9338
9339         aligned_height = intel_fb_align_height(fb, 0, fb->height);
9340
9341         plane_config->size = fb->pitches[0] * aligned_height;
9342
9343         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9344                       crtc->base.name, plane->base.name, fb->width, fb->height,
9345                       fb->format->cpp[0] * 8, base, fb->pitches[0],
9346                       plane_config->size);
9347
9348         plane_config->fb = intel_fb;
9349         return;
9350
9351 error:
9352         kfree(intel_fb);
9353 }
9354
9355 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
9356                                      struct intel_crtc_state *pipe_config)
9357 {
9358         struct drm_device *dev = crtc->base.dev;
9359         struct drm_i915_private *dev_priv = to_i915(dev);
9360         u32 tmp;
9361
9362         tmp = I915_READ(PF_CTL(crtc->pipe));
9363
9364         if (tmp & PF_ENABLE) {
9365                 pipe_config->pch_pfit.enabled = true;
9366                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
9367                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
9368
9369                 /* We currently do not free assignements of panel fitters on
9370                  * ivb/hsw (since we don't use the higher upscaling modes which
9371                  * differentiates them) so just WARN about this case for now. */
9372                 if (IS_GEN(dev_priv, 7)) {
9373                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
9374                                 PF_PIPE_SEL_IVB(crtc->pipe));
9375                 }
9376         }
9377 }
9378
9379 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
9380                                      struct intel_crtc_state *pipe_config)
9381 {
9382         struct drm_device *dev = crtc->base.dev;
9383         struct drm_i915_private *dev_priv = to_i915(dev);
9384         enum intel_display_power_domain power_domain;
9385         intel_wakeref_t wakeref;
9386         u32 tmp;
9387         bool ret;
9388
9389         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9390         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
9391         if (!wakeref)
9392                 return false;
9393
9394         pipe_config->output_format = INTEL_OUTPUT_FORMAT_RGB;
9395         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9396         pipe_config->shared_dpll = NULL;
9397
9398         ret = false;
9399         tmp = I915_READ(PIPECONF(crtc->pipe));
9400         if (!(tmp & PIPECONF_ENABLE))
9401                 goto out;
9402
9403         switch (tmp & PIPECONF_BPC_MASK) {
9404         case PIPECONF_6BPC:
9405                 pipe_config->pipe_bpp = 18;
9406                 break;
9407         case PIPECONF_8BPC:
9408                 pipe_config->pipe_bpp = 24;
9409                 break;
9410         case PIPECONF_10BPC:
9411                 pipe_config->pipe_bpp = 30;
9412                 break;
9413         case PIPECONF_12BPC:
9414                 pipe_config->pipe_bpp = 36;
9415                 break;
9416         default:
9417                 break;
9418         }
9419
9420         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
9421                 pipe_config->limited_color_range = true;
9422
9423         pipe_config->gamma_mode = (tmp & PIPECONF_GAMMA_MODE_MASK_ILK) >>
9424                 PIPECONF_GAMMA_MODE_SHIFT;
9425
9426         pipe_config->csc_mode = I915_READ(PIPE_CSC_MODE(crtc->pipe));
9427
9428         i9xx_get_pipe_color_config(pipe_config);
9429
9430         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
9431                 struct intel_shared_dpll *pll;
9432                 enum intel_dpll_id pll_id;
9433
9434                 pipe_config->has_pch_encoder = true;
9435
9436                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
9437                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9438                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9439
9440                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9441
9442                 if (HAS_PCH_IBX(dev_priv)) {
9443                         /*
9444                          * The pipe->pch transcoder and pch transcoder->pll
9445                          * mapping is fixed.
9446                          */
9447                         pll_id = (enum intel_dpll_id) crtc->pipe;
9448                 } else {
9449                         tmp = I915_READ(PCH_DPLL_SEL);
9450                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
9451                                 pll_id = DPLL_ID_PCH_PLL_B;
9452                         else
9453                                 pll_id= DPLL_ID_PCH_PLL_A;
9454                 }
9455
9456                 pipe_config->shared_dpll =
9457                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
9458                 pll = pipe_config->shared_dpll;
9459
9460                 WARN_ON(!pll->info->funcs->get_hw_state(dev_priv, pll,
9461                                                 &pipe_config->dpll_hw_state));
9462
9463                 tmp = pipe_config->dpll_hw_state.dpll;
9464                 pipe_config->pixel_multiplier =
9465                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
9466                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
9467
9468                 ironlake_pch_clock_get(crtc, pipe_config);
9469         } else {
9470                 pipe_config->pixel_multiplier = 1;
9471         }
9472
9473         intel_get_pipe_timings(crtc, pipe_config);
9474         intel_get_pipe_src_size(crtc, pipe_config);
9475
9476         ironlake_get_pfit_config(crtc, pipe_config);
9477
9478         ret = true;
9479
9480 out:
9481         intel_display_power_put(dev_priv, power_domain, wakeref);
9482
9483         return ret;
9484 }
9485
9486 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
9487 {
9488         struct drm_device *dev = &dev_priv->drm;
9489         struct intel_crtc *crtc;
9490
9491         for_each_intel_crtc(dev, crtc)
9492                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
9493                      pipe_name(crtc->pipe));
9494
9495         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_CTL2),
9496                         "Display power well on\n");
9497         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
9498         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
9499         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
9500         I915_STATE_WARN(I915_READ(PP_STATUS(0)) & PP_ON, "Panel power on\n");
9501         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
9502              "CPU PWM1 enabled\n");
9503         if (IS_HASWELL(dev_priv))
9504                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
9505                      "CPU PWM2 enabled\n");
9506         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
9507              "PCH PWM1 enabled\n");
9508         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
9509              "Utility pin enabled\n");
9510         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
9511
9512         /*
9513          * In theory we can still leave IRQs enabled, as long as only the HPD
9514          * interrupts remain enabled. We used to check for that, but since it's
9515          * gen-specific and since we only disable LCPLL after we fully disable
9516          * the interrupts, the check below should be enough.
9517          */
9518         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
9519 }
9520
9521 static u32 hsw_read_dcomp(struct drm_i915_private *dev_priv)
9522 {
9523         if (IS_HASWELL(dev_priv))
9524                 return I915_READ(D_COMP_HSW);
9525         else
9526                 return I915_READ(D_COMP_BDW);
9527 }
9528
9529 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, u32 val)
9530 {
9531         if (IS_HASWELL(dev_priv)) {
9532                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
9533                                             val))
9534                         DRM_DEBUG_KMS("Failed to write to D_COMP\n");
9535         } else {
9536                 I915_WRITE(D_COMP_BDW, val);
9537                 POSTING_READ(D_COMP_BDW);
9538         }
9539 }
9540
9541 /*
9542  * This function implements pieces of two sequences from BSpec:
9543  * - Sequence for display software to disable LCPLL
9544  * - Sequence for display software to allow package C8+
9545  * The steps implemented here are just the steps that actually touch the LCPLL
9546  * register. Callers should take care of disabling all the display engine
9547  * functions, doing the mode unset, fixing interrupts, etc.
9548  */
9549 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
9550                               bool switch_to_fclk, bool allow_power_down)
9551 {
9552         u32 val;
9553
9554         assert_can_disable_lcpll(dev_priv);
9555
9556         val = I915_READ(LCPLL_CTL);
9557
9558         if (switch_to_fclk) {
9559                 val |= LCPLL_CD_SOURCE_FCLK;
9560                 I915_WRITE(LCPLL_CTL, val);
9561
9562                 if (wait_for_us(I915_READ(LCPLL_CTL) &
9563                                 LCPLL_CD_SOURCE_FCLK_DONE, 1))
9564                         DRM_ERROR("Switching to FCLK failed\n");
9565
9566                 val = I915_READ(LCPLL_CTL);
9567         }
9568
9569         val |= LCPLL_PLL_DISABLE;
9570         I915_WRITE(LCPLL_CTL, val);
9571         POSTING_READ(LCPLL_CTL);
9572
9573         if (intel_wait_for_register(&dev_priv->uncore,
9574                                     LCPLL_CTL, LCPLL_PLL_LOCK, 0, 1))
9575                 DRM_ERROR("LCPLL still locked\n");
9576
9577         val = hsw_read_dcomp(dev_priv);
9578         val |= D_COMP_COMP_DISABLE;
9579         hsw_write_dcomp(dev_priv, val);
9580         ndelay(100);
9581
9582         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
9583                      1))
9584                 DRM_ERROR("D_COMP RCOMP still in progress\n");
9585
9586         if (allow_power_down) {
9587                 val = I915_READ(LCPLL_CTL);
9588                 val |= LCPLL_POWER_DOWN_ALLOW;
9589                 I915_WRITE(LCPLL_CTL, val);
9590                 POSTING_READ(LCPLL_CTL);
9591         }
9592 }
9593
9594 /*
9595  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
9596  * source.
9597  */
9598 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
9599 {
9600         u32 val;
9601
9602         val = I915_READ(LCPLL_CTL);
9603
9604         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
9605                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
9606                 return;
9607
9608         /*
9609          * Make sure we're not on PC8 state before disabling PC8, otherwise
9610          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
9611          */
9612         intel_uncore_forcewake_get(&dev_priv->uncore, FORCEWAKE_ALL);
9613
9614         if (val & LCPLL_POWER_DOWN_ALLOW) {
9615                 val &= ~LCPLL_POWER_DOWN_ALLOW;
9616                 I915_WRITE(LCPLL_CTL, val);
9617                 POSTING_READ(LCPLL_CTL);
9618         }
9619
9620         val = hsw_read_dcomp(dev_priv);
9621         val |= D_COMP_COMP_FORCE;
9622         val &= ~D_COMP_COMP_DISABLE;
9623         hsw_write_dcomp(dev_priv, val);
9624
9625         val = I915_READ(LCPLL_CTL);
9626         val &= ~LCPLL_PLL_DISABLE;
9627         I915_WRITE(LCPLL_CTL, val);
9628
9629         if (intel_wait_for_register(&dev_priv->uncore,
9630                                     LCPLL_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
9631                                     5))
9632                 DRM_ERROR("LCPLL not locked yet\n");
9633
9634         if (val & LCPLL_CD_SOURCE_FCLK) {
9635                 val = I915_READ(LCPLL_CTL);
9636                 val &= ~LCPLL_CD_SOURCE_FCLK;
9637                 I915_WRITE(LCPLL_CTL, val);
9638
9639                 if (wait_for_us((I915_READ(LCPLL_CTL) &
9640                                  LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9641                         DRM_ERROR("Switching back to LCPLL failed\n");
9642         }
9643
9644         intel_uncore_forcewake_put(&dev_priv->uncore, FORCEWAKE_ALL);
9645
9646         intel_update_cdclk(dev_priv);
9647         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
9648 }
9649
9650 /*
9651  * Package states C8 and deeper are really deep PC states that can only be
9652  * reached when all the devices on the system allow it, so even if the graphics
9653  * device allows PC8+, it doesn't mean the system will actually get to these
9654  * states. Our driver only allows PC8+ when going into runtime PM.
9655  *
9656  * The requirements for PC8+ are that all the outputs are disabled, the power
9657  * well is disabled and most interrupts are disabled, and these are also
9658  * requirements for runtime PM. When these conditions are met, we manually do
9659  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
9660  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
9661  * hang the machine.
9662  *
9663  * When we really reach PC8 or deeper states (not just when we allow it) we lose
9664  * the state of some registers, so when we come back from PC8+ we need to
9665  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
9666  * need to take care of the registers kept by RC6. Notice that this happens even
9667  * if we don't put the device in PCI D3 state (which is what currently happens
9668  * because of the runtime PM support).
9669  *
9670  * For more, read "Display Sequences for Package C8" on the hardware
9671  * documentation.
9672  */
9673 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
9674 {
9675         u32 val;
9676
9677         DRM_DEBUG_KMS("Enabling package C8+\n");
9678
9679         if (HAS_PCH_LPT_LP(dev_priv)) {
9680                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9681                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
9682                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9683         }
9684
9685         lpt_disable_clkout_dp(dev_priv);
9686         hsw_disable_lcpll(dev_priv, true, true);
9687 }
9688
9689 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
9690 {
9691         u32 val;
9692
9693         DRM_DEBUG_KMS("Disabling package C8+\n");
9694
9695         hsw_restore_lcpll(dev_priv);
9696         lpt_init_pch_refclk(dev_priv);
9697
9698         if (HAS_PCH_LPT_LP(dev_priv)) {
9699                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9700                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
9701                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9702         }
9703 }
9704
9705 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9706                                       struct intel_crtc_state *crtc_state)
9707 {
9708         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9709         struct intel_atomic_state *state =
9710                 to_intel_atomic_state(crtc_state->base.state);
9711
9712         if (!intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DSI) ||
9713             INTEL_GEN(dev_priv) >= 11) {
9714                 struct intel_encoder *encoder =
9715                         intel_get_crtc_new_encoder(state, crtc_state);
9716
9717                 if (!intel_get_shared_dpll(crtc_state, encoder)) {
9718                         DRM_DEBUG_KMS("failed to find PLL for pipe %c\n",
9719                                       pipe_name(crtc->pipe));
9720                         return -EINVAL;
9721                 }
9722         }
9723
9724         return 0;
9725 }
9726
9727 static void cannonlake_get_ddi_pll(struct drm_i915_private *dev_priv,
9728                                    enum port port,
9729                                    struct intel_crtc_state *pipe_config)
9730 {
9731         enum intel_dpll_id id;
9732         u32 temp;
9733
9734         temp = I915_READ(DPCLKA_CFGCR0) & DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
9735         id = temp >> DPCLKA_CFGCR0_DDI_CLK_SEL_SHIFT(port);
9736
9737         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL2))
9738                 return;
9739
9740         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9741 }
9742
9743 static void icelake_get_ddi_pll(struct drm_i915_private *dev_priv,
9744                                 enum port port,
9745                                 struct intel_crtc_state *pipe_config)
9746 {
9747         enum intel_dpll_id id;
9748         u32 temp;
9749
9750         /* TODO: TBT pll not implemented. */
9751         if (intel_port_is_combophy(dev_priv, port)) {
9752                 temp = I915_READ(DPCLKA_CFGCR0_ICL) &
9753                        DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
9754                 id = temp >> DPCLKA_CFGCR0_DDI_CLK_SEL_SHIFT(port);
9755         } else if (intel_port_is_tc(dev_priv, port)) {
9756                 id = icl_tc_port_to_pll_id(intel_port_to_tc(dev_priv, port));
9757         } else {
9758                 WARN(1, "Invalid port %x\n", port);
9759                 return;
9760         }
9761
9762         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9763 }
9764
9765 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9766                                 enum port port,
9767                                 struct intel_crtc_state *pipe_config)
9768 {
9769         enum intel_dpll_id id;
9770
9771         switch (port) {
9772         case PORT_A:
9773                 id = DPLL_ID_SKL_DPLL0;
9774                 break;
9775         case PORT_B:
9776                 id = DPLL_ID_SKL_DPLL1;
9777                 break;
9778         case PORT_C:
9779                 id = DPLL_ID_SKL_DPLL2;
9780                 break;
9781         default:
9782                 DRM_ERROR("Incorrect port type\n");
9783                 return;
9784         }
9785
9786         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9787 }
9788
9789 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9790                                 enum port port,
9791                                 struct intel_crtc_state *pipe_config)
9792 {
9793         enum intel_dpll_id id;
9794         u32 temp;
9795
9796         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9797         id = temp >> (port * 3 + 1);
9798
9799         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL3))
9800                 return;
9801
9802         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9803 }
9804
9805 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9806                                 enum port port,
9807                                 struct intel_crtc_state *pipe_config)
9808 {
9809         enum intel_dpll_id id;
9810         u32 ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9811
9812         switch (ddi_pll_sel) {
9813         case PORT_CLK_SEL_WRPLL1:
9814                 id = DPLL_ID_WRPLL1;
9815                 break;
9816         case PORT_CLK_SEL_WRPLL2:
9817                 id = DPLL_ID_WRPLL2;
9818                 break;
9819         case PORT_CLK_SEL_SPLL:
9820                 id = DPLL_ID_SPLL;
9821                 break;
9822         case PORT_CLK_SEL_LCPLL_810:
9823                 id = DPLL_ID_LCPLL_810;
9824                 break;
9825         case PORT_CLK_SEL_LCPLL_1350:
9826                 id = DPLL_ID_LCPLL_1350;
9827                 break;
9828         case PORT_CLK_SEL_LCPLL_2700:
9829                 id = DPLL_ID_LCPLL_2700;
9830                 break;
9831         default:
9832                 MISSING_CASE(ddi_pll_sel);
9833                 /* fall through */
9834         case PORT_CLK_SEL_NONE:
9835                 return;
9836         }
9837
9838         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9839 }
9840
9841 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
9842                                      struct intel_crtc_state *pipe_config,
9843                                      u64 *power_domain_mask,
9844                                      intel_wakeref_t *wakerefs)
9845 {
9846         struct drm_device *dev = crtc->base.dev;
9847         struct drm_i915_private *dev_priv = to_i915(dev);
9848         enum intel_display_power_domain power_domain;
9849         unsigned long panel_transcoder_mask = 0;
9850         unsigned long enabled_panel_transcoders = 0;
9851         enum transcoder panel_transcoder;
9852         intel_wakeref_t wf;
9853         u32 tmp;
9854
9855         if (INTEL_GEN(dev_priv) >= 11)
9856                 panel_transcoder_mask |=
9857                         BIT(TRANSCODER_DSI_0) | BIT(TRANSCODER_DSI_1);
9858
9859         if (HAS_TRANSCODER_EDP(dev_priv))
9860                 panel_transcoder_mask |= BIT(TRANSCODER_EDP);
9861
9862         /*
9863          * The pipe->transcoder mapping is fixed with the exception of the eDP
9864          * and DSI transcoders handled below.
9865          */
9866         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9867
9868         /*
9869          * XXX: Do intel_display_power_get_if_enabled before reading this (for
9870          * consistency and less surprising code; it's in always on power).
9871          */
9872         for_each_set_bit(panel_transcoder,
9873                          &panel_transcoder_mask,
9874                          ARRAY_SIZE(INTEL_INFO(dev_priv)->trans_offsets)) {
9875                 enum pipe trans_pipe;
9876
9877                 tmp = I915_READ(TRANS_DDI_FUNC_CTL(panel_transcoder));
9878                 if (!(tmp & TRANS_DDI_FUNC_ENABLE))
9879                         continue;
9880
9881                 /*
9882                  * Log all enabled ones, only use the first one.
9883                  *
9884                  * FIXME: This won't work for two separate DSI displays.
9885                  */
9886                 enabled_panel_transcoders |= BIT(panel_transcoder);
9887                 if (enabled_panel_transcoders != BIT(panel_transcoder))
9888                         continue;
9889
9890                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9891                 default:
9892                         WARN(1, "unknown pipe linked to transcoder %s\n",
9893                              transcoder_name(panel_transcoder));
9894                         /* fall through */
9895                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9896                 case TRANS_DDI_EDP_INPUT_A_ON:
9897                         trans_pipe = PIPE_A;
9898                         break;
9899                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
9900                         trans_pipe = PIPE_B;
9901                         break;
9902                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
9903                         trans_pipe = PIPE_C;
9904                         break;
9905                 }
9906
9907                 if (trans_pipe == crtc->pipe)
9908                         pipe_config->cpu_transcoder = panel_transcoder;
9909         }
9910
9911         /*
9912          * Valid combos: none, eDP, DSI0, DSI1, DSI0+DSI1
9913          */
9914         WARN_ON((enabled_panel_transcoders & BIT(TRANSCODER_EDP)) &&
9915                 enabled_panel_transcoders != BIT(TRANSCODER_EDP));
9916
9917         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
9918         WARN_ON(*power_domain_mask & BIT_ULL(power_domain));
9919
9920         wf = intel_display_power_get_if_enabled(dev_priv, power_domain);
9921         if (!wf)
9922                 return false;
9923
9924         wakerefs[power_domain] = wf;
9925         *power_domain_mask |= BIT_ULL(power_domain);
9926
9927         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
9928
9929         return tmp & PIPECONF_ENABLE;
9930 }
9931
9932 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
9933                                          struct intel_crtc_state *pipe_config,
9934                                          u64 *power_domain_mask,
9935                                          intel_wakeref_t *wakerefs)
9936 {
9937         struct drm_device *dev = crtc->base.dev;
9938         struct drm_i915_private *dev_priv = to_i915(dev);
9939         enum intel_display_power_domain power_domain;
9940         enum transcoder cpu_transcoder;
9941         intel_wakeref_t wf;
9942         enum port port;
9943         u32 tmp;
9944
9945         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
9946                 if (port == PORT_A)
9947                         cpu_transcoder = TRANSCODER_DSI_A;
9948                 else
9949                         cpu_transcoder = TRANSCODER_DSI_C;
9950
9951                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
9952                 WARN_ON(*power_domain_mask & BIT_ULL(power_domain));
9953
9954                 wf = intel_display_power_get_if_enabled(dev_priv, power_domain);
9955                 if (!wf)
9956                         continue;
9957
9958                 wakerefs[power_domain] = wf;
9959                 *power_domain_mask |= BIT_ULL(power_domain);
9960
9961                 /*
9962                  * The PLL needs to be enabled with a valid divider
9963                  * configuration, otherwise accessing DSI registers will hang
9964                  * the machine. See BSpec North Display Engine
9965                  * registers/MIPI[BXT]. We can break out here early, since we
9966                  * need the same DSI PLL to be enabled for both DSI ports.
9967                  */
9968                 if (!bxt_dsi_pll_is_enabled(dev_priv))
9969                         break;
9970
9971                 /* XXX: this works for video mode only */
9972                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
9973                 if (!(tmp & DPI_ENABLE))
9974                         continue;
9975
9976                 tmp = I915_READ(MIPI_CTRL(port));
9977                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
9978                         continue;
9979
9980                 pipe_config->cpu_transcoder = cpu_transcoder;
9981                 break;
9982         }
9983
9984         return transcoder_is_dsi(pipe_config->cpu_transcoder);
9985 }
9986
9987 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9988                                        struct intel_crtc_state *pipe_config)
9989 {
9990         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9991         struct intel_shared_dpll *pll;
9992         enum port port;
9993         u32 tmp;
9994
9995         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9996
9997         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9998
9999         if (INTEL_GEN(dev_priv) >= 11)
10000                 icelake_get_ddi_pll(dev_priv, port, pipe_config);
10001         else if (IS_CANNONLAKE(dev_priv))
10002                 cannonlake_get_ddi_pll(dev_priv, port, pipe_config);
10003         else if (IS_GEN9_BC(dev_priv))
10004                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
10005         else if (IS_GEN9_LP(dev_priv))
10006                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
10007         else
10008                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
10009
10010         pll = pipe_config->shared_dpll;
10011         if (pll) {
10012                 WARN_ON(!pll->info->funcs->get_hw_state(dev_priv, pll,
10013                                                 &pipe_config->dpll_hw_state));
10014         }
10015
10016         /*
10017          * Haswell has only FDI/PCH transcoder A. It is which is connected to
10018          * DDI E. So just check whether this pipe is wired to DDI E and whether
10019          * the PCH transcoder is on.
10020          */
10021         if (INTEL_GEN(dev_priv) < 9 &&
10022             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
10023                 pipe_config->has_pch_encoder = true;
10024
10025                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
10026                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
10027                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
10028
10029                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
10030         }
10031 }
10032
10033 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
10034                                     struct intel_crtc_state *pipe_config)
10035 {
10036         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10037         intel_wakeref_t wakerefs[POWER_DOMAIN_NUM], wf;
10038         enum intel_display_power_domain power_domain;
10039         u64 power_domain_mask;
10040         bool active;
10041
10042         intel_crtc_init_scalers(crtc, pipe_config);
10043
10044         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
10045         wf = intel_display_power_get_if_enabled(dev_priv, power_domain);
10046         if (!wf)
10047                 return false;
10048
10049         wakerefs[power_domain] = wf;
10050         power_domain_mask = BIT_ULL(power_domain);
10051
10052         pipe_config->shared_dpll = NULL;
10053
10054         active = hsw_get_transcoder_state(crtc, pipe_config,
10055                                           &power_domain_mask, wakerefs);
10056
10057         if (IS_GEN9_LP(dev_priv) &&
10058             bxt_get_dsi_transcoder_state(crtc, pipe_config,
10059                                          &power_domain_mask, wakerefs)) {
10060                 WARN_ON(active);
10061                 active = true;
10062         }
10063
10064         if (!active)
10065                 goto out;
10066
10067         if (!transcoder_is_dsi(pipe_config->cpu_transcoder) ||
10068             INTEL_GEN(dev_priv) >= 11) {
10069                 haswell_get_ddi_port_state(crtc, pipe_config);
10070                 intel_get_pipe_timings(crtc, pipe_config);
10071         }
10072
10073         intel_get_pipe_src_size(crtc, pipe_config);
10074         intel_get_crtc_ycbcr_config(crtc, pipe_config);
10075
10076         pipe_config->gamma_mode = I915_READ(GAMMA_MODE(crtc->pipe));
10077
10078         pipe_config->csc_mode = I915_READ(PIPE_CSC_MODE(crtc->pipe));
10079
10080         if (INTEL_GEN(dev_priv) >= 9) {
10081                 u32 tmp = I915_READ(SKL_BOTTOM_COLOR(crtc->pipe));
10082
10083                 if (tmp & SKL_BOTTOM_COLOR_GAMMA_ENABLE)
10084                         pipe_config->gamma_enable = true;
10085
10086                 if (tmp & SKL_BOTTOM_COLOR_CSC_ENABLE)
10087                         pipe_config->csc_enable = true;
10088         } else {
10089                 i9xx_get_pipe_color_config(pipe_config);
10090         }
10091
10092         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
10093         WARN_ON(power_domain_mask & BIT_ULL(power_domain));
10094
10095         wf = intel_display_power_get_if_enabled(dev_priv, power_domain);
10096         if (wf) {
10097                 wakerefs[power_domain] = wf;
10098                 power_domain_mask |= BIT_ULL(power_domain);
10099
10100                 if (INTEL_GEN(dev_priv) >= 9)
10101                         skylake_get_pfit_config(crtc, pipe_config);
10102                 else
10103                         ironlake_get_pfit_config(crtc, pipe_config);
10104         }
10105
10106         if (hsw_crtc_supports_ips(crtc)) {
10107                 if (IS_HASWELL(dev_priv))
10108                         pipe_config->ips_enabled = I915_READ(IPS_CTL) & IPS_ENABLE;
10109                 else {
10110                         /*
10111                          * We cannot readout IPS state on broadwell, set to
10112                          * true so we can set it to a defined state on first
10113                          * commit.
10114                          */
10115                         pipe_config->ips_enabled = true;
10116                 }
10117         }
10118
10119         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
10120             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
10121                 pipe_config->pixel_multiplier =
10122                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
10123         } else {
10124                 pipe_config->pixel_multiplier = 1;
10125         }
10126
10127 out:
10128         for_each_power_domain(power_domain, power_domain_mask)
10129                 intel_display_power_put(dev_priv,
10130                                         power_domain, wakerefs[power_domain]);
10131
10132         return active;
10133 }
10134
10135 static u32 intel_cursor_base(const struct intel_plane_state *plane_state)
10136 {
10137         struct drm_i915_private *dev_priv =
10138                 to_i915(plane_state->base.plane->dev);
10139         const struct drm_framebuffer *fb = plane_state->base.fb;
10140         const struct drm_i915_gem_object *obj = intel_fb_obj(fb);
10141         u32 base;
10142
10143         if (INTEL_INFO(dev_priv)->display.cursor_needs_physical)
10144                 base = obj->phys_handle->busaddr;
10145         else
10146                 base = intel_plane_ggtt_offset(plane_state);
10147
10148         base += plane_state->color_plane[0].offset;
10149
10150         /* ILK+ do this automagically */
10151         if (HAS_GMCH(dev_priv) &&
10152             plane_state->base.rotation & DRM_MODE_ROTATE_180)
10153                 base += (plane_state->base.crtc_h *
10154                          plane_state->base.crtc_w - 1) * fb->format->cpp[0];
10155
10156         return base;
10157 }
10158
10159 static u32 intel_cursor_position(const struct intel_plane_state *plane_state)
10160 {
10161         int x = plane_state->base.crtc_x;
10162         int y = plane_state->base.crtc_y;
10163         u32 pos = 0;
10164
10165         if (x < 0) {
10166                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
10167                 x = -x;
10168         }
10169         pos |= x << CURSOR_X_SHIFT;
10170
10171         if (y < 0) {
10172                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
10173                 y = -y;
10174         }
10175         pos |= y << CURSOR_Y_SHIFT;
10176
10177         return pos;
10178 }
10179
10180 static bool intel_cursor_size_ok(const struct intel_plane_state *plane_state)
10181 {
10182         const struct drm_mode_config *config =
10183                 &plane_state->base.plane->dev->mode_config;
10184         int width = plane_state->base.crtc_w;
10185         int height = plane_state->base.crtc_h;
10186
10187         return width > 0 && width <= config->cursor_width &&
10188                 height > 0 && height <= config->cursor_height;
10189 }
10190
10191 static int intel_cursor_check_surface(struct intel_plane_state *plane_state)
10192 {
10193         const struct drm_framebuffer *fb = plane_state->base.fb;
10194         unsigned int rotation = plane_state->base.rotation;
10195         int src_x, src_y;
10196         u32 offset;
10197         int ret;
10198
10199         intel_fill_fb_ggtt_view(&plane_state->view, fb, rotation);
10200         plane_state->color_plane[0].stride = intel_fb_pitch(fb, 0, rotation);
10201
10202         ret = intel_plane_check_stride(plane_state);
10203         if (ret)
10204                 return ret;
10205
10206         src_x = plane_state->base.src_x >> 16;
10207         src_y = plane_state->base.src_y >> 16;
10208
10209         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
10210         offset = intel_plane_compute_aligned_offset(&src_x, &src_y,
10211                                                     plane_state, 0);
10212
10213         if (src_x != 0 || src_y != 0) {
10214                 DRM_DEBUG_KMS("Arbitrary cursor panning not supported\n");
10215                 return -EINVAL;
10216         }
10217
10218         plane_state->color_plane[0].offset = offset;
10219
10220         return 0;
10221 }
10222
10223 static int intel_check_cursor(struct intel_crtc_state *crtc_state,
10224                               struct intel_plane_state *plane_state)
10225 {
10226         const struct drm_framebuffer *fb = plane_state->base.fb;
10227         int ret;
10228
10229         if (fb && fb->modifier != DRM_FORMAT_MOD_LINEAR) {
10230                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
10231                 return -EINVAL;
10232         }
10233
10234         ret = drm_atomic_helper_check_plane_state(&plane_state->base,
10235                                                   &crtc_state->base,
10236                                                   DRM_PLANE_HELPER_NO_SCALING,
10237                                                   DRM_PLANE_HELPER_NO_SCALING,
10238                                                   true, true);
10239         if (ret)
10240                 return ret;
10241
10242         if (!plane_state->base.visible)
10243                 return 0;
10244
10245         ret = intel_plane_check_src_coordinates(plane_state);
10246         if (ret)
10247                 return ret;
10248
10249         ret = intel_cursor_check_surface(plane_state);
10250         if (ret)
10251                 return ret;
10252
10253         return 0;
10254 }
10255
10256 static unsigned int
10257 i845_cursor_max_stride(struct intel_plane *plane,
10258                        u32 pixel_format, u64 modifier,
10259                        unsigned int rotation)
10260 {
10261         return 2048;
10262 }
10263
10264 static u32 i845_cursor_ctl_crtc(const struct intel_crtc_state *crtc_state)
10265 {
10266         u32 cntl = 0;
10267
10268         if (crtc_state->gamma_enable)
10269                 cntl |= CURSOR_GAMMA_ENABLE;
10270
10271         return cntl;
10272 }
10273
10274 static u32 i845_cursor_ctl(const struct intel_crtc_state *crtc_state,
10275                            const struct intel_plane_state *plane_state)
10276 {
10277         return CURSOR_ENABLE |
10278                 CURSOR_FORMAT_ARGB |
10279                 CURSOR_STRIDE(plane_state->color_plane[0].stride);
10280 }
10281
10282 static bool i845_cursor_size_ok(const struct intel_plane_state *plane_state)
10283 {
10284         int width = plane_state->base.crtc_w;
10285
10286         /*
10287          * 845g/865g are only limited by the width of their cursors,
10288          * the height is arbitrary up to the precision of the register.
10289          */
10290         return intel_cursor_size_ok(plane_state) && IS_ALIGNED(width, 64);
10291 }
10292
10293 static int i845_check_cursor(struct intel_crtc_state *crtc_state,
10294                              struct intel_plane_state *plane_state)
10295 {
10296         const struct drm_framebuffer *fb = plane_state->base.fb;
10297         int ret;
10298
10299         ret = intel_check_cursor(crtc_state, plane_state);
10300         if (ret)
10301                 return ret;
10302
10303         /* if we want to turn off the cursor ignore width and height */
10304         if (!fb)
10305                 return 0;
10306
10307         /* Check for which cursor types we support */
10308         if (!i845_cursor_size_ok(plane_state)) {
10309                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
10310                           plane_state->base.crtc_w,
10311                           plane_state->base.crtc_h);
10312                 return -EINVAL;
10313         }
10314
10315         WARN_ON(plane_state->base.visible &&
10316                 plane_state->color_plane[0].stride != fb->pitches[0]);
10317
10318         switch (fb->pitches[0]) {
10319         case 256:
10320         case 512:
10321         case 1024:
10322         case 2048:
10323                 break;
10324         default:
10325                 DRM_DEBUG_KMS("Invalid cursor stride (%u)\n",
10326                               fb->pitches[0]);
10327                 return -EINVAL;
10328         }
10329
10330         plane_state->ctl = i845_cursor_ctl(crtc_state, plane_state);
10331
10332         return 0;
10333 }
10334
10335 static void i845_update_cursor(struct intel_plane *plane,
10336                                const struct intel_crtc_state *crtc_state,
10337                                const struct intel_plane_state *plane_state)
10338 {
10339         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10340         u32 cntl = 0, base = 0, pos = 0, size = 0;
10341         unsigned long irqflags;
10342
10343         if (plane_state && plane_state->base.visible) {
10344                 unsigned int width = plane_state->base.crtc_w;
10345                 unsigned int height = plane_state->base.crtc_h;
10346
10347                 cntl = plane_state->ctl |
10348                         i845_cursor_ctl_crtc(crtc_state);
10349
10350                 size = (height << 12) | width;
10351
10352                 base = intel_cursor_base(plane_state);
10353                 pos = intel_cursor_position(plane_state);
10354         }
10355
10356         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
10357
10358         /* On these chipsets we can only modify the base/size/stride
10359          * whilst the cursor is disabled.
10360          */
10361         if (plane->cursor.base != base ||
10362             plane->cursor.size != size ||
10363             plane->cursor.cntl != cntl) {
10364                 I915_WRITE_FW(CURCNTR(PIPE_A), 0);
10365                 I915_WRITE_FW(CURBASE(PIPE_A), base);
10366                 I915_WRITE_FW(CURSIZE, size);
10367                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
10368                 I915_WRITE_FW(CURCNTR(PIPE_A), cntl);
10369
10370                 plane->cursor.base = base;
10371                 plane->cursor.size = size;
10372                 plane->cursor.cntl = cntl;
10373         } else {
10374                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
10375         }
10376
10377         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
10378 }
10379
10380 static void i845_disable_cursor(struct intel_plane *plane,
10381                                 const struct intel_crtc_state *crtc_state)
10382 {
10383         i845_update_cursor(plane, crtc_state, NULL);
10384 }
10385
10386 static bool i845_cursor_get_hw_state(struct intel_plane *plane,
10387                                      enum pipe *pipe)
10388 {
10389         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10390         enum intel_display_power_domain power_domain;
10391         intel_wakeref_t wakeref;
10392         bool ret;
10393
10394         power_domain = POWER_DOMAIN_PIPE(PIPE_A);
10395         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
10396         if (!wakeref)
10397                 return false;
10398
10399         ret = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
10400
10401         *pipe = PIPE_A;
10402
10403         intel_display_power_put(dev_priv, power_domain, wakeref);
10404
10405         return ret;
10406 }
10407
10408 static unsigned int
10409 i9xx_cursor_max_stride(struct intel_plane *plane,
10410                        u32 pixel_format, u64 modifier,
10411                        unsigned int rotation)
10412 {
10413         return plane->base.dev->mode_config.cursor_width * 4;
10414 }
10415
10416 static u32 i9xx_cursor_ctl_crtc(const struct intel_crtc_state *crtc_state)
10417 {
10418         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
10419         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10420         u32 cntl = 0;
10421
10422         if (INTEL_GEN(dev_priv) >= 11)
10423                 return cntl;
10424
10425         if (crtc_state->gamma_enable)
10426                 cntl = MCURSOR_GAMMA_ENABLE;
10427
10428         if (crtc_state->csc_enable)
10429                 cntl |= MCURSOR_PIPE_CSC_ENABLE;
10430
10431         if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10432                 cntl |= MCURSOR_PIPE_SELECT(crtc->pipe);
10433
10434         return cntl;
10435 }
10436
10437 static u32 i9xx_cursor_ctl(const struct intel_crtc_state *crtc_state,
10438                            const struct intel_plane_state *plane_state)
10439 {
10440         struct drm_i915_private *dev_priv =
10441                 to_i915(plane_state->base.plane->dev);
10442         u32 cntl = 0;
10443
10444         if (IS_GEN(dev_priv, 6) || IS_IVYBRIDGE(dev_priv))
10445                 cntl |= MCURSOR_TRICKLE_FEED_DISABLE;
10446
10447         switch (plane_state->base.crtc_w) {
10448         case 64:
10449                 cntl |= MCURSOR_MODE_64_ARGB_AX;
10450                 break;
10451         case 128:
10452                 cntl |= MCURSOR_MODE_128_ARGB_AX;
10453                 break;
10454         case 256:
10455                 cntl |= MCURSOR_MODE_256_ARGB_AX;
10456                 break;
10457         default:
10458                 MISSING_CASE(plane_state->base.crtc_w);
10459                 return 0;
10460         }
10461
10462         if (plane_state->base.rotation & DRM_MODE_ROTATE_180)
10463                 cntl |= MCURSOR_ROTATE_180;
10464
10465         return cntl;
10466 }
10467
10468 static bool i9xx_cursor_size_ok(const struct intel_plane_state *plane_state)
10469 {
10470         struct drm_i915_private *dev_priv =
10471                 to_i915(plane_state->base.plane->dev);
10472         int width = plane_state->base.crtc_w;
10473         int height = plane_state->base.crtc_h;
10474
10475         if (!intel_cursor_size_ok(plane_state))
10476                 return false;
10477
10478         /* Cursor width is limited to a few power-of-two sizes */
10479         switch (width) {
10480         case 256:
10481         case 128:
10482         case 64:
10483                 break;
10484         default:
10485                 return false;
10486         }
10487
10488         /*
10489          * IVB+ have CUR_FBC_CTL which allows an arbitrary cursor
10490          * height from 8 lines up to the cursor width, when the
10491          * cursor is not rotated. Everything else requires square
10492          * cursors.
10493          */
10494         if (HAS_CUR_FBC(dev_priv) &&
10495             plane_state->base.rotation & DRM_MODE_ROTATE_0) {
10496                 if (height < 8 || height > width)
10497                         return false;
10498         } else {
10499                 if (height != width)
10500                         return false;
10501         }
10502
10503         return true;
10504 }
10505
10506 static int i9xx_check_cursor(struct intel_crtc_state *crtc_state,
10507                              struct intel_plane_state *plane_state)
10508 {
10509         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
10510         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10511         const struct drm_framebuffer *fb = plane_state->base.fb;
10512         enum pipe pipe = plane->pipe;
10513         int ret;
10514
10515         ret = intel_check_cursor(crtc_state, plane_state);
10516         if (ret)
10517                 return ret;
10518
10519         /* if we want to turn off the cursor ignore width and height */
10520         if (!fb)
10521                 return 0;
10522
10523         /* Check for which cursor types we support */
10524         if (!i9xx_cursor_size_ok(plane_state)) {
10525                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
10526                           plane_state->base.crtc_w,
10527                           plane_state->base.crtc_h);
10528                 return -EINVAL;
10529         }
10530
10531         WARN_ON(plane_state->base.visible &&
10532                 plane_state->color_plane[0].stride != fb->pitches[0]);
10533
10534         if (fb->pitches[0] != plane_state->base.crtc_w * fb->format->cpp[0]) {
10535                 DRM_DEBUG_KMS("Invalid cursor stride (%u) (cursor width %d)\n",
10536                               fb->pitches[0], plane_state->base.crtc_w);
10537                 return -EINVAL;
10538         }
10539
10540         /*
10541          * There's something wrong with the cursor on CHV pipe C.
10542          * If it straddles the left edge of the screen then
10543          * moving it away from the edge or disabling it often
10544          * results in a pipe underrun, and often that can lead to
10545          * dead pipe (constant underrun reported, and it scans
10546          * out just a solid color). To recover from that, the
10547          * display power well must be turned off and on again.
10548          * Refuse the put the cursor into that compromised position.
10549          */
10550         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_C &&
10551             plane_state->base.visible && plane_state->base.crtc_x < 0) {
10552                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
10553                 return -EINVAL;
10554         }
10555
10556         plane_state->ctl = i9xx_cursor_ctl(crtc_state, plane_state);
10557
10558         return 0;
10559 }
10560
10561 static void i9xx_update_cursor(struct intel_plane *plane,
10562                                const struct intel_crtc_state *crtc_state,
10563                                const struct intel_plane_state *plane_state)
10564 {
10565         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10566         enum pipe pipe = plane->pipe;
10567         u32 cntl = 0, base = 0, pos = 0, fbc_ctl = 0;
10568         unsigned long irqflags;
10569
10570         if (plane_state && plane_state->base.visible) {
10571                 cntl = plane_state->ctl |
10572                         i9xx_cursor_ctl_crtc(crtc_state);
10573
10574                 if (plane_state->base.crtc_h != plane_state->base.crtc_w)
10575                         fbc_ctl = CUR_FBC_CTL_EN | (plane_state->base.crtc_h - 1);
10576
10577                 base = intel_cursor_base(plane_state);
10578                 pos = intel_cursor_position(plane_state);
10579         }
10580
10581         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
10582
10583         /*
10584          * On some platforms writing CURCNTR first will also
10585          * cause CURPOS to be armed by the CURBASE write.
10586          * Without the CURCNTR write the CURPOS write would
10587          * arm itself. Thus we always update CURCNTR before
10588          * CURPOS.
10589          *
10590          * On other platforms CURPOS always requires the
10591          * CURBASE write to arm the update. Additonally
10592          * a write to any of the cursor register will cancel
10593          * an already armed cursor update. Thus leaving out
10594          * the CURBASE write after CURPOS could lead to a
10595          * cursor that doesn't appear to move, or even change
10596          * shape. Thus we always write CURBASE.
10597          *
10598          * The other registers are armed by by the CURBASE write
10599          * except when the plane is getting enabled at which time
10600          * the CURCNTR write arms the update.
10601          */
10602
10603         if (INTEL_GEN(dev_priv) >= 9)
10604                 skl_write_cursor_wm(plane, crtc_state);
10605
10606         if (plane->cursor.base != base ||
10607             plane->cursor.size != fbc_ctl ||
10608             plane->cursor.cntl != cntl) {
10609                 if (HAS_CUR_FBC(dev_priv))
10610                         I915_WRITE_FW(CUR_FBC_CTL(pipe), fbc_ctl);
10611                 I915_WRITE_FW(CURCNTR(pipe), cntl);
10612                 I915_WRITE_FW(CURPOS(pipe), pos);
10613                 I915_WRITE_FW(CURBASE(pipe), base);
10614
10615                 plane->cursor.base = base;
10616                 plane->cursor.size = fbc_ctl;
10617                 plane->cursor.cntl = cntl;
10618         } else {
10619                 I915_WRITE_FW(CURPOS(pipe), pos);
10620                 I915_WRITE_FW(CURBASE(pipe), base);
10621         }
10622
10623         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
10624 }
10625
10626 static void i9xx_disable_cursor(struct intel_plane *plane,
10627                                 const struct intel_crtc_state *crtc_state)
10628 {
10629         i9xx_update_cursor(plane, crtc_state, NULL);
10630 }
10631
10632 static bool i9xx_cursor_get_hw_state(struct intel_plane *plane,
10633                                      enum pipe *pipe)
10634 {
10635         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10636         enum intel_display_power_domain power_domain;
10637         intel_wakeref_t wakeref;
10638         bool ret;
10639         u32 val;
10640
10641         /*
10642          * Not 100% correct for planes that can move between pipes,
10643          * but that's only the case for gen2-3 which don't have any
10644          * display power wells.
10645          */
10646         power_domain = POWER_DOMAIN_PIPE(plane->pipe);
10647         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
10648         if (!wakeref)
10649                 return false;
10650
10651         val = I915_READ(CURCNTR(plane->pipe));
10652
10653         ret = val & MCURSOR_MODE;
10654
10655         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
10656                 *pipe = plane->pipe;
10657         else
10658                 *pipe = (val & MCURSOR_PIPE_SELECT_MASK) >>
10659                         MCURSOR_PIPE_SELECT_SHIFT;
10660
10661         intel_display_power_put(dev_priv, power_domain, wakeref);
10662
10663         return ret;
10664 }
10665
10666 /* VESA 640x480x72Hz mode to set on the pipe */
10667 static const struct drm_display_mode load_detect_mode = {
10668         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10669                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10670 };
10671
10672 struct drm_framebuffer *
10673 intel_framebuffer_create(struct drm_i915_gem_object *obj,
10674                          struct drm_mode_fb_cmd2 *mode_cmd)
10675 {
10676         struct intel_framebuffer *intel_fb;
10677         int ret;
10678
10679         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10680         if (!intel_fb)
10681                 return ERR_PTR(-ENOMEM);
10682
10683         ret = intel_framebuffer_init(intel_fb, obj, mode_cmd);
10684         if (ret)
10685                 goto err;
10686
10687         return &intel_fb->base;
10688
10689 err:
10690         kfree(intel_fb);
10691         return ERR_PTR(ret);
10692 }
10693
10694 static int intel_modeset_disable_planes(struct drm_atomic_state *state,
10695                                         struct drm_crtc *crtc)
10696 {
10697         struct drm_plane *plane;
10698         struct drm_plane_state *plane_state;
10699         int ret, i;
10700
10701         ret = drm_atomic_add_affected_planes(state, crtc);
10702         if (ret)
10703                 return ret;
10704
10705         for_each_new_plane_in_state(state, plane, plane_state, i) {
10706                 if (plane_state->crtc != crtc)
10707                         continue;
10708
10709                 ret = drm_atomic_set_crtc_for_plane(plane_state, NULL);
10710                 if (ret)
10711                         return ret;
10712
10713                 drm_atomic_set_fb_for_plane(plane_state, NULL);
10714         }
10715
10716         return 0;
10717 }
10718
10719 int intel_get_load_detect_pipe(struct drm_connector *connector,
10720                                const struct drm_display_mode *mode,
10721                                struct intel_load_detect_pipe *old,
10722                                struct drm_modeset_acquire_ctx *ctx)
10723 {
10724         struct intel_crtc *intel_crtc;
10725         struct intel_encoder *intel_encoder =
10726                 intel_attached_encoder(connector);
10727         struct drm_crtc *possible_crtc;
10728         struct drm_encoder *encoder = &intel_encoder->base;
10729         struct drm_crtc *crtc = NULL;
10730         struct drm_device *dev = encoder->dev;
10731         struct drm_i915_private *dev_priv = to_i915(dev);
10732         struct drm_mode_config *config = &dev->mode_config;
10733         struct drm_atomic_state *state = NULL, *restore_state = NULL;
10734         struct drm_connector_state *connector_state;
10735         struct intel_crtc_state *crtc_state;
10736         int ret, i = -1;
10737
10738         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10739                       connector->base.id, connector->name,
10740                       encoder->base.id, encoder->name);
10741
10742         old->restore_state = NULL;
10743
10744         WARN_ON(!drm_modeset_is_locked(&config->connection_mutex));
10745
10746         /*
10747          * Algorithm gets a little messy:
10748          *
10749          *   - if the connector already has an assigned crtc, use it (but make
10750          *     sure it's on first)
10751          *
10752          *   - try to find the first unused crtc that can drive this connector,
10753          *     and use that if we find one
10754          */
10755
10756         /* See if we already have a CRTC for this connector */
10757         if (connector->state->crtc) {
10758                 crtc = connector->state->crtc;
10759
10760                 ret = drm_modeset_lock(&crtc->mutex, ctx);
10761                 if (ret)
10762                         goto fail;
10763
10764                 /* Make sure the crtc and connector are running */
10765                 goto found;
10766         }
10767
10768         /* Find an unused one (if possible) */
10769         for_each_crtc(dev, possible_crtc) {
10770                 i++;
10771                 if (!(encoder->possible_crtcs & (1 << i)))
10772                         continue;
10773
10774                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
10775                 if (ret)
10776                         goto fail;
10777
10778                 if (possible_crtc->state->enable) {
10779                         drm_modeset_unlock(&possible_crtc->mutex);
10780                         continue;
10781                 }
10782
10783                 crtc = possible_crtc;
10784                 break;
10785         }
10786
10787         /*
10788          * If we didn't find an unused CRTC, don't use any.
10789          */
10790         if (!crtc) {
10791                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
10792                 ret = -ENODEV;
10793                 goto fail;
10794         }
10795
10796 found:
10797         intel_crtc = to_intel_crtc(crtc);
10798
10799         state = drm_atomic_state_alloc(dev);
10800         restore_state = drm_atomic_state_alloc(dev);
10801         if (!state || !restore_state) {
10802                 ret = -ENOMEM;
10803                 goto fail;
10804         }
10805
10806         state->acquire_ctx = ctx;
10807         restore_state->acquire_ctx = ctx;
10808
10809         connector_state = drm_atomic_get_connector_state(state, connector);
10810         if (IS_ERR(connector_state)) {
10811                 ret = PTR_ERR(connector_state);
10812                 goto fail;
10813         }
10814
10815         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
10816         if (ret)
10817                 goto fail;
10818
10819         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10820         if (IS_ERR(crtc_state)) {
10821                 ret = PTR_ERR(crtc_state);
10822                 goto fail;
10823         }
10824
10825         crtc_state->base.active = crtc_state->base.enable = true;
10826
10827         if (!mode)
10828                 mode = &load_detect_mode;
10829
10830         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
10831         if (ret)
10832                 goto fail;
10833
10834         ret = intel_modeset_disable_planes(state, crtc);
10835         if (ret)
10836                 goto fail;
10837
10838         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
10839         if (!ret)
10840                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
10841         if (!ret)
10842                 ret = drm_atomic_add_affected_planes(restore_state, crtc);
10843         if (ret) {
10844                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
10845                 goto fail;
10846         }
10847
10848         ret = drm_atomic_commit(state);
10849         if (ret) {
10850                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
10851                 goto fail;
10852         }
10853
10854         old->restore_state = restore_state;
10855         drm_atomic_state_put(state);
10856
10857         /* let the connector get through one full cycle before testing */
10858         intel_wait_for_vblank(dev_priv, intel_crtc->pipe);
10859         return true;
10860
10861 fail:
10862         if (state) {
10863                 drm_atomic_state_put(state);
10864                 state = NULL;
10865         }
10866         if (restore_state) {
10867                 drm_atomic_state_put(restore_state);
10868                 restore_state = NULL;
10869         }
10870
10871         if (ret == -EDEADLK)
10872                 return ret;
10873
10874         return false;
10875 }
10876
10877 void intel_release_load_detect_pipe(struct drm_connector *connector,
10878                                     struct intel_load_detect_pipe *old,
10879                                     struct drm_modeset_acquire_ctx *ctx)
10880 {
10881         struct intel_encoder *intel_encoder =
10882                 intel_attached_encoder(connector);
10883         struct drm_encoder *encoder = &intel_encoder->base;
10884         struct drm_atomic_state *state = old->restore_state;
10885         int ret;
10886
10887         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10888                       connector->base.id, connector->name,
10889                       encoder->base.id, encoder->name);
10890
10891         if (!state)
10892                 return;
10893
10894         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
10895         if (ret)
10896                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
10897         drm_atomic_state_put(state);
10898 }
10899
10900 static int i9xx_pll_refclk(struct drm_device *dev,
10901                            const struct intel_crtc_state *pipe_config)
10902 {
10903         struct drm_i915_private *dev_priv = to_i915(dev);
10904         u32 dpll = pipe_config->dpll_hw_state.dpll;
10905
10906         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10907                 return dev_priv->vbt.lvds_ssc_freq;
10908         else if (HAS_PCH_SPLIT(dev_priv))
10909                 return 120000;
10910         else if (!IS_GEN(dev_priv, 2))
10911                 return 96000;
10912         else
10913                 return 48000;
10914 }
10915
10916 /* Returns the clock of the currently programmed mode of the given pipe. */
10917 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
10918                                 struct intel_crtc_state *pipe_config)
10919 {
10920         struct drm_device *dev = crtc->base.dev;
10921         struct drm_i915_private *dev_priv = to_i915(dev);
10922         int pipe = pipe_config->cpu_transcoder;
10923         u32 dpll = pipe_config->dpll_hw_state.dpll;
10924         u32 fp;
10925         struct dpll clock;
10926         int port_clock;
10927         int refclk = i9xx_pll_refclk(dev, pipe_config);
10928
10929         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10930                 fp = pipe_config->dpll_hw_state.fp0;
10931         else
10932                 fp = pipe_config->dpll_hw_state.fp1;
10933
10934         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10935         if (IS_PINEVIEW(dev_priv)) {
10936                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10937                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10938         } else {
10939                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10940                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10941         }
10942
10943         if (!IS_GEN(dev_priv, 2)) {
10944                 if (IS_PINEVIEW(dev_priv))
10945                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10946                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10947                 else
10948                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10949                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10950
10951                 switch (dpll & DPLL_MODE_MASK) {
10952                 case DPLLB_MODE_DAC_SERIAL:
10953                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10954                                 5 : 10;
10955                         break;
10956                 case DPLLB_MODE_LVDS:
10957                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10958                                 7 : 14;
10959                         break;
10960                 default:
10961                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10962                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10963                         return;
10964                 }
10965
10966                 if (IS_PINEVIEW(dev_priv))
10967                         port_clock = pnv_calc_dpll_params(refclk, &clock);
10968                 else
10969                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
10970         } else {
10971                 u32 lvds = IS_I830(dev_priv) ? 0 : I915_READ(LVDS);
10972                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10973
10974                 if (is_lvds) {
10975                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10976                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10977
10978                         if (lvds & LVDS_CLKB_POWER_UP)
10979                                 clock.p2 = 7;
10980                         else
10981                                 clock.p2 = 14;
10982                 } else {
10983                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10984                                 clock.p1 = 2;
10985                         else {
10986                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10987                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10988                         }
10989                         if (dpll & PLL_P2_DIVIDE_BY_4)
10990                                 clock.p2 = 4;
10991                         else
10992                                 clock.p2 = 2;
10993                 }
10994
10995                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10996         }
10997
10998         /*
10999          * This value includes pixel_multiplier. We will use
11000          * port_clock to compute adjusted_mode.crtc_clock in the
11001          * encoder's get_config() function.
11002          */
11003         pipe_config->port_clock = port_clock;
11004 }
11005
11006 int intel_dotclock_calculate(int link_freq,
11007                              const struct intel_link_m_n *m_n)
11008 {
11009         /*
11010          * The calculation for the data clock is:
11011          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
11012          * But we want to avoid losing precison if possible, so:
11013          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
11014          *
11015          * and the link clock is simpler:
11016          * link_clock = (m * link_clock) / n
11017          */
11018
11019         if (!m_n->link_n)
11020                 return 0;
11021
11022         return div_u64(mul_u32_u32(m_n->link_m, link_freq), m_n->link_n);
11023 }
11024
11025 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
11026                                    struct intel_crtc_state *pipe_config)
11027 {
11028         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11029
11030         /* read out port_clock from the DPLL */
11031         i9xx_crtc_clock_get(crtc, pipe_config);
11032
11033         /*
11034          * In case there is an active pipe without active ports,
11035          * we may need some idea for the dotclock anyway.
11036          * Calculate one based on the FDI configuration.
11037          */
11038         pipe_config->base.adjusted_mode.crtc_clock =
11039                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
11040                                          &pipe_config->fdi_m_n);
11041 }
11042
11043 /* Returns the currently programmed mode of the given encoder. */
11044 struct drm_display_mode *
11045 intel_encoder_current_mode(struct intel_encoder *encoder)
11046 {
11047         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
11048         struct intel_crtc_state *crtc_state;
11049         struct drm_display_mode *mode;
11050         struct intel_crtc *crtc;
11051         enum pipe pipe;
11052
11053         if (!encoder->get_hw_state(encoder, &pipe))
11054                 return NULL;
11055
11056         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
11057
11058         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
11059         if (!mode)
11060                 return NULL;
11061
11062         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
11063         if (!crtc_state) {
11064                 kfree(mode);
11065                 return NULL;
11066         }
11067
11068         crtc_state->base.crtc = &crtc->base;
11069
11070         if (!dev_priv->display.get_pipe_config(crtc, crtc_state)) {
11071                 kfree(crtc_state);
11072                 kfree(mode);
11073                 return NULL;
11074         }
11075
11076         encoder->get_config(encoder, crtc_state);
11077
11078         intel_mode_from_pipe_config(mode, crtc_state);
11079
11080         kfree(crtc_state);
11081
11082         return mode;
11083 }
11084
11085 static void intel_crtc_destroy(struct drm_crtc *crtc)
11086 {
11087         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11088
11089         drm_crtc_cleanup(crtc);
11090         kfree(intel_crtc);
11091 }
11092
11093 /**
11094  * intel_wm_need_update - Check whether watermarks need updating
11095  * @cur: current plane state
11096  * @new: new plane state
11097  *
11098  * Check current plane state versus the new one to determine whether
11099  * watermarks need to be recalculated.
11100  *
11101  * Returns true or false.
11102  */
11103 static bool intel_wm_need_update(struct intel_plane_state *cur,
11104                                  struct intel_plane_state *new)
11105 {
11106         /* Update watermarks on tiling or size changes. */
11107         if (new->base.visible != cur->base.visible)
11108                 return true;
11109
11110         if (!cur->base.fb || !new->base.fb)
11111                 return false;
11112
11113         if (cur->base.fb->modifier != new->base.fb->modifier ||
11114             cur->base.rotation != new->base.rotation ||
11115             drm_rect_width(&new->base.src) != drm_rect_width(&cur->base.src) ||
11116             drm_rect_height(&new->base.src) != drm_rect_height(&cur->base.src) ||
11117             drm_rect_width(&new->base.dst) != drm_rect_width(&cur->base.dst) ||
11118             drm_rect_height(&new->base.dst) != drm_rect_height(&cur->base.dst))
11119                 return true;
11120
11121         return false;
11122 }
11123
11124 static bool needs_scaling(const struct intel_plane_state *state)
11125 {
11126         int src_w = drm_rect_width(&state->base.src) >> 16;
11127         int src_h = drm_rect_height(&state->base.src) >> 16;
11128         int dst_w = drm_rect_width(&state->base.dst);
11129         int dst_h = drm_rect_height(&state->base.dst);
11130
11131         return (src_w != dst_w || src_h != dst_h);
11132 }
11133
11134 int intel_plane_atomic_calc_changes(const struct intel_crtc_state *old_crtc_state,
11135                                     struct drm_crtc_state *crtc_state,
11136                                     const struct intel_plane_state *old_plane_state,
11137                                     struct drm_plane_state *plane_state)
11138 {
11139         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
11140         struct drm_crtc *crtc = crtc_state->crtc;
11141         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11142         struct intel_plane *plane = to_intel_plane(plane_state->plane);
11143         struct drm_device *dev = crtc->dev;
11144         struct drm_i915_private *dev_priv = to_i915(dev);
11145         bool mode_changed = needs_modeset(crtc_state);
11146         bool was_crtc_enabled = old_crtc_state->base.active;
11147         bool is_crtc_enabled = crtc_state->active;
11148         bool turn_off, turn_on, visible, was_visible;
11149         struct drm_framebuffer *fb = plane_state->fb;
11150         int ret;
11151
11152         if (INTEL_GEN(dev_priv) >= 9 && plane->id != PLANE_CURSOR) {
11153                 ret = skl_update_scaler_plane(
11154                         to_intel_crtc_state(crtc_state),
11155                         to_intel_plane_state(plane_state));
11156                 if (ret)
11157                         return ret;
11158         }
11159
11160         was_visible = old_plane_state->base.visible;
11161         visible = plane_state->visible;
11162
11163         if (!was_crtc_enabled && WARN_ON(was_visible))
11164                 was_visible = false;
11165
11166         /*
11167          * Visibility is calculated as if the crtc was on, but
11168          * after scaler setup everything depends on it being off
11169          * when the crtc isn't active.
11170          *
11171          * FIXME this is wrong for watermarks. Watermarks should also
11172          * be computed as if the pipe would be active. Perhaps move
11173          * per-plane wm computation to the .check_plane() hook, and
11174          * only combine the results from all planes in the current place?
11175          */
11176         if (!is_crtc_enabled) {
11177                 plane_state->visible = visible = false;
11178                 to_intel_crtc_state(crtc_state)->active_planes &= ~BIT(plane->id);
11179         }
11180
11181         if (!was_visible && !visible)
11182                 return 0;
11183
11184         if (fb != old_plane_state->base.fb)
11185                 pipe_config->fb_changed = true;
11186
11187         turn_off = was_visible && (!visible || mode_changed);
11188         turn_on = visible && (!was_visible || mode_changed);
11189
11190         DRM_DEBUG_ATOMIC("[CRTC:%d:%s] has [PLANE:%d:%s] with fb %i\n",
11191                          intel_crtc->base.base.id, intel_crtc->base.name,
11192                          plane->base.base.id, plane->base.name,
11193                          fb ? fb->base.id : -1);
11194
11195         DRM_DEBUG_ATOMIC("[PLANE:%d:%s] visible %i -> %i, off %i, on %i, ms %i\n",
11196                          plane->base.base.id, plane->base.name,
11197                          was_visible, visible,
11198                          turn_off, turn_on, mode_changed);
11199
11200         if (turn_on) {
11201                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
11202                         pipe_config->update_wm_pre = true;
11203
11204                 /* must disable cxsr around plane enable/disable */
11205                 if (plane->id != PLANE_CURSOR)
11206                         pipe_config->disable_cxsr = true;
11207         } else if (turn_off) {
11208                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
11209                         pipe_config->update_wm_post = true;
11210
11211                 /* must disable cxsr around plane enable/disable */
11212                 if (plane->id != PLANE_CURSOR)
11213                         pipe_config->disable_cxsr = true;
11214         } else if (intel_wm_need_update(to_intel_plane_state(plane->base.state),
11215                                         to_intel_plane_state(plane_state))) {
11216                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
11217                         /* FIXME bollocks */
11218                         pipe_config->update_wm_pre = true;
11219                         pipe_config->update_wm_post = true;
11220                 }
11221         }
11222
11223         if (visible || was_visible)
11224                 pipe_config->fb_bits |= plane->frontbuffer_bit;
11225
11226         /*
11227          * ILK/SNB DVSACNTR/Sprite Enable
11228          * IVB SPR_CTL/Sprite Enable
11229          * "When in Self Refresh Big FIFO mode, a write to enable the
11230          *  plane will be internally buffered and delayed while Big FIFO
11231          *  mode is exiting."
11232          *
11233          * Which means that enabling the sprite can take an extra frame
11234          * when we start in big FIFO mode (LP1+). Thus we need to drop
11235          * down to LP0 and wait for vblank in order to make sure the
11236          * sprite gets enabled on the next vblank after the register write.
11237          * Doing otherwise would risk enabling the sprite one frame after
11238          * we've already signalled flip completion. We can resume LP1+
11239          * once the sprite has been enabled.
11240          *
11241          *
11242          * WaCxSRDisabledForSpriteScaling:ivb
11243          * IVB SPR_SCALE/Scaling Enable
11244          * "Low Power watermarks must be disabled for at least one
11245          *  frame before enabling sprite scaling, and kept disabled
11246          *  until sprite scaling is disabled."
11247          *
11248          * ILK/SNB DVSASCALE/Scaling Enable
11249          * "When in Self Refresh Big FIFO mode, scaling enable will be
11250          *  masked off while Big FIFO mode is exiting."
11251          *
11252          * Despite the w/a only being listed for IVB we assume that
11253          * the ILK/SNB note has similar ramifications, hence we apply
11254          * the w/a on all three platforms.
11255          *
11256          * With experimental results seems this is needed also for primary
11257          * plane, not only sprite plane.
11258          */
11259         if (plane->id != PLANE_CURSOR &&
11260             (IS_GEN_RANGE(dev_priv, 5, 6) ||
11261              IS_IVYBRIDGE(dev_priv)) &&
11262             (turn_on || (!needs_scaling(old_plane_state) &&
11263                          needs_scaling(to_intel_plane_state(plane_state)))))
11264                 pipe_config->disable_lp_wm = true;
11265
11266         return 0;
11267 }
11268
11269 static bool encoders_cloneable(const struct intel_encoder *a,
11270                                const struct intel_encoder *b)
11271 {
11272         /* masks could be asymmetric, so check both ways */
11273         return a == b || (a->cloneable & (1 << b->type) &&
11274                           b->cloneable & (1 << a->type));
11275 }
11276
11277 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
11278                                          struct intel_crtc *crtc,
11279                                          struct intel_encoder *encoder)
11280 {
11281         struct intel_encoder *source_encoder;
11282         struct drm_connector *connector;
11283         struct drm_connector_state *connector_state;
11284         int i;
11285
11286         for_each_new_connector_in_state(state, connector, connector_state, i) {
11287                 if (connector_state->crtc != &crtc->base)
11288                         continue;
11289
11290                 source_encoder =
11291                         to_intel_encoder(connector_state->best_encoder);
11292                 if (!encoders_cloneable(encoder, source_encoder))
11293                         return false;
11294         }
11295
11296         return true;
11297 }
11298
11299 static int icl_add_linked_planes(struct intel_atomic_state *state)
11300 {
11301         struct intel_plane *plane, *linked;
11302         struct intel_plane_state *plane_state, *linked_plane_state;
11303         int i;
11304
11305         for_each_new_intel_plane_in_state(state, plane, plane_state, i) {
11306                 linked = plane_state->linked_plane;
11307
11308                 if (!linked)
11309                         continue;
11310
11311                 linked_plane_state = intel_atomic_get_plane_state(state, linked);
11312                 if (IS_ERR(linked_plane_state))
11313                         return PTR_ERR(linked_plane_state);
11314
11315                 WARN_ON(linked_plane_state->linked_plane != plane);
11316                 WARN_ON(linked_plane_state->slave == plane_state->slave);
11317         }
11318
11319         return 0;
11320 }
11321
11322 static int icl_check_nv12_planes(struct intel_crtc_state *crtc_state)
11323 {
11324         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
11325         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11326         struct intel_atomic_state *state = to_intel_atomic_state(crtc_state->base.state);
11327         struct intel_plane *plane, *linked;
11328         struct intel_plane_state *plane_state;
11329         int i;
11330
11331         if (INTEL_GEN(dev_priv) < 11)
11332                 return 0;
11333
11334         /*
11335          * Destroy all old plane links and make the slave plane invisible
11336          * in the crtc_state->active_planes mask.
11337          */
11338         for_each_new_intel_plane_in_state(state, plane, plane_state, i) {
11339                 if (plane->pipe != crtc->pipe || !plane_state->linked_plane)
11340                         continue;
11341
11342                 plane_state->linked_plane = NULL;
11343                 if (plane_state->slave && !plane_state->base.visible) {
11344                         crtc_state->active_planes &= ~BIT(plane->id);
11345                         crtc_state->update_planes |= BIT(plane->id);
11346                 }
11347
11348                 plane_state->slave = false;
11349         }
11350
11351         if (!crtc_state->nv12_planes)
11352                 return 0;
11353
11354         for_each_new_intel_plane_in_state(state, plane, plane_state, i) {
11355                 struct intel_plane_state *linked_state = NULL;
11356
11357                 if (plane->pipe != crtc->pipe ||
11358                     !(crtc_state->nv12_planes & BIT(plane->id)))
11359                         continue;
11360
11361                 for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, linked) {
11362                         if (!icl_is_nv12_y_plane(linked->id))
11363                                 continue;
11364
11365                         if (crtc_state->active_planes & BIT(linked->id))
11366                                 continue;
11367
11368                         linked_state = intel_atomic_get_plane_state(state, linked);
11369                         if (IS_ERR(linked_state))
11370                                 return PTR_ERR(linked_state);
11371
11372                         break;
11373                 }
11374
11375                 if (!linked_state) {
11376                         DRM_DEBUG_KMS("Need %d free Y planes for planar YUV\n",
11377                                       hweight8(crtc_state->nv12_planes));
11378
11379                         return -EINVAL;
11380                 }
11381
11382                 plane_state->linked_plane = linked;
11383
11384                 linked_state->slave = true;
11385                 linked_state->linked_plane = plane;
11386                 crtc_state->active_planes |= BIT(linked->id);
11387                 crtc_state->update_planes |= BIT(linked->id);
11388                 DRM_DEBUG_KMS("Using %s as Y plane for %s\n", linked->base.name, plane->base.name);
11389         }
11390
11391         return 0;
11392 }
11393
11394 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
11395                                    struct drm_crtc_state *crtc_state)
11396 {
11397         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
11398         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11399         struct intel_crtc_state *pipe_config =
11400                 to_intel_crtc_state(crtc_state);
11401         int ret;
11402         bool mode_changed = needs_modeset(crtc_state);
11403
11404         if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv) &&
11405             mode_changed && !crtc_state->active)
11406                 pipe_config->update_wm_post = true;
11407
11408         if (mode_changed && crtc_state->enable &&
11409             dev_priv->display.crtc_compute_clock &&
11410             !WARN_ON(pipe_config->shared_dpll)) {
11411                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
11412                                                            pipe_config);
11413                 if (ret)
11414                         return ret;
11415         }
11416
11417         if (mode_changed || pipe_config->update_pipe ||
11418             crtc_state->color_mgmt_changed) {
11419                 ret = intel_color_check(pipe_config);
11420                 if (ret)
11421                         return ret;
11422         }
11423
11424         ret = 0;
11425         if (dev_priv->display.compute_pipe_wm) {
11426                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
11427                 if (ret) {
11428                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
11429                         return ret;
11430                 }
11431         }
11432
11433         if (dev_priv->display.compute_intermediate_wm) {
11434                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
11435                         return 0;
11436
11437                 /*
11438                  * Calculate 'intermediate' watermarks that satisfy both the
11439                  * old state and the new state.  We can program these
11440                  * immediately.
11441                  */
11442                 ret = dev_priv->display.compute_intermediate_wm(pipe_config);
11443                 if (ret) {
11444                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
11445                         return ret;
11446                 }
11447         }
11448
11449         if (INTEL_GEN(dev_priv) >= 9) {
11450                 if (mode_changed || pipe_config->update_pipe)
11451                         ret = skl_update_scaler_crtc(pipe_config);
11452
11453                 if (!ret)
11454                         ret = icl_check_nv12_planes(pipe_config);
11455                 if (!ret)
11456                         ret = skl_check_pipe_max_pixel_rate(intel_crtc,
11457                                                             pipe_config);
11458                 if (!ret)
11459                         ret = intel_atomic_setup_scalers(dev_priv, intel_crtc,
11460                                                          pipe_config);
11461         }
11462
11463         if (HAS_IPS(dev_priv))
11464                 pipe_config->ips_enabled = hsw_compute_ips_config(pipe_config);
11465
11466         return ret;
11467 }
11468
11469 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
11470         .atomic_check = intel_crtc_atomic_check,
11471 };
11472
11473 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
11474 {
11475         struct intel_connector *connector;
11476         struct drm_connector_list_iter conn_iter;
11477
11478         drm_connector_list_iter_begin(dev, &conn_iter);
11479         for_each_intel_connector_iter(connector, &conn_iter) {
11480                 if (connector->base.state->crtc)
11481                         drm_connector_put(&connector->base);
11482
11483                 if (connector->base.encoder) {
11484                         connector->base.state->best_encoder =
11485                                 connector->base.encoder;
11486                         connector->base.state->crtc =
11487                                 connector->base.encoder->crtc;
11488
11489                         drm_connector_get(&connector->base);
11490                 } else {
11491                         connector->base.state->best_encoder = NULL;
11492                         connector->base.state->crtc = NULL;
11493                 }
11494         }
11495         drm_connector_list_iter_end(&conn_iter);
11496 }
11497
11498 static int
11499 compute_sink_pipe_bpp(const struct drm_connector_state *conn_state,
11500                       struct intel_crtc_state *pipe_config)
11501 {
11502         struct drm_connector *connector = conn_state->connector;
11503         const struct drm_display_info *info = &connector->display_info;
11504         int bpp;
11505
11506         switch (conn_state->max_bpc) {
11507         case 6 ... 7:
11508                 bpp = 6 * 3;
11509                 break;
11510         case 8 ... 9:
11511                 bpp = 8 * 3;
11512                 break;
11513         case 10 ... 11:
11514                 bpp = 10 * 3;
11515                 break;
11516         case 12:
11517                 bpp = 12 * 3;
11518                 break;
11519         default:
11520                 return -EINVAL;
11521         }
11522
11523         if (bpp < pipe_config->pipe_bpp) {
11524                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] Limiting display bpp to %d instead of "
11525                               "EDID bpp %d, requested bpp %d, max platform bpp %d\n",
11526                               connector->base.id, connector->name,
11527                               bpp, 3 * info->bpc, 3 * conn_state->max_requested_bpc,
11528                               pipe_config->pipe_bpp);
11529
11530                 pipe_config->pipe_bpp = bpp;
11531         }
11532
11533         return 0;
11534 }
11535
11536 static int
11537 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
11538                           struct intel_crtc_state *pipe_config)
11539 {
11540         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11541         struct drm_atomic_state *state = pipe_config->base.state;
11542         struct drm_connector *connector;
11543         struct drm_connector_state *connector_state;
11544         int bpp, i;
11545
11546         if ((IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
11547             IS_CHERRYVIEW(dev_priv)))
11548                 bpp = 10*3;
11549         else if (INTEL_GEN(dev_priv) >= 5)
11550                 bpp = 12*3;
11551         else
11552                 bpp = 8*3;
11553
11554         pipe_config->pipe_bpp = bpp;
11555
11556         /* Clamp display bpp to connector max bpp */
11557         for_each_new_connector_in_state(state, connector, connector_state, i) {
11558                 int ret;
11559
11560                 if (connector_state->crtc != &crtc->base)
11561                         continue;
11562
11563                 ret = compute_sink_pipe_bpp(connector_state, pipe_config);
11564                 if (ret)
11565                         return ret;
11566         }
11567
11568         return 0;
11569 }
11570
11571 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
11572 {
11573         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
11574                         "type: 0x%x flags: 0x%x\n",
11575                 mode->crtc_clock,
11576                 mode->crtc_hdisplay, mode->crtc_hsync_start,
11577                 mode->crtc_hsync_end, mode->crtc_htotal,
11578                 mode->crtc_vdisplay, mode->crtc_vsync_start,
11579                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
11580 }
11581
11582 static inline void
11583 intel_dump_m_n_config(struct intel_crtc_state *pipe_config, char *id,
11584                       unsigned int lane_count, struct intel_link_m_n *m_n)
11585 {
11586         DRM_DEBUG_KMS("%s: lanes: %i; gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
11587                       id, lane_count,
11588                       m_n->gmch_m, m_n->gmch_n,
11589                       m_n->link_m, m_n->link_n, m_n->tu);
11590 }
11591
11592 static void
11593 intel_dump_infoframe(struct drm_i915_private *dev_priv,
11594                      const union hdmi_infoframe *frame)
11595 {
11596         if ((drm_debug & DRM_UT_KMS) == 0)
11597                 return;
11598
11599         hdmi_infoframe_log(KERN_DEBUG, dev_priv->drm.dev, frame);
11600 }
11601
11602 #define OUTPUT_TYPE(x) [INTEL_OUTPUT_ ## x] = #x
11603
11604 static const char * const output_type_str[] = {
11605         OUTPUT_TYPE(UNUSED),
11606         OUTPUT_TYPE(ANALOG),
11607         OUTPUT_TYPE(DVO),
11608         OUTPUT_TYPE(SDVO),
11609         OUTPUT_TYPE(LVDS),
11610         OUTPUT_TYPE(TVOUT),
11611         OUTPUT_TYPE(HDMI),
11612         OUTPUT_TYPE(DP),
11613         OUTPUT_TYPE(EDP),
11614         OUTPUT_TYPE(DSI),
11615         OUTPUT_TYPE(DDI),
11616         OUTPUT_TYPE(DP_MST),
11617 };
11618
11619 #undef OUTPUT_TYPE
11620
11621 static void snprintf_output_types(char *buf, size_t len,
11622                                   unsigned int output_types)
11623 {
11624         char *str = buf;
11625         int i;
11626
11627         str[0] = '\0';
11628
11629         for (i = 0; i < ARRAY_SIZE(output_type_str); i++) {
11630                 int r;
11631
11632                 if ((output_types & BIT(i)) == 0)
11633                         continue;
11634
11635                 r = snprintf(str, len, "%s%s",
11636                              str != buf ? "," : "", output_type_str[i]);
11637                 if (r >= len)
11638                         break;
11639                 str += r;
11640                 len -= r;
11641
11642                 output_types &= ~BIT(i);
11643         }
11644
11645         WARN_ON_ONCE(output_types != 0);
11646 }
11647
11648 static const char * const output_format_str[] = {
11649         [INTEL_OUTPUT_FORMAT_INVALID] = "Invalid",
11650         [INTEL_OUTPUT_FORMAT_RGB] = "RGB",
11651         [INTEL_OUTPUT_FORMAT_YCBCR420] = "YCBCR4:2:0",
11652         [INTEL_OUTPUT_FORMAT_YCBCR444] = "YCBCR4:4:4",
11653 };
11654
11655 static const char *output_formats(enum intel_output_format format)
11656 {
11657         if (format >= ARRAY_SIZE(output_format_str))
11658                 format = INTEL_OUTPUT_FORMAT_INVALID;
11659         return output_format_str[format];
11660 }
11661
11662 static void intel_dump_pipe_config(struct intel_crtc *crtc,
11663                                    struct intel_crtc_state *pipe_config,
11664                                    const char *context)
11665 {
11666         struct drm_device *dev = crtc->base.dev;
11667         struct drm_i915_private *dev_priv = to_i915(dev);
11668         struct drm_plane *plane;
11669         struct intel_plane *intel_plane;
11670         struct intel_plane_state *state;
11671         struct drm_framebuffer *fb;
11672         char buf[64];
11673
11674         DRM_DEBUG_KMS("[CRTC:%d:%s]%s\n",
11675                       crtc->base.base.id, crtc->base.name, context);
11676
11677         snprintf_output_types(buf, sizeof(buf), pipe_config->output_types);
11678         DRM_DEBUG_KMS("output_types: %s (0x%x)\n",
11679                       buf, pipe_config->output_types);
11680
11681         DRM_DEBUG_KMS("output format: %s\n",
11682                       output_formats(pipe_config->output_format));
11683
11684         DRM_DEBUG_KMS("cpu_transcoder: %s, pipe bpp: %i, dithering: %i\n",
11685                       transcoder_name(pipe_config->cpu_transcoder),
11686                       pipe_config->pipe_bpp, pipe_config->dither);
11687
11688         if (pipe_config->has_pch_encoder)
11689                 intel_dump_m_n_config(pipe_config, "fdi",
11690                                       pipe_config->fdi_lanes,
11691                                       &pipe_config->fdi_m_n);
11692
11693         if (intel_crtc_has_dp_encoder(pipe_config)) {
11694                 intel_dump_m_n_config(pipe_config, "dp m_n",
11695                                 pipe_config->lane_count, &pipe_config->dp_m_n);
11696                 if (pipe_config->has_drrs)
11697                         intel_dump_m_n_config(pipe_config, "dp m2_n2",
11698                                               pipe_config->lane_count,
11699                                               &pipe_config->dp_m2_n2);
11700         }
11701
11702         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
11703                       pipe_config->has_audio, pipe_config->has_infoframe);
11704
11705         DRM_DEBUG_KMS("infoframes enabled: 0x%x\n",
11706                       pipe_config->infoframes.enable);
11707
11708         if (pipe_config->infoframes.enable &
11709             intel_hdmi_infoframe_enable(HDMI_PACKET_TYPE_GENERAL_CONTROL))
11710                 DRM_DEBUG_KMS("GCP: 0x%x\n", pipe_config->infoframes.gcp);
11711         if (pipe_config->infoframes.enable &
11712             intel_hdmi_infoframe_enable(HDMI_INFOFRAME_TYPE_AVI))
11713                 intel_dump_infoframe(dev_priv, &pipe_config->infoframes.avi);
11714         if (pipe_config->infoframes.enable &
11715             intel_hdmi_infoframe_enable(HDMI_INFOFRAME_TYPE_SPD))
11716                 intel_dump_infoframe(dev_priv, &pipe_config->infoframes.spd);
11717         if (pipe_config->infoframes.enable &
11718             intel_hdmi_infoframe_enable(HDMI_INFOFRAME_TYPE_VENDOR))
11719                 intel_dump_infoframe(dev_priv, &pipe_config->infoframes.hdmi);
11720
11721         DRM_DEBUG_KMS("requested mode:\n");
11722         drm_mode_debug_printmodeline(&pipe_config->base.mode);
11723         DRM_DEBUG_KMS("adjusted mode:\n");
11724         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
11725         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
11726         DRM_DEBUG_KMS("port clock: %d, pipe src size: %dx%d, pixel rate %d\n",
11727                       pipe_config->port_clock,
11728                       pipe_config->pipe_src_w, pipe_config->pipe_src_h,
11729                       pipe_config->pixel_rate);
11730
11731         if (INTEL_GEN(dev_priv) >= 9)
11732                 DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
11733                               crtc->num_scalers,
11734                               pipe_config->scaler_state.scaler_users,
11735                               pipe_config->scaler_state.scaler_id);
11736
11737         if (HAS_GMCH(dev_priv))
11738                 DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
11739                               pipe_config->gmch_pfit.control,
11740                               pipe_config->gmch_pfit.pgm_ratios,
11741                               pipe_config->gmch_pfit.lvds_border_bits);
11742         else
11743                 DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
11744                               pipe_config->pch_pfit.pos,
11745                               pipe_config->pch_pfit.size,
11746                               enableddisabled(pipe_config->pch_pfit.enabled));
11747
11748         DRM_DEBUG_KMS("ips: %i, double wide: %i\n",
11749                       pipe_config->ips_enabled, pipe_config->double_wide);
11750
11751         intel_dpll_dump_hw_state(dev_priv, &pipe_config->dpll_hw_state);
11752
11753         DRM_DEBUG_KMS("planes on this crtc\n");
11754         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
11755                 struct drm_format_name_buf format_name;
11756                 intel_plane = to_intel_plane(plane);
11757                 if (intel_plane->pipe != crtc->pipe)
11758                         continue;
11759
11760                 state = to_intel_plane_state(plane->state);
11761                 fb = state->base.fb;
11762                 if (!fb) {
11763                         DRM_DEBUG_KMS("[PLANE:%d:%s] disabled, scaler_id = %d\n",
11764                                       plane->base.id, plane->name, state->scaler_id);
11765                         continue;
11766                 }
11767
11768                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d, fb = %ux%u format = %s\n",
11769                               plane->base.id, plane->name,
11770                               fb->base.id, fb->width, fb->height,
11771                               drm_get_format_name(fb->format->format, &format_name));
11772                 if (INTEL_GEN(dev_priv) >= 9)
11773                         DRM_DEBUG_KMS("\tscaler:%d src %dx%d+%d+%d dst %dx%d+%d+%d\n",
11774                                       state->scaler_id,
11775                                       state->base.src.x1 >> 16,
11776                                       state->base.src.y1 >> 16,
11777                                       drm_rect_width(&state->base.src) >> 16,
11778                                       drm_rect_height(&state->base.src) >> 16,
11779                                       state->base.dst.x1, state->base.dst.y1,
11780                                       drm_rect_width(&state->base.dst),
11781                                       drm_rect_height(&state->base.dst));
11782         }
11783 }
11784
11785 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
11786 {
11787         struct drm_device *dev = state->dev;
11788         struct drm_connector *connector;
11789         struct drm_connector_list_iter conn_iter;
11790         unsigned int used_ports = 0;
11791         unsigned int used_mst_ports = 0;
11792         bool ret = true;
11793
11794         /*
11795          * Walk the connector list instead of the encoder
11796          * list to detect the problem on ddi platforms
11797          * where there's just one encoder per digital port.
11798          */
11799         drm_connector_list_iter_begin(dev, &conn_iter);
11800         drm_for_each_connector_iter(connector, &conn_iter) {
11801                 struct drm_connector_state *connector_state;
11802                 struct intel_encoder *encoder;
11803
11804                 connector_state = drm_atomic_get_new_connector_state(state, connector);
11805                 if (!connector_state)
11806                         connector_state = connector->state;
11807
11808                 if (!connector_state->best_encoder)
11809                         continue;
11810
11811                 encoder = to_intel_encoder(connector_state->best_encoder);
11812
11813                 WARN_ON(!connector_state->crtc);
11814
11815                 switch (encoder->type) {
11816                         unsigned int port_mask;
11817                 case INTEL_OUTPUT_DDI:
11818                         if (WARN_ON(!HAS_DDI(to_i915(dev))))
11819                                 break;
11820                         /* else: fall through */
11821                 case INTEL_OUTPUT_DP:
11822                 case INTEL_OUTPUT_HDMI:
11823                 case INTEL_OUTPUT_EDP:
11824                         port_mask = 1 << encoder->port;
11825
11826                         /* the same port mustn't appear more than once */
11827                         if (used_ports & port_mask)
11828                                 ret = false;
11829
11830                         used_ports |= port_mask;
11831                         break;
11832                 case INTEL_OUTPUT_DP_MST:
11833                         used_mst_ports |=
11834                                 1 << encoder->port;
11835                         break;
11836                 default:
11837                         break;
11838                 }
11839         }
11840         drm_connector_list_iter_end(&conn_iter);
11841
11842         /* can't mix MST and SST/HDMI on the same port */
11843         if (used_ports & used_mst_ports)
11844                 return false;
11845
11846         return ret;
11847 }
11848
11849 static int
11850 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
11851 {
11852         struct drm_i915_private *dev_priv =
11853                 to_i915(crtc_state->base.crtc->dev);
11854         struct intel_crtc_state *saved_state;
11855
11856         saved_state = kzalloc(sizeof(*saved_state), GFP_KERNEL);
11857         if (!saved_state)
11858                 return -ENOMEM;
11859
11860         /* FIXME: before the switch to atomic started, a new pipe_config was
11861          * kzalloc'd. Code that depends on any field being zero should be
11862          * fixed, so that the crtc_state can be safely duplicated. For now,
11863          * only fields that are know to not cause problems are preserved. */
11864
11865         saved_state->scaler_state = crtc_state->scaler_state;
11866         saved_state->shared_dpll = crtc_state->shared_dpll;
11867         saved_state->dpll_hw_state = crtc_state->dpll_hw_state;
11868         saved_state->pch_pfit.force_thru = crtc_state->pch_pfit.force_thru;
11869         saved_state->crc_enabled = crtc_state->crc_enabled;
11870         if (IS_G4X(dev_priv) ||
11871             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11872                 saved_state->wm = crtc_state->wm;
11873
11874         /* Keep base drm_crtc_state intact, only clear our extended struct */
11875         BUILD_BUG_ON(offsetof(struct intel_crtc_state, base));
11876         memcpy(&crtc_state->base + 1, &saved_state->base + 1,
11877                sizeof(*crtc_state) - sizeof(crtc_state->base));
11878
11879         kfree(saved_state);
11880         return 0;
11881 }
11882
11883 static int
11884 intel_modeset_pipe_config(struct drm_crtc *crtc,
11885                           struct intel_crtc_state *pipe_config)
11886 {
11887         struct drm_atomic_state *state = pipe_config->base.state;
11888         struct intel_encoder *encoder;
11889         struct drm_connector *connector;
11890         struct drm_connector_state *connector_state;
11891         int base_bpp, ret;
11892         int i;
11893         bool retry = true;
11894
11895         ret = clear_intel_crtc_state(pipe_config);
11896         if (ret)
11897                 return ret;
11898
11899         pipe_config->cpu_transcoder =
11900                 (enum transcoder) to_intel_crtc(crtc)->pipe;
11901
11902         /*
11903          * Sanitize sync polarity flags based on requested ones. If neither
11904          * positive or negative polarity is requested, treat this as meaning
11905          * negative polarity.
11906          */
11907         if (!(pipe_config->base.adjusted_mode.flags &
11908               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
11909                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
11910
11911         if (!(pipe_config->base.adjusted_mode.flags &
11912               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
11913                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
11914
11915         ret = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
11916                                         pipe_config);
11917         if (ret)
11918                 return ret;
11919
11920         base_bpp = pipe_config->pipe_bpp;
11921
11922         /*
11923          * Determine the real pipe dimensions. Note that stereo modes can
11924          * increase the actual pipe size due to the frame doubling and
11925          * insertion of additional space for blanks between the frame. This
11926          * is stored in the crtc timings. We use the requested mode to do this
11927          * computation to clearly distinguish it from the adjusted mode, which
11928          * can be changed by the connectors in the below retry loop.
11929          */
11930         drm_mode_get_hv_timing(&pipe_config->base.mode,
11931                                &pipe_config->pipe_src_w,
11932                                &pipe_config->pipe_src_h);
11933
11934         for_each_new_connector_in_state(state, connector, connector_state, i) {
11935                 if (connector_state->crtc != crtc)
11936                         continue;
11937
11938                 encoder = to_intel_encoder(connector_state->best_encoder);
11939
11940                 if (!check_single_encoder_cloning(state, to_intel_crtc(crtc), encoder)) {
11941                         DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
11942                         return -EINVAL;
11943                 }
11944
11945                 /*
11946                  * Determine output_types before calling the .compute_config()
11947                  * hooks so that the hooks can use this information safely.
11948                  */
11949                 if (encoder->compute_output_type)
11950                         pipe_config->output_types |=
11951                                 BIT(encoder->compute_output_type(encoder, pipe_config,
11952                                                                  connector_state));
11953                 else
11954                         pipe_config->output_types |= BIT(encoder->type);
11955         }
11956
11957 encoder_retry:
11958         /* Ensure the port clock defaults are reset when retrying. */
11959         pipe_config->port_clock = 0;
11960         pipe_config->pixel_multiplier = 1;
11961
11962         /* Fill in default crtc timings, allow encoders to overwrite them. */
11963         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
11964                               CRTC_STEREO_DOUBLE);
11965
11966         /* Pass our mode to the connectors and the CRTC to give them a chance to
11967          * adjust it according to limitations or connector properties, and also
11968          * a chance to reject the mode entirely.
11969          */
11970         for_each_new_connector_in_state(state, connector, connector_state, i) {
11971                 if (connector_state->crtc != crtc)
11972                         continue;
11973
11974                 encoder = to_intel_encoder(connector_state->best_encoder);
11975                 ret = encoder->compute_config(encoder, pipe_config,
11976                                               connector_state);
11977                 if (ret < 0) {
11978                         if (ret != -EDEADLK)
11979                                 DRM_DEBUG_KMS("Encoder config failure: %d\n",
11980                                               ret);
11981                         return ret;
11982                 }
11983         }
11984
11985         /* Set default port clock if not overwritten by the encoder. Needs to be
11986          * done afterwards in case the encoder adjusts the mode. */
11987         if (!pipe_config->port_clock)
11988                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
11989                         * pipe_config->pixel_multiplier;
11990
11991         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
11992         if (ret == -EDEADLK)
11993                 return ret;
11994         if (ret < 0) {
11995                 DRM_DEBUG_KMS("CRTC fixup failed\n");
11996                 return ret;
11997         }
11998
11999         if (ret == RETRY) {
12000                 if (WARN(!retry, "loop in pipe configuration computation\n"))
12001                         return -EINVAL;
12002
12003                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
12004                 retry = false;
12005                 goto encoder_retry;
12006         }
12007
12008         /* Dithering seems to not pass-through bits correctly when it should, so
12009          * only enable it on 6bpc panels and when its not a compliance
12010          * test requesting 6bpc video pattern.
12011          */
12012         pipe_config->dither = (pipe_config->pipe_bpp == 6*3) &&
12013                 !pipe_config->dither_force_disable;
12014         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
12015                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
12016
12017         return 0;
12018 }
12019
12020 static bool intel_fuzzy_clock_check(int clock1, int clock2)
12021 {
12022         int diff;
12023
12024         if (clock1 == clock2)
12025                 return true;
12026
12027         if (!clock1 || !clock2)
12028                 return false;
12029
12030         diff = abs(clock1 - clock2);
12031
12032         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
12033                 return true;
12034
12035         return false;
12036 }
12037
12038 static bool
12039 intel_compare_m_n(unsigned int m, unsigned int n,
12040                   unsigned int m2, unsigned int n2,
12041                   bool exact)
12042 {
12043         if (m == m2 && n == n2)
12044                 return true;
12045
12046         if (exact || !m || !n || !m2 || !n2)
12047                 return false;
12048
12049         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
12050
12051         if (n > n2) {
12052                 while (n > n2) {
12053                         m2 <<= 1;
12054                         n2 <<= 1;
12055                 }
12056         } else if (n < n2) {
12057                 while (n < n2) {
12058                         m <<= 1;
12059                         n <<= 1;
12060                 }
12061         }
12062
12063         if (n != n2)
12064                 return false;
12065
12066         return intel_fuzzy_clock_check(m, m2);
12067 }
12068
12069 static bool
12070 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
12071                        struct intel_link_m_n *m2_n2,
12072                        bool adjust)
12073 {
12074         if (m_n->tu == m2_n2->tu &&
12075             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
12076                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
12077             intel_compare_m_n(m_n->link_m, m_n->link_n,
12078                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
12079                 if (adjust)
12080                         *m2_n2 = *m_n;
12081
12082                 return true;
12083         }
12084
12085         return false;
12086 }
12087
12088 static bool
12089 intel_compare_infoframe(const union hdmi_infoframe *a,
12090                         const union hdmi_infoframe *b)
12091 {
12092         return memcmp(a, b, sizeof(*a)) == 0;
12093 }
12094
12095 static void
12096 pipe_config_infoframe_err(struct drm_i915_private *dev_priv,
12097                           bool adjust, const char *name,
12098                           const union hdmi_infoframe *a,
12099                           const union hdmi_infoframe *b)
12100 {
12101         if (adjust) {
12102                 if ((drm_debug & DRM_UT_KMS) == 0)
12103                         return;
12104
12105                 drm_dbg(DRM_UT_KMS, "mismatch in %s infoframe", name);
12106                 drm_dbg(DRM_UT_KMS, "expected:");
12107                 hdmi_infoframe_log(KERN_DEBUG, dev_priv->drm.dev, a);
12108                 drm_dbg(DRM_UT_KMS, "found");
12109                 hdmi_infoframe_log(KERN_DEBUG, dev_priv->drm.dev, b);
12110         } else {
12111                 drm_err("mismatch in %s infoframe", name);
12112                 drm_err("expected:");
12113                 hdmi_infoframe_log(KERN_ERR, dev_priv->drm.dev, a);
12114                 drm_err("found");
12115                 hdmi_infoframe_log(KERN_ERR, dev_priv->drm.dev, b);
12116         }
12117 }
12118
12119 static void __printf(3, 4)
12120 pipe_config_err(bool adjust, const char *name, const char *format, ...)
12121 {
12122         struct va_format vaf;
12123         va_list args;
12124
12125         va_start(args, format);
12126         vaf.fmt = format;
12127         vaf.va = &args;
12128
12129         if (adjust)
12130                 drm_dbg(DRM_UT_KMS, "mismatch in %s %pV", name, &vaf);
12131         else
12132                 drm_err("mismatch in %s %pV", name, &vaf);
12133
12134         va_end(args);
12135 }
12136
12137 static bool fastboot_enabled(struct drm_i915_private *dev_priv)
12138 {
12139         if (i915_modparams.fastboot != -1)
12140                 return i915_modparams.fastboot;
12141
12142         /* Enable fastboot by default on Skylake and newer */
12143         if (INTEL_GEN(dev_priv) >= 9)
12144                 return true;
12145
12146         /* Enable fastboot by default on VLV and CHV */
12147         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
12148                 return true;
12149
12150         /* Disabled by default on all others */
12151         return false;
12152 }
12153
12154 static bool
12155 intel_pipe_config_compare(struct drm_i915_private *dev_priv,
12156                           struct intel_crtc_state *current_config,
12157                           struct intel_crtc_state *pipe_config,
12158                           bool adjust)
12159 {
12160         bool ret = true;
12161         bool fixup_inherited = adjust &&
12162                 (current_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED) &&
12163                 !(pipe_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED);
12164
12165         if (fixup_inherited && !fastboot_enabled(dev_priv)) {
12166                 DRM_DEBUG_KMS("initial modeset and fastboot not set\n");
12167                 ret = false;
12168         }
12169
12170 #define PIPE_CONF_CHECK_X(name) do { \
12171         if (current_config->name != pipe_config->name) { \
12172                 pipe_config_err(adjust, __stringify(name), \
12173                           "(expected 0x%08x, found 0x%08x)\n", \
12174                           current_config->name, \
12175                           pipe_config->name); \
12176                 ret = false; \
12177         } \
12178 } while (0)
12179
12180 #define PIPE_CONF_CHECK_I(name) do { \
12181         if (current_config->name != pipe_config->name) { \
12182                 pipe_config_err(adjust, __stringify(name), \
12183                           "(expected %i, found %i)\n", \
12184                           current_config->name, \
12185                           pipe_config->name); \
12186                 ret = false; \
12187         } \
12188 } while (0)
12189
12190 #define PIPE_CONF_CHECK_BOOL(name) do { \
12191         if (current_config->name != pipe_config->name) { \
12192                 pipe_config_err(adjust, __stringify(name), \
12193                           "(expected %s, found %s)\n", \
12194                           yesno(current_config->name), \
12195                           yesno(pipe_config->name)); \
12196                 ret = false; \
12197         } \
12198 } while (0)
12199
12200 /*
12201  * Checks state where we only read out the enabling, but not the entire
12202  * state itself (like full infoframes or ELD for audio). These states
12203  * require a full modeset on bootup to fix up.
12204  */
12205 #define PIPE_CONF_CHECK_BOOL_INCOMPLETE(name) do { \
12206         if (!fixup_inherited || (!current_config->name && !pipe_config->name)) { \
12207                 PIPE_CONF_CHECK_BOOL(name); \
12208         } else { \
12209                 pipe_config_err(adjust, __stringify(name), \
12210                           "unable to verify whether state matches exactly, forcing modeset (expected %s, found %s)\n", \
12211                           yesno(current_config->name), \
12212                           yesno(pipe_config->name)); \
12213                 ret = false; \
12214         } \
12215 } while (0)
12216
12217 #define PIPE_CONF_CHECK_P(name) do { \
12218         if (current_config->name != pipe_config->name) { \
12219                 pipe_config_err(adjust, __stringify(name), \
12220                           "(expected %p, found %p)\n", \
12221                           current_config->name, \
12222                           pipe_config->name); \
12223                 ret = false; \
12224         } \
12225 } while (0)
12226
12227 #define PIPE_CONF_CHECK_M_N(name) do { \
12228         if (!intel_compare_link_m_n(&current_config->name, \
12229                                     &pipe_config->name,\
12230                                     adjust)) { \
12231                 pipe_config_err(adjust, __stringify(name), \
12232                           "(expected tu %i gmch %i/%i link %i/%i, " \
12233                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12234                           current_config->name.tu, \
12235                           current_config->name.gmch_m, \
12236                           current_config->name.gmch_n, \
12237                           current_config->name.link_m, \
12238                           current_config->name.link_n, \
12239                           pipe_config->name.tu, \
12240                           pipe_config->name.gmch_m, \
12241                           pipe_config->name.gmch_n, \
12242                           pipe_config->name.link_m, \
12243                           pipe_config->name.link_n); \
12244                 ret = false; \
12245         } \
12246 } while (0)
12247
12248 /* This is required for BDW+ where there is only one set of registers for
12249  * switching between high and low RR.
12250  * This macro can be used whenever a comparison has to be made between one
12251  * hw state and multiple sw state variables.
12252  */
12253 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) do { \
12254         if (!intel_compare_link_m_n(&current_config->name, \
12255                                     &pipe_config->name, adjust) && \
12256             !intel_compare_link_m_n(&current_config->alt_name, \
12257                                     &pipe_config->name, adjust)) { \
12258                 pipe_config_err(adjust, __stringify(name), \
12259                           "(expected tu %i gmch %i/%i link %i/%i, " \
12260                           "or tu %i gmch %i/%i link %i/%i, " \
12261                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12262                           current_config->name.tu, \
12263                           current_config->name.gmch_m, \
12264                           current_config->name.gmch_n, \
12265                           current_config->name.link_m, \
12266                           current_config->name.link_n, \
12267                           current_config->alt_name.tu, \
12268                           current_config->alt_name.gmch_m, \
12269                           current_config->alt_name.gmch_n, \
12270                           current_config->alt_name.link_m, \
12271                           current_config->alt_name.link_n, \
12272                           pipe_config->name.tu, \
12273                           pipe_config->name.gmch_m, \
12274                           pipe_config->name.gmch_n, \
12275                           pipe_config->name.link_m, \
12276                           pipe_config->name.link_n); \
12277                 ret = false; \
12278         } \
12279 } while (0)
12280
12281 #define PIPE_CONF_CHECK_FLAGS(name, mask) do { \
12282         if ((current_config->name ^ pipe_config->name) & (mask)) { \
12283                 pipe_config_err(adjust, __stringify(name), \
12284                           "(%x) (expected %i, found %i)\n", \
12285                           (mask), \
12286                           current_config->name & (mask), \
12287                           pipe_config->name & (mask)); \
12288                 ret = false; \
12289         } \
12290 } while (0)
12291
12292 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) do { \
12293         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
12294                 pipe_config_err(adjust, __stringify(name), \
12295                           "(expected %i, found %i)\n", \
12296                           current_config->name, \
12297                           pipe_config->name); \
12298                 ret = false; \
12299         } \
12300 } while (0)
12301
12302 #define PIPE_CONF_CHECK_INFOFRAME(name) do { \
12303         if (!intel_compare_infoframe(&current_config->infoframes.name, \
12304                                      &pipe_config->infoframes.name)) { \
12305                 pipe_config_infoframe_err(dev_priv, adjust, __stringify(name), \
12306                                           &current_config->infoframes.name, \
12307                                           &pipe_config->infoframes.name); \
12308                 ret = false; \
12309         } \
12310 } while (0)
12311
12312 #define PIPE_CONF_QUIRK(quirk) \
12313         ((current_config->quirks | pipe_config->quirks) & (quirk))
12314
12315         PIPE_CONF_CHECK_I(cpu_transcoder);
12316
12317         PIPE_CONF_CHECK_BOOL(has_pch_encoder);
12318         PIPE_CONF_CHECK_I(fdi_lanes);
12319         PIPE_CONF_CHECK_M_N(fdi_m_n);
12320
12321         PIPE_CONF_CHECK_I(lane_count);
12322         PIPE_CONF_CHECK_X(lane_lat_optim_mask);
12323
12324         if (INTEL_GEN(dev_priv) < 8) {
12325                 PIPE_CONF_CHECK_M_N(dp_m_n);
12326
12327                 if (current_config->has_drrs)
12328                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
12329         } else
12330                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
12331
12332         PIPE_CONF_CHECK_X(output_types);
12333
12334         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
12335         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
12336         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
12337         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
12338         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
12339         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
12340
12341         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
12342         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
12343         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
12344         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
12345         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
12346         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
12347
12348         PIPE_CONF_CHECK_I(pixel_multiplier);
12349         PIPE_CONF_CHECK_I(output_format);
12350         PIPE_CONF_CHECK_BOOL(has_hdmi_sink);
12351         if ((INTEL_GEN(dev_priv) < 8 && !IS_HASWELL(dev_priv)) ||
12352             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
12353                 PIPE_CONF_CHECK_BOOL(limited_color_range);
12354
12355         PIPE_CONF_CHECK_BOOL(hdmi_scrambling);
12356         PIPE_CONF_CHECK_BOOL(hdmi_high_tmds_clock_ratio);
12357         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_infoframe);
12358
12359         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_audio);
12360
12361         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12362                               DRM_MODE_FLAG_INTERLACE);
12363
12364         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
12365                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12366                                       DRM_MODE_FLAG_PHSYNC);
12367                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12368                                       DRM_MODE_FLAG_NHSYNC);
12369                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12370                                       DRM_MODE_FLAG_PVSYNC);
12371                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12372                                       DRM_MODE_FLAG_NVSYNC);
12373         }
12374
12375         PIPE_CONF_CHECK_X(gmch_pfit.control);
12376         /* pfit ratios are autocomputed by the hw on gen4+ */
12377         if (INTEL_GEN(dev_priv) < 4)
12378                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
12379         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
12380
12381         if (!adjust) {
12382                 PIPE_CONF_CHECK_I(pipe_src_w);
12383                 PIPE_CONF_CHECK_I(pipe_src_h);
12384
12385                 PIPE_CONF_CHECK_BOOL(pch_pfit.enabled);
12386                 if (current_config->pch_pfit.enabled) {
12387                         PIPE_CONF_CHECK_X(pch_pfit.pos);
12388                         PIPE_CONF_CHECK_X(pch_pfit.size);
12389                 }
12390
12391                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
12392                 PIPE_CONF_CHECK_CLOCK_FUZZY(pixel_rate);
12393
12394                 PIPE_CONF_CHECK_X(gamma_mode);
12395                 if (IS_CHERRYVIEW(dev_priv))
12396                         PIPE_CONF_CHECK_X(cgm_mode);
12397                 else
12398                         PIPE_CONF_CHECK_X(csc_mode);
12399                 PIPE_CONF_CHECK_BOOL(gamma_enable);
12400                 PIPE_CONF_CHECK_BOOL(csc_enable);
12401         }
12402
12403         PIPE_CONF_CHECK_BOOL(double_wide);
12404
12405         PIPE_CONF_CHECK_P(shared_dpll);
12406         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
12407         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
12408         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
12409         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
12410         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
12411         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
12412         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
12413         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
12414         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
12415         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr0);
12416         PIPE_CONF_CHECK_X(dpll_hw_state.ebb0);
12417         PIPE_CONF_CHECK_X(dpll_hw_state.ebb4);
12418         PIPE_CONF_CHECK_X(dpll_hw_state.pll0);
12419         PIPE_CONF_CHECK_X(dpll_hw_state.pll1);
12420         PIPE_CONF_CHECK_X(dpll_hw_state.pll2);
12421         PIPE_CONF_CHECK_X(dpll_hw_state.pll3);
12422         PIPE_CONF_CHECK_X(dpll_hw_state.pll6);
12423         PIPE_CONF_CHECK_X(dpll_hw_state.pll8);
12424         PIPE_CONF_CHECK_X(dpll_hw_state.pll9);
12425         PIPE_CONF_CHECK_X(dpll_hw_state.pll10);
12426         PIPE_CONF_CHECK_X(dpll_hw_state.pcsdw12);
12427         PIPE_CONF_CHECK_X(dpll_hw_state.mg_refclkin_ctl);
12428         PIPE_CONF_CHECK_X(dpll_hw_state.mg_clktop2_coreclkctl1);
12429         PIPE_CONF_CHECK_X(dpll_hw_state.mg_clktop2_hsclkctl);
12430         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_div0);
12431         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_div1);
12432         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_lf);
12433         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_frac_lock);
12434         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_ssc);
12435         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_bias);
12436         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_tdc_coldst_bias);
12437
12438         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
12439         PIPE_CONF_CHECK_X(dsi_pll.div);
12440
12441         if (IS_G4X(dev_priv) || INTEL_GEN(dev_priv) >= 5)
12442                 PIPE_CONF_CHECK_I(pipe_bpp);
12443
12444         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
12445         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
12446
12447         PIPE_CONF_CHECK_I(min_voltage_level);
12448
12449         PIPE_CONF_CHECK_X(infoframes.enable);
12450         PIPE_CONF_CHECK_X(infoframes.gcp);
12451         PIPE_CONF_CHECK_INFOFRAME(avi);
12452         PIPE_CONF_CHECK_INFOFRAME(spd);
12453         PIPE_CONF_CHECK_INFOFRAME(hdmi);
12454
12455 #undef PIPE_CONF_CHECK_X
12456 #undef PIPE_CONF_CHECK_I
12457 #undef PIPE_CONF_CHECK_BOOL
12458 #undef PIPE_CONF_CHECK_BOOL_INCOMPLETE
12459 #undef PIPE_CONF_CHECK_P
12460 #undef PIPE_CONF_CHECK_FLAGS
12461 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
12462 #undef PIPE_CONF_QUIRK
12463
12464         return ret;
12465 }
12466
12467 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
12468                                            const struct intel_crtc_state *pipe_config)
12469 {
12470         if (pipe_config->has_pch_encoder) {
12471                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
12472                                                             &pipe_config->fdi_m_n);
12473                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
12474
12475                 /*
12476                  * FDI already provided one idea for the dotclock.
12477                  * Yell if the encoder disagrees.
12478                  */
12479                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
12480                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
12481                      fdi_dotclock, dotclock);
12482         }
12483 }
12484
12485 static void verify_wm_state(struct drm_crtc *crtc,
12486                             struct drm_crtc_state *new_state)
12487 {
12488         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
12489         struct skl_hw_state {
12490                 struct skl_ddb_entry ddb_y[I915_MAX_PLANES];
12491                 struct skl_ddb_entry ddb_uv[I915_MAX_PLANES];
12492                 struct skl_ddb_allocation ddb;
12493                 struct skl_pipe_wm wm;
12494         } *hw;
12495         struct skl_ddb_allocation *sw_ddb;
12496         struct skl_pipe_wm *sw_wm;
12497         struct skl_ddb_entry *hw_ddb_entry, *sw_ddb_entry;
12498         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12499         const enum pipe pipe = intel_crtc->pipe;
12500         int plane, level, max_level = ilk_wm_max_level(dev_priv);
12501
12502         if (INTEL_GEN(dev_priv) < 9 || !new_state->active)
12503                 return;
12504
12505         hw = kzalloc(sizeof(*hw), GFP_KERNEL);
12506         if (!hw)
12507                 return;
12508
12509         skl_pipe_wm_get_hw_state(intel_crtc, &hw->wm);
12510         sw_wm = &to_intel_crtc_state(new_state)->wm.skl.optimal;
12511
12512         skl_pipe_ddb_get_hw_state(intel_crtc, hw->ddb_y, hw->ddb_uv);
12513
12514         skl_ddb_get_hw_state(dev_priv, &hw->ddb);
12515         sw_ddb = &dev_priv->wm.skl_hw.ddb;
12516
12517         if (INTEL_GEN(dev_priv) >= 11 &&
12518             hw->ddb.enabled_slices != sw_ddb->enabled_slices)
12519                 DRM_ERROR("mismatch in DBUF Slices (expected %u, got %u)\n",
12520                           sw_ddb->enabled_slices,
12521                           hw->ddb.enabled_slices);
12522
12523         /* planes */
12524         for_each_universal_plane(dev_priv, pipe, plane) {
12525                 struct skl_plane_wm *hw_plane_wm, *sw_plane_wm;
12526
12527                 hw_plane_wm = &hw->wm.planes[plane];
12528                 sw_plane_wm = &sw_wm->planes[plane];
12529
12530                 /* Watermarks */
12531                 for (level = 0; level <= max_level; level++) {
12532                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
12533                                                 &sw_plane_wm->wm[level]))
12534                                 continue;
12535
12536                         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",
12537                                   pipe_name(pipe), plane + 1, level,
12538                                   sw_plane_wm->wm[level].plane_en,
12539                                   sw_plane_wm->wm[level].plane_res_b,
12540                                   sw_plane_wm->wm[level].plane_res_l,
12541                                   hw_plane_wm->wm[level].plane_en,
12542                                   hw_plane_wm->wm[level].plane_res_b,
12543                                   hw_plane_wm->wm[level].plane_res_l);
12544                 }
12545
12546                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
12547                                          &sw_plane_wm->trans_wm)) {
12548                         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",
12549                                   pipe_name(pipe), plane + 1,
12550                                   sw_plane_wm->trans_wm.plane_en,
12551                                   sw_plane_wm->trans_wm.plane_res_b,
12552                                   sw_plane_wm->trans_wm.plane_res_l,
12553                                   hw_plane_wm->trans_wm.plane_en,
12554                                   hw_plane_wm->trans_wm.plane_res_b,
12555                                   hw_plane_wm->trans_wm.plane_res_l);
12556                 }
12557
12558                 /* DDB */
12559                 hw_ddb_entry = &hw->ddb_y[plane];
12560                 sw_ddb_entry = &to_intel_crtc_state(new_state)->wm.skl.plane_ddb_y[plane];
12561
12562                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
12563                         DRM_ERROR("mismatch in DDB state pipe %c plane %d (expected (%u,%u), found (%u,%u))\n",
12564                                   pipe_name(pipe), plane + 1,
12565                                   sw_ddb_entry->start, sw_ddb_entry->end,
12566                                   hw_ddb_entry->start, hw_ddb_entry->end);
12567                 }
12568         }
12569
12570         /*
12571          * cursor
12572          * If the cursor plane isn't active, we may not have updated it's ddb
12573          * allocation. In that case since the ddb allocation will be updated
12574          * once the plane becomes visible, we can skip this check
12575          */
12576         if (1) {
12577                 struct skl_plane_wm *hw_plane_wm, *sw_plane_wm;
12578
12579                 hw_plane_wm = &hw->wm.planes[PLANE_CURSOR];
12580                 sw_plane_wm = &sw_wm->planes[PLANE_CURSOR];
12581
12582                 /* Watermarks */
12583                 for (level = 0; level <= max_level; level++) {
12584                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
12585                                                 &sw_plane_wm->wm[level]))
12586                                 continue;
12587
12588                         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",
12589                                   pipe_name(pipe), level,
12590                                   sw_plane_wm->wm[level].plane_en,
12591                                   sw_plane_wm->wm[level].plane_res_b,
12592                                   sw_plane_wm->wm[level].plane_res_l,
12593                                   hw_plane_wm->wm[level].plane_en,
12594                                   hw_plane_wm->wm[level].plane_res_b,
12595                                   hw_plane_wm->wm[level].plane_res_l);
12596                 }
12597
12598                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
12599                                          &sw_plane_wm->trans_wm)) {
12600                         DRM_ERROR("mismatch in trans WM pipe %c cursor (expected e=%d b=%u l=%u, got e=%d b=%u l=%u)\n",
12601                                   pipe_name(pipe),
12602                                   sw_plane_wm->trans_wm.plane_en,
12603                                   sw_plane_wm->trans_wm.plane_res_b,
12604                                   sw_plane_wm->trans_wm.plane_res_l,
12605                                   hw_plane_wm->trans_wm.plane_en,
12606                                   hw_plane_wm->trans_wm.plane_res_b,
12607                                   hw_plane_wm->trans_wm.plane_res_l);
12608                 }
12609
12610                 /* DDB */
12611                 hw_ddb_entry = &hw->ddb_y[PLANE_CURSOR];
12612                 sw_ddb_entry = &to_intel_crtc_state(new_state)->wm.skl.plane_ddb_y[PLANE_CURSOR];
12613
12614                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
12615                         DRM_ERROR("mismatch in DDB state pipe %c cursor (expected (%u,%u), found (%u,%u))\n",
12616                                   pipe_name(pipe),
12617                                   sw_ddb_entry->start, sw_ddb_entry->end,
12618                                   hw_ddb_entry->start, hw_ddb_entry->end);
12619                 }
12620         }
12621
12622         kfree(hw);
12623 }
12624
12625 static void
12626 verify_connector_state(struct drm_device *dev,
12627                        struct drm_atomic_state *state,
12628                        struct drm_crtc *crtc)
12629 {
12630         struct drm_connector *connector;
12631         struct drm_connector_state *new_conn_state;
12632         int i;
12633
12634         for_each_new_connector_in_state(state, connector, new_conn_state, i) {
12635                 struct drm_encoder *encoder = connector->encoder;
12636                 struct drm_crtc_state *crtc_state = NULL;
12637
12638                 if (new_conn_state->crtc != crtc)
12639                         continue;
12640
12641                 if (crtc)
12642                         crtc_state = drm_atomic_get_new_crtc_state(state, new_conn_state->crtc);
12643
12644                 intel_connector_verify_state(crtc_state, new_conn_state);
12645
12646                 I915_STATE_WARN(new_conn_state->best_encoder != encoder,
12647                      "connector's atomic encoder doesn't match legacy encoder\n");
12648         }
12649 }
12650
12651 static void
12652 verify_encoder_state(struct drm_device *dev, struct drm_atomic_state *state)
12653 {
12654         struct intel_encoder *encoder;
12655         struct drm_connector *connector;
12656         struct drm_connector_state *old_conn_state, *new_conn_state;
12657         int i;
12658
12659         for_each_intel_encoder(dev, encoder) {
12660                 bool enabled = false, found = false;
12661                 enum pipe pipe;
12662
12663                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
12664                               encoder->base.base.id,
12665                               encoder->base.name);
12666
12667                 for_each_oldnew_connector_in_state(state, connector, old_conn_state,
12668                                                    new_conn_state, i) {
12669                         if (old_conn_state->best_encoder == &encoder->base)
12670                                 found = true;
12671
12672                         if (new_conn_state->best_encoder != &encoder->base)
12673                                 continue;
12674                         found = enabled = true;
12675
12676                         I915_STATE_WARN(new_conn_state->crtc !=
12677                                         encoder->base.crtc,
12678                              "connector's crtc doesn't match encoder crtc\n");
12679                 }
12680
12681                 if (!found)
12682                         continue;
12683
12684                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
12685                      "encoder's enabled state mismatch "
12686                      "(expected %i, found %i)\n",
12687                      !!encoder->base.crtc, enabled);
12688
12689                 if (!encoder->base.crtc) {
12690                         bool active;
12691
12692                         active = encoder->get_hw_state(encoder, &pipe);
12693                         I915_STATE_WARN(active,
12694                              "encoder detached but still enabled on pipe %c.\n",
12695                              pipe_name(pipe));
12696                 }
12697         }
12698 }
12699
12700 static void
12701 verify_crtc_state(struct drm_crtc *crtc,
12702                   struct drm_crtc_state *old_crtc_state,
12703                   struct drm_crtc_state *new_crtc_state)
12704 {
12705         struct drm_device *dev = crtc->dev;
12706         struct drm_i915_private *dev_priv = to_i915(dev);
12707         struct intel_encoder *encoder;
12708         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12709         struct intel_crtc_state *pipe_config, *sw_config;
12710         struct drm_atomic_state *old_state;
12711         bool active;
12712
12713         old_state = old_crtc_state->state;
12714         __drm_atomic_helper_crtc_destroy_state(old_crtc_state);
12715         pipe_config = to_intel_crtc_state(old_crtc_state);
12716         memset(pipe_config, 0, sizeof(*pipe_config));
12717         pipe_config->base.crtc = crtc;
12718         pipe_config->base.state = old_state;
12719
12720         DRM_DEBUG_KMS("[CRTC:%d:%s]\n", crtc->base.id, crtc->name);
12721
12722         active = dev_priv->display.get_pipe_config(intel_crtc, pipe_config);
12723
12724         /* we keep both pipes enabled on 830 */
12725         if (IS_I830(dev_priv))
12726                 active = new_crtc_state->active;
12727
12728         I915_STATE_WARN(new_crtc_state->active != active,
12729              "crtc active state doesn't match with hw state "
12730              "(expected %i, found %i)\n", new_crtc_state->active, active);
12731
12732         I915_STATE_WARN(intel_crtc->active != new_crtc_state->active,
12733              "transitional active state does not match atomic hw state "
12734              "(expected %i, found %i)\n", new_crtc_state->active, intel_crtc->active);
12735
12736         for_each_encoder_on_crtc(dev, crtc, encoder) {
12737                 enum pipe pipe;
12738
12739                 active = encoder->get_hw_state(encoder, &pipe);
12740                 I915_STATE_WARN(active != new_crtc_state->active,
12741                         "[ENCODER:%i] active %i with crtc active %i\n",
12742                         encoder->base.base.id, active, new_crtc_state->active);
12743
12744                 I915_STATE_WARN(active && intel_crtc->pipe != pipe,
12745                                 "Encoder connected to wrong pipe %c\n",
12746                                 pipe_name(pipe));
12747
12748                 if (active)
12749                         encoder->get_config(encoder, pipe_config);
12750         }
12751
12752         intel_crtc_compute_pixel_rate(pipe_config);
12753
12754         if (!new_crtc_state->active)
12755                 return;
12756
12757         intel_pipe_config_sanity_check(dev_priv, pipe_config);
12758
12759         sw_config = to_intel_crtc_state(new_crtc_state);
12760         if (!intel_pipe_config_compare(dev_priv, sw_config,
12761                                        pipe_config, false)) {
12762                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
12763                 intel_dump_pipe_config(intel_crtc, pipe_config,
12764                                        "[hw state]");
12765                 intel_dump_pipe_config(intel_crtc, sw_config,
12766                                        "[sw state]");
12767         }
12768 }
12769
12770 static void
12771 intel_verify_planes(struct intel_atomic_state *state)
12772 {
12773         struct intel_plane *plane;
12774         const struct intel_plane_state *plane_state;
12775         int i;
12776
12777         for_each_new_intel_plane_in_state(state, plane,
12778                                           plane_state, i)
12779                 assert_plane(plane, plane_state->slave ||
12780                              plane_state->base.visible);
12781 }
12782
12783 static void
12784 verify_single_dpll_state(struct drm_i915_private *dev_priv,
12785                          struct intel_shared_dpll *pll,
12786                          struct drm_crtc *crtc,
12787                          struct drm_crtc_state *new_state)
12788 {
12789         struct intel_dpll_hw_state dpll_hw_state;
12790         unsigned int crtc_mask;
12791         bool active;
12792
12793         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
12794
12795         DRM_DEBUG_KMS("%s\n", pll->info->name);
12796
12797         active = pll->info->funcs->get_hw_state(dev_priv, pll, &dpll_hw_state);
12798
12799         if (!(pll->info->flags & INTEL_DPLL_ALWAYS_ON)) {
12800                 I915_STATE_WARN(!pll->on && pll->active_mask,
12801                      "pll in active use but not on in sw tracking\n");
12802                 I915_STATE_WARN(pll->on && !pll->active_mask,
12803                      "pll is on but not used by any active crtc\n");
12804                 I915_STATE_WARN(pll->on != active,
12805                      "pll on state mismatch (expected %i, found %i)\n",
12806                      pll->on, active);
12807         }
12808
12809         if (!crtc) {
12810                 I915_STATE_WARN(pll->active_mask & ~pll->state.crtc_mask,
12811                                 "more active pll users than references: %x vs %x\n",
12812                                 pll->active_mask, pll->state.crtc_mask);
12813
12814                 return;
12815         }
12816
12817         crtc_mask = drm_crtc_mask(crtc);
12818
12819         if (new_state->active)
12820                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
12821                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
12822                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
12823         else
12824                 I915_STATE_WARN(pll->active_mask & crtc_mask,
12825                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
12826                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
12827
12828         I915_STATE_WARN(!(pll->state.crtc_mask & crtc_mask),
12829                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
12830                         crtc_mask, pll->state.crtc_mask);
12831
12832         I915_STATE_WARN(pll->on && memcmp(&pll->state.hw_state,
12833                                           &dpll_hw_state,
12834                                           sizeof(dpll_hw_state)),
12835                         "pll hw state mismatch\n");
12836 }
12837
12838 static void
12839 verify_shared_dpll_state(struct drm_device *dev, struct drm_crtc *crtc,
12840                          struct drm_crtc_state *old_crtc_state,
12841                          struct drm_crtc_state *new_crtc_state)
12842 {
12843         struct drm_i915_private *dev_priv = to_i915(dev);
12844         struct intel_crtc_state *old_state = to_intel_crtc_state(old_crtc_state);
12845         struct intel_crtc_state *new_state = to_intel_crtc_state(new_crtc_state);
12846
12847         if (new_state->shared_dpll)
12848                 verify_single_dpll_state(dev_priv, new_state->shared_dpll, crtc, new_crtc_state);
12849
12850         if (old_state->shared_dpll &&
12851             old_state->shared_dpll != new_state->shared_dpll) {
12852                 unsigned int crtc_mask = drm_crtc_mask(crtc);
12853                 struct intel_shared_dpll *pll = old_state->shared_dpll;
12854
12855                 I915_STATE_WARN(pll->active_mask & crtc_mask,
12856                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
12857                                 pipe_name(drm_crtc_index(crtc)));
12858                 I915_STATE_WARN(pll->state.crtc_mask & crtc_mask,
12859                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
12860                                 pipe_name(drm_crtc_index(crtc)));
12861         }
12862 }
12863
12864 static void
12865 intel_modeset_verify_crtc(struct drm_crtc *crtc,
12866                           struct drm_atomic_state *state,
12867                           struct drm_crtc_state *old_state,
12868                           struct drm_crtc_state *new_state)
12869 {
12870         if (!needs_modeset(new_state) &&
12871             !to_intel_crtc_state(new_state)->update_pipe)
12872                 return;
12873
12874         verify_wm_state(crtc, new_state);
12875         verify_connector_state(crtc->dev, state, crtc);
12876         verify_crtc_state(crtc, old_state, new_state);
12877         verify_shared_dpll_state(crtc->dev, crtc, old_state, new_state);
12878 }
12879
12880 static void
12881 verify_disabled_dpll_state(struct drm_device *dev)
12882 {
12883         struct drm_i915_private *dev_priv = to_i915(dev);
12884         int i;
12885
12886         for (i = 0; i < dev_priv->num_shared_dpll; i++)
12887                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
12888 }
12889
12890 static void
12891 intel_modeset_verify_disabled(struct drm_device *dev,
12892                               struct drm_atomic_state *state)
12893 {
12894         verify_encoder_state(dev, state);
12895         verify_connector_state(dev, state, NULL);
12896         verify_disabled_dpll_state(dev);
12897 }
12898
12899 static void update_scanline_offset(const struct intel_crtc_state *crtc_state)
12900 {
12901         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
12902         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
12903
12904         /*
12905          * The scanline counter increments at the leading edge of hsync.
12906          *
12907          * On most platforms it starts counting from vtotal-1 on the
12908          * first active line. That means the scanline counter value is
12909          * always one less than what we would expect. Ie. just after
12910          * start of vblank, which also occurs at start of hsync (on the
12911          * last active line), the scanline counter will read vblank_start-1.
12912          *
12913          * On gen2 the scanline counter starts counting from 1 instead
12914          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
12915          * to keep the value positive), instead of adding one.
12916          *
12917          * On HSW+ the behaviour of the scanline counter depends on the output
12918          * type. For DP ports it behaves like most other platforms, but on HDMI
12919          * there's an extra 1 line difference. So we need to add two instead of
12920          * one to the value.
12921          *
12922          * On VLV/CHV DSI the scanline counter would appear to increment
12923          * approx. 1/3 of a scanline before start of vblank. Unfortunately
12924          * that means we can't tell whether we're in vblank or not while
12925          * we're on that particular line. We must still set scanline_offset
12926          * to 1 so that the vblank timestamps come out correct when we query
12927          * the scanline counter from within the vblank interrupt handler.
12928          * However if queried just before the start of vblank we'll get an
12929          * answer that's slightly in the future.
12930          */
12931         if (IS_GEN(dev_priv, 2)) {
12932                 const struct drm_display_mode *adjusted_mode = &crtc_state->base.adjusted_mode;
12933                 int vtotal;
12934
12935                 vtotal = adjusted_mode->crtc_vtotal;
12936                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
12937                         vtotal /= 2;
12938
12939                 crtc->scanline_offset = vtotal - 1;
12940         } else if (HAS_DDI(dev_priv) &&
12941                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI)) {
12942                 crtc->scanline_offset = 2;
12943         } else
12944                 crtc->scanline_offset = 1;
12945 }
12946
12947 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
12948 {
12949         struct drm_device *dev = state->dev;
12950         struct drm_i915_private *dev_priv = to_i915(dev);
12951         struct drm_crtc *crtc;
12952         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12953         int i;
12954
12955         if (!dev_priv->display.crtc_compute_clock)
12956                 return;
12957
12958         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12959                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12960                 struct intel_shared_dpll *old_dpll =
12961                         to_intel_crtc_state(old_crtc_state)->shared_dpll;
12962
12963                 if (!needs_modeset(new_crtc_state))
12964                         continue;
12965
12966                 to_intel_crtc_state(new_crtc_state)->shared_dpll = NULL;
12967
12968                 if (!old_dpll)
12969                         continue;
12970
12971                 intel_release_shared_dpll(old_dpll, intel_crtc, state);
12972         }
12973 }
12974
12975 /*
12976  * This implements the workaround described in the "notes" section of the mode
12977  * set sequence documentation. When going from no pipes or single pipe to
12978  * multiple pipes, and planes are enabled after the pipe, we need to wait at
12979  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
12980  */
12981 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
12982 {
12983         struct drm_crtc_state *crtc_state;
12984         struct intel_crtc *intel_crtc;
12985         struct drm_crtc *crtc;
12986         struct intel_crtc_state *first_crtc_state = NULL;
12987         struct intel_crtc_state *other_crtc_state = NULL;
12988         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
12989         int i;
12990
12991         /* look at all crtc's that are going to be enabled in during modeset */
12992         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
12993                 intel_crtc = to_intel_crtc(crtc);
12994
12995                 if (!crtc_state->active || !needs_modeset(crtc_state))
12996                         continue;
12997
12998                 if (first_crtc_state) {
12999                         other_crtc_state = to_intel_crtc_state(crtc_state);
13000                         break;
13001                 } else {
13002                         first_crtc_state = to_intel_crtc_state(crtc_state);
13003                         first_pipe = intel_crtc->pipe;
13004                 }
13005         }
13006
13007         /* No workaround needed? */
13008         if (!first_crtc_state)
13009                 return 0;
13010
13011         /* w/a possibly needed, check how many crtc's are already enabled. */
13012         for_each_intel_crtc(state->dev, intel_crtc) {
13013                 struct intel_crtc_state *pipe_config;
13014
13015                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
13016                 if (IS_ERR(pipe_config))
13017                         return PTR_ERR(pipe_config);
13018
13019                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
13020
13021                 if (!pipe_config->base.active ||
13022                     needs_modeset(&pipe_config->base))
13023                         continue;
13024
13025                 /* 2 or more enabled crtcs means no need for w/a */
13026                 if (enabled_pipe != INVALID_PIPE)
13027                         return 0;
13028
13029                 enabled_pipe = intel_crtc->pipe;
13030         }
13031
13032         if (enabled_pipe != INVALID_PIPE)
13033                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
13034         else if (other_crtc_state)
13035                 other_crtc_state->hsw_workaround_pipe = first_pipe;
13036
13037         return 0;
13038 }
13039
13040 static int intel_lock_all_pipes(struct drm_atomic_state *state)
13041 {
13042         struct drm_crtc *crtc;
13043
13044         /* Add all pipes to the state */
13045         for_each_crtc(state->dev, crtc) {
13046                 struct drm_crtc_state *crtc_state;
13047
13048                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
13049                 if (IS_ERR(crtc_state))
13050                         return PTR_ERR(crtc_state);
13051         }
13052
13053         return 0;
13054 }
13055
13056 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
13057 {
13058         struct drm_crtc *crtc;
13059
13060         /*
13061          * Add all pipes to the state, and force
13062          * a modeset on all the active ones.
13063          */
13064         for_each_crtc(state->dev, crtc) {
13065                 struct drm_crtc_state *crtc_state;
13066                 int ret;
13067
13068                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
13069                 if (IS_ERR(crtc_state))
13070                         return PTR_ERR(crtc_state);
13071
13072                 if (!crtc_state->active || needs_modeset(crtc_state))
13073                         continue;
13074
13075                 crtc_state->mode_changed = true;
13076
13077                 ret = drm_atomic_add_affected_connectors(state, crtc);
13078                 if (ret)
13079                         return ret;
13080
13081                 ret = drm_atomic_add_affected_planes(state, crtc);
13082                 if (ret)
13083                         return ret;
13084         }
13085
13086         return 0;
13087 }
13088
13089 static int intel_modeset_checks(struct drm_atomic_state *state)
13090 {
13091         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13092         struct drm_i915_private *dev_priv = to_i915(state->dev);
13093         struct drm_crtc *crtc;
13094         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
13095         int ret = 0, i;
13096
13097         if (!check_digital_port_conflicts(state)) {
13098                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
13099                 return -EINVAL;
13100         }
13101
13102         /* keep the current setting */
13103         if (!intel_state->cdclk.force_min_cdclk_changed)
13104                 intel_state->cdclk.force_min_cdclk =
13105                         dev_priv->cdclk.force_min_cdclk;
13106
13107         intel_state->modeset = true;
13108         intel_state->active_crtcs = dev_priv->active_crtcs;
13109         intel_state->cdclk.logical = dev_priv->cdclk.logical;
13110         intel_state->cdclk.actual = dev_priv->cdclk.actual;
13111         intel_state->cdclk.pipe = INVALID_PIPE;
13112
13113         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13114                 if (new_crtc_state->active)
13115                         intel_state->active_crtcs |= 1 << i;
13116                 else
13117                         intel_state->active_crtcs &= ~(1 << i);
13118
13119                 if (old_crtc_state->active != new_crtc_state->active)
13120                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
13121         }
13122
13123         /*
13124          * See if the config requires any additional preparation, e.g.
13125          * to adjust global state with pipes off.  We need to do this
13126          * here so we can get the modeset_pipe updated config for the new
13127          * mode set on this crtc.  For other crtcs we need to use the
13128          * adjusted_mode bits in the crtc directly.
13129          */
13130         if (dev_priv->display.modeset_calc_cdclk) {
13131                 enum pipe pipe;
13132
13133                 ret = dev_priv->display.modeset_calc_cdclk(state);
13134                 if (ret < 0)
13135                         return ret;
13136
13137                 /*
13138                  * Writes to dev_priv->cdclk.logical must protected by
13139                  * holding all the crtc locks, even if we don't end up
13140                  * touching the hardware
13141                  */
13142                 if (intel_cdclk_changed(&dev_priv->cdclk.logical,
13143                                         &intel_state->cdclk.logical)) {
13144                         ret = intel_lock_all_pipes(state);
13145                         if (ret < 0)
13146                                 return ret;
13147                 }
13148
13149                 if (is_power_of_2(intel_state->active_crtcs)) {
13150                         struct drm_crtc *crtc;
13151                         struct drm_crtc_state *crtc_state;
13152
13153                         pipe = ilog2(intel_state->active_crtcs);
13154                         crtc = &intel_get_crtc_for_pipe(dev_priv, pipe)->base;
13155                         crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
13156                         if (crtc_state && needs_modeset(crtc_state))
13157                                 pipe = INVALID_PIPE;
13158                 } else {
13159                         pipe = INVALID_PIPE;
13160                 }
13161
13162                 /* All pipes must be switched off while we change the cdclk. */
13163                 if (pipe != INVALID_PIPE &&
13164                     intel_cdclk_needs_cd2x_update(dev_priv,
13165                                                   &dev_priv->cdclk.actual,
13166                                                   &intel_state->cdclk.actual)) {
13167                         ret = intel_lock_all_pipes(state);
13168                         if (ret < 0)
13169                                 return ret;
13170
13171                         intel_state->cdclk.pipe = pipe;
13172                 } else if (intel_cdclk_needs_modeset(&dev_priv->cdclk.actual,
13173                                                      &intel_state->cdclk.actual)) {
13174                         ret = intel_modeset_all_pipes(state);
13175                         if (ret < 0)
13176                                 return ret;
13177
13178                         intel_state->cdclk.pipe = INVALID_PIPE;
13179                 }
13180
13181                 DRM_DEBUG_KMS("New cdclk calculated to be logical %u kHz, actual %u kHz\n",
13182                               intel_state->cdclk.logical.cdclk,
13183                               intel_state->cdclk.actual.cdclk);
13184                 DRM_DEBUG_KMS("New voltage level calculated to be logical %u, actual %u\n",
13185                               intel_state->cdclk.logical.voltage_level,
13186                               intel_state->cdclk.actual.voltage_level);
13187         }
13188
13189         intel_modeset_clear_plls(state);
13190
13191         if (IS_HASWELL(dev_priv))
13192                 return haswell_mode_set_planes_workaround(state);
13193
13194         return 0;
13195 }
13196
13197 /*
13198  * Handle calculation of various watermark data at the end of the atomic check
13199  * phase.  The code here should be run after the per-crtc and per-plane 'check'
13200  * handlers to ensure that all derived state has been updated.
13201  */
13202 static int calc_watermark_data(struct intel_atomic_state *state)
13203 {
13204         struct drm_device *dev = state->base.dev;
13205         struct drm_i915_private *dev_priv = to_i915(dev);
13206
13207         /* Is there platform-specific watermark information to calculate? */
13208         if (dev_priv->display.compute_global_watermarks)
13209                 return dev_priv->display.compute_global_watermarks(state);
13210
13211         return 0;
13212 }
13213
13214 /**
13215  * intel_atomic_check - validate state object
13216  * @dev: drm device
13217  * @state: state to validate
13218  */
13219 static int intel_atomic_check(struct drm_device *dev,
13220                               struct drm_atomic_state *state)
13221 {
13222         struct drm_i915_private *dev_priv = to_i915(dev);
13223         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13224         struct drm_crtc *crtc;
13225         struct drm_crtc_state *old_crtc_state, *crtc_state;
13226         int ret, i;
13227         bool any_ms = intel_state->cdclk.force_min_cdclk_changed;
13228
13229         /* Catch I915_MODE_FLAG_INHERITED */
13230         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
13231                                       crtc_state, i) {
13232                 if (crtc_state->mode.private_flags !=
13233                     old_crtc_state->mode.private_flags)
13234                         crtc_state->mode_changed = true;
13235         }
13236
13237         ret = drm_atomic_helper_check_modeset(dev, state);
13238         if (ret)
13239                 return ret;
13240
13241         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, crtc_state, i) {
13242                 struct intel_crtc_state *pipe_config =
13243                         to_intel_crtc_state(crtc_state);
13244
13245                 if (!needs_modeset(crtc_state))
13246                         continue;
13247
13248                 if (!crtc_state->enable) {
13249                         any_ms = true;
13250                         continue;
13251                 }
13252
13253                 ret = intel_modeset_pipe_config(crtc, pipe_config);
13254                 if (ret == -EDEADLK)
13255                         return ret;
13256                 if (ret) {
13257                         intel_dump_pipe_config(to_intel_crtc(crtc),
13258                                                pipe_config, "[failed]");
13259                         return ret;
13260                 }
13261
13262                 if (intel_pipe_config_compare(dev_priv,
13263                                         to_intel_crtc_state(old_crtc_state),
13264                                         pipe_config, true)) {
13265                         crtc_state->mode_changed = false;
13266                         pipe_config->update_pipe = true;
13267                 }
13268
13269                 if (needs_modeset(crtc_state))
13270                         any_ms = true;
13271
13272                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
13273                                        needs_modeset(crtc_state) ?
13274                                        "[modeset]" : "[fastset]");
13275         }
13276
13277         ret = drm_dp_mst_atomic_check(state);
13278         if (ret)
13279                 return ret;
13280
13281         if (any_ms) {
13282                 ret = intel_modeset_checks(state);
13283
13284                 if (ret)
13285                         return ret;
13286         } else {
13287                 intel_state->cdclk.logical = dev_priv->cdclk.logical;
13288         }
13289
13290         ret = icl_add_linked_planes(intel_state);
13291         if (ret)
13292                 return ret;
13293
13294         ret = drm_atomic_helper_check_planes(dev, state);
13295         if (ret)
13296                 return ret;
13297
13298         intel_fbc_choose_crtc(dev_priv, intel_state);
13299         return calc_watermark_data(intel_state);
13300 }
13301
13302 static int intel_atomic_prepare_commit(struct drm_device *dev,
13303                                        struct drm_atomic_state *state)
13304 {
13305         return drm_atomic_helper_prepare_planes(dev, state);
13306 }
13307
13308 u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc)
13309 {
13310         struct drm_device *dev = crtc->base.dev;
13311         struct drm_vblank_crtc *vblank = &dev->vblank[drm_crtc_index(&crtc->base)];
13312
13313         if (!vblank->max_vblank_count)
13314                 return (u32)drm_crtc_accurate_vblank_count(&crtc->base);
13315
13316         return dev->driver->get_vblank_counter(dev, crtc->pipe);
13317 }
13318
13319 static void intel_update_crtc(struct drm_crtc *crtc,
13320                               struct drm_atomic_state *state,
13321                               struct drm_crtc_state *old_crtc_state,
13322                               struct drm_crtc_state *new_crtc_state)
13323 {
13324         struct drm_device *dev = crtc->dev;
13325         struct drm_i915_private *dev_priv = to_i915(dev);
13326         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13327         struct intel_crtc_state *pipe_config = to_intel_crtc_state(new_crtc_state);
13328         bool modeset = needs_modeset(new_crtc_state);
13329         struct intel_plane_state *new_plane_state =
13330                 intel_atomic_get_new_plane_state(to_intel_atomic_state(state),
13331                                                  to_intel_plane(crtc->primary));
13332
13333         if (modeset) {
13334                 update_scanline_offset(pipe_config);
13335                 dev_priv->display.crtc_enable(pipe_config, state);
13336
13337                 /* vblanks work again, re-enable pipe CRC. */
13338                 intel_crtc_enable_pipe_crc(intel_crtc);
13339         } else {
13340                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
13341                                        pipe_config);
13342
13343                 if (pipe_config->update_pipe)
13344                         intel_encoders_update_pipe(crtc, pipe_config, state);
13345         }
13346
13347         if (pipe_config->update_pipe && !pipe_config->enable_fbc)
13348                 intel_fbc_disable(intel_crtc);
13349         else if (new_plane_state)
13350                 intel_fbc_enable(intel_crtc, pipe_config, new_plane_state);
13351
13352         intel_begin_crtc_commit(to_intel_atomic_state(state), intel_crtc);
13353
13354         if (INTEL_GEN(dev_priv) >= 9)
13355                 skl_update_planes_on_crtc(to_intel_atomic_state(state), intel_crtc);
13356         else
13357                 i9xx_update_planes_on_crtc(to_intel_atomic_state(state), intel_crtc);
13358
13359         intel_finish_crtc_commit(to_intel_atomic_state(state), intel_crtc);
13360 }
13361
13362 static void intel_update_crtcs(struct drm_atomic_state *state)
13363 {
13364         struct drm_crtc *crtc;
13365         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
13366         int i;
13367
13368         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13369                 if (!new_crtc_state->active)
13370                         continue;
13371
13372                 intel_update_crtc(crtc, state, old_crtc_state,
13373                                   new_crtc_state);
13374         }
13375 }
13376
13377 static void skl_update_crtcs(struct drm_atomic_state *state)
13378 {
13379         struct drm_i915_private *dev_priv = to_i915(state->dev);
13380         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13381         struct drm_crtc *crtc;
13382         struct intel_crtc *intel_crtc;
13383         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
13384         struct intel_crtc_state *cstate;
13385         unsigned int updated = 0;
13386         bool progress;
13387         enum pipe pipe;
13388         int i;
13389         u8 hw_enabled_slices = dev_priv->wm.skl_hw.ddb.enabled_slices;
13390         u8 required_slices = intel_state->wm_results.ddb.enabled_slices;
13391         struct skl_ddb_entry entries[I915_MAX_PIPES] = {};
13392
13393         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i)
13394                 /* ignore allocations for crtc's that have been turned off. */
13395                 if (new_crtc_state->active)
13396                         entries[i] = to_intel_crtc_state(old_crtc_state)->wm.skl.ddb;
13397
13398         /* If 2nd DBuf slice required, enable it here */
13399         if (INTEL_GEN(dev_priv) >= 11 && required_slices > hw_enabled_slices)
13400                 icl_dbuf_slices_update(dev_priv, required_slices);
13401
13402         /*
13403          * Whenever the number of active pipes changes, we need to make sure we
13404          * update the pipes in the right order so that their ddb allocations
13405          * never overlap with eachother inbetween CRTC updates. Otherwise we'll
13406          * cause pipe underruns and other bad stuff.
13407          */
13408         do {
13409                 progress = false;
13410
13411                 for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13412                         bool vbl_wait = false;
13413                         unsigned int cmask = drm_crtc_mask(crtc);
13414
13415                         intel_crtc = to_intel_crtc(crtc);
13416                         cstate = to_intel_crtc_state(new_crtc_state);
13417                         pipe = intel_crtc->pipe;
13418
13419                         if (updated & cmask || !cstate->base.active)
13420                                 continue;
13421
13422                         if (skl_ddb_allocation_overlaps(&cstate->wm.skl.ddb,
13423                                                         entries,
13424                                                         INTEL_INFO(dev_priv)->num_pipes, i))
13425                                 continue;
13426
13427                         updated |= cmask;
13428                         entries[i] = cstate->wm.skl.ddb;
13429
13430                         /*
13431                          * If this is an already active pipe, it's DDB changed,
13432                          * and this isn't the last pipe that needs updating
13433                          * then we need to wait for a vblank to pass for the
13434                          * new ddb allocation to take effect.
13435                          */
13436                         if (!skl_ddb_entry_equal(&cstate->wm.skl.ddb,
13437                                                  &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb) &&
13438                             !new_crtc_state->active_changed &&
13439                             intel_state->wm_results.dirty_pipes != updated)
13440                                 vbl_wait = true;
13441
13442                         intel_update_crtc(crtc, state, old_crtc_state,
13443                                           new_crtc_state);
13444
13445                         if (vbl_wait)
13446                                 intel_wait_for_vblank(dev_priv, pipe);
13447
13448                         progress = true;
13449                 }
13450         } while (progress);
13451
13452         /* If 2nd DBuf slice is no more required disable it */
13453         if (INTEL_GEN(dev_priv) >= 11 && required_slices < hw_enabled_slices)
13454                 icl_dbuf_slices_update(dev_priv, required_slices);
13455 }
13456
13457 static void intel_atomic_helper_free_state(struct drm_i915_private *dev_priv)
13458 {
13459         struct intel_atomic_state *state, *next;
13460         struct llist_node *freed;
13461
13462         freed = llist_del_all(&dev_priv->atomic_helper.free_list);
13463         llist_for_each_entry_safe(state, next, freed, freed)
13464                 drm_atomic_state_put(&state->base);
13465 }
13466
13467 static void intel_atomic_helper_free_state_worker(struct work_struct *work)
13468 {
13469         struct drm_i915_private *dev_priv =
13470                 container_of(work, typeof(*dev_priv), atomic_helper.free_work);
13471
13472         intel_atomic_helper_free_state(dev_priv);
13473 }
13474
13475 static void intel_atomic_commit_fence_wait(struct intel_atomic_state *intel_state)
13476 {
13477         struct wait_queue_entry wait_fence, wait_reset;
13478         struct drm_i915_private *dev_priv = to_i915(intel_state->base.dev);
13479
13480         init_wait_entry(&wait_fence, 0);
13481         init_wait_entry(&wait_reset, 0);
13482         for (;;) {
13483                 prepare_to_wait(&intel_state->commit_ready.wait,
13484                                 &wait_fence, TASK_UNINTERRUPTIBLE);
13485                 prepare_to_wait(&dev_priv->gpu_error.wait_queue,
13486                                 &wait_reset, TASK_UNINTERRUPTIBLE);
13487
13488
13489                 if (i915_sw_fence_done(&intel_state->commit_ready)
13490                     || test_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags))
13491                         break;
13492
13493                 schedule();
13494         }
13495         finish_wait(&intel_state->commit_ready.wait, &wait_fence);
13496         finish_wait(&dev_priv->gpu_error.wait_queue, &wait_reset);
13497 }
13498
13499 static void intel_atomic_cleanup_work(struct work_struct *work)
13500 {
13501         struct drm_atomic_state *state =
13502                 container_of(work, struct drm_atomic_state, commit_work);
13503         struct drm_i915_private *i915 = to_i915(state->dev);
13504
13505         drm_atomic_helper_cleanup_planes(&i915->drm, state);
13506         drm_atomic_helper_commit_cleanup_done(state);
13507         drm_atomic_state_put(state);
13508
13509         intel_atomic_helper_free_state(i915);
13510 }
13511
13512 static void intel_atomic_commit_tail(struct drm_atomic_state *state)
13513 {
13514         struct drm_device *dev = state->dev;
13515         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13516         struct drm_i915_private *dev_priv = to_i915(dev);
13517         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
13518         struct intel_crtc_state *new_intel_crtc_state, *old_intel_crtc_state;
13519         struct drm_crtc *crtc;
13520         struct intel_crtc *intel_crtc;
13521         u64 put_domains[I915_MAX_PIPES] = {};
13522         intel_wakeref_t wakeref = 0;
13523         int i;
13524
13525         intel_atomic_commit_fence_wait(intel_state);
13526
13527         drm_atomic_helper_wait_for_dependencies(state);
13528
13529         if (intel_state->modeset)
13530                 wakeref = intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
13531
13532         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13533                 old_intel_crtc_state = to_intel_crtc_state(old_crtc_state);
13534                 new_intel_crtc_state = to_intel_crtc_state(new_crtc_state);
13535                 intel_crtc = to_intel_crtc(crtc);
13536
13537                 if (needs_modeset(new_crtc_state) ||
13538                     to_intel_crtc_state(new_crtc_state)->update_pipe) {
13539
13540                         put_domains[intel_crtc->pipe] =
13541                                 modeset_get_crtc_power_domains(crtc,
13542                                         new_intel_crtc_state);
13543                 }
13544
13545                 if (!needs_modeset(new_crtc_state))
13546                         continue;
13547
13548                 intel_pre_plane_update(old_intel_crtc_state, new_intel_crtc_state);
13549
13550                 if (old_crtc_state->active) {
13551                         intel_crtc_disable_planes(intel_state, intel_crtc);
13552
13553                         /*
13554                          * We need to disable pipe CRC before disabling the pipe,
13555                          * or we race against vblank off.
13556                          */
13557                         intel_crtc_disable_pipe_crc(intel_crtc);
13558
13559                         dev_priv->display.crtc_disable(old_intel_crtc_state, state);
13560                         intel_crtc->active = false;
13561                         intel_fbc_disable(intel_crtc);
13562                         intel_disable_shared_dpll(old_intel_crtc_state);
13563
13564                         /*
13565                          * Underruns don't always raise
13566                          * interrupts, so check manually.
13567                          */
13568                         intel_check_cpu_fifo_underruns(dev_priv);
13569                         intel_check_pch_fifo_underruns(dev_priv);
13570
13571                         /* FIXME unify this for all platforms */
13572                         if (!new_crtc_state->active &&
13573                             !HAS_GMCH(dev_priv) &&
13574                             dev_priv->display.initial_watermarks)
13575                                 dev_priv->display.initial_watermarks(intel_state,
13576                                                                      new_intel_crtc_state);
13577                 }
13578         }
13579
13580         /* FIXME: Eventually get rid of our intel_crtc->config pointer */
13581         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i)
13582                 to_intel_crtc(crtc)->config = to_intel_crtc_state(new_crtc_state);
13583
13584         if (intel_state->modeset) {
13585                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
13586
13587                 intel_set_cdclk_pre_plane_update(dev_priv,
13588                                                  &intel_state->cdclk.actual,
13589                                                  &dev_priv->cdclk.actual,
13590                                                  intel_state->cdclk.pipe);
13591
13592                 /*
13593                  * SKL workaround: bspec recommends we disable the SAGV when we
13594                  * have more then one pipe enabled
13595                  */
13596                 if (!intel_can_enable_sagv(state))
13597                         intel_disable_sagv(dev_priv);
13598
13599                 intel_modeset_verify_disabled(dev, state);
13600         }
13601
13602         /* Complete the events for pipes that have now been disabled */
13603         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13604                 bool modeset = needs_modeset(new_crtc_state);
13605
13606                 /* Complete events for now disable pipes here. */
13607                 if (modeset && !new_crtc_state->active && new_crtc_state->event) {
13608                         spin_lock_irq(&dev->event_lock);
13609                         drm_crtc_send_vblank_event(crtc, new_crtc_state->event);
13610                         spin_unlock_irq(&dev->event_lock);
13611
13612                         new_crtc_state->event = NULL;
13613                 }
13614         }
13615
13616         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
13617         dev_priv->display.update_crtcs(state);
13618
13619         if (intel_state->modeset)
13620                 intel_set_cdclk_post_plane_update(dev_priv,
13621                                                   &intel_state->cdclk.actual,
13622                                                   &dev_priv->cdclk.actual,
13623                                                   intel_state->cdclk.pipe);
13624
13625         /* FIXME: We should call drm_atomic_helper_commit_hw_done() here
13626          * already, but still need the state for the delayed optimization. To
13627          * fix this:
13628          * - wrap the optimization/post_plane_update stuff into a per-crtc work.
13629          * - schedule that vblank worker _before_ calling hw_done
13630          * - at the start of commit_tail, cancel it _synchrously
13631          * - switch over to the vblank wait helper in the core after that since
13632          *   we don't need out special handling any more.
13633          */
13634         drm_atomic_helper_wait_for_flip_done(dev, state);
13635
13636         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13637                 new_intel_crtc_state = to_intel_crtc_state(new_crtc_state);
13638
13639                 if (new_crtc_state->active &&
13640                     !needs_modeset(new_crtc_state) &&
13641                     (new_intel_crtc_state->base.color_mgmt_changed ||
13642                      new_intel_crtc_state->update_pipe))
13643                         intel_color_load_luts(new_intel_crtc_state);
13644         }
13645
13646         /*
13647          * Now that the vblank has passed, we can go ahead and program the
13648          * optimal watermarks on platforms that need two-step watermark
13649          * programming.
13650          *
13651          * TODO: Move this (and other cleanup) to an async worker eventually.
13652          */
13653         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13654                 new_intel_crtc_state = to_intel_crtc_state(new_crtc_state);
13655
13656                 if (dev_priv->display.optimize_watermarks)
13657                         dev_priv->display.optimize_watermarks(intel_state,
13658                                                               new_intel_crtc_state);
13659         }
13660
13661         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13662                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
13663
13664                 if (put_domains[i])
13665                         modeset_put_power_domains(dev_priv, put_domains[i]);
13666
13667                 intel_modeset_verify_crtc(crtc, state, old_crtc_state, new_crtc_state);
13668         }
13669
13670         if (intel_state->modeset)
13671                 intel_verify_planes(intel_state);
13672
13673         if (intel_state->modeset && intel_can_enable_sagv(state))
13674                 intel_enable_sagv(dev_priv);
13675
13676         drm_atomic_helper_commit_hw_done(state);
13677
13678         if (intel_state->modeset) {
13679                 /* As one of the primary mmio accessors, KMS has a high
13680                  * likelihood of triggering bugs in unclaimed access. After we
13681                  * finish modesetting, see if an error has been flagged, and if
13682                  * so enable debugging for the next modeset - and hope we catch
13683                  * the culprit.
13684                  */
13685                 intel_uncore_arm_unclaimed_mmio_detection(&dev_priv->uncore);
13686                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET, wakeref);
13687         }
13688
13689         /*
13690          * Defer the cleanup of the old state to a separate worker to not
13691          * impede the current task (userspace for blocking modesets) that
13692          * are executed inline. For out-of-line asynchronous modesets/flips,
13693          * deferring to a new worker seems overkill, but we would place a
13694          * schedule point (cond_resched()) here anyway to keep latencies
13695          * down.
13696          */
13697         INIT_WORK(&state->commit_work, intel_atomic_cleanup_work);
13698         queue_work(system_highpri_wq, &state->commit_work);
13699 }
13700
13701 static void intel_atomic_commit_work(struct work_struct *work)
13702 {
13703         struct drm_atomic_state *state =
13704                 container_of(work, struct drm_atomic_state, commit_work);
13705
13706         intel_atomic_commit_tail(state);
13707 }
13708
13709 static int __i915_sw_fence_call
13710 intel_atomic_commit_ready(struct i915_sw_fence *fence,
13711                           enum i915_sw_fence_notify notify)
13712 {
13713         struct intel_atomic_state *state =
13714                 container_of(fence, struct intel_atomic_state, commit_ready);
13715
13716         switch (notify) {
13717         case FENCE_COMPLETE:
13718                 /* we do blocking waits in the worker, nothing to do here */
13719                 break;
13720         case FENCE_FREE:
13721                 {
13722                         struct intel_atomic_helper *helper =
13723                                 &to_i915(state->base.dev)->atomic_helper;
13724
13725                         if (llist_add(&state->freed, &helper->free_list))
13726                                 schedule_work(&helper->free_work);
13727                         break;
13728                 }
13729         }
13730
13731         return NOTIFY_DONE;
13732 }
13733
13734 static void intel_atomic_track_fbs(struct drm_atomic_state *state)
13735 {
13736         struct drm_plane_state *old_plane_state, *new_plane_state;
13737         struct drm_plane *plane;
13738         int i;
13739
13740         for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i)
13741                 i915_gem_track_fb(intel_fb_obj(old_plane_state->fb),
13742                                   intel_fb_obj(new_plane_state->fb),
13743                                   to_intel_plane(plane)->frontbuffer_bit);
13744 }
13745
13746 /**
13747  * intel_atomic_commit - commit validated state object
13748  * @dev: DRM device
13749  * @state: the top-level driver state object
13750  * @nonblock: nonblocking commit
13751  *
13752  * This function commits a top-level state object that has been validated
13753  * with drm_atomic_helper_check().
13754  *
13755  * RETURNS
13756  * Zero for success or -errno.
13757  */
13758 static int intel_atomic_commit(struct drm_device *dev,
13759                                struct drm_atomic_state *state,
13760                                bool nonblock)
13761 {
13762         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13763         struct drm_i915_private *dev_priv = to_i915(dev);
13764         int ret = 0;
13765
13766         drm_atomic_state_get(state);
13767         i915_sw_fence_init(&intel_state->commit_ready,
13768                            intel_atomic_commit_ready);
13769
13770         /*
13771          * The intel_legacy_cursor_update() fast path takes care
13772          * of avoiding the vblank waits for simple cursor
13773          * movement and flips. For cursor on/off and size changes,
13774          * we want to perform the vblank waits so that watermark
13775          * updates happen during the correct frames. Gen9+ have
13776          * double buffered watermarks and so shouldn't need this.
13777          *
13778          * Unset state->legacy_cursor_update before the call to
13779          * drm_atomic_helper_setup_commit() because otherwise
13780          * drm_atomic_helper_wait_for_flip_done() is a noop and
13781          * we get FIFO underruns because we didn't wait
13782          * for vblank.
13783          *
13784          * FIXME doing watermarks and fb cleanup from a vblank worker
13785          * (assuming we had any) would solve these problems.
13786          */
13787         if (INTEL_GEN(dev_priv) < 9 && state->legacy_cursor_update) {
13788                 struct intel_crtc_state *new_crtc_state;
13789                 struct intel_crtc *crtc;
13790                 int i;
13791
13792                 for_each_new_intel_crtc_in_state(intel_state, crtc, new_crtc_state, i)
13793                         if (new_crtc_state->wm.need_postvbl_update ||
13794                             new_crtc_state->update_wm_post)
13795                                 state->legacy_cursor_update = false;
13796         }
13797
13798         ret = intel_atomic_prepare_commit(dev, state);
13799         if (ret) {
13800                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
13801                 i915_sw_fence_commit(&intel_state->commit_ready);
13802                 return ret;
13803         }
13804
13805         ret = drm_atomic_helper_setup_commit(state, nonblock);
13806         if (!ret)
13807                 ret = drm_atomic_helper_swap_state(state, true);
13808
13809         if (ret) {
13810                 i915_sw_fence_commit(&intel_state->commit_ready);
13811
13812                 drm_atomic_helper_cleanup_planes(dev, state);
13813                 return ret;
13814         }
13815         dev_priv->wm.distrust_bios_wm = false;
13816         intel_shared_dpll_swap_state(state);
13817         intel_atomic_track_fbs(state);
13818
13819         if (intel_state->modeset) {
13820                 memcpy(dev_priv->min_cdclk, intel_state->min_cdclk,
13821                        sizeof(intel_state->min_cdclk));
13822                 memcpy(dev_priv->min_voltage_level,
13823                        intel_state->min_voltage_level,
13824                        sizeof(intel_state->min_voltage_level));
13825                 dev_priv->active_crtcs = intel_state->active_crtcs;
13826                 dev_priv->cdclk.force_min_cdclk =
13827                         intel_state->cdclk.force_min_cdclk;
13828
13829                 intel_cdclk_swap_state(intel_state);
13830         }
13831
13832         drm_atomic_state_get(state);
13833         INIT_WORK(&state->commit_work, intel_atomic_commit_work);
13834
13835         i915_sw_fence_commit(&intel_state->commit_ready);
13836         if (nonblock && intel_state->modeset) {
13837                 queue_work(dev_priv->modeset_wq, &state->commit_work);
13838         } else if (nonblock) {
13839                 queue_work(system_unbound_wq, &state->commit_work);
13840         } else {
13841                 if (intel_state->modeset)
13842                         flush_workqueue(dev_priv->modeset_wq);
13843                 intel_atomic_commit_tail(state);
13844         }
13845
13846         return 0;
13847 }
13848
13849 static const struct drm_crtc_funcs intel_crtc_funcs = {
13850         .gamma_set = drm_atomic_helper_legacy_gamma_set,
13851         .set_config = drm_atomic_helper_set_config,
13852         .destroy = intel_crtc_destroy,
13853         .page_flip = drm_atomic_helper_page_flip,
13854         .atomic_duplicate_state = intel_crtc_duplicate_state,
13855         .atomic_destroy_state = intel_crtc_destroy_state,
13856         .set_crc_source = intel_crtc_set_crc_source,
13857         .verify_crc_source = intel_crtc_verify_crc_source,
13858         .get_crc_sources = intel_crtc_get_crc_sources,
13859 };
13860
13861 struct wait_rps_boost {
13862         struct wait_queue_entry wait;
13863
13864         struct drm_crtc *crtc;
13865         struct i915_request *request;
13866 };
13867
13868 static int do_rps_boost(struct wait_queue_entry *_wait,
13869                         unsigned mode, int sync, void *key)
13870 {
13871         struct wait_rps_boost *wait = container_of(_wait, typeof(*wait), wait);
13872         struct i915_request *rq = wait->request;
13873
13874         /*
13875          * If we missed the vblank, but the request is already running it
13876          * is reasonable to assume that it will complete before the next
13877          * vblank without our intervention, so leave RPS alone.
13878          */
13879         if (!i915_request_started(rq))
13880                 gen6_rps_boost(rq);
13881         i915_request_put(rq);
13882
13883         drm_crtc_vblank_put(wait->crtc);
13884
13885         list_del(&wait->wait.entry);
13886         kfree(wait);
13887         return 1;
13888 }
13889
13890 static void add_rps_boost_after_vblank(struct drm_crtc *crtc,
13891                                        struct dma_fence *fence)
13892 {
13893         struct wait_rps_boost *wait;
13894
13895         if (!dma_fence_is_i915(fence))
13896                 return;
13897
13898         if (INTEL_GEN(to_i915(crtc->dev)) < 6)
13899                 return;
13900
13901         if (drm_crtc_vblank_get(crtc))
13902                 return;
13903
13904         wait = kmalloc(sizeof(*wait), GFP_KERNEL);
13905         if (!wait) {
13906                 drm_crtc_vblank_put(crtc);
13907                 return;
13908         }
13909
13910         wait->request = to_request(dma_fence_get(fence));
13911         wait->crtc = crtc;
13912
13913         wait->wait.func = do_rps_boost;
13914         wait->wait.flags = 0;
13915
13916         add_wait_queue(drm_crtc_vblank_waitqueue(crtc), &wait->wait);
13917 }
13918
13919 static int intel_plane_pin_fb(struct intel_plane_state *plane_state)
13920 {
13921         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
13922         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
13923         struct drm_framebuffer *fb = plane_state->base.fb;
13924         struct i915_vma *vma;
13925
13926         if (plane->id == PLANE_CURSOR &&
13927             INTEL_INFO(dev_priv)->display.cursor_needs_physical) {
13928                 struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13929                 const int align = intel_cursor_alignment(dev_priv);
13930                 int err;
13931
13932                 err = i915_gem_object_attach_phys(obj, align);
13933                 if (err)
13934                         return err;
13935         }
13936
13937         vma = intel_pin_and_fence_fb_obj(fb,
13938                                          &plane_state->view,
13939                                          intel_plane_uses_fence(plane_state),
13940                                          &plane_state->flags);
13941         if (IS_ERR(vma))
13942                 return PTR_ERR(vma);
13943
13944         plane_state->vma = vma;
13945
13946         return 0;
13947 }
13948
13949 static void intel_plane_unpin_fb(struct intel_plane_state *old_plane_state)
13950 {
13951         struct i915_vma *vma;
13952
13953         vma = fetch_and_zero(&old_plane_state->vma);
13954         if (vma)
13955                 intel_unpin_fb_vma(vma, old_plane_state->flags);
13956 }
13957
13958 static void fb_obj_bump_render_priority(struct drm_i915_gem_object *obj)
13959 {
13960         struct i915_sched_attr attr = {
13961                 .priority = I915_PRIORITY_DISPLAY,
13962         };
13963
13964         i915_gem_object_wait_priority(obj, 0, &attr);
13965 }
13966
13967 /**
13968  * intel_prepare_plane_fb - Prepare fb for usage on plane
13969  * @plane: drm plane to prepare for
13970  * @new_state: the plane state being prepared
13971  *
13972  * Prepares a framebuffer for usage on a display plane.  Generally this
13973  * involves pinning the underlying object and updating the frontbuffer tracking
13974  * bits.  Some older platforms need special physical address handling for
13975  * cursor planes.
13976  *
13977  * Must be called with struct_mutex held.
13978  *
13979  * Returns 0 on success, negative error code on failure.
13980  */
13981 int
13982 intel_prepare_plane_fb(struct drm_plane *plane,
13983                        struct drm_plane_state *new_state)
13984 {
13985         struct intel_atomic_state *intel_state =
13986                 to_intel_atomic_state(new_state->state);
13987         struct drm_i915_private *dev_priv = to_i915(plane->dev);
13988         struct drm_framebuffer *fb = new_state->fb;
13989         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13990         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
13991         int ret;
13992
13993         if (old_obj) {
13994                 struct drm_crtc_state *crtc_state =
13995                         drm_atomic_get_new_crtc_state(new_state->state,
13996                                                       plane->state->crtc);
13997
13998                 /* Big Hammer, we also need to ensure that any pending
13999                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
14000                  * current scanout is retired before unpinning the old
14001                  * framebuffer. Note that we rely on userspace rendering
14002                  * into the buffer attached to the pipe they are waiting
14003                  * on. If not, userspace generates a GPU hang with IPEHR
14004                  * point to the MI_WAIT_FOR_EVENT.
14005                  *
14006                  * This should only fail upon a hung GPU, in which case we
14007                  * can safely continue.
14008                  */
14009                 if (needs_modeset(crtc_state)) {
14010                         ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
14011                                                               old_obj->resv, NULL,
14012                                                               false, 0,
14013                                                               GFP_KERNEL);
14014                         if (ret < 0)
14015                                 return ret;
14016                 }
14017         }
14018
14019         if (new_state->fence) { /* explicit fencing */
14020                 ret = i915_sw_fence_await_dma_fence(&intel_state->commit_ready,
14021                                                     new_state->fence,
14022                                                     I915_FENCE_TIMEOUT,
14023                                                     GFP_KERNEL);
14024                 if (ret < 0)
14025                         return ret;
14026         }
14027
14028         if (!obj)
14029                 return 0;
14030
14031         ret = i915_gem_object_pin_pages(obj);
14032         if (ret)
14033                 return ret;
14034
14035         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
14036         if (ret) {
14037                 i915_gem_object_unpin_pages(obj);
14038                 return ret;
14039         }
14040
14041         ret = intel_plane_pin_fb(to_intel_plane_state(new_state));
14042
14043         mutex_unlock(&dev_priv->drm.struct_mutex);
14044         i915_gem_object_unpin_pages(obj);
14045         if (ret)
14046                 return ret;
14047
14048         fb_obj_bump_render_priority(obj);
14049         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
14050
14051         if (!new_state->fence) { /* implicit fencing */
14052                 struct dma_fence *fence;
14053
14054                 ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
14055                                                       obj->resv, NULL,
14056                                                       false, I915_FENCE_TIMEOUT,
14057                                                       GFP_KERNEL);
14058                 if (ret < 0)
14059                         return ret;
14060
14061                 fence = reservation_object_get_excl_rcu(obj->resv);
14062                 if (fence) {
14063                         add_rps_boost_after_vblank(new_state->crtc, fence);
14064                         dma_fence_put(fence);
14065                 }
14066         } else {
14067                 add_rps_boost_after_vblank(new_state->crtc, new_state->fence);
14068         }
14069
14070         /*
14071          * We declare pageflips to be interactive and so merit a small bias
14072          * towards upclocking to deliver the frame on time. By only changing
14073          * the RPS thresholds to sample more regularly and aim for higher
14074          * clocks we can hopefully deliver low power workloads (like kodi)
14075          * that are not quite steady state without resorting to forcing
14076          * maximum clocks following a vblank miss (see do_rps_boost()).
14077          */
14078         if (!intel_state->rps_interactive) {
14079                 intel_rps_mark_interactive(dev_priv, true);
14080                 intel_state->rps_interactive = true;
14081         }
14082
14083         return 0;
14084 }
14085
14086 /**
14087  * intel_cleanup_plane_fb - Cleans up an fb after plane use
14088  * @plane: drm plane to clean up for
14089  * @old_state: the state from the previous modeset
14090  *
14091  * Cleans up a framebuffer that has just been removed from a plane.
14092  *
14093  * Must be called with struct_mutex held.
14094  */
14095 void
14096 intel_cleanup_plane_fb(struct drm_plane *plane,
14097                        struct drm_plane_state *old_state)
14098 {
14099         struct intel_atomic_state *intel_state =
14100                 to_intel_atomic_state(old_state->state);
14101         struct drm_i915_private *dev_priv = to_i915(plane->dev);
14102
14103         if (intel_state->rps_interactive) {
14104                 intel_rps_mark_interactive(dev_priv, false);
14105                 intel_state->rps_interactive = false;
14106         }
14107
14108         /* Should only be called after a successful intel_prepare_plane_fb()! */
14109         mutex_lock(&dev_priv->drm.struct_mutex);
14110         intel_plane_unpin_fb(to_intel_plane_state(old_state));
14111         mutex_unlock(&dev_priv->drm.struct_mutex);
14112 }
14113
14114 int
14115 skl_max_scale(const struct intel_crtc_state *crtc_state,
14116               u32 pixel_format)
14117 {
14118         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
14119         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
14120         int max_scale, mult;
14121         int crtc_clock, max_dotclk, tmpclk1, tmpclk2;
14122
14123         if (!crtc_state->base.enable)
14124                 return DRM_PLANE_HELPER_NO_SCALING;
14125
14126         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
14127         max_dotclk = to_intel_atomic_state(crtc_state->base.state)->cdclk.logical.cdclk;
14128
14129         if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) >= 10)
14130                 max_dotclk *= 2;
14131
14132         if (WARN_ON_ONCE(!crtc_clock || max_dotclk < crtc_clock))
14133                 return DRM_PLANE_HELPER_NO_SCALING;
14134
14135         /*
14136          * skl max scale is lower of:
14137          *    close to 3 but not 3, -1 is for that purpose
14138          *            or
14139          *    cdclk/crtc_clock
14140          */
14141         mult = is_planar_yuv_format(pixel_format) ? 2 : 3;
14142         tmpclk1 = (1 << 16) * mult - 1;
14143         tmpclk2 = (1 << 8) * ((max_dotclk << 8) / crtc_clock);
14144         max_scale = min(tmpclk1, tmpclk2);
14145
14146         return max_scale;
14147 }
14148
14149 static void intel_begin_crtc_commit(struct intel_atomic_state *state,
14150                                     struct intel_crtc *crtc)
14151 {
14152         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
14153         struct intel_crtc_state *old_crtc_state =
14154                 intel_atomic_get_old_crtc_state(state, crtc);
14155         struct intel_crtc_state *new_crtc_state =
14156                 intel_atomic_get_new_crtc_state(state, crtc);
14157         bool modeset = needs_modeset(&new_crtc_state->base);
14158
14159         /* Perform vblank evasion around commit operation */
14160         intel_pipe_update_start(new_crtc_state);
14161
14162         if (modeset)
14163                 goto out;
14164
14165         if (new_crtc_state->base.color_mgmt_changed ||
14166             new_crtc_state->update_pipe)
14167                 intel_color_commit(new_crtc_state);
14168
14169         if (new_crtc_state->update_pipe)
14170                 intel_update_pipe_config(old_crtc_state, new_crtc_state);
14171         else if (INTEL_GEN(dev_priv) >= 9)
14172                 skl_detach_scalers(new_crtc_state);
14173
14174         if (INTEL_GEN(dev_priv) >= 9 || IS_BROADWELL(dev_priv))
14175                 bdw_set_pipemisc(new_crtc_state);
14176
14177 out:
14178         if (dev_priv->display.atomic_update_watermarks)
14179                 dev_priv->display.atomic_update_watermarks(state,
14180                                                            new_crtc_state);
14181 }
14182
14183 void intel_crtc_arm_fifo_underrun(struct intel_crtc *crtc,
14184                                   struct intel_crtc_state *crtc_state)
14185 {
14186         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
14187
14188         if (!IS_GEN(dev_priv, 2))
14189                 intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, true);
14190
14191         if (crtc_state->has_pch_encoder) {
14192                 enum pipe pch_transcoder =
14193                         intel_crtc_pch_transcoder(crtc);
14194
14195                 intel_set_pch_fifo_underrun_reporting(dev_priv, pch_transcoder, true);
14196         }
14197 }
14198
14199 static void intel_finish_crtc_commit(struct intel_atomic_state *state,
14200                                      struct intel_crtc *crtc)
14201 {
14202         struct intel_crtc_state *old_crtc_state =
14203                 intel_atomic_get_old_crtc_state(state, crtc);
14204         struct intel_crtc_state *new_crtc_state =
14205                 intel_atomic_get_new_crtc_state(state, crtc);
14206
14207         intel_pipe_update_end(new_crtc_state);
14208
14209         if (new_crtc_state->update_pipe &&
14210             !needs_modeset(&new_crtc_state->base) &&
14211             old_crtc_state->base.mode.private_flags & I915_MODE_FLAG_INHERITED)
14212                 intel_crtc_arm_fifo_underrun(crtc, new_crtc_state);
14213 }
14214
14215 /**
14216  * intel_plane_destroy - destroy a plane
14217  * @plane: plane to destroy
14218  *
14219  * Common destruction function for all types of planes (primary, cursor,
14220  * sprite).
14221  */
14222 void intel_plane_destroy(struct drm_plane *plane)
14223 {
14224         drm_plane_cleanup(plane);
14225         kfree(to_intel_plane(plane));
14226 }
14227
14228 static bool i8xx_plane_format_mod_supported(struct drm_plane *_plane,
14229                                             u32 format, u64 modifier)
14230 {
14231         switch (modifier) {
14232         case DRM_FORMAT_MOD_LINEAR:
14233         case I915_FORMAT_MOD_X_TILED:
14234                 break;
14235         default:
14236                 return false;
14237         }
14238
14239         switch (format) {
14240         case DRM_FORMAT_C8:
14241         case DRM_FORMAT_RGB565:
14242         case DRM_FORMAT_XRGB1555:
14243         case DRM_FORMAT_XRGB8888:
14244                 return modifier == DRM_FORMAT_MOD_LINEAR ||
14245                         modifier == I915_FORMAT_MOD_X_TILED;
14246         default:
14247                 return false;
14248         }
14249 }
14250
14251 static bool i965_plane_format_mod_supported(struct drm_plane *_plane,
14252                                             u32 format, u64 modifier)
14253 {
14254         switch (modifier) {
14255         case DRM_FORMAT_MOD_LINEAR:
14256         case I915_FORMAT_MOD_X_TILED:
14257                 break;
14258         default:
14259                 return false;
14260         }
14261
14262         switch (format) {
14263         case DRM_FORMAT_C8:
14264         case DRM_FORMAT_RGB565:
14265         case DRM_FORMAT_XRGB8888:
14266         case DRM_FORMAT_XBGR8888:
14267         case DRM_FORMAT_XRGB2101010:
14268         case DRM_FORMAT_XBGR2101010:
14269                 return modifier == DRM_FORMAT_MOD_LINEAR ||
14270                         modifier == I915_FORMAT_MOD_X_TILED;
14271         default:
14272                 return false;
14273         }
14274 }
14275
14276 static bool intel_cursor_format_mod_supported(struct drm_plane *_plane,
14277                                               u32 format, u64 modifier)
14278 {
14279         return modifier == DRM_FORMAT_MOD_LINEAR &&
14280                 format == DRM_FORMAT_ARGB8888;
14281 }
14282
14283 static const struct drm_plane_funcs i965_plane_funcs = {
14284         .update_plane = drm_atomic_helper_update_plane,
14285         .disable_plane = drm_atomic_helper_disable_plane,
14286         .destroy = intel_plane_destroy,
14287         .atomic_get_property = intel_plane_atomic_get_property,
14288         .atomic_set_property = intel_plane_atomic_set_property,
14289         .atomic_duplicate_state = intel_plane_duplicate_state,
14290         .atomic_destroy_state = intel_plane_destroy_state,
14291         .format_mod_supported = i965_plane_format_mod_supported,
14292 };
14293
14294 static const struct drm_plane_funcs i8xx_plane_funcs = {
14295         .update_plane = drm_atomic_helper_update_plane,
14296         .disable_plane = drm_atomic_helper_disable_plane,
14297         .destroy = intel_plane_destroy,
14298         .atomic_get_property = intel_plane_atomic_get_property,
14299         .atomic_set_property = intel_plane_atomic_set_property,
14300         .atomic_duplicate_state = intel_plane_duplicate_state,
14301         .atomic_destroy_state = intel_plane_destroy_state,
14302         .format_mod_supported = i8xx_plane_format_mod_supported,
14303 };
14304
14305 static int
14306 intel_legacy_cursor_update(struct drm_plane *plane,
14307                            struct drm_crtc *crtc,
14308                            struct drm_framebuffer *fb,
14309                            int crtc_x, int crtc_y,
14310                            unsigned int crtc_w, unsigned int crtc_h,
14311                            u32 src_x, u32 src_y,
14312                            u32 src_w, u32 src_h,
14313                            struct drm_modeset_acquire_ctx *ctx)
14314 {
14315         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
14316         int ret;
14317         struct drm_plane_state *old_plane_state, *new_plane_state;
14318         struct intel_plane *intel_plane = to_intel_plane(plane);
14319         struct drm_framebuffer *old_fb;
14320         struct intel_crtc_state *crtc_state =
14321                 to_intel_crtc_state(crtc->state);
14322         struct intel_crtc_state *new_crtc_state;
14323
14324         /*
14325          * When crtc is inactive or there is a modeset pending,
14326          * wait for it to complete in the slowpath
14327          */
14328         if (!crtc_state->base.active || needs_modeset(&crtc_state->base) ||
14329             crtc_state->update_pipe)
14330                 goto slow;
14331
14332         old_plane_state = plane->state;
14333         /*
14334          * Don't do an async update if there is an outstanding commit modifying
14335          * the plane.  This prevents our async update's changes from getting
14336          * overridden by a previous synchronous update's state.
14337          */
14338         if (old_plane_state->commit &&
14339             !try_wait_for_completion(&old_plane_state->commit->hw_done))
14340                 goto slow;
14341
14342         /*
14343          * If any parameters change that may affect watermarks,
14344          * take the slowpath. Only changing fb or position should be
14345          * in the fastpath.
14346          */
14347         if (old_plane_state->crtc != crtc ||
14348             old_plane_state->src_w != src_w ||
14349             old_plane_state->src_h != src_h ||
14350             old_plane_state->crtc_w != crtc_w ||
14351             old_plane_state->crtc_h != crtc_h ||
14352             !old_plane_state->fb != !fb)
14353                 goto slow;
14354
14355         new_plane_state = intel_plane_duplicate_state(plane);
14356         if (!new_plane_state)
14357                 return -ENOMEM;
14358
14359         new_crtc_state = to_intel_crtc_state(intel_crtc_duplicate_state(crtc));
14360         if (!new_crtc_state) {
14361                 ret = -ENOMEM;
14362                 goto out_free;
14363         }
14364
14365         drm_atomic_set_fb_for_plane(new_plane_state, fb);
14366
14367         new_plane_state->src_x = src_x;
14368         new_plane_state->src_y = src_y;
14369         new_plane_state->src_w = src_w;
14370         new_plane_state->src_h = src_h;
14371         new_plane_state->crtc_x = crtc_x;
14372         new_plane_state->crtc_y = crtc_y;
14373         new_plane_state->crtc_w = crtc_w;
14374         new_plane_state->crtc_h = crtc_h;
14375
14376         ret = intel_plane_atomic_check_with_state(crtc_state, new_crtc_state,
14377                                                   to_intel_plane_state(old_plane_state),
14378                                                   to_intel_plane_state(new_plane_state));
14379         if (ret)
14380                 goto out_free;
14381
14382         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
14383         if (ret)
14384                 goto out_free;
14385
14386         ret = intel_plane_pin_fb(to_intel_plane_state(new_plane_state));
14387         if (ret)
14388                 goto out_unlock;
14389
14390         intel_fb_obj_flush(intel_fb_obj(fb), ORIGIN_FLIP);
14391
14392         old_fb = old_plane_state->fb;
14393         i915_gem_track_fb(intel_fb_obj(old_fb), intel_fb_obj(fb),
14394                           intel_plane->frontbuffer_bit);
14395
14396         /* Swap plane state */
14397         plane->state = new_plane_state;
14398
14399         /*
14400          * We cannot swap crtc_state as it may be in use by an atomic commit or
14401          * page flip that's running simultaneously. If we swap crtc_state and
14402          * destroy the old state, we will cause a use-after-free there.
14403          *
14404          * Only update active_planes, which is needed for our internal
14405          * bookkeeping. Either value will do the right thing when updating
14406          * planes atomically. If the cursor was part of the atomic update then
14407          * we would have taken the slowpath.
14408          */
14409         crtc_state->active_planes = new_crtc_state->active_planes;
14410
14411         if (plane->state->visible)
14412                 intel_update_plane(intel_plane, crtc_state,
14413                                    to_intel_plane_state(plane->state));
14414         else
14415                 intel_disable_plane(intel_plane, crtc_state);
14416
14417         intel_plane_unpin_fb(to_intel_plane_state(old_plane_state));
14418
14419 out_unlock:
14420         mutex_unlock(&dev_priv->drm.struct_mutex);
14421 out_free:
14422         if (new_crtc_state)
14423                 intel_crtc_destroy_state(crtc, &new_crtc_state->base);
14424         if (ret)
14425                 intel_plane_destroy_state(plane, new_plane_state);
14426         else
14427                 intel_plane_destroy_state(plane, old_plane_state);
14428         return ret;
14429
14430 slow:
14431         return drm_atomic_helper_update_plane(plane, crtc, fb,
14432                                               crtc_x, crtc_y, crtc_w, crtc_h,
14433                                               src_x, src_y, src_w, src_h, ctx);
14434 }
14435
14436 static const struct drm_plane_funcs intel_cursor_plane_funcs = {
14437         .update_plane = intel_legacy_cursor_update,
14438         .disable_plane = drm_atomic_helper_disable_plane,
14439         .destroy = intel_plane_destroy,
14440         .atomic_get_property = intel_plane_atomic_get_property,
14441         .atomic_set_property = intel_plane_atomic_set_property,
14442         .atomic_duplicate_state = intel_plane_duplicate_state,
14443         .atomic_destroy_state = intel_plane_destroy_state,
14444         .format_mod_supported = intel_cursor_format_mod_supported,
14445 };
14446
14447 static bool i9xx_plane_has_fbc(struct drm_i915_private *dev_priv,
14448                                enum i9xx_plane_id i9xx_plane)
14449 {
14450         if (!HAS_FBC(dev_priv))
14451                 return false;
14452
14453         if (IS_BROADWELL(dev_priv) || IS_HASWELL(dev_priv))
14454                 return i9xx_plane == PLANE_A; /* tied to pipe A */
14455         else if (IS_IVYBRIDGE(dev_priv))
14456                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B ||
14457                         i9xx_plane == PLANE_C;
14458         else if (INTEL_GEN(dev_priv) >= 4)
14459                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B;
14460         else
14461                 return i9xx_plane == PLANE_A;
14462 }
14463
14464 static struct intel_plane *
14465 intel_primary_plane_create(struct drm_i915_private *dev_priv, enum pipe pipe)
14466 {
14467         struct intel_plane *plane;
14468         const struct drm_plane_funcs *plane_funcs;
14469         unsigned int supported_rotations;
14470         unsigned int possible_crtcs;
14471         const u64 *modifiers;
14472         const u32 *formats;
14473         int num_formats;
14474         int ret;
14475
14476         if (INTEL_GEN(dev_priv) >= 9)
14477                 return skl_universal_plane_create(dev_priv, pipe,
14478                                                   PLANE_PRIMARY);
14479
14480         plane = intel_plane_alloc();
14481         if (IS_ERR(plane))
14482                 return plane;
14483
14484         plane->pipe = pipe;
14485         /*
14486          * On gen2/3 only plane A can do FBC, but the panel fitter and LVDS
14487          * port is hooked to pipe B. Hence we want plane A feeding pipe B.
14488          */
14489         if (HAS_FBC(dev_priv) && INTEL_GEN(dev_priv) < 4)
14490                 plane->i9xx_plane = (enum i9xx_plane_id) !pipe;
14491         else
14492                 plane->i9xx_plane = (enum i9xx_plane_id) pipe;
14493         plane->id = PLANE_PRIMARY;
14494         plane->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, plane->id);
14495
14496         plane->has_fbc = i9xx_plane_has_fbc(dev_priv, plane->i9xx_plane);
14497         if (plane->has_fbc) {
14498                 struct intel_fbc *fbc = &dev_priv->fbc;
14499
14500                 fbc->possible_framebuffer_bits |= plane->frontbuffer_bit;
14501         }
14502
14503         if (INTEL_GEN(dev_priv) >= 4) {
14504                 formats = i965_primary_formats;
14505                 num_formats = ARRAY_SIZE(i965_primary_formats);
14506                 modifiers = i9xx_format_modifiers;
14507
14508                 plane->max_stride = i9xx_plane_max_stride;
14509                 plane->update_plane = i9xx_update_plane;
14510                 plane->disable_plane = i9xx_disable_plane;
14511                 plane->get_hw_state = i9xx_plane_get_hw_state;
14512                 plane->check_plane = i9xx_plane_check;
14513
14514                 plane_funcs = &i965_plane_funcs;
14515         } else {
14516                 formats = i8xx_primary_formats;
14517                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
14518                 modifiers = i9xx_format_modifiers;
14519
14520                 plane->max_stride = i9xx_plane_max_stride;
14521                 plane->update_plane = i9xx_update_plane;
14522                 plane->disable_plane = i9xx_disable_plane;
14523                 plane->get_hw_state = i9xx_plane_get_hw_state;
14524                 plane->check_plane = i9xx_plane_check;
14525
14526                 plane_funcs = &i8xx_plane_funcs;
14527         }
14528
14529         possible_crtcs = BIT(pipe);
14530
14531         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
14532                 ret = drm_universal_plane_init(&dev_priv->drm, &plane->base,
14533                                                possible_crtcs, plane_funcs,
14534                                                formats, num_formats, modifiers,
14535                                                DRM_PLANE_TYPE_PRIMARY,
14536                                                "primary %c", pipe_name(pipe));
14537         else
14538                 ret = drm_universal_plane_init(&dev_priv->drm, &plane->base,
14539                                                possible_crtcs, plane_funcs,
14540                                                formats, num_formats, modifiers,
14541                                                DRM_PLANE_TYPE_PRIMARY,
14542                                                "plane %c",
14543                                                plane_name(plane->i9xx_plane));
14544         if (ret)
14545                 goto fail;
14546
14547         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
14548                 supported_rotations =
14549                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180 |
14550                         DRM_MODE_REFLECT_X;
14551         } else if (INTEL_GEN(dev_priv) >= 4) {
14552                 supported_rotations =
14553                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180;
14554         } else {
14555                 supported_rotations = DRM_MODE_ROTATE_0;
14556         }
14557
14558         if (INTEL_GEN(dev_priv) >= 4)
14559                 drm_plane_create_rotation_property(&plane->base,
14560                                                    DRM_MODE_ROTATE_0,
14561                                                    supported_rotations);
14562
14563         drm_plane_helper_add(&plane->base, &intel_plane_helper_funcs);
14564
14565         return plane;
14566
14567 fail:
14568         intel_plane_free(plane);
14569
14570         return ERR_PTR(ret);
14571 }
14572
14573 static struct intel_plane *
14574 intel_cursor_plane_create(struct drm_i915_private *dev_priv,
14575                           enum pipe pipe)
14576 {
14577         unsigned int possible_crtcs;
14578         struct intel_plane *cursor;
14579         int ret;
14580
14581         cursor = intel_plane_alloc();
14582         if (IS_ERR(cursor))
14583                 return cursor;
14584
14585         cursor->pipe = pipe;
14586         cursor->i9xx_plane = (enum i9xx_plane_id) pipe;
14587         cursor->id = PLANE_CURSOR;
14588         cursor->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, cursor->id);
14589
14590         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
14591                 cursor->max_stride = i845_cursor_max_stride;
14592                 cursor->update_plane = i845_update_cursor;
14593                 cursor->disable_plane = i845_disable_cursor;
14594                 cursor->get_hw_state = i845_cursor_get_hw_state;
14595                 cursor->check_plane = i845_check_cursor;
14596         } else {
14597                 cursor->max_stride = i9xx_cursor_max_stride;
14598                 cursor->update_plane = i9xx_update_cursor;
14599                 cursor->disable_plane = i9xx_disable_cursor;
14600                 cursor->get_hw_state = i9xx_cursor_get_hw_state;
14601                 cursor->check_plane = i9xx_check_cursor;
14602         }
14603
14604         cursor->cursor.base = ~0;
14605         cursor->cursor.cntl = ~0;
14606
14607         if (IS_I845G(dev_priv) || IS_I865G(dev_priv) || HAS_CUR_FBC(dev_priv))
14608                 cursor->cursor.size = ~0;
14609
14610         possible_crtcs = BIT(pipe);
14611
14612         ret = drm_universal_plane_init(&dev_priv->drm, &cursor->base,
14613                                        possible_crtcs, &intel_cursor_plane_funcs,
14614                                        intel_cursor_formats,
14615                                        ARRAY_SIZE(intel_cursor_formats),
14616                                        cursor_format_modifiers,
14617                                        DRM_PLANE_TYPE_CURSOR,
14618                                        "cursor %c", pipe_name(pipe));
14619         if (ret)
14620                 goto fail;
14621
14622         if (INTEL_GEN(dev_priv) >= 4)
14623                 drm_plane_create_rotation_property(&cursor->base,
14624                                                    DRM_MODE_ROTATE_0,
14625                                                    DRM_MODE_ROTATE_0 |
14626                                                    DRM_MODE_ROTATE_180);
14627
14628         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
14629
14630         return cursor;
14631
14632 fail:
14633         intel_plane_free(cursor);
14634
14635         return ERR_PTR(ret);
14636 }
14637
14638 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
14639                                     struct intel_crtc_state *crtc_state)
14640 {
14641         struct intel_crtc_scaler_state *scaler_state =
14642                 &crtc_state->scaler_state;
14643         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
14644         int i;
14645
14646         crtc->num_scalers = RUNTIME_INFO(dev_priv)->num_scalers[crtc->pipe];
14647         if (!crtc->num_scalers)
14648                 return;
14649
14650         for (i = 0; i < crtc->num_scalers; i++) {
14651                 struct intel_scaler *scaler = &scaler_state->scalers[i];
14652
14653                 scaler->in_use = 0;
14654                 scaler->mode = 0;
14655         }
14656
14657         scaler_state->scaler_id = -1;
14658 }
14659
14660 static int intel_crtc_init(struct drm_i915_private *dev_priv, enum pipe pipe)
14661 {
14662         struct intel_crtc *intel_crtc;
14663         struct intel_crtc_state *crtc_state = NULL;
14664         struct intel_plane *primary = NULL;
14665         struct intel_plane *cursor = NULL;
14666         int sprite, ret;
14667
14668         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
14669         if (!intel_crtc)
14670                 return -ENOMEM;
14671
14672         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
14673         if (!crtc_state) {
14674                 ret = -ENOMEM;
14675                 goto fail;
14676         }
14677         intel_crtc->config = crtc_state;
14678         intel_crtc->base.state = &crtc_state->base;
14679         crtc_state->base.crtc = &intel_crtc->base;
14680
14681         primary = intel_primary_plane_create(dev_priv, pipe);
14682         if (IS_ERR(primary)) {
14683                 ret = PTR_ERR(primary);
14684                 goto fail;
14685         }
14686         intel_crtc->plane_ids_mask |= BIT(primary->id);
14687
14688         for_each_sprite(dev_priv, pipe, sprite) {
14689                 struct intel_plane *plane;
14690
14691                 plane = intel_sprite_plane_create(dev_priv, pipe, sprite);
14692                 if (IS_ERR(plane)) {
14693                         ret = PTR_ERR(plane);
14694                         goto fail;
14695                 }
14696                 intel_crtc->plane_ids_mask |= BIT(plane->id);
14697         }
14698
14699         cursor = intel_cursor_plane_create(dev_priv, pipe);
14700         if (IS_ERR(cursor)) {
14701                 ret = PTR_ERR(cursor);
14702                 goto fail;
14703         }
14704         intel_crtc->plane_ids_mask |= BIT(cursor->id);
14705
14706         ret = drm_crtc_init_with_planes(&dev_priv->drm, &intel_crtc->base,
14707                                         &primary->base, &cursor->base,
14708                                         &intel_crtc_funcs,
14709                                         "pipe %c", pipe_name(pipe));
14710         if (ret)
14711                 goto fail;
14712
14713         intel_crtc->pipe = pipe;
14714
14715         /* initialize shared scalers */
14716         intel_crtc_init_scalers(intel_crtc, crtc_state);
14717
14718         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->pipe_to_crtc_mapping) ||
14719                dev_priv->pipe_to_crtc_mapping[pipe] != NULL);
14720         dev_priv->pipe_to_crtc_mapping[pipe] = intel_crtc;
14721
14722         if (INTEL_GEN(dev_priv) < 9) {
14723                 enum i9xx_plane_id i9xx_plane = primary->i9xx_plane;
14724
14725                 BUG_ON(i9xx_plane >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
14726                        dev_priv->plane_to_crtc_mapping[i9xx_plane] != NULL);
14727                 dev_priv->plane_to_crtc_mapping[i9xx_plane] = intel_crtc;
14728         }
14729
14730         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
14731
14732         intel_color_init(intel_crtc);
14733
14734         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
14735
14736         return 0;
14737
14738 fail:
14739         /*
14740          * drm_mode_config_cleanup() will free up any
14741          * crtcs/planes already initialized.
14742          */
14743         kfree(crtc_state);
14744         kfree(intel_crtc);
14745
14746         return ret;
14747 }
14748
14749 int intel_get_pipe_from_crtc_id_ioctl(struct drm_device *dev, void *data,
14750                                       struct drm_file *file)
14751 {
14752         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
14753         struct drm_crtc *drmmode_crtc;
14754         struct intel_crtc *crtc;
14755
14756         drmmode_crtc = drm_crtc_find(dev, file, pipe_from_crtc_id->crtc_id);
14757         if (!drmmode_crtc)
14758                 return -ENOENT;
14759
14760         crtc = to_intel_crtc(drmmode_crtc);
14761         pipe_from_crtc_id->pipe = crtc->pipe;
14762
14763         return 0;
14764 }
14765
14766 static int intel_encoder_clones(struct intel_encoder *encoder)
14767 {
14768         struct drm_device *dev = encoder->base.dev;
14769         struct intel_encoder *source_encoder;
14770         int index_mask = 0;
14771         int entry = 0;
14772
14773         for_each_intel_encoder(dev, source_encoder) {
14774                 if (encoders_cloneable(encoder, source_encoder))
14775                         index_mask |= (1 << entry);
14776
14777                 entry++;
14778         }
14779
14780         return index_mask;
14781 }
14782
14783 static bool ilk_has_edp_a(struct drm_i915_private *dev_priv)
14784 {
14785         if (!IS_MOBILE(dev_priv))
14786                 return false;
14787
14788         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
14789                 return false;
14790
14791         if (IS_GEN(dev_priv, 5) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
14792                 return false;
14793
14794         return true;
14795 }
14796
14797 static bool intel_ddi_crt_present(struct drm_i915_private *dev_priv)
14798 {
14799         if (INTEL_GEN(dev_priv) >= 9)
14800                 return false;
14801
14802         if (IS_HSW_ULT(dev_priv) || IS_BDW_ULT(dev_priv))
14803                 return false;
14804
14805         if (HAS_PCH_LPT_H(dev_priv) &&
14806             I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
14807                 return false;
14808
14809         /* DDI E can't be used if DDI A requires 4 lanes */
14810         if (I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
14811                 return false;
14812
14813         if (!dev_priv->vbt.int_crt_support)
14814                 return false;
14815
14816         return true;
14817 }
14818
14819 void intel_pps_unlock_regs_wa(struct drm_i915_private *dev_priv)
14820 {
14821         int pps_num;
14822         int pps_idx;
14823
14824         if (HAS_DDI(dev_priv))
14825                 return;
14826         /*
14827          * This w/a is needed at least on CPT/PPT, but to be sure apply it
14828          * everywhere where registers can be write protected.
14829          */
14830         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
14831                 pps_num = 2;
14832         else
14833                 pps_num = 1;
14834
14835         for (pps_idx = 0; pps_idx < pps_num; pps_idx++) {
14836                 u32 val = I915_READ(PP_CONTROL(pps_idx));
14837
14838                 val = (val & ~PANEL_UNLOCK_MASK) | PANEL_UNLOCK_REGS;
14839                 I915_WRITE(PP_CONTROL(pps_idx), val);
14840         }
14841 }
14842
14843 static void intel_pps_init(struct drm_i915_private *dev_priv)
14844 {
14845         if (HAS_PCH_SPLIT(dev_priv) || IS_GEN9_LP(dev_priv))
14846                 dev_priv->pps_mmio_base = PCH_PPS_BASE;
14847         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
14848                 dev_priv->pps_mmio_base = VLV_PPS_BASE;
14849         else
14850                 dev_priv->pps_mmio_base = PPS_BASE;
14851
14852         intel_pps_unlock_regs_wa(dev_priv);
14853 }
14854
14855 static void intel_setup_outputs(struct drm_i915_private *dev_priv)
14856 {
14857         struct intel_encoder *encoder;
14858         bool dpd_is_edp = false;
14859
14860         intel_pps_init(dev_priv);
14861
14862         if (!HAS_DISPLAY(dev_priv))
14863                 return;
14864
14865         if (IS_ELKHARTLAKE(dev_priv)) {
14866                 intel_ddi_init(dev_priv, PORT_A);
14867                 intel_ddi_init(dev_priv, PORT_B);
14868                 intel_ddi_init(dev_priv, PORT_C);
14869                 icl_dsi_init(dev_priv);
14870         } else if (INTEL_GEN(dev_priv) >= 11) {
14871                 intel_ddi_init(dev_priv, PORT_A);
14872                 intel_ddi_init(dev_priv, PORT_B);
14873                 intel_ddi_init(dev_priv, PORT_C);
14874                 intel_ddi_init(dev_priv, PORT_D);
14875                 intel_ddi_init(dev_priv, PORT_E);
14876                 /*
14877                  * On some ICL SKUs port F is not present. No strap bits for
14878                  * this, so rely on VBT.
14879                  * Work around broken VBTs on SKUs known to have no port F.
14880                  */
14881                 if (IS_ICL_WITH_PORT_F(dev_priv) &&
14882                     intel_bios_is_port_present(dev_priv, PORT_F))
14883                         intel_ddi_init(dev_priv, PORT_F);
14884
14885                 icl_dsi_init(dev_priv);
14886         } else if (IS_GEN9_LP(dev_priv)) {
14887                 /*
14888                  * FIXME: Broxton doesn't support port detection via the
14889                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
14890                  * detect the ports.
14891                  */
14892                 intel_ddi_init(dev_priv, PORT_A);
14893                 intel_ddi_init(dev_priv, PORT_B);
14894                 intel_ddi_init(dev_priv, PORT_C);
14895
14896                 vlv_dsi_init(dev_priv);
14897         } else if (HAS_DDI(dev_priv)) {
14898                 int found;
14899
14900                 if (intel_ddi_crt_present(dev_priv))
14901                         intel_crt_init(dev_priv);
14902
14903                 /*
14904                  * Haswell uses DDI functions to detect digital outputs.
14905                  * On SKL pre-D0 the strap isn't connected, so we assume
14906                  * it's there.
14907                  */
14908                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
14909                 /* WaIgnoreDDIAStrap: skl */
14910                 if (found || IS_GEN9_BC(dev_priv))
14911                         intel_ddi_init(dev_priv, PORT_A);
14912
14913                 /* DDI B, C, D, and F detection is indicated by the SFUSE_STRAP
14914                  * register */
14915                 found = I915_READ(SFUSE_STRAP);
14916
14917                 if (found & SFUSE_STRAP_DDIB_DETECTED)
14918                         intel_ddi_init(dev_priv, PORT_B);
14919                 if (found & SFUSE_STRAP_DDIC_DETECTED)
14920                         intel_ddi_init(dev_priv, PORT_C);
14921                 if (found & SFUSE_STRAP_DDID_DETECTED)
14922                         intel_ddi_init(dev_priv, PORT_D);
14923                 if (found & SFUSE_STRAP_DDIF_DETECTED)
14924                         intel_ddi_init(dev_priv, PORT_F);
14925                 /*
14926                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
14927                  */
14928                 if (IS_GEN9_BC(dev_priv) &&
14929                     intel_bios_is_port_present(dev_priv, PORT_E))
14930                         intel_ddi_init(dev_priv, PORT_E);
14931
14932         } else if (HAS_PCH_SPLIT(dev_priv)) {
14933                 int found;
14934
14935                 /*
14936                  * intel_edp_init_connector() depends on this completing first,
14937                  * to prevent the registration of both eDP and LVDS and the
14938                  * incorrect sharing of the PPS.
14939                  */
14940                 intel_lvds_init(dev_priv);
14941                 intel_crt_init(dev_priv);
14942
14943                 dpd_is_edp = intel_dp_is_port_edp(dev_priv, PORT_D);
14944
14945                 if (ilk_has_edp_a(dev_priv))
14946                         intel_dp_init(dev_priv, DP_A, PORT_A);
14947
14948                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
14949                         /* PCH SDVOB multiplex with HDMIB */
14950                         found = intel_sdvo_init(dev_priv, PCH_SDVOB, PORT_B);
14951                         if (!found)
14952                                 intel_hdmi_init(dev_priv, PCH_HDMIB, PORT_B);
14953                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
14954                                 intel_dp_init(dev_priv, PCH_DP_B, PORT_B);
14955                 }
14956
14957                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
14958                         intel_hdmi_init(dev_priv, PCH_HDMIC, PORT_C);
14959
14960                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
14961                         intel_hdmi_init(dev_priv, PCH_HDMID, PORT_D);
14962
14963                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
14964                         intel_dp_init(dev_priv, PCH_DP_C, PORT_C);
14965
14966                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
14967                         intel_dp_init(dev_priv, PCH_DP_D, PORT_D);
14968         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
14969                 bool has_edp, has_port;
14970
14971                 if (IS_VALLEYVIEW(dev_priv) && dev_priv->vbt.int_crt_support)
14972                         intel_crt_init(dev_priv);
14973
14974                 /*
14975                  * The DP_DETECTED bit is the latched state of the DDC
14976                  * SDA pin at boot. However since eDP doesn't require DDC
14977                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
14978                  * eDP ports may have been muxed to an alternate function.
14979                  * Thus we can't rely on the DP_DETECTED bit alone to detect
14980                  * eDP ports. Consult the VBT as well as DP_DETECTED to
14981                  * detect eDP ports.
14982                  *
14983                  * Sadly the straps seem to be missing sometimes even for HDMI
14984                  * ports (eg. on Voyo V3 - CHT x7-Z8700), so check both strap
14985                  * and VBT for the presence of the port. Additionally we can't
14986                  * trust the port type the VBT declares as we've seen at least
14987                  * HDMI ports that the VBT claim are DP or eDP.
14988                  */
14989                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_B);
14990                 has_port = intel_bios_is_port_present(dev_priv, PORT_B);
14991                 if (I915_READ(VLV_DP_B) & DP_DETECTED || has_port)
14992                         has_edp &= intel_dp_init(dev_priv, VLV_DP_B, PORT_B);
14993                 if ((I915_READ(VLV_HDMIB) & SDVO_DETECTED || has_port) && !has_edp)
14994                         intel_hdmi_init(dev_priv, VLV_HDMIB, PORT_B);
14995
14996                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_C);
14997                 has_port = intel_bios_is_port_present(dev_priv, PORT_C);
14998                 if (I915_READ(VLV_DP_C) & DP_DETECTED || has_port)
14999                         has_edp &= intel_dp_init(dev_priv, VLV_DP_C, PORT_C);
15000                 if ((I915_READ(VLV_HDMIC) & SDVO_DETECTED || has_port) && !has_edp)
15001                         intel_hdmi_init(dev_priv, VLV_HDMIC, PORT_C);
15002
15003                 if (IS_CHERRYVIEW(dev_priv)) {
15004                         /*
15005                          * eDP not supported on port D,
15006                          * so no need to worry about it
15007                          */
15008                         has_port = intel_bios_is_port_present(dev_priv, PORT_D);
15009                         if (I915_READ(CHV_DP_D) & DP_DETECTED || has_port)
15010                                 intel_dp_init(dev_priv, CHV_DP_D, PORT_D);
15011                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED || has_port)
15012                                 intel_hdmi_init(dev_priv, CHV_HDMID, PORT_D);
15013                 }
15014
15015                 vlv_dsi_init(dev_priv);
15016         } else if (IS_PINEVIEW(dev_priv)) {
15017                 intel_lvds_init(dev_priv);
15018                 intel_crt_init(dev_priv);
15019         } else if (IS_GEN_RANGE(dev_priv, 3, 4)) {
15020                 bool found = false;
15021
15022                 if (IS_MOBILE(dev_priv))
15023                         intel_lvds_init(dev_priv);
15024
15025                 intel_crt_init(dev_priv);
15026
15027                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
15028                         DRM_DEBUG_KMS("probing SDVOB\n");
15029                         found = intel_sdvo_init(dev_priv, GEN3_SDVOB, PORT_B);
15030                         if (!found && IS_G4X(dev_priv)) {
15031                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
15032                                 intel_hdmi_init(dev_priv, GEN4_HDMIB, PORT_B);
15033                         }
15034
15035                         if (!found && IS_G4X(dev_priv))
15036                                 intel_dp_init(dev_priv, DP_B, PORT_B);
15037                 }
15038
15039                 /* Before G4X SDVOC doesn't have its own detect register */
15040
15041                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
15042                         DRM_DEBUG_KMS("probing SDVOC\n");
15043                         found = intel_sdvo_init(dev_priv, GEN3_SDVOC, PORT_C);
15044                 }
15045
15046                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
15047
15048                         if (IS_G4X(dev_priv)) {
15049                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
15050                                 intel_hdmi_init(dev_priv, GEN4_HDMIC, PORT_C);
15051                         }
15052                         if (IS_G4X(dev_priv))
15053                                 intel_dp_init(dev_priv, DP_C, PORT_C);
15054                 }
15055
15056                 if (IS_G4X(dev_priv) && (I915_READ(DP_D) & DP_DETECTED))
15057                         intel_dp_init(dev_priv, DP_D, PORT_D);
15058
15059                 if (SUPPORTS_TV(dev_priv))
15060                         intel_tv_init(dev_priv);
15061         } else if (IS_GEN(dev_priv, 2)) {
15062                 if (IS_I85X(dev_priv))
15063                         intel_lvds_init(dev_priv);
15064
15065                 intel_crt_init(dev_priv);
15066                 intel_dvo_init(dev_priv);
15067         }
15068
15069         intel_psr_init(dev_priv);
15070
15071         for_each_intel_encoder(&dev_priv->drm, encoder) {
15072                 encoder->base.possible_crtcs = encoder->crtc_mask;
15073                 encoder->base.possible_clones =
15074                         intel_encoder_clones(encoder);
15075         }
15076
15077         intel_init_pch_refclk(dev_priv);
15078
15079         drm_helper_move_panel_connectors_to_head(&dev_priv->drm);
15080 }
15081
15082 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
15083 {
15084         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
15085         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
15086
15087         drm_framebuffer_cleanup(fb);
15088
15089         i915_gem_object_lock(obj);
15090         WARN_ON(!obj->framebuffer_references--);
15091         i915_gem_object_unlock(obj);
15092
15093         i915_gem_object_put(obj);
15094
15095         kfree(intel_fb);
15096 }
15097
15098 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
15099                                                 struct drm_file *file,
15100                                                 unsigned int *handle)
15101 {
15102         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
15103
15104         if (obj->userptr.mm) {
15105                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
15106                 return -EINVAL;
15107         }
15108
15109         return drm_gem_handle_create(file, &obj->base, handle);
15110 }
15111
15112 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
15113                                         struct drm_file *file,
15114                                         unsigned flags, unsigned color,
15115                                         struct drm_clip_rect *clips,
15116                                         unsigned num_clips)
15117 {
15118         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
15119
15120         i915_gem_object_flush_if_display(obj);
15121         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
15122
15123         return 0;
15124 }
15125
15126 static const struct drm_framebuffer_funcs intel_fb_funcs = {
15127         .destroy = intel_user_framebuffer_destroy,
15128         .create_handle = intel_user_framebuffer_create_handle,
15129         .dirty = intel_user_framebuffer_dirty,
15130 };
15131
15132 static
15133 u32 intel_fb_pitch_limit(struct drm_i915_private *dev_priv,
15134                          u32 pixel_format, u64 fb_modifier)
15135 {
15136         struct intel_crtc *crtc;
15137         struct intel_plane *plane;
15138
15139         /*
15140          * We assume the primary plane for pipe A has
15141          * the highest stride limits of them all.
15142          */
15143         crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_A);
15144         plane = to_intel_plane(crtc->base.primary);
15145
15146         return plane->max_stride(plane, pixel_format, fb_modifier,
15147                                  DRM_MODE_ROTATE_0);
15148 }
15149
15150 static int intel_framebuffer_init(struct intel_framebuffer *intel_fb,
15151                                   struct drm_i915_gem_object *obj,
15152                                   struct drm_mode_fb_cmd2 *mode_cmd)
15153 {
15154         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
15155         struct drm_framebuffer *fb = &intel_fb->base;
15156         u32 pitch_limit;
15157         unsigned int tiling, stride;
15158         int ret = -EINVAL;
15159         int i;
15160
15161         i915_gem_object_lock(obj);
15162         obj->framebuffer_references++;
15163         tiling = i915_gem_object_get_tiling(obj);
15164         stride = i915_gem_object_get_stride(obj);
15165         i915_gem_object_unlock(obj);
15166
15167         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
15168                 /*
15169                  * If there's a fence, enforce that
15170                  * the fb modifier and tiling mode match.
15171                  */
15172                 if (tiling != I915_TILING_NONE &&
15173                     tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
15174                         DRM_DEBUG_KMS("tiling_mode doesn't match fb modifier\n");
15175                         goto err;
15176                 }
15177         } else {
15178                 if (tiling == I915_TILING_X) {
15179                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
15180                 } else if (tiling == I915_TILING_Y) {
15181                         DRM_DEBUG_KMS("No Y tiling for legacy addfb\n");
15182                         goto err;
15183                 }
15184         }
15185
15186         if (!drm_any_plane_has_format(&dev_priv->drm,
15187                                       mode_cmd->pixel_format,
15188                                       mode_cmd->modifier[0])) {
15189                 struct drm_format_name_buf format_name;
15190
15191                 DRM_DEBUG_KMS("unsupported pixel format %s / modifier 0x%llx\n",
15192                               drm_get_format_name(mode_cmd->pixel_format,
15193                                                   &format_name),
15194                               mode_cmd->modifier[0]);
15195                 goto err;
15196         }
15197
15198         /*
15199          * gen2/3 display engine uses the fence if present,
15200          * so the tiling mode must match the fb modifier exactly.
15201          */
15202         if (INTEL_GEN(dev_priv) < 4 &&
15203             tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
15204                 DRM_DEBUG_KMS("tiling_mode must match fb modifier exactly on gen2/3\n");
15205                 goto err;
15206         }
15207
15208         pitch_limit = intel_fb_pitch_limit(dev_priv, mode_cmd->pixel_format,
15209                                            mode_cmd->modifier[0]);
15210         if (mode_cmd->pitches[0] > pitch_limit) {
15211                 DRM_DEBUG_KMS("%s pitch (%u) must be at most %d\n",
15212                               mode_cmd->modifier[0] != DRM_FORMAT_MOD_LINEAR ?
15213                               "tiled" : "linear",
15214                               mode_cmd->pitches[0], pitch_limit);
15215                 goto err;
15216         }
15217
15218         /*
15219          * If there's a fence, enforce that
15220          * the fb pitch and fence stride match.
15221          */
15222         if (tiling != I915_TILING_NONE && mode_cmd->pitches[0] != stride) {
15223                 DRM_DEBUG_KMS("pitch (%d) must match tiling stride (%d)\n",
15224                               mode_cmd->pitches[0], stride);
15225                 goto err;
15226         }
15227
15228         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
15229         if (mode_cmd->offsets[0] != 0)
15230                 goto err;
15231
15232         drm_helper_mode_fill_fb_struct(&dev_priv->drm, fb, mode_cmd);
15233
15234         for (i = 0; i < fb->format->num_planes; i++) {
15235                 u32 stride_alignment;
15236
15237                 if (mode_cmd->handles[i] != mode_cmd->handles[0]) {
15238                         DRM_DEBUG_KMS("bad plane %d handle\n", i);
15239                         goto err;
15240                 }
15241
15242                 stride_alignment = intel_fb_stride_alignment(fb, i);
15243
15244                 /*
15245                  * Display WA #0531: skl,bxt,kbl,glk
15246                  *
15247                  * Render decompression and plane width > 3840
15248                  * combined with horizontal panning requires the
15249                  * plane stride to be a multiple of 4. We'll just
15250                  * require the entire fb to accommodate that to avoid
15251                  * potential runtime errors at plane configuration time.
15252                  */
15253                 if (IS_GEN(dev_priv, 9) && i == 0 && fb->width > 3840 &&
15254                     is_ccs_modifier(fb->modifier))
15255                         stride_alignment *= 4;
15256
15257                 if (fb->pitches[i] & (stride_alignment - 1)) {
15258                         DRM_DEBUG_KMS("plane %d pitch (%d) must be at least %u byte aligned\n",
15259                                       i, fb->pitches[i], stride_alignment);
15260                         goto err;
15261                 }
15262
15263                 fb->obj[i] = &obj->base;
15264         }
15265
15266         ret = intel_fill_fb_info(dev_priv, fb);
15267         if (ret)
15268                 goto err;
15269
15270         ret = drm_framebuffer_init(&dev_priv->drm, fb, &intel_fb_funcs);
15271         if (ret) {
15272                 DRM_ERROR("framebuffer init failed %d\n", ret);
15273                 goto err;
15274         }
15275
15276         return 0;
15277
15278 err:
15279         i915_gem_object_lock(obj);
15280         obj->framebuffer_references--;
15281         i915_gem_object_unlock(obj);
15282         return ret;
15283 }
15284
15285 static struct drm_framebuffer *
15286 intel_user_framebuffer_create(struct drm_device *dev,
15287                               struct drm_file *filp,
15288                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
15289 {
15290         struct drm_framebuffer *fb;
15291         struct drm_i915_gem_object *obj;
15292         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
15293
15294         obj = i915_gem_object_lookup(filp, mode_cmd.handles[0]);
15295         if (!obj)
15296                 return ERR_PTR(-ENOENT);
15297
15298         fb = intel_framebuffer_create(obj, &mode_cmd);
15299         if (IS_ERR(fb))
15300                 i915_gem_object_put(obj);
15301
15302         return fb;
15303 }
15304
15305 static void intel_atomic_state_free(struct drm_atomic_state *state)
15306 {
15307         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
15308
15309         drm_atomic_state_default_release(state);
15310
15311         i915_sw_fence_fini(&intel_state->commit_ready);
15312
15313         kfree(state);
15314 }
15315
15316 static enum drm_mode_status
15317 intel_mode_valid(struct drm_device *dev,
15318                  const struct drm_display_mode *mode)
15319 {
15320         struct drm_i915_private *dev_priv = to_i915(dev);
15321         int hdisplay_max, htotal_max;
15322         int vdisplay_max, vtotal_max;
15323
15324         /*
15325          * Can't reject DBLSCAN here because Xorg ddxen can add piles
15326          * of DBLSCAN modes to the output's mode list when they detect
15327          * the scaling mode property on the connector. And they don't
15328          * ask the kernel to validate those modes in any way until
15329          * modeset time at which point the client gets a protocol error.
15330          * So in order to not upset those clients we silently ignore the
15331          * DBLSCAN flag on such connectors. For other connectors we will
15332          * reject modes with the DBLSCAN flag in encoder->compute_config().
15333          * And we always reject DBLSCAN modes in connector->mode_valid()
15334          * as we never want such modes on the connector's mode list.
15335          */
15336
15337         if (mode->vscan > 1)
15338                 return MODE_NO_VSCAN;
15339
15340         if (mode->flags & DRM_MODE_FLAG_HSKEW)
15341                 return MODE_H_ILLEGAL;
15342
15343         if (mode->flags & (DRM_MODE_FLAG_CSYNC |
15344                            DRM_MODE_FLAG_NCSYNC |
15345                            DRM_MODE_FLAG_PCSYNC))
15346                 return MODE_HSYNC;
15347
15348         if (mode->flags & (DRM_MODE_FLAG_BCAST |
15349                            DRM_MODE_FLAG_PIXMUX |
15350                            DRM_MODE_FLAG_CLKDIV2))
15351                 return MODE_BAD;
15352
15353         if (INTEL_GEN(dev_priv) >= 9 ||
15354             IS_BROADWELL(dev_priv) || IS_HASWELL(dev_priv)) {
15355                 hdisplay_max = 8192; /* FDI max 4096 handled elsewhere */
15356                 vdisplay_max = 4096;
15357                 htotal_max = 8192;
15358                 vtotal_max = 8192;
15359         } else if (INTEL_GEN(dev_priv) >= 3) {
15360                 hdisplay_max = 4096;
15361                 vdisplay_max = 4096;
15362                 htotal_max = 8192;
15363                 vtotal_max = 8192;
15364         } else {
15365                 hdisplay_max = 2048;
15366                 vdisplay_max = 2048;
15367                 htotal_max = 4096;
15368                 vtotal_max = 4096;
15369         }
15370
15371         if (mode->hdisplay > hdisplay_max ||
15372             mode->hsync_start > htotal_max ||
15373             mode->hsync_end > htotal_max ||
15374             mode->htotal > htotal_max)
15375                 return MODE_H_ILLEGAL;
15376
15377         if (mode->vdisplay > vdisplay_max ||
15378             mode->vsync_start > vtotal_max ||
15379             mode->vsync_end > vtotal_max ||
15380             mode->vtotal > vtotal_max)
15381                 return MODE_V_ILLEGAL;
15382
15383         return MODE_OK;
15384 }
15385
15386 static const struct drm_mode_config_funcs intel_mode_funcs = {
15387         .fb_create = intel_user_framebuffer_create,
15388         .get_format_info = intel_get_format_info,
15389         .output_poll_changed = intel_fbdev_output_poll_changed,
15390         .mode_valid = intel_mode_valid,
15391         .atomic_check = intel_atomic_check,
15392         .atomic_commit = intel_atomic_commit,
15393         .atomic_state_alloc = intel_atomic_state_alloc,
15394         .atomic_state_clear = intel_atomic_state_clear,
15395         .atomic_state_free = intel_atomic_state_free,
15396 };
15397
15398 /**
15399  * intel_init_display_hooks - initialize the display modesetting hooks
15400  * @dev_priv: device private
15401  */
15402 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
15403 {
15404         intel_init_cdclk_hooks(dev_priv);
15405
15406         if (INTEL_GEN(dev_priv) >= 9) {
15407                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
15408                 dev_priv->display.get_initial_plane_config =
15409                         skylake_get_initial_plane_config;
15410                 dev_priv->display.crtc_compute_clock =
15411                         haswell_crtc_compute_clock;
15412                 dev_priv->display.crtc_enable = haswell_crtc_enable;
15413                 dev_priv->display.crtc_disable = haswell_crtc_disable;
15414         } else if (HAS_DDI(dev_priv)) {
15415                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
15416                 dev_priv->display.get_initial_plane_config =
15417                         i9xx_get_initial_plane_config;
15418                 dev_priv->display.crtc_compute_clock =
15419                         haswell_crtc_compute_clock;
15420                 dev_priv->display.crtc_enable = haswell_crtc_enable;
15421                 dev_priv->display.crtc_disable = haswell_crtc_disable;
15422         } else if (HAS_PCH_SPLIT(dev_priv)) {
15423                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
15424                 dev_priv->display.get_initial_plane_config =
15425                         i9xx_get_initial_plane_config;
15426                 dev_priv->display.crtc_compute_clock =
15427                         ironlake_crtc_compute_clock;
15428                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
15429                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
15430         } else if (IS_CHERRYVIEW(dev_priv)) {
15431                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15432                 dev_priv->display.get_initial_plane_config =
15433                         i9xx_get_initial_plane_config;
15434                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
15435                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
15436                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15437         } else if (IS_VALLEYVIEW(dev_priv)) {
15438                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15439                 dev_priv->display.get_initial_plane_config =
15440                         i9xx_get_initial_plane_config;
15441                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
15442                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
15443                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15444         } else if (IS_G4X(dev_priv)) {
15445                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15446                 dev_priv->display.get_initial_plane_config =
15447                         i9xx_get_initial_plane_config;
15448                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
15449                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15450                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15451         } else if (IS_PINEVIEW(dev_priv)) {
15452                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15453                 dev_priv->display.get_initial_plane_config =
15454                         i9xx_get_initial_plane_config;
15455                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
15456                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15457                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15458         } else if (!IS_GEN(dev_priv, 2)) {
15459                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15460                 dev_priv->display.get_initial_plane_config =
15461                         i9xx_get_initial_plane_config;
15462                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
15463                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15464                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15465         } else {
15466                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15467                 dev_priv->display.get_initial_plane_config =
15468                         i9xx_get_initial_plane_config;
15469                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
15470                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15471                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15472         }
15473
15474         if (IS_GEN(dev_priv, 5)) {
15475                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
15476         } else if (IS_GEN(dev_priv, 6)) {
15477                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
15478         } else if (IS_IVYBRIDGE(dev_priv)) {
15479                 /* FIXME: detect B0+ stepping and use auto training */
15480                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
15481         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
15482                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
15483         }
15484
15485         if (INTEL_GEN(dev_priv) >= 9)
15486                 dev_priv->display.update_crtcs = skl_update_crtcs;
15487         else
15488                 dev_priv->display.update_crtcs = intel_update_crtcs;
15489 }
15490
15491 static i915_reg_t i915_vgacntrl_reg(struct drm_i915_private *dev_priv)
15492 {
15493         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
15494                 return VLV_VGACNTRL;
15495         else if (INTEL_GEN(dev_priv) >= 5)
15496                 return CPU_VGACNTRL;
15497         else
15498                 return VGACNTRL;
15499 }
15500
15501 /* Disable the VGA plane that we never use */
15502 static void i915_disable_vga(struct drm_i915_private *dev_priv)
15503 {
15504         struct pci_dev *pdev = dev_priv->drm.pdev;
15505         u8 sr1;
15506         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
15507
15508         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
15509         vga_get_uninterruptible(pdev, VGA_RSRC_LEGACY_IO);
15510         outb(SR01, VGA_SR_INDEX);
15511         sr1 = inb(VGA_SR_DATA);
15512         outb(sr1 | 1<<5, VGA_SR_DATA);
15513         vga_put(pdev, VGA_RSRC_LEGACY_IO);
15514         udelay(300);
15515
15516         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
15517         POSTING_READ(vga_reg);
15518 }
15519
15520 void intel_modeset_init_hw(struct drm_device *dev)
15521 {
15522         struct drm_i915_private *dev_priv = to_i915(dev);
15523
15524         intel_update_cdclk(dev_priv);
15525         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
15526         dev_priv->cdclk.logical = dev_priv->cdclk.actual = dev_priv->cdclk.hw;
15527 }
15528
15529 /*
15530  * Calculate what we think the watermarks should be for the state we've read
15531  * out of the hardware and then immediately program those watermarks so that
15532  * we ensure the hardware settings match our internal state.
15533  *
15534  * We can calculate what we think WM's should be by creating a duplicate of the
15535  * current state (which was constructed during hardware readout) and running it
15536  * through the atomic check code to calculate new watermark values in the
15537  * state object.
15538  */
15539 static void sanitize_watermarks(struct drm_device *dev)
15540 {
15541         struct drm_i915_private *dev_priv = to_i915(dev);
15542         struct drm_atomic_state *state;
15543         struct intel_atomic_state *intel_state;
15544         struct drm_crtc *crtc;
15545         struct drm_crtc_state *cstate;
15546         struct drm_modeset_acquire_ctx ctx;
15547         int ret;
15548         int i;
15549
15550         /* Only supported on platforms that use atomic watermark design */
15551         if (!dev_priv->display.optimize_watermarks)
15552                 return;
15553
15554         /*
15555          * We need to hold connection_mutex before calling duplicate_state so
15556          * that the connector loop is protected.
15557          */
15558         drm_modeset_acquire_init(&ctx, 0);
15559 retry:
15560         ret = drm_modeset_lock_all_ctx(dev, &ctx);
15561         if (ret == -EDEADLK) {
15562                 drm_modeset_backoff(&ctx);
15563                 goto retry;
15564         } else if (WARN_ON(ret)) {
15565                 goto fail;
15566         }
15567
15568         state = drm_atomic_helper_duplicate_state(dev, &ctx);
15569         if (WARN_ON(IS_ERR(state)))
15570                 goto fail;
15571
15572         intel_state = to_intel_atomic_state(state);
15573
15574         /*
15575          * Hardware readout is the only time we don't want to calculate
15576          * intermediate watermarks (since we don't trust the current
15577          * watermarks).
15578          */
15579         if (!HAS_GMCH(dev_priv))
15580                 intel_state->skip_intermediate_wm = true;
15581
15582         ret = intel_atomic_check(dev, state);
15583         if (ret) {
15584                 /*
15585                  * If we fail here, it means that the hardware appears to be
15586                  * programmed in a way that shouldn't be possible, given our
15587                  * understanding of watermark requirements.  This might mean a
15588                  * mistake in the hardware readout code or a mistake in the
15589                  * watermark calculations for a given platform.  Raise a WARN
15590                  * so that this is noticeable.
15591                  *
15592                  * If this actually happens, we'll have to just leave the
15593                  * BIOS-programmed watermarks untouched and hope for the best.
15594                  */
15595                 WARN(true, "Could not determine valid watermarks for inherited state\n");
15596                 goto put_state;
15597         }
15598
15599         /* Write calculated watermark values back */
15600         for_each_new_crtc_in_state(state, crtc, cstate, i) {
15601                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
15602
15603                 cs->wm.need_postvbl_update = true;
15604                 dev_priv->display.optimize_watermarks(intel_state, cs);
15605
15606                 to_intel_crtc_state(crtc->state)->wm = cs->wm;
15607         }
15608
15609 put_state:
15610         drm_atomic_state_put(state);
15611 fail:
15612         drm_modeset_drop_locks(&ctx);
15613         drm_modeset_acquire_fini(&ctx);
15614 }
15615
15616 static void intel_update_fdi_pll_freq(struct drm_i915_private *dev_priv)
15617 {
15618         if (IS_GEN(dev_priv, 5)) {
15619                 u32 fdi_pll_clk =
15620                         I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK;
15621
15622                 dev_priv->fdi_pll_freq = (fdi_pll_clk + 2) * 10000;
15623         } else if (IS_GEN(dev_priv, 6) || IS_IVYBRIDGE(dev_priv)) {
15624                 dev_priv->fdi_pll_freq = 270000;
15625         } else {
15626                 return;
15627         }
15628
15629         DRM_DEBUG_DRIVER("FDI PLL freq=%d\n", dev_priv->fdi_pll_freq);
15630 }
15631
15632 static int intel_initial_commit(struct drm_device *dev)
15633 {
15634         struct drm_atomic_state *state = NULL;
15635         struct drm_modeset_acquire_ctx ctx;
15636         struct drm_crtc *crtc;
15637         struct drm_crtc_state *crtc_state;
15638         int ret = 0;
15639
15640         state = drm_atomic_state_alloc(dev);
15641         if (!state)
15642                 return -ENOMEM;
15643
15644         drm_modeset_acquire_init(&ctx, 0);
15645
15646 retry:
15647         state->acquire_ctx = &ctx;
15648
15649         drm_for_each_crtc(crtc, dev) {
15650                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
15651                 if (IS_ERR(crtc_state)) {
15652                         ret = PTR_ERR(crtc_state);
15653                         goto out;
15654                 }
15655
15656                 if (crtc_state->active) {
15657                         ret = drm_atomic_add_affected_planes(state, crtc);
15658                         if (ret)
15659                                 goto out;
15660
15661                         /*
15662                          * FIXME hack to force a LUT update to avoid the
15663                          * plane update forcing the pipe gamma on without
15664                          * having a proper LUT loaded. Remove once we
15665                          * have readout for pipe gamma enable.
15666                          */
15667                         crtc_state->color_mgmt_changed = true;
15668                 }
15669         }
15670
15671         ret = drm_atomic_commit(state);
15672
15673 out:
15674         if (ret == -EDEADLK) {
15675                 drm_atomic_state_clear(state);
15676                 drm_modeset_backoff(&ctx);
15677                 goto retry;
15678         }
15679
15680         drm_atomic_state_put(state);
15681
15682         drm_modeset_drop_locks(&ctx);
15683         drm_modeset_acquire_fini(&ctx);
15684
15685         return ret;
15686 }
15687
15688 int intel_modeset_init(struct drm_device *dev)
15689 {
15690         struct drm_i915_private *dev_priv = to_i915(dev);
15691         struct i915_ggtt *ggtt = &dev_priv->ggtt;
15692         enum pipe pipe;
15693         struct intel_crtc *crtc;
15694         int ret;
15695
15696         dev_priv->modeset_wq = alloc_ordered_workqueue("i915_modeset", 0);
15697
15698         drm_mode_config_init(dev);
15699
15700         dev->mode_config.min_width = 0;
15701         dev->mode_config.min_height = 0;
15702
15703         dev->mode_config.preferred_depth = 24;
15704         dev->mode_config.prefer_shadow = 1;
15705
15706         dev->mode_config.allow_fb_modifiers = true;
15707
15708         dev->mode_config.funcs = &intel_mode_funcs;
15709
15710         init_llist_head(&dev_priv->atomic_helper.free_list);
15711         INIT_WORK(&dev_priv->atomic_helper.free_work,
15712                   intel_atomic_helper_free_state_worker);
15713
15714         intel_init_quirks(dev_priv);
15715
15716         intel_fbc_init(dev_priv);
15717
15718         intel_init_pm(dev_priv);
15719
15720         /*
15721          * There may be no VBT; and if the BIOS enabled SSC we can
15722          * just keep using it to avoid unnecessary flicker.  Whereas if the
15723          * BIOS isn't using it, don't assume it will work even if the VBT
15724          * indicates as much.
15725          */
15726         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv)) {
15727                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
15728                                             DREF_SSC1_ENABLE);
15729
15730                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
15731                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
15732                                      bios_lvds_use_ssc ? "en" : "dis",
15733                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
15734                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
15735                 }
15736         }
15737
15738         /* maximum framebuffer dimensions */
15739         if (IS_GEN(dev_priv, 2)) {
15740                 dev->mode_config.max_width = 2048;
15741                 dev->mode_config.max_height = 2048;
15742         } else if (IS_GEN(dev_priv, 3)) {
15743                 dev->mode_config.max_width = 4096;
15744                 dev->mode_config.max_height = 4096;
15745         } else {
15746                 dev->mode_config.max_width = 8192;
15747                 dev->mode_config.max_height = 8192;
15748         }
15749
15750         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
15751                 dev->mode_config.cursor_width = IS_I845G(dev_priv) ? 64 : 512;
15752                 dev->mode_config.cursor_height = 1023;
15753         } else if (IS_GEN(dev_priv, 2)) {
15754                 dev->mode_config.cursor_width = 64;
15755                 dev->mode_config.cursor_height = 64;
15756         } else {
15757                 dev->mode_config.cursor_width = 256;
15758                 dev->mode_config.cursor_height = 256;
15759         }
15760
15761         dev->mode_config.fb_base = ggtt->gmadr.start;
15762
15763         DRM_DEBUG_KMS("%d display pipe%s available.\n",
15764                       INTEL_INFO(dev_priv)->num_pipes,
15765                       INTEL_INFO(dev_priv)->num_pipes > 1 ? "s" : "");
15766
15767         for_each_pipe(dev_priv, pipe) {
15768                 ret = intel_crtc_init(dev_priv, pipe);
15769                 if (ret) {
15770                         drm_mode_config_cleanup(dev);
15771                         return ret;
15772                 }
15773         }
15774
15775         intel_shared_dpll_init(dev);
15776         intel_update_fdi_pll_freq(dev_priv);
15777
15778         intel_update_czclk(dev_priv);
15779         intel_modeset_init_hw(dev);
15780
15781         intel_hdcp_component_init(dev_priv);
15782
15783         if (dev_priv->max_cdclk_freq == 0)
15784                 intel_update_max_cdclk(dev_priv);
15785
15786         /* Just disable it once at startup */
15787         i915_disable_vga(dev_priv);
15788         intel_setup_outputs(dev_priv);
15789
15790         drm_modeset_lock_all(dev);
15791         intel_modeset_setup_hw_state(dev, dev->mode_config.acquire_ctx);
15792         drm_modeset_unlock_all(dev);
15793
15794         for_each_intel_crtc(dev, crtc) {
15795                 struct intel_initial_plane_config plane_config = {};
15796
15797                 if (!crtc->active)
15798                         continue;
15799
15800                 /*
15801                  * Note that reserving the BIOS fb up front prevents us
15802                  * from stuffing other stolen allocations like the ring
15803                  * on top.  This prevents some ugliness at boot time, and
15804                  * can even allow for smooth boot transitions if the BIOS
15805                  * fb is large enough for the active pipe configuration.
15806                  */
15807                 dev_priv->display.get_initial_plane_config(crtc,
15808                                                            &plane_config);
15809
15810                 /*
15811                  * If the fb is shared between multiple heads, we'll
15812                  * just get the first one.
15813                  */
15814                 intel_find_initial_plane_obj(crtc, &plane_config);
15815         }
15816
15817         /*
15818          * Make sure hardware watermarks really match the state we read out.
15819          * Note that we need to do this after reconstructing the BIOS fb's
15820          * since the watermark calculation done here will use pstate->fb.
15821          */
15822         if (!HAS_GMCH(dev_priv))
15823                 sanitize_watermarks(dev);
15824
15825         /*
15826          * Force all active planes to recompute their states. So that on
15827          * mode_setcrtc after probe, all the intel_plane_state variables
15828          * are already calculated and there is no assert_plane warnings
15829          * during bootup.
15830          */
15831         ret = intel_initial_commit(dev);
15832         if (ret)
15833                 DRM_DEBUG_KMS("Initial commit in probe failed.\n");
15834
15835         return 0;
15836 }
15837
15838 void i830_enable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
15839 {
15840         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15841         /* 640x480@60Hz, ~25175 kHz */
15842         struct dpll clock = {
15843                 .m1 = 18,
15844                 .m2 = 7,
15845                 .p1 = 13,
15846                 .p2 = 4,
15847                 .n = 2,
15848         };
15849         u32 dpll, fp;
15850         int i;
15851
15852         WARN_ON(i9xx_calc_dpll_params(48000, &clock) != 25154);
15853
15854         DRM_DEBUG_KMS("enabling pipe %c due to force quirk (vco=%d dot=%d)\n",
15855                       pipe_name(pipe), clock.vco, clock.dot);
15856
15857         fp = i9xx_dpll_compute_fp(&clock);
15858         dpll = DPLL_DVO_2X_MODE |
15859                 DPLL_VGA_MODE_DIS |
15860                 ((clock.p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT) |
15861                 PLL_P2_DIVIDE_BY_4 |
15862                 PLL_REF_INPUT_DREFCLK |
15863                 DPLL_VCO_ENABLE;
15864
15865         I915_WRITE(FP0(pipe), fp);
15866         I915_WRITE(FP1(pipe), fp);
15867
15868         I915_WRITE(HTOTAL(pipe), (640 - 1) | ((800 - 1) << 16));
15869         I915_WRITE(HBLANK(pipe), (640 - 1) | ((800 - 1) << 16));
15870         I915_WRITE(HSYNC(pipe), (656 - 1) | ((752 - 1) << 16));
15871         I915_WRITE(VTOTAL(pipe), (480 - 1) | ((525 - 1) << 16));
15872         I915_WRITE(VBLANK(pipe), (480 - 1) | ((525 - 1) << 16));
15873         I915_WRITE(VSYNC(pipe), (490 - 1) | ((492 - 1) << 16));
15874         I915_WRITE(PIPESRC(pipe), ((640 - 1) << 16) | (480 - 1));
15875
15876         /*
15877          * Apparently we need to have VGA mode enabled prior to changing
15878          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
15879          * dividers, even though the register value does change.
15880          */
15881         I915_WRITE(DPLL(pipe), dpll & ~DPLL_VGA_MODE_DIS);
15882         I915_WRITE(DPLL(pipe), dpll);
15883
15884         /* Wait for the clocks to stabilize. */
15885         POSTING_READ(DPLL(pipe));
15886         udelay(150);
15887
15888         /* The pixel multiplier can only be updated once the
15889          * DPLL is enabled and the clocks are stable.
15890          *
15891          * So write it again.
15892          */
15893         I915_WRITE(DPLL(pipe), dpll);
15894
15895         /* We do this three times for luck */
15896         for (i = 0; i < 3 ; i++) {
15897                 I915_WRITE(DPLL(pipe), dpll);
15898                 POSTING_READ(DPLL(pipe));
15899                 udelay(150); /* wait for warmup */
15900         }
15901
15902         I915_WRITE(PIPECONF(pipe), PIPECONF_ENABLE | PIPECONF_PROGRESSIVE);
15903         POSTING_READ(PIPECONF(pipe));
15904
15905         intel_wait_for_pipe_scanline_moving(crtc);
15906 }
15907
15908 void i830_disable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
15909 {
15910         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15911
15912         DRM_DEBUG_KMS("disabling pipe %c due to force quirk\n",
15913                       pipe_name(pipe));
15914
15915         WARN_ON(I915_READ(DSPCNTR(PLANE_A)) & DISPLAY_PLANE_ENABLE);
15916         WARN_ON(I915_READ(DSPCNTR(PLANE_B)) & DISPLAY_PLANE_ENABLE);
15917         WARN_ON(I915_READ(DSPCNTR(PLANE_C)) & DISPLAY_PLANE_ENABLE);
15918         WARN_ON(I915_READ(CURCNTR(PIPE_A)) & MCURSOR_MODE);
15919         WARN_ON(I915_READ(CURCNTR(PIPE_B)) & MCURSOR_MODE);
15920
15921         I915_WRITE(PIPECONF(pipe), 0);
15922         POSTING_READ(PIPECONF(pipe));
15923
15924         intel_wait_for_pipe_scanline_stopped(crtc);
15925
15926         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
15927         POSTING_READ(DPLL(pipe));
15928 }
15929
15930 static void
15931 intel_sanitize_plane_mapping(struct drm_i915_private *dev_priv)
15932 {
15933         struct intel_crtc *crtc;
15934
15935         if (INTEL_GEN(dev_priv) >= 4)
15936                 return;
15937
15938         for_each_intel_crtc(&dev_priv->drm, crtc) {
15939                 struct intel_plane *plane =
15940                         to_intel_plane(crtc->base.primary);
15941                 struct intel_crtc *plane_crtc;
15942                 enum pipe pipe;
15943
15944                 if (!plane->get_hw_state(plane, &pipe))
15945                         continue;
15946
15947                 if (pipe == crtc->pipe)
15948                         continue;
15949
15950                 DRM_DEBUG_KMS("[PLANE:%d:%s] attached to the wrong pipe, disabling plane\n",
15951                               plane->base.base.id, plane->base.name);
15952
15953                 plane_crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15954                 intel_plane_disable_noatomic(plane_crtc, plane);
15955         }
15956 }
15957
15958 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
15959 {
15960         struct drm_device *dev = crtc->base.dev;
15961         struct intel_encoder *encoder;
15962
15963         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
15964                 return true;
15965
15966         return false;
15967 }
15968
15969 static struct intel_connector *intel_encoder_find_connector(struct intel_encoder *encoder)
15970 {
15971         struct drm_device *dev = encoder->base.dev;
15972         struct intel_connector *connector;
15973
15974         for_each_connector_on_encoder(dev, &encoder->base, connector)
15975                 return connector;
15976
15977         return NULL;
15978 }
15979
15980 static bool has_pch_trancoder(struct drm_i915_private *dev_priv,
15981                               enum pipe pch_transcoder)
15982 {
15983         return HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv) ||
15984                 (HAS_PCH_LPT_H(dev_priv) && pch_transcoder == PIPE_A);
15985 }
15986
15987 static void intel_sanitize_crtc(struct intel_crtc *crtc,
15988                                 struct drm_modeset_acquire_ctx *ctx)
15989 {
15990         struct drm_device *dev = crtc->base.dev;
15991         struct drm_i915_private *dev_priv = to_i915(dev);
15992         struct intel_crtc_state *crtc_state = to_intel_crtc_state(crtc->base.state);
15993         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
15994
15995         /* Clear any frame start delays used for debugging left by the BIOS */
15996         if (crtc->active && !transcoder_is_dsi(cpu_transcoder)) {
15997                 i915_reg_t reg = PIPECONF(cpu_transcoder);
15998
15999                 I915_WRITE(reg,
16000                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
16001         }
16002
16003         if (crtc_state->base.active) {
16004                 struct intel_plane *plane;
16005
16006                 /* Disable everything but the primary plane */
16007                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
16008                         const struct intel_plane_state *plane_state =
16009                                 to_intel_plane_state(plane->base.state);
16010
16011                         if (plane_state->base.visible &&
16012                             plane->base.type != DRM_PLANE_TYPE_PRIMARY)
16013                                 intel_plane_disable_noatomic(crtc, plane);
16014                 }
16015
16016                 /*
16017                  * Disable any background color set by the BIOS, but enable the
16018                  * gamma and CSC to match how we program our planes.
16019                  */
16020                 if (INTEL_GEN(dev_priv) >= 9)
16021                         I915_WRITE(SKL_BOTTOM_COLOR(crtc->pipe),
16022                                    SKL_BOTTOM_COLOR_GAMMA_ENABLE |
16023                                    SKL_BOTTOM_COLOR_CSC_ENABLE);
16024         }
16025
16026         /* Adjust the state of the output pipe according to whether we
16027          * have active connectors/encoders. */
16028         if (crtc_state->base.active && !intel_crtc_has_encoders(crtc))
16029                 intel_crtc_disable_noatomic(&crtc->base, ctx);
16030
16031         if (crtc_state->base.active || HAS_GMCH(dev_priv)) {
16032                 /*
16033                  * We start out with underrun reporting disabled to avoid races.
16034                  * For correct bookkeeping mark this on active crtcs.
16035                  *
16036                  * Also on gmch platforms we dont have any hardware bits to
16037                  * disable the underrun reporting. Which means we need to start
16038                  * out with underrun reporting disabled also on inactive pipes,
16039                  * since otherwise we'll complain about the garbage we read when
16040                  * e.g. coming up after runtime pm.
16041                  *
16042                  * No protection against concurrent access is required - at
16043                  * worst a fifo underrun happens which also sets this to false.
16044                  */
16045                 crtc->cpu_fifo_underrun_disabled = true;
16046                 /*
16047                  * We track the PCH trancoder underrun reporting state
16048                  * within the crtc. With crtc for pipe A housing the underrun
16049                  * reporting state for PCH transcoder A, crtc for pipe B housing
16050                  * it for PCH transcoder B, etc. LPT-H has only PCH transcoder A,
16051                  * and marking underrun reporting as disabled for the non-existing
16052                  * PCH transcoders B and C would prevent enabling the south
16053                  * error interrupt (see cpt_can_enable_serr_int()).
16054                  */
16055                 if (has_pch_trancoder(dev_priv, crtc->pipe))
16056                         crtc->pch_fifo_underrun_disabled = true;
16057         }
16058 }
16059
16060 static bool has_bogus_dpll_config(const struct intel_crtc_state *crtc_state)
16061 {
16062         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
16063
16064         /*
16065          * Some SNB BIOSen (eg. ASUS K53SV) are known to misprogram
16066          * the hardware when a high res displays plugged in. DPLL P
16067          * divider is zero, and the pipe timings are bonkers. We'll
16068          * try to disable everything in that case.
16069          *
16070          * FIXME would be nice to be able to sanitize this state
16071          * without several WARNs, but for now let's take the easy
16072          * road.
16073          */
16074         return IS_GEN(dev_priv, 6) &&
16075                 crtc_state->base.active &&
16076                 crtc_state->shared_dpll &&
16077                 crtc_state->port_clock == 0;
16078 }
16079
16080 static void intel_sanitize_encoder(struct intel_encoder *encoder)
16081 {
16082         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
16083         struct intel_connector *connector;
16084         struct intel_crtc *crtc = to_intel_crtc(encoder->base.crtc);
16085         struct intel_crtc_state *crtc_state = crtc ?
16086                 to_intel_crtc_state(crtc->base.state) : NULL;
16087
16088         /* We need to check both for a crtc link (meaning that the
16089          * encoder is active and trying to read from a pipe) and the
16090          * pipe itself being active. */
16091         bool has_active_crtc = crtc_state &&
16092                 crtc_state->base.active;
16093
16094         if (crtc_state && has_bogus_dpll_config(crtc_state)) {
16095                 DRM_DEBUG_KMS("BIOS has misprogrammed the hardware. Disabling pipe %c\n",
16096                               pipe_name(crtc->pipe));
16097                 has_active_crtc = false;
16098         }
16099
16100         connector = intel_encoder_find_connector(encoder);
16101         if (connector && !has_active_crtc) {
16102                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
16103                               encoder->base.base.id,
16104                               encoder->base.name);
16105
16106                 /* Connector is active, but has no active pipe. This is
16107                  * fallout from our resume register restoring. Disable
16108                  * the encoder manually again. */
16109                 if (crtc_state) {
16110                         struct drm_encoder *best_encoder;
16111
16112                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
16113                                       encoder->base.base.id,
16114                                       encoder->base.name);
16115
16116                         /* avoid oopsing in case the hooks consult best_encoder */
16117                         best_encoder = connector->base.state->best_encoder;
16118                         connector->base.state->best_encoder = &encoder->base;
16119
16120                         if (encoder->disable)
16121                                 encoder->disable(encoder, crtc_state,
16122                                                  connector->base.state);
16123                         if (encoder->post_disable)
16124                                 encoder->post_disable(encoder, crtc_state,
16125                                                       connector->base.state);
16126
16127                         connector->base.state->best_encoder = best_encoder;
16128                 }
16129                 encoder->base.crtc = NULL;
16130
16131                 /* Inconsistent output/port/pipe state happens presumably due to
16132                  * a bug in one of the get_hw_state functions. Or someplace else
16133                  * in our code, like the register restore mess on resume. Clamp
16134                  * things to off as a safer default. */
16135
16136                 connector->base.dpms = DRM_MODE_DPMS_OFF;
16137                 connector->base.encoder = NULL;
16138         }
16139
16140         /* notify opregion of the sanitized encoder state */
16141         intel_opregion_notify_encoder(encoder, connector && has_active_crtc);
16142
16143         if (INTEL_GEN(dev_priv) >= 11)
16144                 icl_sanitize_encoder_pll_mapping(encoder);
16145 }
16146
16147 void i915_redisable_vga_power_on(struct drm_i915_private *dev_priv)
16148 {
16149         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
16150
16151         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
16152                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
16153                 i915_disable_vga(dev_priv);
16154         }
16155 }
16156
16157 void i915_redisable_vga(struct drm_i915_private *dev_priv)
16158 {
16159         intel_wakeref_t wakeref;
16160
16161         /*
16162          * This function can be called both from intel_modeset_setup_hw_state or
16163          * at a very early point in our resume sequence, where the power well
16164          * structures are not yet restored. Since this function is at a very
16165          * paranoid "someone might have enabled VGA while we were not looking"
16166          * level, just check if the power well is enabled instead of trying to
16167          * follow the "don't touch the power well if we don't need it" policy
16168          * the rest of the driver uses.
16169          */
16170         wakeref = intel_display_power_get_if_enabled(dev_priv,
16171                                                      POWER_DOMAIN_VGA);
16172         if (!wakeref)
16173                 return;
16174
16175         i915_redisable_vga_power_on(dev_priv);
16176
16177         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA, wakeref);
16178 }
16179
16180 /* FIXME read out full plane state for all planes */
16181 static void readout_plane_state(struct drm_i915_private *dev_priv)
16182 {
16183         struct intel_plane *plane;
16184         struct intel_crtc *crtc;
16185
16186         for_each_intel_plane(&dev_priv->drm, plane) {
16187                 struct intel_plane_state *plane_state =
16188                         to_intel_plane_state(plane->base.state);
16189                 struct intel_crtc_state *crtc_state;
16190                 enum pipe pipe = PIPE_A;
16191                 bool visible;
16192
16193                 visible = plane->get_hw_state(plane, &pipe);
16194
16195                 crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
16196                 crtc_state = to_intel_crtc_state(crtc->base.state);
16197
16198                 intel_set_plane_visible(crtc_state, plane_state, visible);
16199
16200                 DRM_DEBUG_KMS("[PLANE:%d:%s] hw state readout: %s, pipe %c\n",
16201                               plane->base.base.id, plane->base.name,
16202                               enableddisabled(visible), pipe_name(pipe));
16203         }
16204
16205         for_each_intel_crtc(&dev_priv->drm, crtc) {
16206                 struct intel_crtc_state *crtc_state =
16207                         to_intel_crtc_state(crtc->base.state);
16208
16209                 fixup_active_planes(crtc_state);
16210         }
16211 }
16212
16213 static void intel_modeset_readout_hw_state(struct drm_device *dev)
16214 {
16215         struct drm_i915_private *dev_priv = to_i915(dev);
16216         enum pipe pipe;
16217         struct intel_crtc *crtc;
16218         struct intel_encoder *encoder;
16219         struct intel_connector *connector;
16220         struct drm_connector_list_iter conn_iter;
16221         int i;
16222
16223         dev_priv->active_crtcs = 0;
16224
16225         for_each_intel_crtc(dev, crtc) {
16226                 struct intel_crtc_state *crtc_state =
16227                         to_intel_crtc_state(crtc->base.state);
16228
16229                 __drm_atomic_helper_crtc_destroy_state(&crtc_state->base);
16230                 memset(crtc_state, 0, sizeof(*crtc_state));
16231                 crtc_state->base.crtc = &crtc->base;
16232
16233                 crtc_state->base.active = crtc_state->base.enable =
16234                         dev_priv->display.get_pipe_config(crtc, crtc_state);
16235
16236                 crtc->base.enabled = crtc_state->base.enable;
16237                 crtc->active = crtc_state->base.active;
16238
16239                 if (crtc_state->base.active)
16240                         dev_priv->active_crtcs |= 1 << crtc->pipe;
16241
16242                 DRM_DEBUG_KMS("[CRTC:%d:%s] hw state readout: %s\n",
16243                               crtc->base.base.id, crtc->base.name,
16244                               enableddisabled(crtc_state->base.active));
16245         }
16246
16247         readout_plane_state(dev_priv);
16248
16249         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
16250                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
16251
16252                 pll->on = pll->info->funcs->get_hw_state(dev_priv, pll,
16253                                                         &pll->state.hw_state);
16254                 pll->state.crtc_mask = 0;
16255                 for_each_intel_crtc(dev, crtc) {
16256                         struct intel_crtc_state *crtc_state =
16257                                 to_intel_crtc_state(crtc->base.state);
16258
16259                         if (crtc_state->base.active &&
16260                             crtc_state->shared_dpll == pll)
16261                                 pll->state.crtc_mask |= 1 << crtc->pipe;
16262                 }
16263                 pll->active_mask = pll->state.crtc_mask;
16264
16265                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
16266                               pll->info->name, pll->state.crtc_mask, pll->on);
16267         }
16268
16269         for_each_intel_encoder(dev, encoder) {
16270                 pipe = 0;
16271
16272                 if (encoder->get_hw_state(encoder, &pipe)) {
16273                         struct intel_crtc_state *crtc_state;
16274
16275                         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
16276                         crtc_state = to_intel_crtc_state(crtc->base.state);
16277
16278                         encoder->base.crtc = &crtc->base;
16279                         encoder->get_config(encoder, crtc_state);
16280                 } else {
16281                         encoder->base.crtc = NULL;
16282                 }
16283
16284                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
16285                               encoder->base.base.id, encoder->base.name,
16286                               enableddisabled(encoder->base.crtc),
16287                               pipe_name(pipe));
16288         }
16289
16290         drm_connector_list_iter_begin(dev, &conn_iter);
16291         for_each_intel_connector_iter(connector, &conn_iter) {
16292                 if (connector->get_hw_state(connector)) {
16293                         connector->base.dpms = DRM_MODE_DPMS_ON;
16294
16295                         encoder = connector->encoder;
16296                         connector->base.encoder = &encoder->base;
16297
16298                         if (encoder->base.crtc &&
16299                             encoder->base.crtc->state->active) {
16300                                 /*
16301                                  * This has to be done during hardware readout
16302                                  * because anything calling .crtc_disable may
16303                                  * rely on the connector_mask being accurate.
16304                                  */
16305                                 encoder->base.crtc->state->connector_mask |=
16306                                         drm_connector_mask(&connector->base);
16307                                 encoder->base.crtc->state->encoder_mask |=
16308                                         drm_encoder_mask(&encoder->base);
16309                         }
16310
16311                 } else {
16312                         connector->base.dpms = DRM_MODE_DPMS_OFF;
16313                         connector->base.encoder = NULL;
16314                 }
16315                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
16316                               connector->base.base.id, connector->base.name,
16317                               enableddisabled(connector->base.encoder));
16318         }
16319         drm_connector_list_iter_end(&conn_iter);
16320
16321         for_each_intel_crtc(dev, crtc) {
16322                 struct intel_crtc_state *crtc_state =
16323                         to_intel_crtc_state(crtc->base.state);
16324                 int min_cdclk = 0;
16325
16326                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
16327                 if (crtc_state->base.active) {
16328                         intel_mode_from_pipe_config(&crtc->base.mode, crtc_state);
16329                         crtc->base.mode.hdisplay = crtc_state->pipe_src_w;
16330                         crtc->base.mode.vdisplay = crtc_state->pipe_src_h;
16331                         intel_mode_from_pipe_config(&crtc_state->base.adjusted_mode, crtc_state);
16332                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
16333
16334                         /*
16335                          * The initial mode needs to be set in order to keep
16336                          * the atomic core happy. It wants a valid mode if the
16337                          * crtc's enabled, so we do the above call.
16338                          *
16339                          * But we don't set all the derived state fully, hence
16340                          * set a flag to indicate that a full recalculation is
16341                          * needed on the next commit.
16342                          */
16343                         crtc_state->base.mode.private_flags = I915_MODE_FLAG_INHERITED;
16344
16345                         intel_crtc_compute_pixel_rate(crtc_state);
16346
16347                         if (dev_priv->display.modeset_calc_cdclk) {
16348                                 min_cdclk = intel_crtc_compute_min_cdclk(crtc_state);
16349                                 if (WARN_ON(min_cdclk < 0))
16350                                         min_cdclk = 0;
16351                         }
16352
16353                         drm_calc_timestamping_constants(&crtc->base,
16354                                                         &crtc_state->base.adjusted_mode);
16355                         update_scanline_offset(crtc_state);
16356                 }
16357
16358                 dev_priv->min_cdclk[crtc->pipe] = min_cdclk;
16359                 dev_priv->min_voltage_level[crtc->pipe] =
16360                         crtc_state->min_voltage_level;
16361
16362                 intel_pipe_config_sanity_check(dev_priv, crtc_state);
16363         }
16364 }
16365
16366 static void
16367 get_encoder_power_domains(struct drm_i915_private *dev_priv)
16368 {
16369         struct intel_encoder *encoder;
16370
16371         for_each_intel_encoder(&dev_priv->drm, encoder) {
16372                 struct intel_crtc_state *crtc_state;
16373
16374                 if (!encoder->get_power_domains)
16375                         continue;
16376
16377                 /*
16378                  * MST-primary and inactive encoders don't have a crtc state
16379                  * and neither of these require any power domain references.
16380                  */
16381                 if (!encoder->base.crtc)
16382                         continue;
16383
16384                 crtc_state = to_intel_crtc_state(encoder->base.crtc->state);
16385                 encoder->get_power_domains(encoder, crtc_state);
16386         }
16387 }
16388
16389 static void intel_early_display_was(struct drm_i915_private *dev_priv)
16390 {
16391         /* Display WA #1185 WaDisableDARBFClkGating:cnl,glk */
16392         if (IS_CANNONLAKE(dev_priv) || IS_GEMINILAKE(dev_priv))
16393                 I915_WRITE(GEN9_CLKGATE_DIS_0, I915_READ(GEN9_CLKGATE_DIS_0) |
16394                            DARBF_GATING_DIS);
16395
16396         if (IS_HASWELL(dev_priv)) {
16397                 /*
16398                  * WaRsPkgCStateDisplayPMReq:hsw
16399                  * System hang if this isn't done before disabling all planes!
16400                  */
16401                 I915_WRITE(CHICKEN_PAR1_1,
16402                            I915_READ(CHICKEN_PAR1_1) | FORCE_ARB_IDLE_PLANES);
16403         }
16404 }
16405
16406 static void ibx_sanitize_pch_hdmi_port(struct drm_i915_private *dev_priv,
16407                                        enum port port, i915_reg_t hdmi_reg)
16408 {
16409         u32 val = I915_READ(hdmi_reg);
16410
16411         if (val & SDVO_ENABLE ||
16412             (val & SDVO_PIPE_SEL_MASK) == SDVO_PIPE_SEL(PIPE_A))
16413                 return;
16414
16415         DRM_DEBUG_KMS("Sanitizing transcoder select for HDMI %c\n",
16416                       port_name(port));
16417
16418         val &= ~SDVO_PIPE_SEL_MASK;
16419         val |= SDVO_PIPE_SEL(PIPE_A);
16420
16421         I915_WRITE(hdmi_reg, val);
16422 }
16423
16424 static void ibx_sanitize_pch_dp_port(struct drm_i915_private *dev_priv,
16425                                      enum port port, i915_reg_t dp_reg)
16426 {
16427         u32 val = I915_READ(dp_reg);
16428
16429         if (val & DP_PORT_EN ||
16430             (val & DP_PIPE_SEL_MASK) == DP_PIPE_SEL(PIPE_A))
16431                 return;
16432
16433         DRM_DEBUG_KMS("Sanitizing transcoder select for DP %c\n",
16434                       port_name(port));
16435
16436         val &= ~DP_PIPE_SEL_MASK;
16437         val |= DP_PIPE_SEL(PIPE_A);
16438
16439         I915_WRITE(dp_reg, val);
16440 }
16441
16442 static void ibx_sanitize_pch_ports(struct drm_i915_private *dev_priv)
16443 {
16444         /*
16445          * The BIOS may select transcoder B on some of the PCH
16446          * ports even it doesn't enable the port. This would trip
16447          * assert_pch_dp_disabled() and assert_pch_hdmi_disabled().
16448          * Sanitize the transcoder select bits to prevent that. We
16449          * assume that the BIOS never actually enabled the port,
16450          * because if it did we'd actually have to toggle the port
16451          * on and back off to make the transcoder A select stick
16452          * (see. intel_dp_link_down(), intel_disable_hdmi(),
16453          * intel_disable_sdvo()).
16454          */
16455         ibx_sanitize_pch_dp_port(dev_priv, PORT_B, PCH_DP_B);
16456         ibx_sanitize_pch_dp_port(dev_priv, PORT_C, PCH_DP_C);
16457         ibx_sanitize_pch_dp_port(dev_priv, PORT_D, PCH_DP_D);
16458
16459         /* PCH SDVOB multiplex with HDMIB */
16460         ibx_sanitize_pch_hdmi_port(dev_priv, PORT_B, PCH_HDMIB);
16461         ibx_sanitize_pch_hdmi_port(dev_priv, PORT_C, PCH_HDMIC);
16462         ibx_sanitize_pch_hdmi_port(dev_priv, PORT_D, PCH_HDMID);
16463 }
16464
16465 /* Scan out the current hw modeset state,
16466  * and sanitizes it to the current state
16467  */
16468 static void
16469 intel_modeset_setup_hw_state(struct drm_device *dev,
16470                              struct drm_modeset_acquire_ctx *ctx)
16471 {
16472         struct drm_i915_private *dev_priv = to_i915(dev);
16473         struct intel_crtc_state *crtc_state;
16474         struct intel_encoder *encoder;
16475         struct intel_crtc *crtc;
16476         intel_wakeref_t wakeref;
16477         int i;
16478
16479         wakeref = intel_display_power_get(dev_priv, POWER_DOMAIN_INIT);
16480
16481         intel_early_display_was(dev_priv);
16482         intel_modeset_readout_hw_state(dev);
16483
16484         /* HW state is read out, now we need to sanitize this mess. */
16485         get_encoder_power_domains(dev_priv);
16486
16487         if (HAS_PCH_IBX(dev_priv))
16488                 ibx_sanitize_pch_ports(dev_priv);
16489
16490         /*
16491          * intel_sanitize_plane_mapping() may need to do vblank
16492          * waits, so we need vblank interrupts restored beforehand.
16493          */
16494         for_each_intel_crtc(&dev_priv->drm, crtc) {
16495                 crtc_state = to_intel_crtc_state(crtc->base.state);
16496
16497                 drm_crtc_vblank_reset(&crtc->base);
16498
16499                 if (crtc_state->base.active)
16500                         intel_crtc_vblank_on(crtc_state);
16501         }
16502
16503         intel_sanitize_plane_mapping(dev_priv);
16504
16505         for_each_intel_encoder(dev, encoder)
16506                 intel_sanitize_encoder(encoder);
16507
16508         for_each_intel_crtc(&dev_priv->drm, crtc) {
16509                 crtc_state = to_intel_crtc_state(crtc->base.state);
16510                 intel_sanitize_crtc(crtc, ctx);
16511                 intel_dump_pipe_config(crtc, crtc_state,
16512                                        "[setup_hw_state]");
16513         }
16514
16515         intel_modeset_update_connector_atomic_state(dev);
16516
16517         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
16518                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
16519
16520                 if (!pll->on || pll->active_mask)
16521                         continue;
16522
16523                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n",
16524                               pll->info->name);
16525
16526                 pll->info->funcs->disable(dev_priv, pll);
16527                 pll->on = false;
16528         }
16529
16530         if (IS_G4X(dev_priv)) {
16531                 g4x_wm_get_hw_state(dev_priv);
16532                 g4x_wm_sanitize(dev_priv);
16533         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
16534                 vlv_wm_get_hw_state(dev_priv);
16535                 vlv_wm_sanitize(dev_priv);
16536         } else if (INTEL_GEN(dev_priv) >= 9) {
16537                 skl_wm_get_hw_state(dev_priv);
16538         } else if (HAS_PCH_SPLIT(dev_priv)) {
16539                 ilk_wm_get_hw_state(dev_priv);
16540         }
16541
16542         for_each_intel_crtc(dev, crtc) {
16543                 u64 put_domains;
16544
16545                 crtc_state = to_intel_crtc_state(crtc->base.state);
16546                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc_state);
16547                 if (WARN_ON(put_domains))
16548                         modeset_put_power_domains(dev_priv, put_domains);
16549         }
16550
16551         intel_display_power_put(dev_priv, POWER_DOMAIN_INIT, wakeref);
16552
16553         intel_fbc_init_pipe_state(dev_priv);
16554 }
16555
16556 void intel_display_resume(struct drm_device *dev)
16557 {
16558         struct drm_i915_private *dev_priv = to_i915(dev);
16559         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
16560         struct drm_modeset_acquire_ctx ctx;
16561         int ret;
16562
16563         dev_priv->modeset_restore_state = NULL;
16564         if (state)
16565                 state->acquire_ctx = &ctx;
16566
16567         drm_modeset_acquire_init(&ctx, 0);
16568
16569         while (1) {
16570                 ret = drm_modeset_lock_all_ctx(dev, &ctx);
16571                 if (ret != -EDEADLK)
16572                         break;
16573
16574                 drm_modeset_backoff(&ctx);
16575         }
16576
16577         if (!ret)
16578                 ret = __intel_display_resume(dev, state, &ctx);
16579
16580         intel_enable_ipc(dev_priv);
16581         drm_modeset_drop_locks(&ctx);
16582         drm_modeset_acquire_fini(&ctx);
16583
16584         if (ret)
16585                 DRM_ERROR("Restoring old state failed with %i\n", ret);
16586         if (state)
16587                 drm_atomic_state_put(state);
16588 }
16589
16590 static void intel_hpd_poll_fini(struct drm_device *dev)
16591 {
16592         struct intel_connector *connector;
16593         struct drm_connector_list_iter conn_iter;
16594
16595         /* Kill all the work that may have been queued by hpd. */
16596         drm_connector_list_iter_begin(dev, &conn_iter);
16597         for_each_intel_connector_iter(connector, &conn_iter) {
16598                 if (connector->modeset_retry_work.func)
16599                         cancel_work_sync(&connector->modeset_retry_work);
16600                 if (connector->hdcp.shim) {
16601                         cancel_delayed_work_sync(&connector->hdcp.check_work);
16602                         cancel_work_sync(&connector->hdcp.prop_work);
16603                 }
16604         }
16605         drm_connector_list_iter_end(&conn_iter);
16606 }
16607
16608 void intel_modeset_cleanup(struct drm_device *dev)
16609 {
16610         struct drm_i915_private *dev_priv = to_i915(dev);
16611
16612         flush_workqueue(dev_priv->modeset_wq);
16613
16614         flush_work(&dev_priv->atomic_helper.free_work);
16615         WARN_ON(!llist_empty(&dev_priv->atomic_helper.free_list));
16616
16617         /*
16618          * Interrupts and polling as the first thing to avoid creating havoc.
16619          * Too much stuff here (turning of connectors, ...) would
16620          * experience fancy races otherwise.
16621          */
16622         intel_irq_uninstall(dev_priv);
16623
16624         /*
16625          * Due to the hpd irq storm handling the hotplug work can re-arm the
16626          * poll handlers. Hence disable polling after hpd handling is shut down.
16627          */
16628         intel_hpd_poll_fini(dev);
16629
16630         /* poll work can call into fbdev, hence clean that up afterwards */
16631         intel_fbdev_fini(dev_priv);
16632
16633         intel_unregister_dsm_handler();
16634
16635         intel_fbc_global_disable(dev_priv);
16636
16637         /* flush any delayed tasks or pending work */
16638         flush_scheduled_work();
16639
16640         intel_hdcp_component_fini(dev_priv);
16641
16642         drm_mode_config_cleanup(dev);
16643
16644         intel_overlay_cleanup(dev_priv);
16645
16646         intel_gmbus_teardown(dev_priv);
16647
16648         destroy_workqueue(dev_priv->modeset_wq);
16649
16650         intel_fbc_cleanup_cfb(dev_priv);
16651 }
16652
16653 /*
16654  * set vga decode state - true == enable VGA decode
16655  */
16656 int intel_modeset_vga_set_state(struct drm_i915_private *dev_priv, bool state)
16657 {
16658         unsigned reg = INTEL_GEN(dev_priv) >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
16659         u16 gmch_ctrl;
16660
16661         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
16662                 DRM_ERROR("failed to read control word\n");
16663                 return -EIO;
16664         }
16665
16666         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
16667                 return 0;
16668
16669         if (state)
16670                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
16671         else
16672                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
16673
16674         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
16675                 DRM_ERROR("failed to write control word\n");
16676                 return -EIO;
16677         }
16678
16679         return 0;
16680 }
16681
16682 #if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
16683
16684 struct intel_display_error_state {
16685
16686         u32 power_well_driver;
16687
16688         struct intel_cursor_error_state {
16689                 u32 control;
16690                 u32 position;
16691                 u32 base;
16692                 u32 size;
16693         } cursor[I915_MAX_PIPES];
16694
16695         struct intel_pipe_error_state {
16696                 bool power_domain_on;
16697                 u32 source;
16698                 u32 stat;
16699         } pipe[I915_MAX_PIPES];
16700
16701         struct intel_plane_error_state {
16702                 u32 control;
16703                 u32 stride;
16704                 u32 size;
16705                 u32 pos;
16706                 u32 addr;
16707                 u32 surface;
16708                 u32 tile_offset;
16709         } plane[I915_MAX_PIPES];
16710
16711         struct intel_transcoder_error_state {
16712                 bool available;
16713                 bool power_domain_on;
16714                 enum transcoder cpu_transcoder;
16715
16716                 u32 conf;
16717
16718                 u32 htotal;
16719                 u32 hblank;
16720                 u32 hsync;
16721                 u32 vtotal;
16722                 u32 vblank;
16723                 u32 vsync;
16724         } transcoder[4];
16725 };
16726
16727 struct intel_display_error_state *
16728 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
16729 {
16730         struct intel_display_error_state *error;
16731         int transcoders[] = {
16732                 TRANSCODER_A,
16733                 TRANSCODER_B,
16734                 TRANSCODER_C,
16735                 TRANSCODER_EDP,
16736         };
16737         int i;
16738
16739         BUILD_BUG_ON(ARRAY_SIZE(transcoders) != ARRAY_SIZE(error->transcoder));
16740
16741         if (!HAS_DISPLAY(dev_priv))
16742                 return NULL;
16743
16744         error = kzalloc(sizeof(*error), GFP_ATOMIC);
16745         if (error == NULL)
16746                 return NULL;
16747
16748         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
16749                 error->power_well_driver = I915_READ(HSW_PWR_WELL_CTL2);
16750
16751         for_each_pipe(dev_priv, i) {
16752                 error->pipe[i].power_domain_on =
16753                         __intel_display_power_is_enabled(dev_priv,
16754                                                          POWER_DOMAIN_PIPE(i));
16755                 if (!error->pipe[i].power_domain_on)
16756                         continue;
16757
16758                 error->cursor[i].control = I915_READ(CURCNTR(i));
16759                 error->cursor[i].position = I915_READ(CURPOS(i));
16760                 error->cursor[i].base = I915_READ(CURBASE(i));
16761
16762                 error->plane[i].control = I915_READ(DSPCNTR(i));
16763                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
16764                 if (INTEL_GEN(dev_priv) <= 3) {
16765                         error->plane[i].size = I915_READ(DSPSIZE(i));
16766                         error->plane[i].pos = I915_READ(DSPPOS(i));
16767                 }
16768                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
16769                         error->plane[i].addr = I915_READ(DSPADDR(i));
16770                 if (INTEL_GEN(dev_priv) >= 4) {
16771                         error->plane[i].surface = I915_READ(DSPSURF(i));
16772                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
16773                 }
16774
16775                 error->pipe[i].source = I915_READ(PIPESRC(i));
16776
16777                 if (HAS_GMCH(dev_priv))
16778                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
16779         }
16780
16781         for (i = 0; i < ARRAY_SIZE(error->transcoder); i++) {
16782                 enum transcoder cpu_transcoder = transcoders[i];
16783
16784                 if (!INTEL_INFO(dev_priv)->trans_offsets[cpu_transcoder])
16785                         continue;
16786
16787                 error->transcoder[i].available = true;
16788                 error->transcoder[i].power_domain_on =
16789                         __intel_display_power_is_enabled(dev_priv,
16790                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
16791                 if (!error->transcoder[i].power_domain_on)
16792                         continue;
16793
16794                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
16795
16796                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
16797                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
16798                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
16799                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
16800                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
16801                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
16802                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
16803         }
16804
16805         return error;
16806 }
16807
16808 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
16809
16810 void
16811 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
16812                                 struct intel_display_error_state *error)
16813 {
16814         struct drm_i915_private *dev_priv = m->i915;
16815         int i;
16816
16817         if (!error)
16818                 return;
16819
16820         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev_priv)->num_pipes);
16821         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
16822                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
16823                            error->power_well_driver);
16824         for_each_pipe(dev_priv, i) {
16825                 err_printf(m, "Pipe [%d]:\n", i);
16826                 err_printf(m, "  Power: %s\n",
16827                            onoff(error->pipe[i].power_domain_on));
16828                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
16829                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
16830
16831                 err_printf(m, "Plane [%d]:\n", i);
16832                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
16833                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
16834                 if (INTEL_GEN(dev_priv) <= 3) {
16835                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
16836                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
16837                 }
16838                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
16839                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
16840                 if (INTEL_GEN(dev_priv) >= 4) {
16841                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
16842                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
16843                 }
16844
16845                 err_printf(m, "Cursor [%d]:\n", i);
16846                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
16847                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
16848                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
16849         }
16850
16851         for (i = 0; i < ARRAY_SIZE(error->transcoder); i++) {
16852                 if (!error->transcoder[i].available)
16853                         continue;
16854
16855                 err_printf(m, "CPU transcoder: %s\n",
16856                            transcoder_name(error->transcoder[i].cpu_transcoder));
16857                 err_printf(m, "  Power: %s\n",
16858                            onoff(error->transcoder[i].power_domain_on));
16859                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
16860                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
16861                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
16862                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
16863                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
16864                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
16865                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
16866         }
16867 }
16868
16869 #endif