drm/i915: Add a new "remapped" gtt_view
[sfrench/cifs-2.6.git] / drivers / gpu / drm / i915 / intel_display.c
1 /*
2  * Copyright © 2006-2007 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *      Eric Anholt <eric@anholt.net>
25  */
26
27 #include <linux/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(mul_u32_u32(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(mul_u32_u32(target, clock.p * clock.n) << 22,
964                                                    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 unsigned int intel_remapped_info_size(const struct intel_remapped_info *rem_info)
2001 {
2002         unsigned int size = 0;
2003         int i;
2004
2005         for (i = 0 ; i < ARRAY_SIZE(rem_info->plane); i++)
2006                 size += rem_info->plane[i].width * rem_info->plane[i].height;
2007
2008         return size;
2009 }
2010
2011 static void
2012 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view,
2013                         const struct drm_framebuffer *fb,
2014                         unsigned int rotation)
2015 {
2016         view->type = I915_GGTT_VIEW_NORMAL;
2017         if (drm_rotation_90_or_270(rotation)) {
2018                 view->type = I915_GGTT_VIEW_ROTATED;
2019                 view->rotated = to_intel_framebuffer(fb)->rot_info;
2020         }
2021 }
2022
2023 static unsigned int intel_cursor_alignment(const struct drm_i915_private *dev_priv)
2024 {
2025         if (IS_I830(dev_priv))
2026                 return 16 * 1024;
2027         else if (IS_I85X(dev_priv))
2028                 return 256;
2029         else if (IS_I845G(dev_priv) || IS_I865G(dev_priv))
2030                 return 32;
2031         else
2032                 return 4 * 1024;
2033 }
2034
2035 static unsigned int intel_linear_alignment(const struct drm_i915_private *dev_priv)
2036 {
2037         if (INTEL_GEN(dev_priv) >= 9)
2038                 return 256 * 1024;
2039         else if (IS_I965G(dev_priv) || IS_I965GM(dev_priv) ||
2040                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
2041                 return 128 * 1024;
2042         else if (INTEL_GEN(dev_priv) >= 4)
2043                 return 4 * 1024;
2044         else
2045                 return 0;
2046 }
2047
2048 static unsigned int intel_surf_alignment(const struct drm_framebuffer *fb,
2049                                          int color_plane)
2050 {
2051         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2052
2053         /* AUX_DIST needs only 4K alignment */
2054         if (color_plane == 1)
2055                 return 4096;
2056
2057         switch (fb->modifier) {
2058         case DRM_FORMAT_MOD_LINEAR:
2059                 return intel_linear_alignment(dev_priv);
2060         case I915_FORMAT_MOD_X_TILED:
2061                 if (INTEL_GEN(dev_priv) >= 9)
2062                         return 256 * 1024;
2063                 return 0;
2064         case I915_FORMAT_MOD_Y_TILED_CCS:
2065         case I915_FORMAT_MOD_Yf_TILED_CCS:
2066         case I915_FORMAT_MOD_Y_TILED:
2067         case I915_FORMAT_MOD_Yf_TILED:
2068                 return 1 * 1024 * 1024;
2069         default:
2070                 MISSING_CASE(fb->modifier);
2071                 return 0;
2072         }
2073 }
2074
2075 static bool intel_plane_uses_fence(const struct intel_plane_state *plane_state)
2076 {
2077         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2078         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
2079
2080         return INTEL_GEN(dev_priv) < 4 || plane->has_fbc;
2081 }
2082
2083 struct i915_vma *
2084 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb,
2085                            const struct i915_ggtt_view *view,
2086                            bool uses_fence,
2087                            unsigned long *out_flags)
2088 {
2089         struct drm_device *dev = fb->dev;
2090         struct drm_i915_private *dev_priv = to_i915(dev);
2091         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2092         intel_wakeref_t wakeref;
2093         struct i915_vma *vma;
2094         unsigned int pinctl;
2095         u32 alignment;
2096
2097         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2098
2099         alignment = intel_surf_alignment(fb, 0);
2100
2101         /* Note that the w/a also requires 64 PTE of padding following the
2102          * bo. We currently fill all unused PTE with the shadow page and so
2103          * we should always have valid PTE following the scanout preventing
2104          * the VT-d warning.
2105          */
2106         if (intel_scanout_needs_vtd_wa(dev_priv) && alignment < 256 * 1024)
2107                 alignment = 256 * 1024;
2108
2109         /*
2110          * Global gtt pte registers are special registers which actually forward
2111          * writes to a chunk of system memory. Which means that there is no risk
2112          * that the register values disappear as soon as we call
2113          * intel_runtime_pm_put(), so it is correct to wrap only the
2114          * pin/unpin/fence and not more.
2115          */
2116         wakeref = intel_runtime_pm_get(dev_priv);
2117
2118         atomic_inc(&dev_priv->gpu_error.pending_fb_pin);
2119
2120         pinctl = 0;
2121
2122         /* Valleyview is definitely limited to scanning out the first
2123          * 512MiB. Lets presume this behaviour was inherited from the
2124          * g4x display engine and that all earlier gen are similarly
2125          * limited. Testing suggests that it is a little more
2126          * complicated than this. For example, Cherryview appears quite
2127          * happy to scanout from anywhere within its global aperture.
2128          */
2129         if (HAS_GMCH(dev_priv))
2130                 pinctl |= PIN_MAPPABLE;
2131
2132         vma = i915_gem_object_pin_to_display_plane(obj,
2133                                                    alignment, view, pinctl);
2134         if (IS_ERR(vma))
2135                 goto err;
2136
2137         if (uses_fence && i915_vma_is_map_and_fenceable(vma)) {
2138                 int ret;
2139
2140                 /* Install a fence for tiled scan-out. Pre-i965 always needs a
2141                  * fence, whereas 965+ only requires a fence if using
2142                  * framebuffer compression.  For simplicity, we always, when
2143                  * possible, install a fence as the cost is not that onerous.
2144                  *
2145                  * If we fail to fence the tiled scanout, then either the
2146                  * modeset will reject the change (which is highly unlikely as
2147                  * the affected systems, all but one, do not have unmappable
2148                  * space) or we will not be able to enable full powersaving
2149                  * techniques (also likely not to apply due to various limits
2150                  * FBC and the like impose on the size of the buffer, which
2151                  * presumably we violated anyway with this unmappable buffer).
2152                  * Anyway, it is presumably better to stumble onwards with
2153                  * something and try to run the system in a "less than optimal"
2154                  * mode that matches the user configuration.
2155                  */
2156                 ret = i915_vma_pin_fence(vma);
2157                 if (ret != 0 && INTEL_GEN(dev_priv) < 4) {
2158                         i915_gem_object_unpin_from_display_plane(vma);
2159                         vma = ERR_PTR(ret);
2160                         goto err;
2161                 }
2162
2163                 if (ret == 0 && vma->fence)
2164                         *out_flags |= PLANE_HAS_FENCE;
2165         }
2166
2167         i915_vma_get(vma);
2168 err:
2169         atomic_dec(&dev_priv->gpu_error.pending_fb_pin);
2170
2171         intel_runtime_pm_put(dev_priv, wakeref);
2172         return vma;
2173 }
2174
2175 void intel_unpin_fb_vma(struct i915_vma *vma, unsigned long flags)
2176 {
2177         lockdep_assert_held(&vma->vm->i915->drm.struct_mutex);
2178
2179         if (flags & PLANE_HAS_FENCE)
2180                 i915_vma_unpin_fence(vma);
2181         i915_gem_object_unpin_from_display_plane(vma);
2182         i915_vma_put(vma);
2183 }
2184
2185 static int intel_fb_pitch(const struct drm_framebuffer *fb, int color_plane,
2186                           unsigned int rotation)
2187 {
2188         if (drm_rotation_90_or_270(rotation))
2189                 return to_intel_framebuffer(fb)->rotated[color_plane].pitch;
2190         else
2191                 return fb->pitches[color_plane];
2192 }
2193
2194 /*
2195  * Convert the x/y offsets into a linear offset.
2196  * Only valid with 0/180 degree rotation, which is fine since linear
2197  * offset is only used with linear buffers on pre-hsw and tiled buffers
2198  * with gen2/3, and 90/270 degree rotations isn't supported on any of them.
2199  */
2200 u32 intel_fb_xy_to_linear(int x, int y,
2201                           const struct intel_plane_state *state,
2202                           int color_plane)
2203 {
2204         const struct drm_framebuffer *fb = state->base.fb;
2205         unsigned int cpp = fb->format->cpp[color_plane];
2206         unsigned int pitch = state->color_plane[color_plane].stride;
2207
2208         return y * pitch + x * cpp;
2209 }
2210
2211 /*
2212  * Add the x/y offsets derived from fb->offsets[] to the user
2213  * specified plane src x/y offsets. The resulting x/y offsets
2214  * specify the start of scanout from the beginning of the gtt mapping.
2215  */
2216 void intel_add_fb_offsets(int *x, int *y,
2217                           const struct intel_plane_state *state,
2218                           int color_plane)
2219
2220 {
2221         const struct intel_framebuffer *intel_fb = to_intel_framebuffer(state->base.fb);
2222         unsigned int rotation = state->base.rotation;
2223
2224         if (drm_rotation_90_or_270(rotation)) {
2225                 *x += intel_fb->rotated[color_plane].x;
2226                 *y += intel_fb->rotated[color_plane].y;
2227         } else {
2228                 *x += intel_fb->normal[color_plane].x;
2229                 *y += intel_fb->normal[color_plane].y;
2230         }
2231 }
2232
2233 static u32 intel_adjust_tile_offset(int *x, int *y,
2234                                     unsigned int tile_width,
2235                                     unsigned int tile_height,
2236                                     unsigned int tile_size,
2237                                     unsigned int pitch_tiles,
2238                                     u32 old_offset,
2239                                     u32 new_offset)
2240 {
2241         unsigned int pitch_pixels = pitch_tiles * tile_width;
2242         unsigned int tiles;
2243
2244         WARN_ON(old_offset & (tile_size - 1));
2245         WARN_ON(new_offset & (tile_size - 1));
2246         WARN_ON(new_offset > old_offset);
2247
2248         tiles = (old_offset - new_offset) / tile_size;
2249
2250         *y += tiles / pitch_tiles * tile_height;
2251         *x += tiles % pitch_tiles * tile_width;
2252
2253         /* minimize x in case it got needlessly big */
2254         *y += *x / pitch_pixels * tile_height;
2255         *x %= pitch_pixels;
2256
2257         return new_offset;
2258 }
2259
2260 static bool is_surface_linear(u64 modifier, int color_plane)
2261 {
2262         return modifier == DRM_FORMAT_MOD_LINEAR;
2263 }
2264
2265 static u32 intel_adjust_aligned_offset(int *x, int *y,
2266                                        const struct drm_framebuffer *fb,
2267                                        int color_plane,
2268                                        unsigned int rotation,
2269                                        unsigned int pitch,
2270                                        u32 old_offset, u32 new_offset)
2271 {
2272         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2273         unsigned int cpp = fb->format->cpp[color_plane];
2274
2275         WARN_ON(new_offset > old_offset);
2276
2277         if (!is_surface_linear(fb->modifier, color_plane)) {
2278                 unsigned int tile_size, tile_width, tile_height;
2279                 unsigned int pitch_tiles;
2280
2281                 tile_size = intel_tile_size(dev_priv);
2282                 intel_tile_dims(fb, color_plane, &tile_width, &tile_height);
2283
2284                 if (drm_rotation_90_or_270(rotation)) {
2285                         pitch_tiles = pitch / tile_height;
2286                         swap(tile_width, tile_height);
2287                 } else {
2288                         pitch_tiles = pitch / (tile_width * cpp);
2289                 }
2290
2291                 intel_adjust_tile_offset(x, y, tile_width, tile_height,
2292                                          tile_size, pitch_tiles,
2293                                          old_offset, new_offset);
2294         } else {
2295                 old_offset += *y * pitch + *x * cpp;
2296
2297                 *y = (old_offset - new_offset) / pitch;
2298                 *x = ((old_offset - new_offset) - *y * pitch) / cpp;
2299         }
2300
2301         return new_offset;
2302 }
2303
2304 /*
2305  * Adjust the tile offset by moving the difference into
2306  * the x/y offsets.
2307  */
2308 static u32 intel_plane_adjust_aligned_offset(int *x, int *y,
2309                                              const struct intel_plane_state *state,
2310                                              int color_plane,
2311                                              u32 old_offset, u32 new_offset)
2312 {
2313         return intel_adjust_aligned_offset(x, y, state->base.fb, color_plane,
2314                                            state->base.rotation,
2315                                            state->color_plane[color_plane].stride,
2316                                            old_offset, new_offset);
2317 }
2318
2319 /*
2320  * Computes the aligned offset to the base tile and adjusts
2321  * x, y. bytes per pixel is assumed to be a power-of-two.
2322  *
2323  * In the 90/270 rotated case, x and y are assumed
2324  * to be already rotated to match the rotated GTT view, and
2325  * pitch is the tile_height aligned framebuffer height.
2326  *
2327  * This function is used when computing the derived information
2328  * under intel_framebuffer, so using any of that information
2329  * here is not allowed. Anything under drm_framebuffer can be
2330  * used. This is why the user has to pass in the pitch since it
2331  * is specified in the rotated orientation.
2332  */
2333 static u32 intel_compute_aligned_offset(struct drm_i915_private *dev_priv,
2334                                         int *x, int *y,
2335                                         const struct drm_framebuffer *fb,
2336                                         int color_plane,
2337                                         unsigned int pitch,
2338                                         unsigned int rotation,
2339                                         u32 alignment)
2340 {
2341         unsigned int cpp = fb->format->cpp[color_plane];
2342         u32 offset, offset_aligned;
2343
2344         if (alignment)
2345                 alignment--;
2346
2347         if (!is_surface_linear(fb->modifier, color_plane)) {
2348                 unsigned int tile_size, tile_width, tile_height;
2349                 unsigned int tile_rows, tiles, pitch_tiles;
2350
2351                 tile_size = intel_tile_size(dev_priv);
2352                 intel_tile_dims(fb, color_plane, &tile_width, &tile_height);
2353
2354                 if (drm_rotation_90_or_270(rotation)) {
2355                         pitch_tiles = pitch / tile_height;
2356                         swap(tile_width, tile_height);
2357                 } else {
2358                         pitch_tiles = pitch / (tile_width * cpp);
2359                 }
2360
2361                 tile_rows = *y / tile_height;
2362                 *y %= tile_height;
2363
2364                 tiles = *x / tile_width;
2365                 *x %= tile_width;
2366
2367                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2368                 offset_aligned = offset & ~alignment;
2369
2370                 intel_adjust_tile_offset(x, y, tile_width, tile_height,
2371                                          tile_size, pitch_tiles,
2372                                          offset, offset_aligned);
2373         } else {
2374                 offset = *y * pitch + *x * cpp;
2375                 offset_aligned = offset & ~alignment;
2376
2377                 *y = (offset & alignment) / pitch;
2378                 *x = ((offset & alignment) - *y * pitch) / cpp;
2379         }
2380
2381         return offset_aligned;
2382 }
2383
2384 static u32 intel_plane_compute_aligned_offset(int *x, int *y,
2385                                               const struct intel_plane_state *state,
2386                                               int color_plane)
2387 {
2388         struct intel_plane *intel_plane = to_intel_plane(state->base.plane);
2389         struct drm_i915_private *dev_priv = to_i915(intel_plane->base.dev);
2390         const struct drm_framebuffer *fb = state->base.fb;
2391         unsigned int rotation = state->base.rotation;
2392         int pitch = state->color_plane[color_plane].stride;
2393         u32 alignment;
2394
2395         if (intel_plane->id == PLANE_CURSOR)
2396                 alignment = intel_cursor_alignment(dev_priv);
2397         else
2398                 alignment = intel_surf_alignment(fb, color_plane);
2399
2400         return intel_compute_aligned_offset(dev_priv, x, y, fb, color_plane,
2401                                             pitch, rotation, alignment);
2402 }
2403
2404 /* Convert the fb->offset[] into x/y offsets */
2405 static int intel_fb_offset_to_xy(int *x, int *y,
2406                                  const struct drm_framebuffer *fb,
2407                                  int color_plane)
2408 {
2409         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2410         unsigned int height;
2411
2412         if (fb->modifier != DRM_FORMAT_MOD_LINEAR &&
2413             fb->offsets[color_plane] % intel_tile_size(dev_priv)) {
2414                 DRM_DEBUG_KMS("Misaligned offset 0x%08x for color plane %d\n",
2415                               fb->offsets[color_plane], color_plane);
2416                 return -EINVAL;
2417         }
2418
2419         height = drm_framebuffer_plane_height(fb->height, fb, color_plane);
2420         height = ALIGN(height, intel_tile_height(fb, color_plane));
2421
2422         /* Catch potential overflows early */
2423         if (add_overflows_t(u32, mul_u32_u32(height, fb->pitches[color_plane]),
2424                             fb->offsets[color_plane])) {
2425                 DRM_DEBUG_KMS("Bad offset 0x%08x or pitch %d for color plane %d\n",
2426                               fb->offsets[color_plane], fb->pitches[color_plane],
2427                               color_plane);
2428                 return -ERANGE;
2429         }
2430
2431         *x = 0;
2432         *y = 0;
2433
2434         intel_adjust_aligned_offset(x, y,
2435                                     fb, color_plane, DRM_MODE_ROTATE_0,
2436                                     fb->pitches[color_plane],
2437                                     fb->offsets[color_plane], 0);
2438
2439         return 0;
2440 }
2441
2442 static unsigned int intel_fb_modifier_to_tiling(u64 fb_modifier)
2443 {
2444         switch (fb_modifier) {
2445         case I915_FORMAT_MOD_X_TILED:
2446                 return I915_TILING_X;
2447         case I915_FORMAT_MOD_Y_TILED:
2448         case I915_FORMAT_MOD_Y_TILED_CCS:
2449                 return I915_TILING_Y;
2450         default:
2451                 return I915_TILING_NONE;
2452         }
2453 }
2454
2455 /*
2456  * From the Sky Lake PRM:
2457  * "The Color Control Surface (CCS) contains the compression status of
2458  *  the cache-line pairs. The compression state of the cache-line pair
2459  *  is specified by 2 bits in the CCS. Each CCS cache-line represents
2460  *  an area on the main surface of 16 x16 sets of 128 byte Y-tiled
2461  *  cache-line-pairs. CCS is always Y tiled."
2462  *
2463  * Since cache line pairs refers to horizontally adjacent cache lines,
2464  * each cache line in the CCS corresponds to an area of 32x16 cache
2465  * lines on the main surface. Since each pixel is 4 bytes, this gives
2466  * us a ratio of one byte in the CCS for each 8x16 pixels in the
2467  * main surface.
2468  */
2469 static const struct drm_format_info ccs_formats[] = {
2470         { .format = DRM_FORMAT_XRGB8888, .depth = 24, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2471         { .format = DRM_FORMAT_XBGR8888, .depth = 24, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2472         { .format = DRM_FORMAT_ARGB8888, .depth = 32, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2473         { .format = DRM_FORMAT_ABGR8888, .depth = 32, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2474 };
2475
2476 static const struct drm_format_info *
2477 lookup_format_info(const struct drm_format_info formats[],
2478                    int num_formats, u32 format)
2479 {
2480         int i;
2481
2482         for (i = 0; i < num_formats; i++) {
2483                 if (formats[i].format == format)
2484                         return &formats[i];
2485         }
2486
2487         return NULL;
2488 }
2489
2490 static const struct drm_format_info *
2491 intel_get_format_info(const struct drm_mode_fb_cmd2 *cmd)
2492 {
2493         switch (cmd->modifier[0]) {
2494         case I915_FORMAT_MOD_Y_TILED_CCS:
2495         case I915_FORMAT_MOD_Yf_TILED_CCS:
2496                 return lookup_format_info(ccs_formats,
2497                                           ARRAY_SIZE(ccs_formats),
2498                                           cmd->pixel_format);
2499         default:
2500                 return NULL;
2501         }
2502 }
2503
2504 bool is_ccs_modifier(u64 modifier)
2505 {
2506         return modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
2507                modifier == I915_FORMAT_MOD_Yf_TILED_CCS;
2508 }
2509
2510 static int
2511 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2512                    struct drm_framebuffer *fb)
2513 {
2514         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
2515         struct intel_rotation_info *rot_info = &intel_fb->rot_info;
2516         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2517         u32 gtt_offset_rotated = 0;
2518         unsigned int max_size = 0;
2519         int i, num_planes = fb->format->num_planes;
2520         unsigned int tile_size = intel_tile_size(dev_priv);
2521
2522         for (i = 0; i < num_planes; i++) {
2523                 unsigned int width, height;
2524                 unsigned int cpp, size;
2525                 u32 offset;
2526                 int x, y;
2527                 int ret;
2528
2529                 cpp = fb->format->cpp[i];
2530                 width = drm_framebuffer_plane_width(fb->width, fb, i);
2531                 height = drm_framebuffer_plane_height(fb->height, fb, i);
2532
2533                 ret = intel_fb_offset_to_xy(&x, &y, fb, i);
2534                 if (ret) {
2535                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2536                                       i, fb->offsets[i]);
2537                         return ret;
2538                 }
2539
2540                 if (is_ccs_modifier(fb->modifier) && i == 1) {
2541                         int hsub = fb->format->hsub;
2542                         int vsub = fb->format->vsub;
2543                         int tile_width, tile_height;
2544                         int main_x, main_y;
2545                         int ccs_x, ccs_y;
2546
2547                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2548                         tile_width *= hsub;
2549                         tile_height *= vsub;
2550
2551                         ccs_x = (x * hsub) % tile_width;
2552                         ccs_y = (y * vsub) % tile_height;
2553                         main_x = intel_fb->normal[0].x % tile_width;
2554                         main_y = intel_fb->normal[0].y % tile_height;
2555
2556                         /*
2557                          * CCS doesn't have its own x/y offset register, so the intra CCS tile
2558                          * x/y offsets must match between CCS and the main surface.
2559                          */
2560                         if (main_x != ccs_x || main_y != ccs_y) {
2561                                 DRM_DEBUG_KMS("Bad CCS x/y (main %d,%d ccs %d,%d) full (main %d,%d ccs %d,%d)\n",
2562                                               main_x, main_y,
2563                                               ccs_x, ccs_y,
2564                                               intel_fb->normal[0].x,
2565                                               intel_fb->normal[0].y,
2566                                               x, y);
2567                                 return -EINVAL;
2568                         }
2569                 }
2570
2571                 /*
2572                  * The fence (if used) is aligned to the start of the object
2573                  * so having the framebuffer wrap around across the edge of the
2574                  * fenced region doesn't really work. We have no API to configure
2575                  * the fence start offset within the object (nor could we probably
2576                  * on gen2/3). So it's just easier if we just require that the
2577                  * fb layout agrees with the fence layout. We already check that the
2578                  * fb stride matches the fence stride elsewhere.
2579                  */
2580                 if (i == 0 && i915_gem_object_is_tiled(obj) &&
2581                     (x + width) * cpp > fb->pitches[i]) {
2582                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2583                                       i, fb->offsets[i]);
2584                         return -EINVAL;
2585                 }
2586
2587                 /*
2588                  * First pixel of the framebuffer from
2589                  * the start of the normal gtt mapping.
2590                  */
2591                 intel_fb->normal[i].x = x;
2592                 intel_fb->normal[i].y = y;
2593
2594                 offset = intel_compute_aligned_offset(dev_priv, &x, &y, fb, i,
2595                                                       fb->pitches[i],
2596                                                       DRM_MODE_ROTATE_0,
2597                                                       tile_size);
2598                 offset /= tile_size;
2599
2600                 if (!is_surface_linear(fb->modifier, i)) {
2601                         unsigned int tile_width, tile_height;
2602                         unsigned int pitch_tiles;
2603                         struct drm_rect r;
2604
2605                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2606
2607                         rot_info->plane[i].offset = offset;
2608                         rot_info->plane[i].stride = DIV_ROUND_UP(fb->pitches[i], tile_width * cpp);
2609                         rot_info->plane[i].width = DIV_ROUND_UP(x + width, tile_width);
2610                         rot_info->plane[i].height = DIV_ROUND_UP(y + height, tile_height);
2611
2612                         intel_fb->rotated[i].pitch =
2613                                 rot_info->plane[i].height * tile_height;
2614
2615                         /* how many tiles does this plane need */
2616                         size = rot_info->plane[i].stride * rot_info->plane[i].height;
2617                         /*
2618                          * If the plane isn't horizontally tile aligned,
2619                          * we need one more tile.
2620                          */
2621                         if (x != 0)
2622                                 size++;
2623
2624                         /* rotate the x/y offsets to match the GTT view */
2625                         r.x1 = x;
2626                         r.y1 = y;
2627                         r.x2 = x + width;
2628                         r.y2 = y + height;
2629                         drm_rect_rotate(&r,
2630                                         rot_info->plane[i].width * tile_width,
2631                                         rot_info->plane[i].height * tile_height,
2632                                         DRM_MODE_ROTATE_270);
2633                         x = r.x1;
2634                         y = r.y1;
2635
2636                         /* rotate the tile dimensions to match the GTT view */
2637                         pitch_tiles = intel_fb->rotated[i].pitch / tile_height;
2638                         swap(tile_width, tile_height);
2639
2640                         /*
2641                          * We only keep the x/y offsets, so push all of the
2642                          * gtt offset into the x/y offsets.
2643                          */
2644                         intel_adjust_tile_offset(&x, &y,
2645                                                  tile_width, tile_height,
2646                                                  tile_size, pitch_tiles,
2647                                                  gtt_offset_rotated * tile_size, 0);
2648
2649                         gtt_offset_rotated += rot_info->plane[i].width * rot_info->plane[i].height;
2650
2651                         /*
2652                          * First pixel of the framebuffer from
2653                          * the start of the rotated gtt mapping.
2654                          */
2655                         intel_fb->rotated[i].x = x;
2656                         intel_fb->rotated[i].y = y;
2657                 } else {
2658                         size = DIV_ROUND_UP((y + height) * fb->pitches[i] +
2659                                             x * cpp, tile_size);
2660                 }
2661
2662                 /* how many tiles in total needed in the bo */
2663                 max_size = max(max_size, offset + size);
2664         }
2665
2666         if (mul_u32_u32(max_size, tile_size) > obj->base.size) {
2667                 DRM_DEBUG_KMS("fb too big for bo (need %llu bytes, have %zu bytes)\n",
2668                               mul_u32_u32(max_size, tile_size), obj->base.size);
2669                 return -EINVAL;
2670         }
2671
2672         return 0;
2673 }
2674
2675 static int i9xx_format_to_fourcc(int format)
2676 {
2677         switch (format) {
2678         case DISPPLANE_8BPP:
2679                 return DRM_FORMAT_C8;
2680         case DISPPLANE_BGRX555:
2681                 return DRM_FORMAT_XRGB1555;
2682         case DISPPLANE_BGRX565:
2683                 return DRM_FORMAT_RGB565;
2684         default:
2685         case DISPPLANE_BGRX888:
2686                 return DRM_FORMAT_XRGB8888;
2687         case DISPPLANE_RGBX888:
2688                 return DRM_FORMAT_XBGR8888;
2689         case DISPPLANE_BGRX101010:
2690                 return DRM_FORMAT_XRGB2101010;
2691         case DISPPLANE_RGBX101010:
2692                 return DRM_FORMAT_XBGR2101010;
2693         }
2694 }
2695
2696 int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2697 {
2698         switch (format) {
2699         case PLANE_CTL_FORMAT_RGB_565:
2700                 return DRM_FORMAT_RGB565;
2701         case PLANE_CTL_FORMAT_NV12:
2702                 return DRM_FORMAT_NV12;
2703         case PLANE_CTL_FORMAT_P010:
2704                 return DRM_FORMAT_P010;
2705         case PLANE_CTL_FORMAT_P012:
2706                 return DRM_FORMAT_P012;
2707         case PLANE_CTL_FORMAT_P016:
2708                 return DRM_FORMAT_P016;
2709         case PLANE_CTL_FORMAT_Y210:
2710                 return DRM_FORMAT_Y210;
2711         case PLANE_CTL_FORMAT_Y212:
2712                 return DRM_FORMAT_Y212;
2713         case PLANE_CTL_FORMAT_Y216:
2714                 return DRM_FORMAT_Y216;
2715         case PLANE_CTL_FORMAT_Y410:
2716                 return DRM_FORMAT_XVYU2101010;
2717         case PLANE_CTL_FORMAT_Y412:
2718                 return DRM_FORMAT_XVYU12_16161616;
2719         case PLANE_CTL_FORMAT_Y416:
2720                 return DRM_FORMAT_XVYU16161616;
2721         default:
2722         case PLANE_CTL_FORMAT_XRGB_8888:
2723                 if (rgb_order) {
2724                         if (alpha)
2725                                 return DRM_FORMAT_ABGR8888;
2726                         else
2727                                 return DRM_FORMAT_XBGR8888;
2728                 } else {
2729                         if (alpha)
2730                                 return DRM_FORMAT_ARGB8888;
2731                         else
2732                                 return DRM_FORMAT_XRGB8888;
2733                 }
2734         case PLANE_CTL_FORMAT_XRGB_2101010:
2735                 if (rgb_order)
2736                         return DRM_FORMAT_XBGR2101010;
2737                 else
2738                         return DRM_FORMAT_XRGB2101010;
2739         case PLANE_CTL_FORMAT_XRGB_16161616F:
2740                 if (rgb_order) {
2741                         if (alpha)
2742                                 return DRM_FORMAT_ABGR16161616F;
2743                         else
2744                                 return DRM_FORMAT_XBGR16161616F;
2745                 } else {
2746                         if (alpha)
2747                                 return DRM_FORMAT_ARGB16161616F;
2748                         else
2749                                 return DRM_FORMAT_XRGB16161616F;
2750                 }
2751         }
2752 }
2753
2754 static bool
2755 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2756                               struct intel_initial_plane_config *plane_config)
2757 {
2758         struct drm_device *dev = crtc->base.dev;
2759         struct drm_i915_private *dev_priv = to_i915(dev);
2760         struct drm_i915_gem_object *obj = NULL;
2761         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2762         struct drm_framebuffer *fb = &plane_config->fb->base;
2763         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2764         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2765                                     PAGE_SIZE);
2766
2767         size_aligned -= base_aligned;
2768
2769         if (plane_config->size == 0)
2770                 return false;
2771
2772         /* If the FB is too big, just don't use it since fbdev is not very
2773          * important and we should probably use that space with FBC or other
2774          * features. */
2775         if (size_aligned * 2 > dev_priv->stolen_usable_size)
2776                 return false;
2777
2778         switch (fb->modifier) {
2779         case DRM_FORMAT_MOD_LINEAR:
2780         case I915_FORMAT_MOD_X_TILED:
2781         case I915_FORMAT_MOD_Y_TILED:
2782                 break;
2783         default:
2784                 DRM_DEBUG_DRIVER("Unsupported modifier for initial FB: 0x%llx\n",
2785                                  fb->modifier);
2786                 return false;
2787         }
2788
2789         mutex_lock(&dev->struct_mutex);
2790         obj = i915_gem_object_create_stolen_for_preallocated(dev_priv,
2791                                                              base_aligned,
2792                                                              base_aligned,
2793                                                              size_aligned);
2794         mutex_unlock(&dev->struct_mutex);
2795         if (!obj)
2796                 return false;
2797
2798         switch (plane_config->tiling) {
2799         case I915_TILING_NONE:
2800                 break;
2801         case I915_TILING_X:
2802         case I915_TILING_Y:
2803                 obj->tiling_and_stride = fb->pitches[0] | plane_config->tiling;
2804                 break;
2805         default:
2806                 MISSING_CASE(plane_config->tiling);
2807                 return false;
2808         }
2809
2810         mode_cmd.pixel_format = fb->format->format;
2811         mode_cmd.width = fb->width;
2812         mode_cmd.height = fb->height;
2813         mode_cmd.pitches[0] = fb->pitches[0];
2814         mode_cmd.modifier[0] = fb->modifier;
2815         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2816
2817         if (intel_framebuffer_init(to_intel_framebuffer(fb), obj, &mode_cmd)) {
2818                 DRM_DEBUG_KMS("intel fb init failed\n");
2819                 goto out_unref_obj;
2820         }
2821
2822
2823         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2824         return true;
2825
2826 out_unref_obj:
2827         i915_gem_object_put(obj);
2828         return false;
2829 }
2830
2831 static void
2832 intel_set_plane_visible(struct intel_crtc_state *crtc_state,
2833                         struct intel_plane_state *plane_state,
2834                         bool visible)
2835 {
2836         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2837
2838         plane_state->base.visible = visible;
2839
2840         if (visible)
2841                 crtc_state->base.plane_mask |= drm_plane_mask(&plane->base);
2842         else
2843                 crtc_state->base.plane_mask &= ~drm_plane_mask(&plane->base);
2844 }
2845
2846 static void fixup_active_planes(struct intel_crtc_state *crtc_state)
2847 {
2848         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
2849         struct drm_plane *plane;
2850
2851         /*
2852          * Active_planes aliases if multiple "primary" or cursor planes
2853          * have been used on the same (or wrong) pipe. plane_mask uses
2854          * unique ids, hence we can use that to reconstruct active_planes.
2855          */
2856         crtc_state->active_planes = 0;
2857
2858         drm_for_each_plane_mask(plane, &dev_priv->drm,
2859                                 crtc_state->base.plane_mask)
2860                 crtc_state->active_planes |= BIT(to_intel_plane(plane)->id);
2861 }
2862
2863 static void intel_plane_disable_noatomic(struct intel_crtc *crtc,
2864                                          struct intel_plane *plane)
2865 {
2866         struct intel_crtc_state *crtc_state =
2867                 to_intel_crtc_state(crtc->base.state);
2868         struct intel_plane_state *plane_state =
2869                 to_intel_plane_state(plane->base.state);
2870
2871         DRM_DEBUG_KMS("Disabling [PLANE:%d:%s] on [CRTC:%d:%s]\n",
2872                       plane->base.base.id, plane->base.name,
2873                       crtc->base.base.id, crtc->base.name);
2874
2875         intel_set_plane_visible(crtc_state, plane_state, false);
2876         fixup_active_planes(crtc_state);
2877
2878         if (plane->id == PLANE_PRIMARY)
2879                 intel_pre_disable_primary_noatomic(&crtc->base);
2880
2881         intel_disable_plane(plane, crtc_state);
2882 }
2883
2884 static void
2885 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2886                              struct intel_initial_plane_config *plane_config)
2887 {
2888         struct drm_device *dev = intel_crtc->base.dev;
2889         struct drm_i915_private *dev_priv = to_i915(dev);
2890         struct drm_crtc *c;
2891         struct drm_i915_gem_object *obj;
2892         struct drm_plane *primary = intel_crtc->base.primary;
2893         struct drm_plane_state *plane_state = primary->state;
2894         struct intel_plane *intel_plane = to_intel_plane(primary);
2895         struct intel_plane_state *intel_state =
2896                 to_intel_plane_state(plane_state);
2897         struct drm_framebuffer *fb;
2898
2899         if (!plane_config->fb)
2900                 return;
2901
2902         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2903                 fb = &plane_config->fb->base;
2904                 goto valid_fb;
2905         }
2906
2907         kfree(plane_config->fb);
2908
2909         /*
2910          * Failed to alloc the obj, check to see if we should share
2911          * an fb with another CRTC instead
2912          */
2913         for_each_crtc(dev, c) {
2914                 struct intel_plane_state *state;
2915
2916                 if (c == &intel_crtc->base)
2917                         continue;
2918
2919                 if (!to_intel_crtc(c)->active)
2920                         continue;
2921
2922                 state = to_intel_plane_state(c->primary->state);
2923                 if (!state->vma)
2924                         continue;
2925
2926                 if (intel_plane_ggtt_offset(state) == plane_config->base) {
2927                         fb = state->base.fb;
2928                         drm_framebuffer_get(fb);
2929                         goto valid_fb;
2930                 }
2931         }
2932
2933         /*
2934          * We've failed to reconstruct the BIOS FB.  Current display state
2935          * indicates that the primary plane is visible, but has a NULL FB,
2936          * which will lead to problems later if we don't fix it up.  The
2937          * simplest solution is to just disable the primary plane now and
2938          * pretend the BIOS never had it enabled.
2939          */
2940         intel_plane_disable_noatomic(intel_crtc, intel_plane);
2941
2942         return;
2943
2944 valid_fb:
2945         intel_state->base.rotation = plane_config->rotation;
2946         intel_fill_fb_ggtt_view(&intel_state->view, fb,
2947                                 intel_state->base.rotation);
2948         intel_state->color_plane[0].stride =
2949                 intel_fb_pitch(fb, 0, intel_state->base.rotation);
2950
2951         mutex_lock(&dev->struct_mutex);
2952         intel_state->vma =
2953                 intel_pin_and_fence_fb_obj(fb,
2954                                            &intel_state->view,
2955                                            intel_plane_uses_fence(intel_state),
2956                                            &intel_state->flags);
2957         mutex_unlock(&dev->struct_mutex);
2958         if (IS_ERR(intel_state->vma)) {
2959                 DRM_ERROR("failed to pin boot fb on pipe %d: %li\n",
2960                           intel_crtc->pipe, PTR_ERR(intel_state->vma));
2961
2962                 intel_state->vma = NULL;
2963                 drm_framebuffer_put(fb);
2964                 return;
2965         }
2966
2967         obj = intel_fb_obj(fb);
2968         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
2969
2970         plane_state->src_x = 0;
2971         plane_state->src_y = 0;
2972         plane_state->src_w = fb->width << 16;
2973         plane_state->src_h = fb->height << 16;
2974
2975         plane_state->crtc_x = 0;
2976         plane_state->crtc_y = 0;
2977         plane_state->crtc_w = fb->width;
2978         plane_state->crtc_h = fb->height;
2979
2980         intel_state->base.src = drm_plane_state_src(plane_state);
2981         intel_state->base.dst = drm_plane_state_dest(plane_state);
2982
2983         if (i915_gem_object_is_tiled(obj))
2984                 dev_priv->preserve_bios_swizzle = true;
2985
2986         plane_state->fb = fb;
2987         plane_state->crtc = &intel_crtc->base;
2988
2989         atomic_or(to_intel_plane(primary)->frontbuffer_bit,
2990                   &obj->frontbuffer_bits);
2991 }
2992
2993 static int skl_max_plane_width(const struct drm_framebuffer *fb,
2994                                int color_plane,
2995                                unsigned int rotation)
2996 {
2997         int cpp = fb->format->cpp[color_plane];
2998
2999         switch (fb->modifier) {
3000         case DRM_FORMAT_MOD_LINEAR:
3001         case I915_FORMAT_MOD_X_TILED:
3002                 return 4096;
3003         case I915_FORMAT_MOD_Y_TILED_CCS:
3004         case I915_FORMAT_MOD_Yf_TILED_CCS:
3005                 /* FIXME AUX plane? */
3006         case I915_FORMAT_MOD_Y_TILED:
3007         case I915_FORMAT_MOD_Yf_TILED:
3008                 if (cpp == 8)
3009                         return 2048;
3010                 else
3011                         return 4096;
3012         default:
3013                 MISSING_CASE(fb->modifier);
3014                 return 2048;
3015         }
3016 }
3017
3018 static int glk_max_plane_width(const struct drm_framebuffer *fb,
3019                                int color_plane,
3020                                unsigned int rotation)
3021 {
3022         int cpp = fb->format->cpp[color_plane];
3023
3024         switch (fb->modifier) {
3025         case DRM_FORMAT_MOD_LINEAR:
3026         case I915_FORMAT_MOD_X_TILED:
3027                 if (cpp == 8)
3028                         return 4096;
3029                 else
3030                         return 5120;
3031         case I915_FORMAT_MOD_Y_TILED_CCS:
3032         case I915_FORMAT_MOD_Yf_TILED_CCS:
3033                 /* FIXME AUX plane? */
3034         case I915_FORMAT_MOD_Y_TILED:
3035         case I915_FORMAT_MOD_Yf_TILED:
3036                 if (cpp == 8)
3037                         return 2048;
3038                 else
3039                         return 5120;
3040         default:
3041                 MISSING_CASE(fb->modifier);
3042                 return 2048;
3043         }
3044 }
3045
3046 static int icl_max_plane_width(const struct drm_framebuffer *fb,
3047                                int color_plane,
3048                                unsigned int rotation)
3049 {
3050         return 5120;
3051 }
3052
3053 static bool skl_check_main_ccs_coordinates(struct intel_plane_state *plane_state,
3054                                            int main_x, int main_y, u32 main_offset)
3055 {
3056         const struct drm_framebuffer *fb = plane_state->base.fb;
3057         int hsub = fb->format->hsub;
3058         int vsub = fb->format->vsub;
3059         int aux_x = plane_state->color_plane[1].x;
3060         int aux_y = plane_state->color_plane[1].y;
3061         u32 aux_offset = plane_state->color_plane[1].offset;
3062         u32 alignment = intel_surf_alignment(fb, 1);
3063
3064         while (aux_offset >= main_offset && aux_y <= main_y) {
3065                 int x, y;
3066
3067                 if (aux_x == main_x && aux_y == main_y)
3068                         break;
3069
3070                 if (aux_offset == 0)
3071                         break;
3072
3073                 x = aux_x / hsub;
3074                 y = aux_y / vsub;
3075                 aux_offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 1,
3076                                                                aux_offset, aux_offset - alignment);
3077                 aux_x = x * hsub + aux_x % hsub;
3078                 aux_y = y * vsub + aux_y % vsub;
3079         }
3080
3081         if (aux_x != main_x || aux_y != main_y)
3082                 return false;
3083
3084         plane_state->color_plane[1].offset = aux_offset;
3085         plane_state->color_plane[1].x = aux_x;
3086         plane_state->color_plane[1].y = aux_y;
3087
3088         return true;
3089 }
3090
3091 static int skl_check_main_surface(struct intel_plane_state *plane_state)
3092 {
3093         struct drm_i915_private *dev_priv = to_i915(plane_state->base.plane->dev);
3094         const struct drm_framebuffer *fb = plane_state->base.fb;
3095         unsigned int rotation = plane_state->base.rotation;
3096         int x = plane_state->base.src.x1 >> 16;
3097         int y = plane_state->base.src.y1 >> 16;
3098         int w = drm_rect_width(&plane_state->base.src) >> 16;
3099         int h = drm_rect_height(&plane_state->base.src) >> 16;
3100         int max_width;
3101         int max_height = 4096;
3102         u32 alignment, offset, aux_offset = plane_state->color_plane[1].offset;
3103
3104         if (INTEL_GEN(dev_priv) >= 11)
3105                 max_width = icl_max_plane_width(fb, 0, rotation);
3106         else if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv))
3107                 max_width = glk_max_plane_width(fb, 0, rotation);
3108         else
3109                 max_width = skl_max_plane_width(fb, 0, rotation);
3110
3111         if (w > max_width || h > max_height) {
3112                 DRM_DEBUG_KMS("requested Y/RGB source size %dx%d too big (limit %dx%d)\n",
3113                               w, h, max_width, max_height);
3114                 return -EINVAL;
3115         }
3116
3117         intel_add_fb_offsets(&x, &y, plane_state, 0);
3118         offset = intel_plane_compute_aligned_offset(&x, &y, plane_state, 0);
3119         alignment = intel_surf_alignment(fb, 0);
3120
3121         /*
3122          * AUX surface offset is specified as the distance from the
3123          * main surface offset, and it must be non-negative. Make
3124          * sure that is what we will get.
3125          */
3126         if (offset > aux_offset)
3127                 offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 0,
3128                                                            offset, aux_offset & ~(alignment - 1));
3129
3130         /*
3131          * When using an X-tiled surface, the plane blows up
3132          * if the x offset + width exceed the stride.
3133          *
3134          * TODO: linear and Y-tiled seem fine, Yf untested,
3135          */
3136         if (fb->modifier == I915_FORMAT_MOD_X_TILED) {
3137                 int cpp = fb->format->cpp[0];
3138
3139                 while ((x + w) * cpp > plane_state->color_plane[0].stride) {
3140                         if (offset == 0) {
3141                                 DRM_DEBUG_KMS("Unable to find suitable display surface offset due to X-tiling\n");
3142                                 return -EINVAL;
3143                         }
3144
3145                         offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 0,
3146                                                                    offset, offset - alignment);
3147                 }
3148         }
3149
3150         /*
3151          * CCS AUX surface doesn't have its own x/y offsets, we must make sure
3152          * they match with the main surface x/y offsets.
3153          */
3154         if (is_ccs_modifier(fb->modifier)) {
3155                 while (!skl_check_main_ccs_coordinates(plane_state, x, y, offset)) {
3156                         if (offset == 0)
3157                                 break;
3158
3159                         offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 0,
3160                                                                    offset, offset - alignment);
3161                 }
3162
3163                 if (x != plane_state->color_plane[1].x || y != plane_state->color_plane[1].y) {
3164                         DRM_DEBUG_KMS("Unable to find suitable display surface offset due to CCS\n");
3165                         return -EINVAL;
3166                 }
3167         }
3168
3169         plane_state->color_plane[0].offset = offset;
3170         plane_state->color_plane[0].x = x;
3171         plane_state->color_plane[0].y = y;
3172
3173         return 0;
3174 }
3175
3176 static int skl_check_nv12_aux_surface(struct intel_plane_state *plane_state)
3177 {
3178         const struct drm_framebuffer *fb = plane_state->base.fb;
3179         unsigned int rotation = plane_state->base.rotation;
3180         int max_width = skl_max_plane_width(fb, 1, rotation);
3181         int max_height = 4096;
3182         int x = plane_state->base.src.x1 >> 17;
3183         int y = plane_state->base.src.y1 >> 17;
3184         int w = drm_rect_width(&plane_state->base.src) >> 17;
3185         int h = drm_rect_height(&plane_state->base.src) >> 17;
3186         u32 offset;
3187
3188         intel_add_fb_offsets(&x, &y, plane_state, 1);
3189         offset = intel_plane_compute_aligned_offset(&x, &y, plane_state, 1);
3190
3191         /* FIXME not quite sure how/if these apply to the chroma plane */
3192         if (w > max_width || h > max_height) {
3193                 DRM_DEBUG_KMS("CbCr source size %dx%d too big (limit %dx%d)\n",
3194                               w, h, max_width, max_height);
3195                 return -EINVAL;
3196         }
3197
3198         plane_state->color_plane[1].offset = offset;
3199         plane_state->color_plane[1].x = x;
3200         plane_state->color_plane[1].y = y;
3201
3202         return 0;
3203 }
3204
3205 static int skl_check_ccs_aux_surface(struct intel_plane_state *plane_state)
3206 {
3207         const struct drm_framebuffer *fb = plane_state->base.fb;
3208         int src_x = plane_state->base.src.x1 >> 16;
3209         int src_y = plane_state->base.src.y1 >> 16;
3210         int hsub = fb->format->hsub;
3211         int vsub = fb->format->vsub;
3212         int x = src_x / hsub;
3213         int y = src_y / vsub;
3214         u32 offset;
3215
3216         intel_add_fb_offsets(&x, &y, plane_state, 1);
3217         offset = intel_plane_compute_aligned_offset(&x, &y, plane_state, 1);
3218
3219         plane_state->color_plane[1].offset = offset;
3220         plane_state->color_plane[1].x = x * hsub + src_x % hsub;
3221         plane_state->color_plane[1].y = y * vsub + src_y % vsub;
3222
3223         return 0;
3224 }
3225
3226 int skl_check_plane_surface(struct intel_plane_state *plane_state)
3227 {
3228         const struct drm_framebuffer *fb = plane_state->base.fb;
3229         unsigned int rotation = plane_state->base.rotation;
3230         int ret;
3231
3232         intel_fill_fb_ggtt_view(&plane_state->view, fb, rotation);
3233         plane_state->color_plane[0].stride = intel_fb_pitch(fb, 0, rotation);
3234         plane_state->color_plane[1].stride = intel_fb_pitch(fb, 1, rotation);
3235
3236         ret = intel_plane_check_stride(plane_state);
3237         if (ret)
3238                 return ret;
3239
3240         if (!plane_state->base.visible)
3241                 return 0;
3242
3243         /* Rotate src coordinates to match rotated GTT view */
3244         if (drm_rotation_90_or_270(rotation))
3245                 drm_rect_rotate(&plane_state->base.src,
3246                                 fb->width << 16, fb->height << 16,
3247                                 DRM_MODE_ROTATE_270);
3248
3249         /*
3250          * Handle the AUX surface first since
3251          * the main surface setup depends on it.
3252          */
3253         if (is_planar_yuv_format(fb->format->format)) {
3254                 ret = skl_check_nv12_aux_surface(plane_state);
3255                 if (ret)
3256                         return ret;
3257         } else if (is_ccs_modifier(fb->modifier)) {
3258                 ret = skl_check_ccs_aux_surface(plane_state);
3259                 if (ret)
3260                         return ret;
3261         } else {
3262                 plane_state->color_plane[1].offset = ~0xfff;
3263                 plane_state->color_plane[1].x = 0;
3264                 plane_state->color_plane[1].y = 0;
3265         }
3266
3267         ret = skl_check_main_surface(plane_state);
3268         if (ret)
3269                 return ret;
3270
3271         return 0;
3272 }
3273
3274 unsigned int
3275 i9xx_plane_max_stride(struct intel_plane *plane,
3276                       u32 pixel_format, u64 modifier,
3277                       unsigned int rotation)
3278 {
3279         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3280
3281         if (!HAS_GMCH(dev_priv)) {
3282                 return 32*1024;
3283         } else if (INTEL_GEN(dev_priv) >= 4) {
3284                 if (modifier == I915_FORMAT_MOD_X_TILED)
3285                         return 16*1024;
3286                 else
3287                         return 32*1024;
3288         } else if (INTEL_GEN(dev_priv) >= 3) {
3289                 if (modifier == I915_FORMAT_MOD_X_TILED)
3290                         return 8*1024;
3291                 else
3292                         return 16*1024;
3293         } else {
3294                 if (plane->i9xx_plane == PLANE_C)
3295                         return 4*1024;
3296                 else
3297                         return 8*1024;
3298         }
3299 }
3300
3301 static u32 i9xx_plane_ctl_crtc(const struct intel_crtc_state *crtc_state)
3302 {
3303         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
3304         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
3305         u32 dspcntr = 0;
3306
3307         if (crtc_state->gamma_enable)
3308                 dspcntr |= DISPPLANE_GAMMA_ENABLE;
3309
3310         if (crtc_state->csc_enable)
3311                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
3312
3313         if (INTEL_GEN(dev_priv) < 5)
3314                 dspcntr |= DISPPLANE_SEL_PIPE(crtc->pipe);
3315
3316         return dspcntr;
3317 }
3318
3319 static u32 i9xx_plane_ctl(const struct intel_crtc_state *crtc_state,
3320                           const struct intel_plane_state *plane_state)
3321 {
3322         struct drm_i915_private *dev_priv =
3323                 to_i915(plane_state->base.plane->dev);
3324         const struct drm_framebuffer *fb = plane_state->base.fb;
3325         unsigned int rotation = plane_state->base.rotation;
3326         u32 dspcntr;
3327
3328         dspcntr = DISPLAY_PLANE_ENABLE;
3329
3330         if (IS_G4X(dev_priv) || IS_GEN(dev_priv, 5) ||
3331             IS_GEN(dev_priv, 6) || IS_IVYBRIDGE(dev_priv))
3332                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
3333
3334         switch (fb->format->format) {
3335         case DRM_FORMAT_C8:
3336                 dspcntr |= DISPPLANE_8BPP;
3337                 break;
3338         case DRM_FORMAT_XRGB1555:
3339                 dspcntr |= DISPPLANE_BGRX555;
3340                 break;
3341         case DRM_FORMAT_RGB565:
3342                 dspcntr |= DISPPLANE_BGRX565;
3343                 break;
3344         case DRM_FORMAT_XRGB8888:
3345                 dspcntr |= DISPPLANE_BGRX888;
3346                 break;
3347         case DRM_FORMAT_XBGR8888:
3348                 dspcntr |= DISPPLANE_RGBX888;
3349                 break;
3350         case DRM_FORMAT_XRGB2101010:
3351                 dspcntr |= DISPPLANE_BGRX101010;
3352                 break;
3353         case DRM_FORMAT_XBGR2101010:
3354                 dspcntr |= DISPPLANE_RGBX101010;
3355                 break;
3356         default:
3357                 MISSING_CASE(fb->format->format);
3358                 return 0;
3359         }
3360
3361         if (INTEL_GEN(dev_priv) >= 4 &&
3362             fb->modifier == I915_FORMAT_MOD_X_TILED)
3363                 dspcntr |= DISPPLANE_TILED;
3364
3365         if (rotation & DRM_MODE_ROTATE_180)
3366                 dspcntr |= DISPPLANE_ROTATE_180;
3367
3368         if (rotation & DRM_MODE_REFLECT_X)
3369                 dspcntr |= DISPPLANE_MIRROR;
3370
3371         return dspcntr;
3372 }
3373
3374 int i9xx_check_plane_surface(struct intel_plane_state *plane_state)
3375 {
3376         struct drm_i915_private *dev_priv =
3377                 to_i915(plane_state->base.plane->dev);
3378         const struct drm_framebuffer *fb = plane_state->base.fb;
3379         unsigned int rotation = plane_state->base.rotation;
3380         int src_x = plane_state->base.src.x1 >> 16;
3381         int src_y = plane_state->base.src.y1 >> 16;
3382         u32 offset;
3383         int ret;
3384
3385         intel_fill_fb_ggtt_view(&plane_state->view, fb, rotation);
3386         plane_state->color_plane[0].stride = intel_fb_pitch(fb, 0, rotation);
3387
3388         ret = intel_plane_check_stride(plane_state);
3389         if (ret)
3390                 return ret;
3391
3392         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
3393
3394         if (INTEL_GEN(dev_priv) >= 4)
3395                 offset = intel_plane_compute_aligned_offset(&src_x, &src_y,
3396                                                             plane_state, 0);
3397         else
3398                 offset = 0;
3399
3400         /* HSW/BDW do this automagically in hardware */
3401         if (!IS_HASWELL(dev_priv) && !IS_BROADWELL(dev_priv)) {
3402                 int src_w = drm_rect_width(&plane_state->base.src) >> 16;
3403                 int src_h = drm_rect_height(&plane_state->base.src) >> 16;
3404
3405                 if (rotation & DRM_MODE_ROTATE_180) {
3406                         src_x += src_w - 1;
3407                         src_y += src_h - 1;
3408                 } else if (rotation & DRM_MODE_REFLECT_X) {
3409                         src_x += src_w - 1;
3410                 }
3411         }
3412
3413         plane_state->color_plane[0].offset = offset;
3414         plane_state->color_plane[0].x = src_x;
3415         plane_state->color_plane[0].y = src_y;
3416
3417         return 0;
3418 }
3419
3420 static int
3421 i9xx_plane_check(struct intel_crtc_state *crtc_state,
3422                  struct intel_plane_state *plane_state)
3423 {
3424         int ret;
3425
3426         ret = chv_plane_check_rotation(plane_state);
3427         if (ret)
3428                 return ret;
3429
3430         ret = drm_atomic_helper_check_plane_state(&plane_state->base,
3431                                                   &crtc_state->base,
3432                                                   DRM_PLANE_HELPER_NO_SCALING,
3433                                                   DRM_PLANE_HELPER_NO_SCALING,
3434                                                   false, true);
3435         if (ret)
3436                 return ret;
3437
3438         if (!plane_state->base.visible)
3439                 return 0;
3440
3441         ret = intel_plane_check_src_coordinates(plane_state);
3442         if (ret)
3443                 return ret;
3444
3445         ret = i9xx_check_plane_surface(plane_state);
3446         if (ret)
3447                 return ret;
3448
3449         plane_state->ctl = i9xx_plane_ctl(crtc_state, plane_state);
3450
3451         return 0;
3452 }
3453
3454 static void i9xx_update_plane(struct intel_plane *plane,
3455                               const struct intel_crtc_state *crtc_state,
3456                               const struct intel_plane_state *plane_state)
3457 {
3458         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3459         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3460         u32 linear_offset;
3461         int x = plane_state->color_plane[0].x;
3462         int y = plane_state->color_plane[0].y;
3463         unsigned long irqflags;
3464         u32 dspaddr_offset;
3465         u32 dspcntr;
3466
3467         dspcntr = plane_state->ctl | i9xx_plane_ctl_crtc(crtc_state);
3468
3469         linear_offset = intel_fb_xy_to_linear(x, y, plane_state, 0);
3470
3471         if (INTEL_GEN(dev_priv) >= 4)
3472                 dspaddr_offset = plane_state->color_plane[0].offset;
3473         else
3474                 dspaddr_offset = linear_offset;
3475
3476         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3477
3478         I915_WRITE_FW(DSPSTRIDE(i9xx_plane), plane_state->color_plane[0].stride);
3479
3480         if (INTEL_GEN(dev_priv) < 4) {
3481                 /* pipesrc and dspsize control the size that is scaled from,
3482                  * which should always be the user's requested size.
3483                  */
3484                 I915_WRITE_FW(DSPPOS(i9xx_plane), 0);
3485                 I915_WRITE_FW(DSPSIZE(i9xx_plane),
3486                               ((crtc_state->pipe_src_h - 1) << 16) |
3487                               (crtc_state->pipe_src_w - 1));
3488         } else if (IS_CHERRYVIEW(dev_priv) && i9xx_plane == PLANE_B) {
3489                 I915_WRITE_FW(PRIMPOS(i9xx_plane), 0);
3490                 I915_WRITE_FW(PRIMSIZE(i9xx_plane),
3491                               ((crtc_state->pipe_src_h - 1) << 16) |
3492                               (crtc_state->pipe_src_w - 1));
3493                 I915_WRITE_FW(PRIMCNSTALPHA(i9xx_plane), 0);
3494         }
3495
3496         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
3497                 I915_WRITE_FW(DSPOFFSET(i9xx_plane), (y << 16) | x);
3498         } else if (INTEL_GEN(dev_priv) >= 4) {
3499                 I915_WRITE_FW(DSPLINOFF(i9xx_plane), linear_offset);
3500                 I915_WRITE_FW(DSPTILEOFF(i9xx_plane), (y << 16) | x);
3501         }
3502
3503         /*
3504          * The control register self-arms if the plane was previously
3505          * disabled. Try to make the plane enable atomic by writing
3506          * the control register just before the surface register.
3507          */
3508         I915_WRITE_FW(DSPCNTR(i9xx_plane), dspcntr);
3509         if (INTEL_GEN(dev_priv) >= 4)
3510                 I915_WRITE_FW(DSPSURF(i9xx_plane),
3511                               intel_plane_ggtt_offset(plane_state) +
3512                               dspaddr_offset);
3513         else
3514                 I915_WRITE_FW(DSPADDR(i9xx_plane),
3515                               intel_plane_ggtt_offset(plane_state) +
3516                               dspaddr_offset);
3517
3518         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3519 }
3520
3521 static void i9xx_disable_plane(struct intel_plane *plane,
3522                                const struct intel_crtc_state *crtc_state)
3523 {
3524         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3525         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3526         unsigned long irqflags;
3527         u32 dspcntr;
3528
3529         /*
3530          * DSPCNTR pipe gamma enable on g4x+ and pipe csc
3531          * enable on ilk+ affect the pipe bottom color as
3532          * well, so we must configure them even if the plane
3533          * is disabled.
3534          *
3535          * On pre-g4x there is no way to gamma correct the
3536          * pipe bottom color but we'll keep on doing this
3537          * anyway so that the crtc state readout works correctly.
3538          */
3539         dspcntr = i9xx_plane_ctl_crtc(crtc_state);
3540
3541         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3542
3543         I915_WRITE_FW(DSPCNTR(i9xx_plane), dspcntr);
3544         if (INTEL_GEN(dev_priv) >= 4)
3545                 I915_WRITE_FW(DSPSURF(i9xx_plane), 0);
3546         else
3547                 I915_WRITE_FW(DSPADDR(i9xx_plane), 0);
3548
3549         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3550 }
3551
3552 static bool i9xx_plane_get_hw_state(struct intel_plane *plane,
3553                                     enum pipe *pipe)
3554 {
3555         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3556         enum intel_display_power_domain power_domain;
3557         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3558         intel_wakeref_t wakeref;
3559         bool ret;
3560         u32 val;
3561
3562         /*
3563          * Not 100% correct for planes that can move between pipes,
3564          * but that's only the case for gen2-4 which don't have any
3565          * display power wells.
3566          */
3567         power_domain = POWER_DOMAIN_PIPE(plane->pipe);
3568         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
3569         if (!wakeref)
3570                 return false;
3571
3572         val = I915_READ(DSPCNTR(i9xx_plane));
3573
3574         ret = val & DISPLAY_PLANE_ENABLE;
3575
3576         if (INTEL_GEN(dev_priv) >= 5)
3577                 *pipe = plane->pipe;
3578         else
3579                 *pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
3580                         DISPPLANE_SEL_PIPE_SHIFT;
3581
3582         intel_display_power_put(dev_priv, power_domain, wakeref);
3583
3584         return ret;
3585 }
3586
3587 static u32
3588 intel_fb_stride_alignment(const struct drm_framebuffer *fb, int color_plane)
3589 {
3590         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
3591                 return 64;
3592         else
3593                 return intel_tile_width_bytes(fb, color_plane);
3594 }
3595
3596 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
3597 {
3598         struct drm_device *dev = intel_crtc->base.dev;
3599         struct drm_i915_private *dev_priv = to_i915(dev);
3600
3601         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
3602         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
3603         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
3604 }
3605
3606 /*
3607  * This function detaches (aka. unbinds) unused scalers in hardware
3608  */
3609 static void skl_detach_scalers(const struct intel_crtc_state *crtc_state)
3610 {
3611         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
3612         const struct intel_crtc_scaler_state *scaler_state =
3613                 &crtc_state->scaler_state;
3614         int i;
3615
3616         /* loop through and disable scalers that aren't in use */
3617         for (i = 0; i < intel_crtc->num_scalers; i++) {
3618                 if (!scaler_state->scalers[i].in_use)
3619                         skl_detach_scaler(intel_crtc, i);
3620         }
3621 }
3622
3623 static unsigned int skl_plane_stride_mult(const struct drm_framebuffer *fb,
3624                                           int color_plane, unsigned int rotation)
3625 {
3626         /*
3627          * The stride is either expressed as a multiple of 64 bytes chunks for
3628          * linear buffers or in number of tiles for tiled buffers.
3629          */
3630         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
3631                 return 64;
3632         else if (drm_rotation_90_or_270(rotation))
3633                 return intel_tile_height(fb, color_plane);
3634         else
3635                 return intel_tile_width_bytes(fb, color_plane);
3636 }
3637
3638 u32 skl_plane_stride(const struct intel_plane_state *plane_state,
3639                      int color_plane)
3640 {
3641         const struct drm_framebuffer *fb = plane_state->base.fb;
3642         unsigned int rotation = plane_state->base.rotation;
3643         u32 stride = plane_state->color_plane[color_plane].stride;
3644
3645         if (color_plane >= fb->format->num_planes)
3646                 return 0;
3647
3648         return stride / skl_plane_stride_mult(fb, color_plane, rotation);
3649 }
3650
3651 static u32 skl_plane_ctl_format(u32 pixel_format)
3652 {
3653         switch (pixel_format) {
3654         case DRM_FORMAT_C8:
3655                 return PLANE_CTL_FORMAT_INDEXED;
3656         case DRM_FORMAT_RGB565:
3657                 return PLANE_CTL_FORMAT_RGB_565;
3658         case DRM_FORMAT_XBGR8888:
3659         case DRM_FORMAT_ABGR8888:
3660                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
3661         case DRM_FORMAT_XRGB8888:
3662         case DRM_FORMAT_ARGB8888:
3663                 return PLANE_CTL_FORMAT_XRGB_8888;
3664         case DRM_FORMAT_XRGB2101010:
3665                 return PLANE_CTL_FORMAT_XRGB_2101010;
3666         case DRM_FORMAT_XBGR2101010:
3667                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
3668         case DRM_FORMAT_XBGR16161616F:
3669         case DRM_FORMAT_ABGR16161616F:
3670                 return PLANE_CTL_FORMAT_XRGB_16161616F | PLANE_CTL_ORDER_RGBX;
3671         case DRM_FORMAT_XRGB16161616F:
3672         case DRM_FORMAT_ARGB16161616F:
3673                 return PLANE_CTL_FORMAT_XRGB_16161616F;
3674         case DRM_FORMAT_YUYV:
3675                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
3676         case DRM_FORMAT_YVYU:
3677                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
3678         case DRM_FORMAT_UYVY:
3679                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
3680         case DRM_FORMAT_VYUY:
3681                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
3682         case DRM_FORMAT_NV12:
3683                 return PLANE_CTL_FORMAT_NV12;
3684         case DRM_FORMAT_P010:
3685                 return PLANE_CTL_FORMAT_P010;
3686         case DRM_FORMAT_P012:
3687                 return PLANE_CTL_FORMAT_P012;
3688         case DRM_FORMAT_P016:
3689                 return PLANE_CTL_FORMAT_P016;
3690         case DRM_FORMAT_Y210:
3691                 return PLANE_CTL_FORMAT_Y210;
3692         case DRM_FORMAT_Y212:
3693                 return PLANE_CTL_FORMAT_Y212;
3694         case DRM_FORMAT_Y216:
3695                 return PLANE_CTL_FORMAT_Y216;
3696         case DRM_FORMAT_XVYU2101010:
3697                 return PLANE_CTL_FORMAT_Y410;
3698         case DRM_FORMAT_XVYU12_16161616:
3699                 return PLANE_CTL_FORMAT_Y412;
3700         case DRM_FORMAT_XVYU16161616:
3701                 return PLANE_CTL_FORMAT_Y416;
3702         default:
3703                 MISSING_CASE(pixel_format);
3704         }
3705
3706         return 0;
3707 }
3708
3709 static u32 skl_plane_ctl_alpha(const struct intel_plane_state *plane_state)
3710 {
3711         if (!plane_state->base.fb->format->has_alpha)
3712                 return PLANE_CTL_ALPHA_DISABLE;
3713
3714         switch (plane_state->base.pixel_blend_mode) {
3715         case DRM_MODE_BLEND_PIXEL_NONE:
3716                 return PLANE_CTL_ALPHA_DISABLE;
3717         case DRM_MODE_BLEND_PREMULTI:
3718                 return PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3719         case DRM_MODE_BLEND_COVERAGE:
3720                 return PLANE_CTL_ALPHA_HW_PREMULTIPLY;
3721         default:
3722                 MISSING_CASE(plane_state->base.pixel_blend_mode);
3723                 return PLANE_CTL_ALPHA_DISABLE;
3724         }
3725 }
3726
3727 static u32 glk_plane_color_ctl_alpha(const struct intel_plane_state *plane_state)
3728 {
3729         if (!plane_state->base.fb->format->has_alpha)
3730                 return PLANE_COLOR_ALPHA_DISABLE;
3731
3732         switch (plane_state->base.pixel_blend_mode) {
3733         case DRM_MODE_BLEND_PIXEL_NONE:
3734                 return PLANE_COLOR_ALPHA_DISABLE;
3735         case DRM_MODE_BLEND_PREMULTI:
3736                 return PLANE_COLOR_ALPHA_SW_PREMULTIPLY;
3737         case DRM_MODE_BLEND_COVERAGE:
3738                 return PLANE_COLOR_ALPHA_HW_PREMULTIPLY;
3739         default:
3740                 MISSING_CASE(plane_state->base.pixel_blend_mode);
3741                 return PLANE_COLOR_ALPHA_DISABLE;
3742         }
3743 }
3744
3745 static u32 skl_plane_ctl_tiling(u64 fb_modifier)
3746 {
3747         switch (fb_modifier) {
3748         case DRM_FORMAT_MOD_LINEAR:
3749                 break;
3750         case I915_FORMAT_MOD_X_TILED:
3751                 return PLANE_CTL_TILED_X;
3752         case I915_FORMAT_MOD_Y_TILED:
3753                 return PLANE_CTL_TILED_Y;
3754         case I915_FORMAT_MOD_Y_TILED_CCS:
3755                 return PLANE_CTL_TILED_Y | PLANE_CTL_RENDER_DECOMPRESSION_ENABLE;
3756         case I915_FORMAT_MOD_Yf_TILED:
3757                 return PLANE_CTL_TILED_YF;
3758         case I915_FORMAT_MOD_Yf_TILED_CCS:
3759                 return PLANE_CTL_TILED_YF | PLANE_CTL_RENDER_DECOMPRESSION_ENABLE;
3760         default:
3761                 MISSING_CASE(fb_modifier);
3762         }
3763
3764         return 0;
3765 }
3766
3767 static u32 skl_plane_ctl_rotate(unsigned int rotate)
3768 {
3769         switch (rotate) {
3770         case DRM_MODE_ROTATE_0:
3771                 break;
3772         /*
3773          * DRM_MODE_ROTATE_ is counter clockwise to stay compatible with Xrandr
3774          * while i915 HW rotation is clockwise, thats why this swapping.
3775          */
3776         case DRM_MODE_ROTATE_90:
3777                 return PLANE_CTL_ROTATE_270;
3778         case DRM_MODE_ROTATE_180:
3779                 return PLANE_CTL_ROTATE_180;
3780         case DRM_MODE_ROTATE_270:
3781                 return PLANE_CTL_ROTATE_90;
3782         default:
3783                 MISSING_CASE(rotate);
3784         }
3785
3786         return 0;
3787 }
3788
3789 static u32 cnl_plane_ctl_flip(unsigned int reflect)
3790 {
3791         switch (reflect) {
3792         case 0:
3793                 break;
3794         case DRM_MODE_REFLECT_X:
3795                 return PLANE_CTL_FLIP_HORIZONTAL;
3796         case DRM_MODE_REFLECT_Y:
3797         default:
3798                 MISSING_CASE(reflect);
3799         }
3800
3801         return 0;
3802 }
3803
3804 u32 skl_plane_ctl_crtc(const struct intel_crtc_state *crtc_state)
3805 {
3806         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
3807         u32 plane_ctl = 0;
3808
3809         if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv))
3810                 return plane_ctl;
3811
3812         if (crtc_state->gamma_enable)
3813                 plane_ctl |= PLANE_CTL_PIPE_GAMMA_ENABLE;
3814
3815         if (crtc_state->csc_enable)
3816                 plane_ctl |= PLANE_CTL_PIPE_CSC_ENABLE;
3817
3818         return plane_ctl;
3819 }
3820
3821 u32 skl_plane_ctl(const struct intel_crtc_state *crtc_state,
3822                   const struct intel_plane_state *plane_state)
3823 {
3824         struct drm_i915_private *dev_priv =
3825                 to_i915(plane_state->base.plane->dev);
3826         const struct drm_framebuffer *fb = plane_state->base.fb;
3827         unsigned int rotation = plane_state->base.rotation;
3828         const struct drm_intel_sprite_colorkey *key = &plane_state->ckey;
3829         u32 plane_ctl;
3830
3831         plane_ctl = PLANE_CTL_ENABLE;
3832
3833         if (INTEL_GEN(dev_priv) < 10 && !IS_GEMINILAKE(dev_priv)) {
3834                 plane_ctl |= skl_plane_ctl_alpha(plane_state);
3835                 plane_ctl |= PLANE_CTL_PLANE_GAMMA_DISABLE;
3836
3837                 if (plane_state->base.color_encoding == DRM_COLOR_YCBCR_BT709)
3838                         plane_ctl |= PLANE_CTL_YUV_TO_RGB_CSC_FORMAT_BT709;
3839
3840                 if (plane_state->base.color_range == DRM_COLOR_YCBCR_FULL_RANGE)
3841                         plane_ctl |= PLANE_CTL_YUV_RANGE_CORRECTION_DISABLE;
3842         }
3843
3844         plane_ctl |= skl_plane_ctl_format(fb->format->format);
3845         plane_ctl |= skl_plane_ctl_tiling(fb->modifier);
3846         plane_ctl |= skl_plane_ctl_rotate(rotation & DRM_MODE_ROTATE_MASK);
3847
3848         if (INTEL_GEN(dev_priv) >= 10)
3849                 plane_ctl |= cnl_plane_ctl_flip(rotation &
3850                                                 DRM_MODE_REFLECT_MASK);
3851
3852         if (key->flags & I915_SET_COLORKEY_DESTINATION)
3853                 plane_ctl |= PLANE_CTL_KEY_ENABLE_DESTINATION;
3854         else if (key->flags & I915_SET_COLORKEY_SOURCE)
3855                 plane_ctl |= PLANE_CTL_KEY_ENABLE_SOURCE;
3856
3857         return plane_ctl;
3858 }
3859
3860 u32 glk_plane_color_ctl_crtc(const struct intel_crtc_state *crtc_state)
3861 {
3862         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
3863         u32 plane_color_ctl = 0;
3864
3865         if (INTEL_GEN(dev_priv) >= 11)
3866                 return plane_color_ctl;
3867
3868         if (crtc_state->gamma_enable)
3869                 plane_color_ctl |= PLANE_COLOR_PIPE_GAMMA_ENABLE;
3870
3871         if (crtc_state->csc_enable)
3872                 plane_color_ctl |= PLANE_COLOR_PIPE_CSC_ENABLE;
3873
3874         return plane_color_ctl;
3875 }
3876
3877 u32 glk_plane_color_ctl(const struct intel_crtc_state *crtc_state,
3878                         const struct intel_plane_state *plane_state)
3879 {
3880         struct drm_i915_private *dev_priv =
3881                 to_i915(plane_state->base.plane->dev);
3882         const struct drm_framebuffer *fb = plane_state->base.fb;
3883         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
3884         u32 plane_color_ctl = 0;
3885
3886         plane_color_ctl |= PLANE_COLOR_PLANE_GAMMA_DISABLE;
3887         plane_color_ctl |= glk_plane_color_ctl_alpha(plane_state);
3888
3889         if (fb->format->is_yuv && !icl_is_hdr_plane(dev_priv, plane->id)) {
3890                 if (plane_state->base.color_encoding == DRM_COLOR_YCBCR_BT709)
3891                         plane_color_ctl |= PLANE_COLOR_CSC_MODE_YUV709_TO_RGB709;
3892                 else
3893                         plane_color_ctl |= PLANE_COLOR_CSC_MODE_YUV601_TO_RGB709;
3894
3895                 if (plane_state->base.color_range == DRM_COLOR_YCBCR_FULL_RANGE)
3896                         plane_color_ctl |= PLANE_COLOR_YUV_RANGE_CORRECTION_DISABLE;
3897         } else if (fb->format->is_yuv) {
3898                 plane_color_ctl |= PLANE_COLOR_INPUT_CSC_ENABLE;
3899         }
3900
3901         return plane_color_ctl;
3902 }
3903
3904 static int
3905 __intel_display_resume(struct drm_device *dev,
3906                        struct drm_atomic_state *state,
3907                        struct drm_modeset_acquire_ctx *ctx)
3908 {
3909         struct drm_crtc_state *crtc_state;
3910         struct drm_crtc *crtc;
3911         int i, ret;
3912
3913         intel_modeset_setup_hw_state(dev, ctx);
3914         i915_redisable_vga(to_i915(dev));
3915
3916         if (!state)
3917                 return 0;
3918
3919         /*
3920          * We've duplicated the state, pointers to the old state are invalid.
3921          *
3922          * Don't attempt to use the old state until we commit the duplicated state.
3923          */
3924         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
3925                 /*
3926                  * Force recalculation even if we restore
3927                  * current state. With fast modeset this may not result
3928                  * in a modeset when the state is compatible.
3929                  */
3930                 crtc_state->mode_changed = true;
3931         }
3932
3933         /* ignore any reset values/BIOS leftovers in the WM registers */
3934         if (!HAS_GMCH(to_i915(dev)))
3935                 to_intel_atomic_state(state)->skip_intermediate_wm = true;
3936
3937         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
3938
3939         WARN_ON(ret == -EDEADLK);
3940         return ret;
3941 }
3942
3943 static bool gpu_reset_clobbers_display(struct drm_i915_private *dev_priv)
3944 {
3945         return (INTEL_INFO(dev_priv)->gpu_reset_clobbers_display &&
3946                 intel_has_gpu_reset(dev_priv));
3947 }
3948
3949 void intel_prepare_reset(struct drm_i915_private *dev_priv)
3950 {
3951         struct drm_device *dev = &dev_priv->drm;
3952         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3953         struct drm_atomic_state *state;
3954         int ret;
3955
3956         /* reset doesn't touch the display */
3957         if (!i915_modparams.force_reset_modeset_test &&
3958             !gpu_reset_clobbers_display(dev_priv))
3959                 return;
3960
3961         /* We have a modeset vs reset deadlock, defensively unbreak it. */
3962         set_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
3963         wake_up_all(&dev_priv->gpu_error.wait_queue);
3964
3965         if (atomic_read(&dev_priv->gpu_error.pending_fb_pin)) {
3966                 DRM_DEBUG_KMS("Modeset potentially stuck, unbreaking through wedging\n");
3967                 i915_gem_set_wedged(dev_priv);
3968         }
3969
3970         /*
3971          * Need mode_config.mutex so that we don't
3972          * trample ongoing ->detect() and whatnot.
3973          */
3974         mutex_lock(&dev->mode_config.mutex);
3975         drm_modeset_acquire_init(ctx, 0);
3976         while (1) {
3977                 ret = drm_modeset_lock_all_ctx(dev, ctx);
3978                 if (ret != -EDEADLK)
3979                         break;
3980
3981                 drm_modeset_backoff(ctx);
3982         }
3983         /*
3984          * Disabling the crtcs gracefully seems nicer. Also the
3985          * g33 docs say we should at least disable all the planes.
3986          */
3987         state = drm_atomic_helper_duplicate_state(dev, ctx);
3988         if (IS_ERR(state)) {
3989                 ret = PTR_ERR(state);
3990                 DRM_ERROR("Duplicating state failed with %i\n", ret);
3991                 return;
3992         }
3993
3994         ret = drm_atomic_helper_disable_all(dev, ctx);
3995         if (ret) {
3996                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
3997                 drm_atomic_state_put(state);
3998                 return;
3999         }
4000
4001         dev_priv->modeset_restore_state = state;
4002         state->acquire_ctx = ctx;
4003 }
4004
4005 void intel_finish_reset(struct drm_i915_private *dev_priv)
4006 {
4007         struct drm_device *dev = &dev_priv->drm;
4008         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
4009         struct drm_atomic_state *state;
4010         int ret;
4011
4012         /* reset doesn't touch the display */
4013         if (!test_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags))
4014                 return;
4015
4016         state = fetch_and_zero(&dev_priv->modeset_restore_state);
4017         if (!state)
4018                 goto unlock;
4019
4020         /* reset doesn't touch the display */
4021         if (!gpu_reset_clobbers_display(dev_priv)) {
4022                 /* for testing only restore the display */
4023                 ret = __intel_display_resume(dev, state, ctx);
4024                 if (ret)
4025                         DRM_ERROR("Restoring old state failed with %i\n", ret);
4026         } else {
4027                 /*
4028                  * The display has been reset as well,
4029                  * so need a full re-initialization.
4030                  */
4031                 intel_pps_unlock_regs_wa(dev_priv);
4032                 intel_modeset_init_hw(dev);
4033                 intel_init_clock_gating(dev_priv);
4034
4035                 spin_lock_irq(&dev_priv->irq_lock);
4036                 if (dev_priv->display.hpd_irq_setup)
4037                         dev_priv->display.hpd_irq_setup(dev_priv);
4038                 spin_unlock_irq(&dev_priv->irq_lock);
4039
4040                 ret = __intel_display_resume(dev, state, ctx);
4041                 if (ret)
4042                         DRM_ERROR("Restoring old state failed with %i\n", ret);
4043
4044                 intel_hpd_init(dev_priv);
4045         }
4046
4047         drm_atomic_state_put(state);
4048 unlock:
4049         drm_modeset_drop_locks(ctx);
4050         drm_modeset_acquire_fini(ctx);
4051         mutex_unlock(&dev->mode_config.mutex);
4052
4053         clear_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
4054 }
4055
4056 static void icl_set_pipe_chicken(struct intel_crtc *crtc)
4057 {
4058         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4059         enum pipe pipe = crtc->pipe;
4060         u32 tmp;
4061
4062         tmp = I915_READ(PIPE_CHICKEN(pipe));
4063
4064         /*
4065          * Display WA #1153: icl
4066          * enable hardware to bypass the alpha math
4067          * and rounding for per-pixel values 00 and 0xff
4068          */
4069         tmp |= PER_PIXEL_ALPHA_BYPASS_EN;
4070         /*
4071          * Display WA # 1605353570: icl
4072          * Set the pixel rounding bit to 1 for allowing
4073          * passthrough of Frame buffer pixels unmodified
4074          * across pipe
4075          */
4076         tmp |= PIXEL_ROUNDING_TRUNC_FB_PASSTHRU;
4077         I915_WRITE(PIPE_CHICKEN(pipe), tmp);
4078 }
4079
4080 static void intel_update_pipe_config(const struct intel_crtc_state *old_crtc_state,
4081                                      const struct intel_crtc_state *new_crtc_state)
4082 {
4083         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
4084         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4085
4086         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
4087         crtc->base.mode = new_crtc_state->base.mode;
4088
4089         /*
4090          * Update pipe size and adjust fitter if needed: the reason for this is
4091          * that in compute_mode_changes we check the native mode (not the pfit
4092          * mode) to see if we can flip rather than do a full mode set. In the
4093          * fastboot case, we'll flip, but if we don't update the pipesrc and
4094          * pfit state, we'll end up with a big fb scanned out into the wrong
4095          * sized surface.
4096          */
4097
4098         I915_WRITE(PIPESRC(crtc->pipe),
4099                    ((new_crtc_state->pipe_src_w - 1) << 16) |
4100                    (new_crtc_state->pipe_src_h - 1));
4101
4102         /* on skylake this is done by detaching scalers */
4103         if (INTEL_GEN(dev_priv) >= 9) {
4104                 skl_detach_scalers(new_crtc_state);
4105
4106                 if (new_crtc_state->pch_pfit.enabled)
4107                         skylake_pfit_enable(new_crtc_state);
4108         } else if (HAS_PCH_SPLIT(dev_priv)) {
4109                 if (new_crtc_state->pch_pfit.enabled)
4110                         ironlake_pfit_enable(new_crtc_state);
4111                 else if (old_crtc_state->pch_pfit.enabled)
4112                         ironlake_pfit_disable(old_crtc_state);
4113         }
4114
4115         if (INTEL_GEN(dev_priv) >= 11)
4116                 icl_set_pipe_chicken(crtc);
4117 }
4118
4119 static void intel_fdi_normal_train(struct intel_crtc *crtc)
4120 {
4121         struct drm_device *dev = crtc->base.dev;
4122         struct drm_i915_private *dev_priv = to_i915(dev);
4123         int pipe = crtc->pipe;
4124         i915_reg_t reg;
4125         u32 temp;
4126
4127         /* enable normal train */
4128         reg = FDI_TX_CTL(pipe);
4129         temp = I915_READ(reg);
4130         if (IS_IVYBRIDGE(dev_priv)) {
4131                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
4132                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
4133         } else {
4134                 temp &= ~FDI_LINK_TRAIN_NONE;
4135                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
4136         }
4137         I915_WRITE(reg, temp);
4138
4139         reg = FDI_RX_CTL(pipe);
4140         temp = I915_READ(reg);
4141         if (HAS_PCH_CPT(dev_priv)) {
4142                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4143                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
4144         } else {
4145                 temp &= ~FDI_LINK_TRAIN_NONE;
4146                 temp |= FDI_LINK_TRAIN_NONE;
4147         }
4148         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
4149
4150         /* wait one idle pattern time */
4151         POSTING_READ(reg);
4152         udelay(1000);
4153
4154         /* IVB wants error correction enabled */
4155         if (IS_IVYBRIDGE(dev_priv))
4156                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
4157                            FDI_FE_ERRC_ENABLE);
4158 }
4159
4160 /* The FDI link training functions for ILK/Ibexpeak. */
4161 static void ironlake_fdi_link_train(struct intel_crtc *crtc,
4162                                     const struct intel_crtc_state *crtc_state)
4163 {
4164         struct drm_device *dev = crtc->base.dev;
4165         struct drm_i915_private *dev_priv = to_i915(dev);
4166         int pipe = crtc->pipe;
4167         i915_reg_t reg;
4168         u32 temp, tries;
4169
4170         /* FDI needs bits from pipe first */
4171         assert_pipe_enabled(dev_priv, pipe);
4172
4173         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4174            for train result */
4175         reg = FDI_RX_IMR(pipe);
4176         temp = I915_READ(reg);
4177         temp &= ~FDI_RX_SYMBOL_LOCK;
4178         temp &= ~FDI_RX_BIT_LOCK;
4179         I915_WRITE(reg, temp);
4180         I915_READ(reg);
4181         udelay(150);
4182
4183         /* enable CPU FDI TX and PCH FDI RX */
4184         reg = FDI_TX_CTL(pipe);
4185         temp = I915_READ(reg);
4186         temp &= ~FDI_DP_PORT_WIDTH_MASK;
4187         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4188         temp &= ~FDI_LINK_TRAIN_NONE;
4189         temp |= FDI_LINK_TRAIN_PATTERN_1;
4190         I915_WRITE(reg, temp | FDI_TX_ENABLE);
4191
4192         reg = FDI_RX_CTL(pipe);
4193         temp = I915_READ(reg);
4194         temp &= ~FDI_LINK_TRAIN_NONE;
4195         temp |= FDI_LINK_TRAIN_PATTERN_1;
4196         I915_WRITE(reg, temp | FDI_RX_ENABLE);
4197
4198         POSTING_READ(reg);
4199         udelay(150);
4200
4201         /* Ironlake workaround, enable clock pointer after FDI enable*/
4202         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
4203         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
4204                    FDI_RX_PHASE_SYNC_POINTER_EN);
4205
4206         reg = FDI_RX_IIR(pipe);
4207         for (tries = 0; tries < 5; tries++) {
4208                 temp = I915_READ(reg);
4209                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4210
4211                 if ((temp & FDI_RX_BIT_LOCK)) {
4212                         DRM_DEBUG_KMS("FDI train 1 done.\n");
4213                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4214                         break;
4215                 }
4216         }
4217         if (tries == 5)
4218                 DRM_ERROR("FDI train 1 fail!\n");
4219
4220         /* Train 2 */
4221         reg = FDI_TX_CTL(pipe);
4222         temp = I915_READ(reg);
4223         temp &= ~FDI_LINK_TRAIN_NONE;
4224         temp |= FDI_LINK_TRAIN_PATTERN_2;
4225         I915_WRITE(reg, temp);
4226
4227         reg = FDI_RX_CTL(pipe);
4228         temp = I915_READ(reg);
4229         temp &= ~FDI_LINK_TRAIN_NONE;
4230         temp |= FDI_LINK_TRAIN_PATTERN_2;
4231         I915_WRITE(reg, temp);
4232
4233         POSTING_READ(reg);
4234         udelay(150);
4235
4236         reg = FDI_RX_IIR(pipe);
4237         for (tries = 0; tries < 5; tries++) {
4238                 temp = I915_READ(reg);
4239                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4240
4241                 if (temp & FDI_RX_SYMBOL_LOCK) {
4242                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4243                         DRM_DEBUG_KMS("FDI train 2 done.\n");
4244                         break;
4245                 }
4246         }
4247         if (tries == 5)
4248                 DRM_ERROR("FDI train 2 fail!\n");
4249
4250         DRM_DEBUG_KMS("FDI train done\n");
4251
4252 }
4253
4254 static const int snb_b_fdi_train_param[] = {
4255         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
4256         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
4257         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
4258         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
4259 };
4260
4261 /* The FDI link training functions for SNB/Cougarpoint. */
4262 static void gen6_fdi_link_train(struct intel_crtc *crtc,
4263                                 const struct intel_crtc_state *crtc_state)
4264 {
4265         struct drm_device *dev = crtc->base.dev;
4266         struct drm_i915_private *dev_priv = to_i915(dev);
4267         int pipe = crtc->pipe;
4268         i915_reg_t reg;
4269         u32 temp, i, retry;
4270
4271         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4272            for train result */
4273         reg = FDI_RX_IMR(pipe);
4274         temp = I915_READ(reg);
4275         temp &= ~FDI_RX_SYMBOL_LOCK;
4276         temp &= ~FDI_RX_BIT_LOCK;
4277         I915_WRITE(reg, temp);
4278
4279         POSTING_READ(reg);
4280         udelay(150);
4281
4282         /* enable CPU FDI TX and PCH FDI RX */
4283         reg = FDI_TX_CTL(pipe);
4284         temp = I915_READ(reg);
4285         temp &= ~FDI_DP_PORT_WIDTH_MASK;
4286         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4287         temp &= ~FDI_LINK_TRAIN_NONE;
4288         temp |= FDI_LINK_TRAIN_PATTERN_1;
4289         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4290         /* SNB-B */
4291         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
4292         I915_WRITE(reg, temp | FDI_TX_ENABLE);
4293
4294         I915_WRITE(FDI_RX_MISC(pipe),
4295                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4296
4297         reg = FDI_RX_CTL(pipe);
4298         temp = I915_READ(reg);
4299         if (HAS_PCH_CPT(dev_priv)) {
4300                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4301                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4302         } else {
4303                 temp &= ~FDI_LINK_TRAIN_NONE;
4304                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4305         }
4306         I915_WRITE(reg, temp | FDI_RX_ENABLE);
4307
4308         POSTING_READ(reg);
4309         udelay(150);
4310
4311         for (i = 0; i < 4; i++) {
4312                 reg = FDI_TX_CTL(pipe);
4313                 temp = I915_READ(reg);
4314                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4315                 temp |= snb_b_fdi_train_param[i];
4316                 I915_WRITE(reg, temp);
4317
4318                 POSTING_READ(reg);
4319                 udelay(500);
4320
4321                 for (retry = 0; retry < 5; retry++) {
4322                         reg = FDI_RX_IIR(pipe);
4323                         temp = I915_READ(reg);
4324                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4325                         if (temp & FDI_RX_BIT_LOCK) {
4326                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4327                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
4328                                 break;
4329                         }
4330                         udelay(50);
4331                 }
4332                 if (retry < 5)
4333                         break;
4334         }
4335         if (i == 4)
4336                 DRM_ERROR("FDI train 1 fail!\n");
4337
4338         /* Train 2 */
4339         reg = FDI_TX_CTL(pipe);
4340         temp = I915_READ(reg);
4341         temp &= ~FDI_LINK_TRAIN_NONE;
4342         temp |= FDI_LINK_TRAIN_PATTERN_2;
4343         if (IS_GEN(dev_priv, 6)) {
4344                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4345                 /* SNB-B */
4346                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
4347         }
4348         I915_WRITE(reg, temp);
4349
4350         reg = FDI_RX_CTL(pipe);
4351         temp = I915_READ(reg);
4352         if (HAS_PCH_CPT(dev_priv)) {
4353                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4354                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4355         } else {
4356                 temp &= ~FDI_LINK_TRAIN_NONE;
4357                 temp |= FDI_LINK_TRAIN_PATTERN_2;
4358         }
4359         I915_WRITE(reg, temp);
4360
4361         POSTING_READ(reg);
4362         udelay(150);
4363
4364         for (i = 0; i < 4; i++) {
4365                 reg = FDI_TX_CTL(pipe);
4366                 temp = I915_READ(reg);
4367                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4368                 temp |= snb_b_fdi_train_param[i];
4369                 I915_WRITE(reg, temp);
4370
4371                 POSTING_READ(reg);
4372                 udelay(500);
4373
4374                 for (retry = 0; retry < 5; retry++) {
4375                         reg = FDI_RX_IIR(pipe);
4376                         temp = I915_READ(reg);
4377                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4378                         if (temp & FDI_RX_SYMBOL_LOCK) {
4379                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4380                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
4381                                 break;
4382                         }
4383                         udelay(50);
4384                 }
4385                 if (retry < 5)
4386                         break;
4387         }
4388         if (i == 4)
4389                 DRM_ERROR("FDI train 2 fail!\n");
4390
4391         DRM_DEBUG_KMS("FDI train done.\n");
4392 }
4393
4394 /* Manual link training for Ivy Bridge A0 parts */
4395 static void ivb_manual_fdi_link_train(struct intel_crtc *crtc,
4396                                       const struct intel_crtc_state *crtc_state)
4397 {
4398         struct drm_device *dev = crtc->base.dev;
4399         struct drm_i915_private *dev_priv = to_i915(dev);
4400         int pipe = crtc->pipe;
4401         i915_reg_t reg;
4402         u32 temp, i, j;
4403
4404         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4405            for train result */
4406         reg = FDI_RX_IMR(pipe);
4407         temp = I915_READ(reg);
4408         temp &= ~FDI_RX_SYMBOL_LOCK;
4409         temp &= ~FDI_RX_BIT_LOCK;
4410         I915_WRITE(reg, temp);
4411
4412         POSTING_READ(reg);
4413         udelay(150);
4414
4415         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
4416                       I915_READ(FDI_RX_IIR(pipe)));
4417
4418         /* Try each vswing and preemphasis setting twice before moving on */
4419         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
4420                 /* disable first in case we need to retry */
4421                 reg = FDI_TX_CTL(pipe);
4422                 temp = I915_READ(reg);
4423                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
4424                 temp &= ~FDI_TX_ENABLE;
4425                 I915_WRITE(reg, temp);
4426
4427                 reg = FDI_RX_CTL(pipe);
4428                 temp = I915_READ(reg);
4429                 temp &= ~FDI_LINK_TRAIN_AUTO;
4430                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4431                 temp &= ~FDI_RX_ENABLE;
4432                 I915_WRITE(reg, temp);
4433
4434                 /* enable CPU FDI TX and PCH FDI RX */
4435                 reg = FDI_TX_CTL(pipe);
4436                 temp = I915_READ(reg);
4437                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
4438                 temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4439                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
4440                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4441                 temp |= snb_b_fdi_train_param[j/2];
4442                 temp |= FDI_COMPOSITE_SYNC;
4443                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
4444
4445                 I915_WRITE(FDI_RX_MISC(pipe),
4446                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4447
4448                 reg = FDI_RX_CTL(pipe);
4449                 temp = I915_READ(reg);
4450                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4451                 temp |= FDI_COMPOSITE_SYNC;
4452                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
4453
4454                 POSTING_READ(reg);
4455                 udelay(1); /* should be 0.5us */
4456
4457                 for (i = 0; i < 4; i++) {
4458                         reg = FDI_RX_IIR(pipe);
4459                         temp = I915_READ(reg);
4460                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4461
4462                         if (temp & FDI_RX_BIT_LOCK ||
4463                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
4464                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4465                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
4466                                               i);
4467                                 break;
4468                         }
4469                         udelay(1); /* should be 0.5us */
4470                 }
4471                 if (i == 4) {
4472                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
4473                         continue;
4474                 }
4475
4476                 /* Train 2 */
4477                 reg = FDI_TX_CTL(pipe);
4478                 temp = I915_READ(reg);
4479                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
4480                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
4481                 I915_WRITE(reg, temp);
4482
4483                 reg = FDI_RX_CTL(pipe);
4484                 temp = I915_READ(reg);
4485                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4486                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4487                 I915_WRITE(reg, temp);
4488
4489                 POSTING_READ(reg);
4490                 udelay(2); /* should be 1.5us */
4491
4492                 for (i = 0; i < 4; i++) {
4493                         reg = FDI_RX_IIR(pipe);
4494                         temp = I915_READ(reg);
4495                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4496
4497                         if (temp & FDI_RX_SYMBOL_LOCK ||
4498                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
4499                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4500                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
4501                                               i);
4502                                 goto train_done;
4503                         }
4504                         udelay(2); /* should be 1.5us */
4505                 }
4506                 if (i == 4)
4507                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
4508         }
4509
4510 train_done:
4511         DRM_DEBUG_KMS("FDI train done.\n");
4512 }
4513
4514 static void ironlake_fdi_pll_enable(const struct intel_crtc_state *crtc_state)
4515 {
4516         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
4517         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
4518         int pipe = intel_crtc->pipe;
4519         i915_reg_t reg;
4520         u32 temp;
4521
4522         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
4523         reg = FDI_RX_CTL(pipe);
4524         temp = I915_READ(reg);
4525         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
4526         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4527         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4528         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
4529
4530         POSTING_READ(reg);
4531         udelay(200);
4532
4533         /* Switch from Rawclk to PCDclk */
4534         temp = I915_READ(reg);
4535         I915_WRITE(reg, temp | FDI_PCDCLK);
4536
4537         POSTING_READ(reg);
4538         udelay(200);
4539
4540         /* Enable CPU FDI TX PLL, always on for Ironlake */
4541         reg = FDI_TX_CTL(pipe);
4542         temp = I915_READ(reg);
4543         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
4544                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
4545
4546                 POSTING_READ(reg);
4547                 udelay(100);
4548         }
4549 }
4550
4551 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
4552 {
4553         struct drm_device *dev = intel_crtc->base.dev;
4554         struct drm_i915_private *dev_priv = to_i915(dev);
4555         int pipe = intel_crtc->pipe;
4556         i915_reg_t reg;
4557         u32 temp;
4558
4559         /* Switch from PCDclk to Rawclk */
4560         reg = FDI_RX_CTL(pipe);
4561         temp = I915_READ(reg);
4562         I915_WRITE(reg, temp & ~FDI_PCDCLK);
4563
4564         /* Disable CPU FDI TX PLL */
4565         reg = FDI_TX_CTL(pipe);
4566         temp = I915_READ(reg);
4567         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
4568
4569         POSTING_READ(reg);
4570         udelay(100);
4571
4572         reg = FDI_RX_CTL(pipe);
4573         temp = I915_READ(reg);
4574         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
4575
4576         /* Wait for the clocks to turn off. */
4577         POSTING_READ(reg);
4578         udelay(100);
4579 }
4580
4581 static void ironlake_fdi_disable(struct drm_crtc *crtc)
4582 {
4583         struct drm_device *dev = crtc->dev;
4584         struct drm_i915_private *dev_priv = to_i915(dev);
4585         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4586         int pipe = intel_crtc->pipe;
4587         i915_reg_t reg;
4588         u32 temp;
4589
4590         /* disable CPU FDI tx and PCH FDI rx */
4591         reg = FDI_TX_CTL(pipe);
4592         temp = I915_READ(reg);
4593         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
4594         POSTING_READ(reg);
4595
4596         reg = FDI_RX_CTL(pipe);
4597         temp = I915_READ(reg);
4598         temp &= ~(0x7 << 16);
4599         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4600         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
4601
4602         POSTING_READ(reg);
4603         udelay(100);
4604
4605         /* Ironlake workaround, disable clock pointer after downing FDI */
4606         if (HAS_PCH_IBX(dev_priv))
4607                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
4608
4609         /* still set train pattern 1 */
4610         reg = FDI_TX_CTL(pipe);
4611         temp = I915_READ(reg);
4612         temp &= ~FDI_LINK_TRAIN_NONE;
4613         temp |= FDI_LINK_TRAIN_PATTERN_1;
4614         I915_WRITE(reg, temp);
4615
4616         reg = FDI_RX_CTL(pipe);
4617         temp = I915_READ(reg);
4618         if (HAS_PCH_CPT(dev_priv)) {
4619                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4620                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4621         } else {
4622                 temp &= ~FDI_LINK_TRAIN_NONE;
4623                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4624         }
4625         /* BPC in FDI rx is consistent with that in PIPECONF */
4626         temp &= ~(0x07 << 16);
4627         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4628         I915_WRITE(reg, temp);
4629
4630         POSTING_READ(reg);
4631         udelay(100);
4632 }
4633
4634 bool intel_has_pending_fb_unpin(struct drm_i915_private *dev_priv)
4635 {
4636         struct drm_crtc *crtc;
4637         bool cleanup_done;
4638
4639         drm_for_each_crtc(crtc, &dev_priv->drm) {
4640                 struct drm_crtc_commit *commit;
4641                 spin_lock(&crtc->commit_lock);
4642                 commit = list_first_entry_or_null(&crtc->commit_list,
4643                                                   struct drm_crtc_commit, commit_entry);
4644                 cleanup_done = commit ?
4645                         try_wait_for_completion(&commit->cleanup_done) : true;
4646                 spin_unlock(&crtc->commit_lock);
4647
4648                 if (cleanup_done)
4649                         continue;
4650
4651                 drm_crtc_wait_one_vblank(crtc);
4652
4653                 return true;
4654         }
4655
4656         return false;
4657 }
4658
4659 void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
4660 {
4661         u32 temp;
4662
4663         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
4664
4665         mutex_lock(&dev_priv->sb_lock);
4666
4667         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4668         temp |= SBI_SSCCTL_DISABLE;
4669         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4670
4671         mutex_unlock(&dev_priv->sb_lock);
4672 }
4673
4674 /* Program iCLKIP clock to the desired frequency */
4675 static void lpt_program_iclkip(const struct intel_crtc_state *crtc_state)
4676 {
4677         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4678         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4679         int clock = crtc_state->base.adjusted_mode.crtc_clock;
4680         u32 divsel, phaseinc, auxdiv, phasedir = 0;
4681         u32 temp;
4682
4683         lpt_disable_iclkip(dev_priv);
4684
4685         /* The iCLK virtual clock root frequency is in MHz,
4686          * but the adjusted_mode->crtc_clock in in KHz. To get the
4687          * divisors, it is necessary to divide one by another, so we
4688          * convert the virtual clock precision to KHz here for higher
4689          * precision.
4690          */
4691         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
4692                 u32 iclk_virtual_root_freq = 172800 * 1000;
4693                 u32 iclk_pi_range = 64;
4694                 u32 desired_divisor;
4695
4696                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4697                                                     clock << auxdiv);
4698                 divsel = (desired_divisor / iclk_pi_range) - 2;
4699                 phaseinc = desired_divisor % iclk_pi_range;
4700
4701                 /*
4702                  * Near 20MHz is a corner case which is
4703                  * out of range for the 7-bit divisor
4704                  */
4705                 if (divsel <= 0x7f)
4706                         break;
4707         }
4708
4709         /* This should not happen with any sane values */
4710         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
4711                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
4712         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
4713                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
4714
4715         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
4716                         clock,
4717                         auxdiv,
4718                         divsel,
4719                         phasedir,
4720                         phaseinc);
4721
4722         mutex_lock(&dev_priv->sb_lock);
4723
4724         /* Program SSCDIVINTPHASE6 */
4725         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4726         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
4727         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
4728         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
4729         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
4730         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
4731         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
4732         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
4733
4734         /* Program SSCAUXDIV */
4735         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4736         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
4737         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
4738         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
4739
4740         /* Enable modulator and associated divider */
4741         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4742         temp &= ~SBI_SSCCTL_DISABLE;
4743         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4744
4745         mutex_unlock(&dev_priv->sb_lock);
4746
4747         /* Wait for initialization time */
4748         udelay(24);
4749
4750         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
4751 }
4752
4753 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
4754 {
4755         u32 divsel, phaseinc, auxdiv;
4756         u32 iclk_virtual_root_freq = 172800 * 1000;
4757         u32 iclk_pi_range = 64;
4758         u32 desired_divisor;
4759         u32 temp;
4760
4761         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
4762                 return 0;
4763
4764         mutex_lock(&dev_priv->sb_lock);
4765
4766         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4767         if (temp & SBI_SSCCTL_DISABLE) {
4768                 mutex_unlock(&dev_priv->sb_lock);
4769                 return 0;
4770         }
4771
4772         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4773         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
4774                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
4775         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
4776                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
4777
4778         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4779         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
4780                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
4781
4782         mutex_unlock(&dev_priv->sb_lock);
4783
4784         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
4785
4786         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4787                                  desired_divisor << auxdiv);
4788 }
4789
4790 static void ironlake_pch_transcoder_set_timings(const struct intel_crtc_state *crtc_state,
4791                                                 enum pipe pch_transcoder)
4792 {
4793         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4794         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4795         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
4796
4797         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
4798                    I915_READ(HTOTAL(cpu_transcoder)));
4799         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4800                    I915_READ(HBLANK(cpu_transcoder)));
4801         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4802                    I915_READ(HSYNC(cpu_transcoder)));
4803
4804         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4805                    I915_READ(VTOTAL(cpu_transcoder)));
4806         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4807                    I915_READ(VBLANK(cpu_transcoder)));
4808         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4809                    I915_READ(VSYNC(cpu_transcoder)));
4810         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4811                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4812 }
4813
4814 static void cpt_set_fdi_bc_bifurcation(struct drm_i915_private *dev_priv, bool enable)
4815 {
4816         u32 temp;
4817
4818         temp = I915_READ(SOUTH_CHICKEN1);
4819         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4820                 return;
4821
4822         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4823         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4824
4825         temp &= ~FDI_BC_BIFURCATION_SELECT;
4826         if (enable)
4827                 temp |= FDI_BC_BIFURCATION_SELECT;
4828
4829         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4830         I915_WRITE(SOUTH_CHICKEN1, temp);
4831         POSTING_READ(SOUTH_CHICKEN1);
4832 }
4833
4834 static void ivybridge_update_fdi_bc_bifurcation(const struct intel_crtc_state *crtc_state)
4835 {
4836         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4837         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4838
4839         switch (crtc->pipe) {
4840         case PIPE_A:
4841                 break;
4842         case PIPE_B:
4843                 if (crtc_state->fdi_lanes > 2)
4844                         cpt_set_fdi_bc_bifurcation(dev_priv, false);
4845                 else
4846                         cpt_set_fdi_bc_bifurcation(dev_priv, true);
4847
4848                 break;
4849         case PIPE_C:
4850                 cpt_set_fdi_bc_bifurcation(dev_priv, true);
4851
4852                 break;
4853         default:
4854                 BUG();
4855         }
4856 }
4857
4858 /*
4859  * Finds the encoder associated with the given CRTC. This can only be
4860  * used when we know that the CRTC isn't feeding multiple encoders!
4861  */
4862 static struct intel_encoder *
4863 intel_get_crtc_new_encoder(const struct intel_atomic_state *state,
4864                            const struct intel_crtc_state *crtc_state)
4865 {
4866         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4867         const struct drm_connector_state *connector_state;
4868         const struct drm_connector *connector;
4869         struct intel_encoder *encoder = NULL;
4870         int num_encoders = 0;
4871         int i;
4872
4873         for_each_new_connector_in_state(&state->base, connector, connector_state, i) {
4874                 if (connector_state->crtc != &crtc->base)
4875                         continue;
4876
4877                 encoder = to_intel_encoder(connector_state->best_encoder);
4878                 num_encoders++;
4879         }
4880
4881         WARN(num_encoders != 1, "%d encoders for pipe %c\n",
4882              num_encoders, pipe_name(crtc->pipe));
4883
4884         return encoder;
4885 }
4886
4887 /*
4888  * Enable PCH resources required for PCH ports:
4889  *   - PCH PLLs
4890  *   - FDI training & RX/TX
4891  *   - update transcoder timings
4892  *   - DP transcoding bits
4893  *   - transcoder
4894  */
4895 static void ironlake_pch_enable(const struct intel_atomic_state *state,
4896                                 const struct intel_crtc_state *crtc_state)
4897 {
4898         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4899         struct drm_device *dev = crtc->base.dev;
4900         struct drm_i915_private *dev_priv = to_i915(dev);
4901         int pipe = crtc->pipe;
4902         u32 temp;
4903
4904         assert_pch_transcoder_disabled(dev_priv, pipe);
4905
4906         if (IS_IVYBRIDGE(dev_priv))
4907                 ivybridge_update_fdi_bc_bifurcation(crtc_state);
4908
4909         /* Write the TU size bits before fdi link training, so that error
4910          * detection works. */
4911         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4912                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4913
4914         /* For PCH output, training FDI link */
4915         dev_priv->display.fdi_link_train(crtc, crtc_state);
4916
4917         /* We need to program the right clock selection before writing the pixel
4918          * mutliplier into the DPLL. */
4919         if (HAS_PCH_CPT(dev_priv)) {
4920                 u32 sel;
4921
4922                 temp = I915_READ(PCH_DPLL_SEL);
4923                 temp |= TRANS_DPLL_ENABLE(pipe);
4924                 sel = TRANS_DPLLB_SEL(pipe);
4925                 if (crtc_state->shared_dpll ==
4926                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
4927                         temp |= sel;
4928                 else
4929                         temp &= ~sel;
4930                 I915_WRITE(PCH_DPLL_SEL, temp);
4931         }
4932
4933         /* XXX: pch pll's can be enabled any time before we enable the PCH
4934          * transcoder, and we actually should do this to not upset any PCH
4935          * transcoder that already use the clock when we share it.
4936          *
4937          * Note that enable_shared_dpll tries to do the right thing, but
4938          * get_shared_dpll unconditionally resets the pll - we need that to have
4939          * the right LVDS enable sequence. */
4940         intel_enable_shared_dpll(crtc_state);
4941
4942         /* set transcoder timing, panel must allow it */
4943         assert_panel_unlocked(dev_priv, pipe);
4944         ironlake_pch_transcoder_set_timings(crtc_state, pipe);
4945
4946         intel_fdi_normal_train(crtc);
4947
4948         /* For PCH DP, enable TRANS_DP_CTL */
4949         if (HAS_PCH_CPT(dev_priv) &&
4950             intel_crtc_has_dp_encoder(crtc_state)) {
4951                 const struct drm_display_mode *adjusted_mode =
4952                         &crtc_state->base.adjusted_mode;
4953                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4954                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4955                 enum port port;
4956
4957                 temp = I915_READ(reg);
4958                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4959                           TRANS_DP_SYNC_MASK |
4960                           TRANS_DP_BPC_MASK);
4961                 temp |= TRANS_DP_OUTPUT_ENABLE;
4962                 temp |= bpc << 9; /* same format but at 11:9 */
4963
4964                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4965                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4966                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4967                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4968
4969                 port = intel_get_crtc_new_encoder(state, crtc_state)->port;
4970                 WARN_ON(port < PORT_B || port > PORT_D);
4971                 temp |= TRANS_DP_PORT_SEL(port);
4972
4973                 I915_WRITE(reg, temp);
4974         }
4975
4976         ironlake_enable_pch_transcoder(crtc_state);
4977 }
4978
4979 static void lpt_pch_enable(const struct intel_atomic_state *state,
4980                            const struct intel_crtc_state *crtc_state)
4981 {
4982         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4983         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4984         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
4985
4986         assert_pch_transcoder_disabled(dev_priv, PIPE_A);
4987
4988         lpt_program_iclkip(crtc_state);
4989
4990         /* Set transcoder timing. */
4991         ironlake_pch_transcoder_set_timings(crtc_state, PIPE_A);
4992
4993         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4994 }
4995
4996 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4997 {
4998         struct drm_i915_private *dev_priv = to_i915(dev);
4999         i915_reg_t dslreg = PIPEDSL(pipe);
5000         u32 temp;
5001
5002         temp = I915_READ(dslreg);
5003         udelay(500);
5004         if (wait_for(I915_READ(dslreg) != temp, 5)) {
5005                 if (wait_for(I915_READ(dslreg) != temp, 5))
5006                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
5007         }
5008 }
5009
5010 /*
5011  * The hardware phase 0.0 refers to the center of the pixel.
5012  * We want to start from the top/left edge which is phase
5013  * -0.5. That matches how the hardware calculates the scaling
5014  * factors (from top-left of the first pixel to bottom-right
5015  * of the last pixel, as opposed to the pixel centers).
5016  *
5017  * For 4:2:0 subsampled chroma planes we obviously have to
5018  * adjust that so that the chroma sample position lands in
5019  * the right spot.
5020  *
5021  * Note that for packed YCbCr 4:2:2 formats there is no way to
5022  * control chroma siting. The hardware simply replicates the
5023  * chroma samples for both of the luma samples, and thus we don't
5024  * actually get the expected MPEG2 chroma siting convention :(
5025  * The same behaviour is observed on pre-SKL platforms as well.
5026  *
5027  * Theory behind the formula (note that we ignore sub-pixel
5028  * source coordinates):
5029  * s = source sample position
5030  * d = destination sample position
5031  *
5032  * Downscaling 4:1:
5033  * -0.5
5034  * | 0.0
5035  * | |     1.5 (initial phase)
5036  * | |     |
5037  * v v     v
5038  * | s | s | s | s |
5039  * |       d       |
5040  *
5041  * Upscaling 1:4:
5042  * -0.5
5043  * | -0.375 (initial phase)
5044  * | |     0.0
5045  * | |     |
5046  * v v     v
5047  * |       s       |
5048  * | d | d | d | d |
5049  */
5050 u16 skl_scaler_calc_phase(int sub, int scale, bool chroma_cosited)
5051 {
5052         int phase = -0x8000;
5053         u16 trip = 0;
5054
5055         if (chroma_cosited)
5056                 phase += (sub - 1) * 0x8000 / sub;
5057
5058         phase += scale / (2 * sub);
5059
5060         /*
5061          * Hardware initial phase limited to [-0.5:1.5].
5062          * Since the max hardware scale factor is 3.0, we
5063          * should never actually excdeed 1.0 here.
5064          */
5065         WARN_ON(phase < -0x8000 || phase > 0x18000);
5066
5067         if (phase < 0)
5068                 phase = 0x10000 + phase;
5069         else
5070                 trip = PS_PHASE_TRIP;
5071
5072         return ((phase >> 2) & PS_PHASE_MASK) | trip;
5073 }
5074
5075 #define SKL_MIN_SRC_W 8
5076 #define SKL_MAX_SRC_W 4096
5077 #define SKL_MIN_SRC_H 8
5078 #define SKL_MAX_SRC_H 4096
5079 #define SKL_MIN_DST_W 8
5080 #define SKL_MAX_DST_W 4096
5081 #define SKL_MIN_DST_H 8
5082 #define SKL_MAX_DST_H 4096
5083 #define ICL_MAX_SRC_W 5120
5084 #define ICL_MAX_SRC_H 4096
5085 #define ICL_MAX_DST_W 5120
5086 #define ICL_MAX_DST_H 4096
5087 #define SKL_MIN_YUV_420_SRC_W 16
5088 #define SKL_MIN_YUV_420_SRC_H 16
5089
5090 static int
5091 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
5092                   unsigned int scaler_user, int *scaler_id,
5093                   int src_w, int src_h, int dst_w, int dst_h,
5094                   const struct drm_format_info *format, bool need_scaler)
5095 {
5096         struct intel_crtc_scaler_state *scaler_state =
5097                 &crtc_state->scaler_state;
5098         struct intel_crtc *intel_crtc =
5099                 to_intel_crtc(crtc_state->base.crtc);
5100         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
5101         const struct drm_display_mode *adjusted_mode =
5102                 &crtc_state->base.adjusted_mode;
5103
5104         /*
5105          * Src coordinates are already rotated by 270 degrees for
5106          * the 90/270 degree plane rotation cases (to match the
5107          * GTT mapping), hence no need to account for rotation here.
5108          */
5109         if (src_w != dst_w || src_h != dst_h)
5110                 need_scaler = true;
5111
5112         /*
5113          * Scaling/fitting not supported in IF-ID mode in GEN9+
5114          * TODO: Interlace fetch mode doesn't support YUV420 planar formats.
5115          * Once NV12 is enabled, handle it here while allocating scaler
5116          * for NV12.
5117          */
5118         if (INTEL_GEN(dev_priv) >= 9 && crtc_state->base.enable &&
5119             need_scaler && adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
5120                 DRM_DEBUG_KMS("Pipe/Plane scaling not supported with IF-ID mode\n");
5121                 return -EINVAL;
5122         }
5123
5124         /*
5125          * if plane is being disabled or scaler is no more required or force detach
5126          *  - free scaler binded to this plane/crtc
5127          *  - in order to do this, update crtc->scaler_usage
5128          *
5129          * Here scaler state in crtc_state is set free so that
5130          * scaler can be assigned to other user. Actual register
5131          * update to free the scaler is done in plane/panel-fit programming.
5132          * For this purpose crtc/plane_state->scaler_id isn't reset here.
5133          */
5134         if (force_detach || !need_scaler) {
5135                 if (*scaler_id >= 0) {
5136                         scaler_state->scaler_users &= ~(1 << scaler_user);
5137                         scaler_state->scalers[*scaler_id].in_use = 0;
5138
5139                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
5140                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
5141                                 intel_crtc->pipe, scaler_user, *scaler_id,
5142                                 scaler_state->scaler_users);
5143                         *scaler_id = -1;
5144                 }
5145                 return 0;
5146         }
5147
5148         if (format && is_planar_yuv_format(format->format) &&
5149             (src_h < SKL_MIN_YUV_420_SRC_H || src_w < SKL_MIN_YUV_420_SRC_W)) {
5150                 DRM_DEBUG_KMS("Planar YUV: src dimensions not met\n");
5151                 return -EINVAL;
5152         }
5153
5154         /* range checks */
5155         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
5156             dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
5157             (INTEL_GEN(dev_priv) >= 11 &&
5158              (src_w > ICL_MAX_SRC_W || src_h > ICL_MAX_SRC_H ||
5159               dst_w > ICL_MAX_DST_W || dst_h > ICL_MAX_DST_H)) ||
5160             (INTEL_GEN(dev_priv) < 11 &&
5161              (src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
5162               dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H))) {
5163                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
5164                         "size is out of scaler range\n",
5165                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
5166                 return -EINVAL;
5167         }
5168
5169         /* mark this plane as a scaler user in crtc_state */
5170         scaler_state->scaler_users |= (1 << scaler_user);
5171         DRM_DEBUG_KMS("scaler_user index %u.%u: "
5172                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
5173                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
5174                 scaler_state->scaler_users);
5175
5176         return 0;
5177 }
5178
5179 /**
5180  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
5181  *
5182  * @state: crtc's scaler state
5183  *
5184  * Return
5185  *     0 - scaler_usage updated successfully
5186  *    error - requested scaling cannot be supported or other error condition
5187  */
5188 int skl_update_scaler_crtc(struct intel_crtc_state *state)
5189 {
5190         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
5191         bool need_scaler = false;
5192
5193         if (state->output_format == INTEL_OUTPUT_FORMAT_YCBCR420)
5194                 need_scaler = true;
5195
5196         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
5197                                  &state->scaler_state.scaler_id,
5198                                  state->pipe_src_w, state->pipe_src_h,
5199                                  adjusted_mode->crtc_hdisplay,
5200                                  adjusted_mode->crtc_vdisplay, NULL, need_scaler);
5201 }
5202
5203 /**
5204  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
5205  * @crtc_state: crtc's scaler state
5206  * @plane_state: atomic plane state to update
5207  *
5208  * Return
5209  *     0 - scaler_usage updated successfully
5210  *    error - requested scaling cannot be supported or other error condition
5211  */
5212 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
5213                                    struct intel_plane_state *plane_state)
5214 {
5215         struct intel_plane *intel_plane =
5216                 to_intel_plane(plane_state->base.plane);
5217         struct drm_i915_private *dev_priv = to_i915(intel_plane->base.dev);
5218         struct drm_framebuffer *fb = plane_state->base.fb;
5219         int ret;
5220         bool force_detach = !fb || !plane_state->base.visible;
5221         bool need_scaler = false;
5222
5223         /* Pre-gen11 and SDR planes always need a scaler for planar formats. */
5224         if (!icl_is_hdr_plane(dev_priv, intel_plane->id) &&
5225             fb && is_planar_yuv_format(fb->format->format))
5226                 need_scaler = true;
5227
5228         ret = skl_update_scaler(crtc_state, force_detach,
5229                                 drm_plane_index(&intel_plane->base),
5230                                 &plane_state->scaler_id,
5231                                 drm_rect_width(&plane_state->base.src) >> 16,
5232                                 drm_rect_height(&plane_state->base.src) >> 16,
5233                                 drm_rect_width(&plane_state->base.dst),
5234                                 drm_rect_height(&plane_state->base.dst),
5235                                 fb ? fb->format : NULL, need_scaler);
5236
5237         if (ret || plane_state->scaler_id < 0)
5238                 return ret;
5239
5240         /* check colorkey */
5241         if (plane_state->ckey.flags) {
5242                 DRM_DEBUG_KMS("[PLANE:%d:%s] scaling with color key not allowed",
5243                               intel_plane->base.base.id,
5244                               intel_plane->base.name);
5245                 return -EINVAL;
5246         }
5247
5248         /* Check src format */
5249         switch (fb->format->format) {
5250         case DRM_FORMAT_RGB565:
5251         case DRM_FORMAT_XBGR8888:
5252         case DRM_FORMAT_XRGB8888:
5253         case DRM_FORMAT_ABGR8888:
5254         case DRM_FORMAT_ARGB8888:
5255         case DRM_FORMAT_XRGB2101010:
5256         case DRM_FORMAT_XBGR2101010:
5257         case DRM_FORMAT_XBGR16161616F:
5258         case DRM_FORMAT_ABGR16161616F:
5259         case DRM_FORMAT_XRGB16161616F:
5260         case DRM_FORMAT_ARGB16161616F:
5261         case DRM_FORMAT_YUYV:
5262         case DRM_FORMAT_YVYU:
5263         case DRM_FORMAT_UYVY:
5264         case DRM_FORMAT_VYUY:
5265         case DRM_FORMAT_NV12:
5266         case DRM_FORMAT_P010:
5267         case DRM_FORMAT_P012:
5268         case DRM_FORMAT_P016:
5269         case DRM_FORMAT_Y210:
5270         case DRM_FORMAT_Y212:
5271         case DRM_FORMAT_Y216:
5272         case DRM_FORMAT_XVYU2101010:
5273         case DRM_FORMAT_XVYU12_16161616:
5274         case DRM_FORMAT_XVYU16161616:
5275                 break;
5276         default:
5277                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d unsupported scaling format 0x%x\n",
5278                               intel_plane->base.base.id, intel_plane->base.name,
5279                               fb->base.id, fb->format->format);
5280                 return -EINVAL;
5281         }
5282
5283         return 0;
5284 }
5285
5286 static void skylake_scaler_disable(struct intel_crtc *crtc)
5287 {
5288         int i;
5289
5290         for (i = 0; i < crtc->num_scalers; i++)
5291                 skl_detach_scaler(crtc, i);
5292 }
5293
5294 static void skylake_pfit_enable(const struct intel_crtc_state *crtc_state)
5295 {
5296         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5297         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5298         enum pipe pipe = crtc->pipe;
5299         const struct intel_crtc_scaler_state *scaler_state =
5300                 &crtc_state->scaler_state;
5301
5302         if (crtc_state->pch_pfit.enabled) {
5303                 u16 uv_rgb_hphase, uv_rgb_vphase;
5304                 int pfit_w, pfit_h, hscale, vscale;
5305                 int id;
5306
5307                 if (WARN_ON(crtc_state->scaler_state.scaler_id < 0))
5308                         return;
5309
5310                 pfit_w = (crtc_state->pch_pfit.size >> 16) & 0xFFFF;
5311                 pfit_h = crtc_state->pch_pfit.size & 0xFFFF;
5312
5313                 hscale = (crtc_state->pipe_src_w << 16) / pfit_w;
5314                 vscale = (crtc_state->pipe_src_h << 16) / pfit_h;
5315
5316                 uv_rgb_hphase = skl_scaler_calc_phase(1, hscale, false);
5317                 uv_rgb_vphase = skl_scaler_calc_phase(1, vscale, false);
5318
5319                 id = scaler_state->scaler_id;
5320                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
5321                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
5322                 I915_WRITE_FW(SKL_PS_VPHASE(pipe, id),
5323                               PS_Y_PHASE(0) | PS_UV_RGB_PHASE(uv_rgb_vphase));
5324                 I915_WRITE_FW(SKL_PS_HPHASE(pipe, id),
5325                               PS_Y_PHASE(0) | PS_UV_RGB_PHASE(uv_rgb_hphase));
5326                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc_state->pch_pfit.pos);
5327                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc_state->pch_pfit.size);
5328         }
5329 }
5330
5331 static void ironlake_pfit_enable(const struct intel_crtc_state *crtc_state)
5332 {
5333         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5334         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5335         int pipe = crtc->pipe;
5336
5337         if (crtc_state->pch_pfit.enabled) {
5338                 /* Force use of hard-coded filter coefficients
5339                  * as some pre-programmed values are broken,
5340                  * e.g. x201.
5341                  */
5342                 if (IS_IVYBRIDGE(dev_priv) || IS_HASWELL(dev_priv))
5343                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
5344                                                  PF_PIPE_SEL_IVB(pipe));
5345                 else
5346                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
5347                 I915_WRITE(PF_WIN_POS(pipe), crtc_state->pch_pfit.pos);
5348                 I915_WRITE(PF_WIN_SZ(pipe), crtc_state->pch_pfit.size);
5349         }
5350 }
5351
5352 void hsw_enable_ips(const struct intel_crtc_state *crtc_state)
5353 {
5354         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5355         struct drm_device *dev = crtc->base.dev;
5356         struct drm_i915_private *dev_priv = to_i915(dev);
5357
5358         if (!crtc_state->ips_enabled)
5359                 return;
5360
5361         /*
5362          * We can only enable IPS after we enable a plane and wait for a vblank
5363          * This function is called from post_plane_update, which is run after
5364          * a vblank wait.
5365          */
5366         WARN_ON(!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)));
5367
5368         if (IS_BROADWELL(dev_priv)) {
5369                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL,
5370                                                 IPS_ENABLE | IPS_PCODE_CONTROL));
5371                 /* Quoting Art Runyan: "its not safe to expect any particular
5372                  * value in IPS_CTL bit 31 after enabling IPS through the
5373                  * mailbox." Moreover, the mailbox may return a bogus state,
5374                  * so we need to just enable it and continue on.
5375                  */
5376         } else {
5377                 I915_WRITE(IPS_CTL, IPS_ENABLE);
5378                 /* The bit only becomes 1 in the next vblank, so this wait here
5379                  * is essentially intel_wait_for_vblank. If we don't have this
5380                  * and don't wait for vblanks until the end of crtc_enable, then
5381                  * the HW state readout code will complain that the expected
5382                  * IPS_CTL value is not the one we read. */
5383                 if (intel_wait_for_register(&dev_priv->uncore,
5384                                             IPS_CTL, IPS_ENABLE, IPS_ENABLE,
5385                                             50))
5386                         DRM_ERROR("Timed out waiting for IPS enable\n");
5387         }
5388 }
5389
5390 void hsw_disable_ips(const struct intel_crtc_state *crtc_state)
5391 {
5392         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5393         struct drm_device *dev = crtc->base.dev;
5394         struct drm_i915_private *dev_priv = to_i915(dev);
5395
5396         if (!crtc_state->ips_enabled)
5397                 return;
5398
5399         if (IS_BROADWELL(dev_priv)) {
5400                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
5401                 /*
5402                  * Wait for PCODE to finish disabling IPS. The BSpec specified
5403                  * 42ms timeout value leads to occasional timeouts so use 100ms
5404                  * instead.
5405                  */
5406                 if (intel_wait_for_register(&dev_priv->uncore,
5407                                             IPS_CTL, IPS_ENABLE, 0,
5408                                             100))
5409                         DRM_ERROR("Timed out waiting for IPS disable\n");
5410         } else {
5411                 I915_WRITE(IPS_CTL, 0);
5412                 POSTING_READ(IPS_CTL);
5413         }
5414
5415         /* We need to wait for a vblank before we can disable the plane. */
5416         intel_wait_for_vblank(dev_priv, crtc->pipe);
5417 }
5418
5419 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
5420 {
5421         if (intel_crtc->overlay) {
5422                 struct drm_device *dev = intel_crtc->base.dev;
5423
5424                 mutex_lock(&dev->struct_mutex);
5425                 (void) intel_overlay_switch_off(intel_crtc->overlay);
5426                 mutex_unlock(&dev->struct_mutex);
5427         }
5428
5429         /* Let userspace switch the overlay on again. In most cases userspace
5430          * has to recompute where to put it anyway.
5431          */
5432 }
5433
5434 /**
5435  * intel_post_enable_primary - Perform operations after enabling primary plane
5436  * @crtc: the CRTC whose primary plane was just enabled
5437  * @new_crtc_state: the enabling state
5438  *
5439  * Performs potentially sleeping operations that must be done after the primary
5440  * plane is enabled, such as updating FBC and IPS.  Note that this may be
5441  * called due to an explicit primary plane update, or due to an implicit
5442  * re-enable that is caused when a sprite plane is updated to no longer
5443  * completely hide the primary plane.
5444  */
5445 static void
5446 intel_post_enable_primary(struct drm_crtc *crtc,
5447                           const struct intel_crtc_state *new_crtc_state)
5448 {
5449         struct drm_device *dev = crtc->dev;
5450         struct drm_i915_private *dev_priv = to_i915(dev);
5451         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5452         int pipe = intel_crtc->pipe;
5453
5454         /*
5455          * Gen2 reports pipe underruns whenever all planes are disabled.
5456          * So don't enable underrun reporting before at least some planes
5457          * are enabled.
5458          * FIXME: Need to fix the logic to work when we turn off all planes
5459          * but leave the pipe running.
5460          */
5461         if (IS_GEN(dev_priv, 2))
5462                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5463
5464         /* Underruns don't always raise interrupts, so check manually. */
5465         intel_check_cpu_fifo_underruns(dev_priv);
5466         intel_check_pch_fifo_underruns(dev_priv);
5467 }
5468
5469 /* FIXME get rid of this and use pre_plane_update */
5470 static void
5471 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
5472 {
5473         struct drm_device *dev = crtc->dev;
5474         struct drm_i915_private *dev_priv = to_i915(dev);
5475         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5476         int pipe = intel_crtc->pipe;
5477
5478         /*
5479          * Gen2 reports pipe underruns whenever all planes are disabled.
5480          * So disable underrun reporting before all the planes get disabled.
5481          */
5482         if (IS_GEN(dev_priv, 2))
5483                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5484
5485         hsw_disable_ips(to_intel_crtc_state(crtc->state));
5486
5487         /*
5488          * Vblank time updates from the shadow to live plane control register
5489          * are blocked if the memory self-refresh mode is active at that
5490          * moment. So to make sure the plane gets truly disabled, disable
5491          * first the self-refresh mode. The self-refresh enable bit in turn
5492          * will be checked/applied by the HW only at the next frame start
5493          * event which is after the vblank start event, so we need to have a
5494          * wait-for-vblank between disabling the plane and the pipe.
5495          */
5496         if (HAS_GMCH(dev_priv) &&
5497             intel_set_memory_cxsr(dev_priv, false))
5498                 intel_wait_for_vblank(dev_priv, pipe);
5499 }
5500
5501 static bool hsw_pre_update_disable_ips(const struct intel_crtc_state *old_crtc_state,
5502                                        const struct intel_crtc_state *new_crtc_state)
5503 {
5504         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
5505         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5506
5507         if (!old_crtc_state->ips_enabled)
5508                 return false;
5509
5510         if (needs_modeset(&new_crtc_state->base))
5511                 return true;
5512
5513         /*
5514          * Workaround : Do not read or write the pipe palette/gamma data while
5515          * GAMMA_MODE is configured for split gamma and IPS_CTL has IPS enabled.
5516          *
5517          * Disable IPS before we program the LUT.
5518          */
5519         if (IS_HASWELL(dev_priv) &&
5520             (new_crtc_state->base.color_mgmt_changed ||
5521              new_crtc_state->update_pipe) &&
5522             new_crtc_state->gamma_mode == GAMMA_MODE_MODE_SPLIT)
5523                 return true;
5524
5525         return !new_crtc_state->ips_enabled;
5526 }
5527
5528 static bool hsw_post_update_enable_ips(const struct intel_crtc_state *old_crtc_state,
5529                                        const struct intel_crtc_state *new_crtc_state)
5530 {
5531         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
5532         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5533
5534         if (!new_crtc_state->ips_enabled)
5535                 return false;
5536
5537         if (needs_modeset(&new_crtc_state->base))
5538                 return true;
5539
5540         /*
5541          * Workaround : Do not read or write the pipe palette/gamma data while
5542          * GAMMA_MODE is configured for split gamma and IPS_CTL has IPS enabled.
5543          *
5544          * Re-enable IPS after the LUT has been programmed.
5545          */
5546         if (IS_HASWELL(dev_priv) &&
5547             (new_crtc_state->base.color_mgmt_changed ||
5548              new_crtc_state->update_pipe) &&
5549             new_crtc_state->gamma_mode == GAMMA_MODE_MODE_SPLIT)
5550                 return true;
5551
5552         /*
5553          * We can't read out IPS on broadwell, assume the worst and
5554          * forcibly enable IPS on the first fastset.
5555          */
5556         if (new_crtc_state->update_pipe &&
5557             old_crtc_state->base.adjusted_mode.private_flags & I915_MODE_FLAG_INHERITED)
5558                 return true;
5559
5560         return !old_crtc_state->ips_enabled;
5561 }
5562
5563 static bool needs_nv12_wa(struct drm_i915_private *dev_priv,
5564                           const struct intel_crtc_state *crtc_state)
5565 {
5566         if (!crtc_state->nv12_planes)
5567                 return false;
5568
5569         /* WA Display #0827: Gen9:all */
5570         if (IS_GEN(dev_priv, 9) && !IS_GEMINILAKE(dev_priv))
5571                 return true;
5572
5573         return false;
5574 }
5575
5576 static bool needs_scalerclk_wa(struct drm_i915_private *dev_priv,
5577                                const struct intel_crtc_state *crtc_state)
5578 {
5579         /* Wa_2006604312:icl */
5580         if (crtc_state->scaler_state.scaler_users > 0 && IS_ICELAKE(dev_priv))
5581                 return true;
5582
5583         return false;
5584 }
5585
5586 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
5587 {
5588         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5589         struct drm_device *dev = crtc->base.dev;
5590         struct drm_i915_private *dev_priv = to_i915(dev);
5591         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5592         struct intel_crtc_state *pipe_config =
5593                 intel_atomic_get_new_crtc_state(to_intel_atomic_state(old_state),
5594                                                 crtc);
5595         struct drm_plane *primary = crtc->base.primary;
5596         struct drm_plane_state *old_primary_state =
5597                 drm_atomic_get_old_plane_state(old_state, primary);
5598
5599         intel_frontbuffer_flip(to_i915(crtc->base.dev), pipe_config->fb_bits);
5600
5601         if (pipe_config->update_wm_post && pipe_config->base.active)
5602                 intel_update_watermarks(crtc);
5603
5604         if (hsw_post_update_enable_ips(old_crtc_state, pipe_config))
5605                 hsw_enable_ips(pipe_config);
5606
5607         if (old_primary_state) {
5608                 struct drm_plane_state *new_primary_state =
5609                         drm_atomic_get_new_plane_state(old_state, primary);
5610
5611                 intel_fbc_post_update(crtc);
5612
5613                 if (new_primary_state->visible &&
5614                     (needs_modeset(&pipe_config->base) ||
5615                      !old_primary_state->visible))
5616                         intel_post_enable_primary(&crtc->base, pipe_config);
5617         }
5618
5619         if (needs_nv12_wa(dev_priv, old_crtc_state) &&
5620             !needs_nv12_wa(dev_priv, pipe_config))
5621                 skl_wa_827(dev_priv, crtc->pipe, false);
5622
5623         if (needs_scalerclk_wa(dev_priv, old_crtc_state) &&
5624             !needs_scalerclk_wa(dev_priv, pipe_config))
5625                 icl_wa_scalerclkgating(dev_priv, crtc->pipe, false);
5626 }
5627
5628 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state,
5629                                    struct intel_crtc_state *pipe_config)
5630 {
5631         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5632         struct drm_device *dev = crtc->base.dev;
5633         struct drm_i915_private *dev_priv = to_i915(dev);
5634         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5635         struct drm_plane *primary = crtc->base.primary;
5636         struct drm_plane_state *old_primary_state =
5637                 drm_atomic_get_old_plane_state(old_state, primary);
5638         bool modeset = needs_modeset(&pipe_config->base);
5639         struct intel_atomic_state *old_intel_state =
5640                 to_intel_atomic_state(old_state);
5641
5642         if (hsw_pre_update_disable_ips(old_crtc_state, pipe_config))
5643                 hsw_disable_ips(old_crtc_state);
5644
5645         if (old_primary_state) {
5646                 struct intel_plane_state *new_primary_state =
5647                         intel_atomic_get_new_plane_state(old_intel_state,
5648                                                          to_intel_plane(primary));
5649
5650                 intel_fbc_pre_update(crtc, pipe_config, new_primary_state);
5651                 /*
5652                  * Gen2 reports pipe underruns whenever all planes are disabled.
5653                  * So disable underrun reporting before all the planes get disabled.
5654                  */
5655                 if (IS_GEN(dev_priv, 2) && old_primary_state->visible &&
5656                     (modeset || !new_primary_state->base.visible))
5657                         intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, false);
5658         }
5659
5660         /* Display WA 827 */
5661         if (!needs_nv12_wa(dev_priv, old_crtc_state) &&
5662             needs_nv12_wa(dev_priv, pipe_config))
5663                 skl_wa_827(dev_priv, crtc->pipe, true);
5664
5665         /* Wa_2006604312:icl */
5666         if (!needs_scalerclk_wa(dev_priv, old_crtc_state) &&
5667             needs_scalerclk_wa(dev_priv, pipe_config))
5668                 icl_wa_scalerclkgating(dev_priv, crtc->pipe, true);
5669
5670         /*
5671          * Vblank time updates from the shadow to live plane control register
5672          * are blocked if the memory self-refresh mode is active at that
5673          * moment. So to make sure the plane gets truly disabled, disable
5674          * first the self-refresh mode. The self-refresh enable bit in turn
5675          * will be checked/applied by the HW only at the next frame start
5676          * event which is after the vblank start event, so we need to have a
5677          * wait-for-vblank between disabling the plane and the pipe.
5678          */
5679         if (HAS_GMCH(dev_priv) && old_crtc_state->base.active &&
5680             pipe_config->disable_cxsr && intel_set_memory_cxsr(dev_priv, false))
5681                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5682
5683         /*
5684          * IVB workaround: must disable low power watermarks for at least
5685          * one frame before enabling scaling.  LP watermarks can be re-enabled
5686          * when scaling is disabled.
5687          *
5688          * WaCxSRDisabledForSpriteScaling:ivb
5689          */
5690         if (pipe_config->disable_lp_wm && ilk_disable_lp_wm(dev) &&
5691             old_crtc_state->base.active)
5692                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5693
5694         /*
5695          * If we're doing a modeset, we're done.  No need to do any pre-vblank
5696          * watermark programming here.
5697          */
5698         if (needs_modeset(&pipe_config->base))
5699                 return;
5700
5701         /*
5702          * For platforms that support atomic watermarks, program the
5703          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
5704          * will be the intermediate values that are safe for both pre- and
5705          * post- vblank; when vblank happens, the 'active' values will be set
5706          * to the final 'target' values and we'll do this again to get the
5707          * optimal watermarks.  For gen9+ platforms, the values we program here
5708          * will be the final target values which will get automatically latched
5709          * at vblank time; no further programming will be necessary.
5710          *
5711          * If a platform hasn't been transitioned to atomic watermarks yet,
5712          * we'll continue to update watermarks the old way, if flags tell
5713          * us to.
5714          */
5715         if (dev_priv->display.initial_watermarks != NULL)
5716                 dev_priv->display.initial_watermarks(old_intel_state,
5717                                                      pipe_config);
5718         else if (pipe_config->update_wm_pre)
5719                 intel_update_watermarks(crtc);
5720 }
5721
5722 static void intel_crtc_disable_planes(struct intel_atomic_state *state,
5723                                       struct intel_crtc *crtc)
5724 {
5725         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5726         const struct intel_crtc_state *new_crtc_state =
5727                 intel_atomic_get_new_crtc_state(state, crtc);
5728         unsigned int update_mask = new_crtc_state->update_planes;
5729         const struct intel_plane_state *old_plane_state;
5730         struct intel_plane *plane;
5731         unsigned fb_bits = 0;
5732         int i;
5733
5734         intel_crtc_dpms_overlay_disable(crtc);
5735
5736         for_each_old_intel_plane_in_state(state, plane, old_plane_state, i) {
5737                 if (crtc->pipe != plane->pipe ||
5738                     !(update_mask & BIT(plane->id)))
5739                         continue;
5740
5741                 intel_disable_plane(plane, new_crtc_state);
5742
5743                 if (old_plane_state->base.visible)
5744                         fb_bits |= plane->frontbuffer_bit;
5745         }
5746
5747         intel_frontbuffer_flip(dev_priv, fb_bits);
5748 }
5749
5750 static void intel_encoders_pre_pll_enable(struct drm_crtc *crtc,
5751                                           struct intel_crtc_state *crtc_state,
5752                                           struct drm_atomic_state *old_state)
5753 {
5754         struct drm_connector_state *conn_state;
5755         struct drm_connector *conn;
5756         int i;
5757
5758         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5759                 struct intel_encoder *encoder =
5760                         to_intel_encoder(conn_state->best_encoder);
5761
5762                 if (conn_state->crtc != crtc)
5763                         continue;
5764
5765                 if (encoder->pre_pll_enable)
5766                         encoder->pre_pll_enable(encoder, crtc_state, conn_state);
5767         }
5768 }
5769
5770 static void intel_encoders_pre_enable(struct drm_crtc *crtc,
5771                                       struct intel_crtc_state *crtc_state,
5772                                       struct drm_atomic_state *old_state)
5773 {
5774         struct drm_connector_state *conn_state;
5775         struct drm_connector *conn;
5776         int i;
5777
5778         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5779                 struct intel_encoder *encoder =
5780                         to_intel_encoder(conn_state->best_encoder);
5781
5782                 if (conn_state->crtc != crtc)
5783                         continue;
5784
5785                 if (encoder->pre_enable)
5786                         encoder->pre_enable(encoder, crtc_state, conn_state);
5787         }
5788 }
5789
5790 static void intel_encoders_enable(struct drm_crtc *crtc,
5791                                   struct intel_crtc_state *crtc_state,
5792                                   struct drm_atomic_state *old_state)
5793 {
5794         struct drm_connector_state *conn_state;
5795         struct drm_connector *conn;
5796         int i;
5797
5798         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5799                 struct intel_encoder *encoder =
5800                         to_intel_encoder(conn_state->best_encoder);
5801
5802                 if (conn_state->crtc != crtc)
5803                         continue;
5804
5805                 if (encoder->enable)
5806                         encoder->enable(encoder, crtc_state, conn_state);
5807                 intel_opregion_notify_encoder(encoder, true);
5808         }
5809 }
5810
5811 static void intel_encoders_disable(struct drm_crtc *crtc,
5812                                    struct intel_crtc_state *old_crtc_state,
5813                                    struct drm_atomic_state *old_state)
5814 {
5815         struct drm_connector_state *old_conn_state;
5816         struct drm_connector *conn;
5817         int i;
5818
5819         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5820                 struct intel_encoder *encoder =
5821                         to_intel_encoder(old_conn_state->best_encoder);
5822
5823                 if (old_conn_state->crtc != crtc)
5824                         continue;
5825
5826                 intel_opregion_notify_encoder(encoder, false);
5827                 if (encoder->disable)
5828                         encoder->disable(encoder, old_crtc_state, old_conn_state);
5829         }
5830 }
5831
5832 static void intel_encoders_post_disable(struct drm_crtc *crtc,
5833                                         struct intel_crtc_state *old_crtc_state,
5834                                         struct drm_atomic_state *old_state)
5835 {
5836         struct drm_connector_state *old_conn_state;
5837         struct drm_connector *conn;
5838         int i;
5839
5840         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5841                 struct intel_encoder *encoder =
5842                         to_intel_encoder(old_conn_state->best_encoder);
5843
5844                 if (old_conn_state->crtc != crtc)
5845                         continue;
5846
5847                 if (encoder->post_disable)
5848                         encoder->post_disable(encoder, old_crtc_state, old_conn_state);
5849         }
5850 }
5851
5852 static void intel_encoders_post_pll_disable(struct drm_crtc *crtc,
5853                                             struct intel_crtc_state *old_crtc_state,
5854                                             struct drm_atomic_state *old_state)
5855 {
5856         struct drm_connector_state *old_conn_state;
5857         struct drm_connector *conn;
5858         int i;
5859
5860         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5861                 struct intel_encoder *encoder =
5862                         to_intel_encoder(old_conn_state->best_encoder);
5863
5864                 if (old_conn_state->crtc != crtc)
5865                         continue;
5866
5867                 if (encoder->post_pll_disable)
5868                         encoder->post_pll_disable(encoder, old_crtc_state, old_conn_state);
5869         }
5870 }
5871
5872 static void intel_encoders_update_pipe(struct drm_crtc *crtc,
5873                                        struct intel_crtc_state *crtc_state,
5874                                        struct drm_atomic_state *old_state)
5875 {
5876         struct drm_connector_state *conn_state;
5877         struct drm_connector *conn;
5878         int i;
5879
5880         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5881                 struct intel_encoder *encoder =
5882                         to_intel_encoder(conn_state->best_encoder);
5883
5884                 if (conn_state->crtc != crtc)
5885                         continue;
5886
5887                 if (encoder->update_pipe)
5888                         encoder->update_pipe(encoder, crtc_state, conn_state);
5889         }
5890 }
5891
5892 static void intel_disable_primary_plane(const struct intel_crtc_state *crtc_state)
5893 {
5894         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5895         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
5896
5897         plane->disable_plane(plane, crtc_state);
5898 }
5899
5900 static void ironlake_crtc_enable(struct intel_crtc_state *pipe_config,
5901                                  struct drm_atomic_state *old_state)
5902 {
5903         struct drm_crtc *crtc = pipe_config->base.crtc;
5904         struct drm_device *dev = crtc->dev;
5905         struct drm_i915_private *dev_priv = to_i915(dev);
5906         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5907         int pipe = intel_crtc->pipe;
5908         struct intel_atomic_state *old_intel_state =
5909                 to_intel_atomic_state(old_state);
5910
5911         if (WARN_ON(intel_crtc->active))
5912                 return;
5913
5914         /*
5915          * Sometimes spurious CPU pipe underruns happen during FDI
5916          * training, at least with VGA+HDMI cloning. Suppress them.
5917          *
5918          * On ILK we get an occasional spurious CPU pipe underruns
5919          * between eDP port A enable and vdd enable. Also PCH port
5920          * enable seems to result in the occasional CPU pipe underrun.
5921          *
5922          * Spurious PCH underruns also occur during PCH enabling.
5923          */
5924         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5925         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5926
5927         if (pipe_config->has_pch_encoder)
5928                 intel_prepare_shared_dpll(pipe_config);
5929
5930         if (intel_crtc_has_dp_encoder(pipe_config))
5931                 intel_dp_set_m_n(pipe_config, M1_N1);
5932
5933         intel_set_pipe_timings(pipe_config);
5934         intel_set_pipe_src_size(pipe_config);
5935
5936         if (pipe_config->has_pch_encoder) {
5937                 intel_cpu_transcoder_set_m_n(pipe_config,
5938                                              &pipe_config->fdi_m_n, NULL);
5939         }
5940
5941         ironlake_set_pipeconf(pipe_config);
5942
5943         intel_crtc->active = true;
5944
5945         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5946
5947         if (pipe_config->has_pch_encoder) {
5948                 /* Note: FDI PLL enabling _must_ be done before we enable the
5949                  * cpu pipes, hence this is separate from all the other fdi/pch
5950                  * enabling. */
5951                 ironlake_fdi_pll_enable(pipe_config);
5952         } else {
5953                 assert_fdi_tx_disabled(dev_priv, pipe);
5954                 assert_fdi_rx_disabled(dev_priv, pipe);
5955         }
5956
5957         ironlake_pfit_enable(pipe_config);
5958
5959         /*
5960          * On ILK+ LUT must be loaded before the pipe is running but with
5961          * clocks enabled
5962          */
5963         intel_color_load_luts(pipe_config);
5964         intel_color_commit(pipe_config);
5965         /* update DSPCNTR to configure gamma for pipe bottom color */
5966         intel_disable_primary_plane(pipe_config);
5967
5968         if (dev_priv->display.initial_watermarks != NULL)
5969                 dev_priv->display.initial_watermarks(old_intel_state, pipe_config);
5970         intel_enable_pipe(pipe_config);
5971
5972         if (pipe_config->has_pch_encoder)
5973                 ironlake_pch_enable(old_intel_state, pipe_config);
5974
5975         assert_vblank_disabled(crtc);
5976         intel_crtc_vblank_on(pipe_config);
5977
5978         intel_encoders_enable(crtc, pipe_config, old_state);
5979
5980         if (HAS_PCH_CPT(dev_priv))
5981                 cpt_verify_modeset(dev, intel_crtc->pipe);
5982
5983         /*
5984          * Must wait for vblank to avoid spurious PCH FIFO underruns.
5985          * And a second vblank wait is needed at least on ILK with
5986          * some interlaced HDMI modes. Let's do the double wait always
5987          * in case there are more corner cases we don't know about.
5988          */
5989         if (pipe_config->has_pch_encoder) {
5990                 intel_wait_for_vblank(dev_priv, pipe);
5991                 intel_wait_for_vblank(dev_priv, pipe);
5992         }
5993         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5994         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5995 }
5996
5997 /* IPS only exists on ULT machines and is tied to pipe A. */
5998 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
5999 {
6000         return HAS_IPS(to_i915(crtc->base.dev)) && crtc->pipe == PIPE_A;
6001 }
6002
6003 static void glk_pipe_scaler_clock_gating_wa(struct drm_i915_private *dev_priv,
6004                                             enum pipe pipe, bool apply)
6005 {
6006         u32 val = I915_READ(CLKGATE_DIS_PSL(pipe));
6007         u32 mask = DPF_GATING_DIS | DPF_RAM_GATING_DIS | DPFR_GATING_DIS;
6008
6009         if (apply)
6010                 val |= mask;
6011         else
6012                 val &= ~mask;
6013
6014         I915_WRITE(CLKGATE_DIS_PSL(pipe), val);
6015 }
6016
6017 static void icl_pipe_mbus_enable(struct intel_crtc *crtc)
6018 {
6019         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6020         enum pipe pipe = crtc->pipe;
6021         u32 val;
6022
6023         val = MBUS_DBOX_A_CREDIT(2);
6024         val |= MBUS_DBOX_BW_CREDIT(1);
6025         val |= MBUS_DBOX_B_CREDIT(8);
6026
6027         I915_WRITE(PIPE_MBUS_DBOX_CTL(pipe), val);
6028 }
6029
6030 static void haswell_crtc_enable(struct intel_crtc_state *pipe_config,
6031                                 struct drm_atomic_state *old_state)
6032 {
6033         struct drm_crtc *crtc = pipe_config->base.crtc;
6034         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6035         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6036         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
6037         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
6038         struct intel_atomic_state *old_intel_state =
6039                 to_intel_atomic_state(old_state);
6040         bool psl_clkgate_wa;
6041
6042         if (WARN_ON(intel_crtc->active))
6043                 return;
6044
6045         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
6046
6047         if (pipe_config->shared_dpll)
6048                 intel_enable_shared_dpll(pipe_config);
6049
6050         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6051
6052         if (intel_crtc_has_dp_encoder(pipe_config))
6053                 intel_dp_set_m_n(pipe_config, M1_N1);
6054
6055         if (!transcoder_is_dsi(cpu_transcoder))
6056                 intel_set_pipe_timings(pipe_config);
6057
6058         intel_set_pipe_src_size(pipe_config);
6059
6060         if (cpu_transcoder != TRANSCODER_EDP &&
6061             !transcoder_is_dsi(cpu_transcoder)) {
6062                 I915_WRITE(PIPE_MULT(cpu_transcoder),
6063                            pipe_config->pixel_multiplier - 1);
6064         }
6065
6066         if (pipe_config->has_pch_encoder) {
6067                 intel_cpu_transcoder_set_m_n(pipe_config,
6068                                              &pipe_config->fdi_m_n, NULL);
6069         }
6070
6071         if (!transcoder_is_dsi(cpu_transcoder))
6072                 haswell_set_pipeconf(pipe_config);
6073
6074         if (INTEL_GEN(dev_priv) >= 9 || IS_BROADWELL(dev_priv))
6075                 bdw_set_pipemisc(pipe_config);
6076
6077         intel_crtc->active = true;
6078
6079         /* Display WA #1180: WaDisableScalarClockGating: glk, cnl */
6080         psl_clkgate_wa = (IS_GEMINILAKE(dev_priv) || IS_CANNONLAKE(dev_priv)) &&
6081                          pipe_config->pch_pfit.enabled;
6082         if (psl_clkgate_wa)
6083                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, true);
6084
6085         if (INTEL_GEN(dev_priv) >= 9)
6086                 skylake_pfit_enable(pipe_config);
6087         else
6088                 ironlake_pfit_enable(pipe_config);
6089
6090         /*
6091          * On ILK+ LUT must be loaded before the pipe is running but with
6092          * clocks enabled
6093          */
6094         intel_color_load_luts(pipe_config);
6095         intel_color_commit(pipe_config);
6096         /* update DSPCNTR to configure gamma/csc for pipe bottom color */
6097         if (INTEL_GEN(dev_priv) < 9)
6098                 intel_disable_primary_plane(pipe_config);
6099
6100         if (INTEL_GEN(dev_priv) >= 11)
6101                 icl_set_pipe_chicken(intel_crtc);
6102
6103         intel_ddi_set_pipe_settings(pipe_config);
6104         if (!transcoder_is_dsi(cpu_transcoder))
6105                 intel_ddi_enable_transcoder_func(pipe_config);
6106
6107         if (dev_priv->display.initial_watermarks != NULL)
6108                 dev_priv->display.initial_watermarks(old_intel_state, pipe_config);
6109
6110         if (INTEL_GEN(dev_priv) >= 11)
6111                 icl_pipe_mbus_enable(intel_crtc);
6112
6113         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
6114         if (!transcoder_is_dsi(cpu_transcoder))
6115                 intel_enable_pipe(pipe_config);
6116
6117         if (pipe_config->has_pch_encoder)
6118                 lpt_pch_enable(old_intel_state, pipe_config);
6119
6120         if (intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DP_MST))
6121                 intel_ddi_set_vc_payload_alloc(pipe_config, true);
6122
6123         assert_vblank_disabled(crtc);
6124         intel_crtc_vblank_on(pipe_config);
6125
6126         intel_encoders_enable(crtc, pipe_config, old_state);
6127
6128         if (psl_clkgate_wa) {
6129                 intel_wait_for_vblank(dev_priv, pipe);
6130                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, false);
6131         }
6132
6133         /* If we change the relative order between pipe/planes enabling, we need
6134          * to change the workaround. */
6135         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
6136         if (IS_HASWELL(dev_priv) && hsw_workaround_pipe != INVALID_PIPE) {
6137                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
6138                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
6139         }
6140 }
6141
6142 static void ironlake_pfit_disable(const struct intel_crtc_state *old_crtc_state)
6143 {
6144         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
6145         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6146         enum pipe pipe = crtc->pipe;
6147
6148         /* To avoid upsetting the power well on haswell only disable the pfit if
6149          * it's in use. The hw state code will make sure we get this right. */
6150         if (old_crtc_state->pch_pfit.enabled) {
6151                 I915_WRITE(PF_CTL(pipe), 0);
6152                 I915_WRITE(PF_WIN_POS(pipe), 0);
6153                 I915_WRITE(PF_WIN_SZ(pipe), 0);
6154         }
6155 }
6156
6157 static void ironlake_crtc_disable(struct intel_crtc_state *old_crtc_state,
6158                                   struct drm_atomic_state *old_state)
6159 {
6160         struct drm_crtc *crtc = old_crtc_state->base.crtc;
6161         struct drm_device *dev = crtc->dev;
6162         struct drm_i915_private *dev_priv = to_i915(dev);
6163         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6164         int pipe = intel_crtc->pipe;
6165
6166         /*
6167          * Sometimes spurious CPU pipe underruns happen when the
6168          * pipe is already disabled, but FDI RX/TX is still enabled.
6169          * Happens at least with VGA+HDMI cloning. Suppress them.
6170          */
6171         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6172         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
6173
6174         intel_encoders_disable(crtc, old_crtc_state, old_state);
6175
6176         drm_crtc_vblank_off(crtc);
6177         assert_vblank_disabled(crtc);
6178
6179         intel_disable_pipe(old_crtc_state);
6180
6181         ironlake_pfit_disable(old_crtc_state);
6182
6183         if (old_crtc_state->has_pch_encoder)
6184                 ironlake_fdi_disable(crtc);
6185
6186         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
6187
6188         if (old_crtc_state->has_pch_encoder) {
6189                 ironlake_disable_pch_transcoder(dev_priv, pipe);
6190
6191                 if (HAS_PCH_CPT(dev_priv)) {
6192                         i915_reg_t reg;
6193                         u32 temp;
6194
6195                         /* disable TRANS_DP_CTL */
6196                         reg = TRANS_DP_CTL(pipe);
6197                         temp = I915_READ(reg);
6198                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
6199                                   TRANS_DP_PORT_SEL_MASK);
6200                         temp |= TRANS_DP_PORT_SEL_NONE;
6201                         I915_WRITE(reg, temp);
6202
6203                         /* disable DPLL_SEL */
6204                         temp = I915_READ(PCH_DPLL_SEL);
6205                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
6206                         I915_WRITE(PCH_DPLL_SEL, temp);
6207                 }
6208
6209                 ironlake_fdi_pll_disable(intel_crtc);
6210         }
6211
6212         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6213         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
6214 }
6215
6216 static void haswell_crtc_disable(struct intel_crtc_state *old_crtc_state,
6217                                  struct drm_atomic_state *old_state)
6218 {
6219         struct drm_crtc *crtc = old_crtc_state->base.crtc;
6220         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6221         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6222         enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
6223
6224         intel_encoders_disable(crtc, old_crtc_state, old_state);
6225
6226         drm_crtc_vblank_off(crtc);
6227         assert_vblank_disabled(crtc);
6228
6229         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
6230         if (!transcoder_is_dsi(cpu_transcoder))
6231                 intel_disable_pipe(old_crtc_state);
6232
6233         if (intel_crtc_has_type(old_crtc_state, INTEL_OUTPUT_DP_MST))
6234                 intel_ddi_set_vc_payload_alloc(old_crtc_state, false);
6235
6236         if (!transcoder_is_dsi(cpu_transcoder))
6237                 intel_ddi_disable_transcoder_func(old_crtc_state);
6238
6239         intel_dsc_disable(old_crtc_state);
6240
6241         if (INTEL_GEN(dev_priv) >= 9)
6242                 skylake_scaler_disable(intel_crtc);
6243         else
6244                 ironlake_pfit_disable(old_crtc_state);
6245
6246         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
6247
6248         intel_encoders_post_pll_disable(crtc, old_crtc_state, old_state);
6249 }
6250
6251 static void i9xx_pfit_enable(const struct intel_crtc_state *crtc_state)
6252 {
6253         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6254         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6255
6256         if (!crtc_state->gmch_pfit.control)
6257                 return;
6258
6259         /*
6260          * The panel fitter should only be adjusted whilst the pipe is disabled,
6261          * according to register description and PRM.
6262          */
6263         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
6264         assert_pipe_disabled(dev_priv, crtc->pipe);
6265
6266         I915_WRITE(PFIT_PGM_RATIOS, crtc_state->gmch_pfit.pgm_ratios);
6267         I915_WRITE(PFIT_CONTROL, crtc_state->gmch_pfit.control);
6268
6269         /* Border color in case we don't scale up to the full screen. Black by
6270          * default, change to something else for debugging. */
6271         I915_WRITE(BCLRPAT(crtc->pipe), 0);
6272 }
6273
6274 bool intel_port_is_combophy(struct drm_i915_private *dev_priv, enum port port)
6275 {
6276         if (port == PORT_NONE)
6277                 return false;
6278
6279         if (IS_ELKHARTLAKE(dev_priv))
6280                 return port <= PORT_C;
6281
6282         if (INTEL_GEN(dev_priv) >= 11)
6283                 return port <= PORT_B;
6284
6285         return false;
6286 }
6287
6288 bool intel_port_is_tc(struct drm_i915_private *dev_priv, enum port port)
6289 {
6290         if (INTEL_GEN(dev_priv) >= 11 && !IS_ELKHARTLAKE(dev_priv))
6291                 return port >= PORT_C && port <= PORT_F;
6292
6293         return false;
6294 }
6295
6296 enum tc_port intel_port_to_tc(struct drm_i915_private *dev_priv, enum port port)
6297 {
6298         if (!intel_port_is_tc(dev_priv, port))
6299                 return PORT_TC_NONE;
6300
6301         return port - PORT_C;
6302 }
6303
6304 enum intel_display_power_domain intel_port_to_power_domain(enum port port)
6305 {
6306         switch (port) {
6307         case PORT_A:
6308                 return POWER_DOMAIN_PORT_DDI_A_LANES;
6309         case PORT_B:
6310                 return POWER_DOMAIN_PORT_DDI_B_LANES;
6311         case PORT_C:
6312                 return POWER_DOMAIN_PORT_DDI_C_LANES;
6313         case PORT_D:
6314                 return POWER_DOMAIN_PORT_DDI_D_LANES;
6315         case PORT_E:
6316                 return POWER_DOMAIN_PORT_DDI_E_LANES;
6317         case PORT_F:
6318                 return POWER_DOMAIN_PORT_DDI_F_LANES;
6319         default:
6320                 MISSING_CASE(port);
6321                 return POWER_DOMAIN_PORT_OTHER;
6322         }
6323 }
6324
6325 enum intel_display_power_domain
6326 intel_aux_power_domain(struct intel_digital_port *dig_port)
6327 {
6328         switch (dig_port->aux_ch) {
6329         case AUX_CH_A:
6330                 return POWER_DOMAIN_AUX_A;
6331         case AUX_CH_B:
6332                 return POWER_DOMAIN_AUX_B;
6333         case AUX_CH_C:
6334                 return POWER_DOMAIN_AUX_C;
6335         case AUX_CH_D:
6336                 return POWER_DOMAIN_AUX_D;
6337         case AUX_CH_E:
6338                 return POWER_DOMAIN_AUX_E;
6339         case AUX_CH_F:
6340                 return POWER_DOMAIN_AUX_F;
6341         default:
6342                 MISSING_CASE(dig_port->aux_ch);
6343                 return POWER_DOMAIN_AUX_A;
6344         }
6345 }
6346
6347 static u64 get_crtc_power_domains(struct drm_crtc *crtc,
6348                                   struct intel_crtc_state *crtc_state)
6349 {
6350         struct drm_device *dev = crtc->dev;
6351         struct drm_i915_private *dev_priv = to_i915(dev);
6352         struct drm_encoder *encoder;
6353         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6354         enum pipe pipe = intel_crtc->pipe;
6355         u64 mask;
6356         enum transcoder transcoder = crtc_state->cpu_transcoder;
6357
6358         if (!crtc_state->base.active)
6359                 return 0;
6360
6361         mask = BIT_ULL(POWER_DOMAIN_PIPE(pipe));
6362         mask |= BIT_ULL(POWER_DOMAIN_TRANSCODER(transcoder));
6363         if (crtc_state->pch_pfit.enabled ||
6364             crtc_state->pch_pfit.force_thru)
6365                 mask |= BIT_ULL(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
6366
6367         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
6368                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6369
6370                 mask |= BIT_ULL(intel_encoder->power_domain);
6371         }
6372
6373         if (HAS_DDI(dev_priv) && crtc_state->has_audio)
6374                 mask |= BIT_ULL(POWER_DOMAIN_AUDIO);
6375
6376         if (crtc_state->shared_dpll)
6377                 mask |= BIT_ULL(POWER_DOMAIN_DISPLAY_CORE);
6378
6379         return mask;
6380 }
6381
6382 static u64
6383 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
6384                                struct intel_crtc_state *crtc_state)
6385 {
6386         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6387         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6388         enum intel_display_power_domain domain;
6389         u64 domains, new_domains, old_domains;
6390
6391         old_domains = intel_crtc->enabled_power_domains;
6392         intel_crtc->enabled_power_domains = new_domains =
6393                 get_crtc_power_domains(crtc, crtc_state);
6394
6395         domains = new_domains & ~old_domains;
6396
6397         for_each_power_domain(domain, domains)
6398                 intel_display_power_get(dev_priv, domain);
6399
6400         return old_domains & ~new_domains;
6401 }
6402
6403 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
6404                                       u64 domains)
6405 {
6406         enum intel_display_power_domain domain;
6407
6408         for_each_power_domain(domain, domains)
6409                 intel_display_power_put_unchecked(dev_priv, domain);
6410 }
6411
6412 static void valleyview_crtc_enable(struct intel_crtc_state *pipe_config,
6413                                    struct drm_atomic_state *old_state)
6414 {
6415         struct intel_atomic_state *old_intel_state =
6416                 to_intel_atomic_state(old_state);
6417         struct drm_crtc *crtc = pipe_config->base.crtc;
6418         struct drm_device *dev = crtc->dev;
6419         struct drm_i915_private *dev_priv = to_i915(dev);
6420         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6421         int pipe = intel_crtc->pipe;
6422
6423         if (WARN_ON(intel_crtc->active))
6424                 return;
6425
6426         if (intel_crtc_has_dp_encoder(pipe_config))
6427                 intel_dp_set_m_n(pipe_config, M1_N1);
6428
6429         intel_set_pipe_timings(pipe_config);
6430         intel_set_pipe_src_size(pipe_config);
6431
6432         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
6433                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6434                 I915_WRITE(CHV_CANVAS(pipe), 0);
6435         }
6436
6437         i9xx_set_pipeconf(pipe_config);
6438
6439         intel_crtc->active = true;
6440
6441         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6442
6443         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
6444
6445         if (IS_CHERRYVIEW(dev_priv)) {
6446                 chv_prepare_pll(intel_crtc, pipe_config);
6447                 chv_enable_pll(intel_crtc, pipe_config);
6448         } else {
6449                 vlv_prepare_pll(intel_crtc, pipe_config);
6450                 vlv_enable_pll(intel_crtc, pipe_config);
6451         }
6452
6453         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6454
6455         i9xx_pfit_enable(pipe_config);
6456
6457         intel_color_load_luts(pipe_config);
6458         intel_color_commit(pipe_config);
6459         /* update DSPCNTR to configure gamma for pipe bottom color */
6460         intel_disable_primary_plane(pipe_config);
6461
6462         dev_priv->display.initial_watermarks(old_intel_state,
6463                                              pipe_config);
6464         intel_enable_pipe(pipe_config);
6465
6466         assert_vblank_disabled(crtc);
6467         intel_crtc_vblank_on(pipe_config);
6468
6469         intel_encoders_enable(crtc, pipe_config, old_state);
6470 }
6471
6472 static void i9xx_set_pll_dividers(const struct intel_crtc_state *crtc_state)
6473 {
6474         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6475         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6476
6477         I915_WRITE(FP0(crtc->pipe), crtc_state->dpll_hw_state.fp0);
6478         I915_WRITE(FP1(crtc->pipe), crtc_state->dpll_hw_state.fp1);
6479 }
6480
6481 static void i9xx_crtc_enable(struct intel_crtc_state *pipe_config,
6482                              struct drm_atomic_state *old_state)
6483 {
6484         struct intel_atomic_state *old_intel_state =
6485                 to_intel_atomic_state(old_state);
6486         struct drm_crtc *crtc = pipe_config->base.crtc;
6487         struct drm_device *dev = crtc->dev;
6488         struct drm_i915_private *dev_priv = to_i915(dev);
6489         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6490         enum pipe pipe = intel_crtc->pipe;
6491
6492         if (WARN_ON(intel_crtc->active))
6493                 return;
6494
6495         i9xx_set_pll_dividers(pipe_config);
6496
6497         if (intel_crtc_has_dp_encoder(pipe_config))
6498                 intel_dp_set_m_n(pipe_config, M1_N1);
6499
6500         intel_set_pipe_timings(pipe_config);
6501         intel_set_pipe_src_size(pipe_config);
6502
6503         i9xx_set_pipeconf(pipe_config);
6504
6505         intel_crtc->active = true;
6506
6507         if (!IS_GEN(dev_priv, 2))
6508                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6509
6510         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6511
6512         i9xx_enable_pll(intel_crtc, pipe_config);
6513
6514         i9xx_pfit_enable(pipe_config);
6515
6516         intel_color_load_luts(pipe_config);
6517         intel_color_commit(pipe_config);
6518         /* update DSPCNTR to configure gamma for pipe bottom color */
6519         intel_disable_primary_plane(pipe_config);
6520
6521         if (dev_priv->display.initial_watermarks != NULL)
6522                 dev_priv->display.initial_watermarks(old_intel_state,
6523                                                      pipe_config);
6524         else
6525                 intel_update_watermarks(intel_crtc);
6526         intel_enable_pipe(pipe_config);
6527
6528         assert_vblank_disabled(crtc);
6529         intel_crtc_vblank_on(pipe_config);
6530
6531         intel_encoders_enable(crtc, pipe_config, old_state);
6532 }
6533
6534 static void i9xx_pfit_disable(const struct intel_crtc_state *old_crtc_state)
6535 {
6536         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
6537         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6538
6539         if (!old_crtc_state->gmch_pfit.control)
6540                 return;
6541
6542         assert_pipe_disabled(dev_priv, crtc->pipe);
6543
6544         DRM_DEBUG_KMS("disabling pfit, current: 0x%08x\n",
6545                       I915_READ(PFIT_CONTROL));
6546         I915_WRITE(PFIT_CONTROL, 0);
6547 }
6548
6549 static void i9xx_crtc_disable(struct intel_crtc_state *old_crtc_state,
6550                               struct drm_atomic_state *old_state)
6551 {
6552         struct drm_crtc *crtc = old_crtc_state->base.crtc;
6553         struct drm_device *dev = crtc->dev;
6554         struct drm_i915_private *dev_priv = to_i915(dev);
6555         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6556         int pipe = intel_crtc->pipe;
6557
6558         /*
6559          * On gen2 planes are double buffered but the pipe isn't, so we must
6560          * wait for planes to fully turn off before disabling the pipe.
6561          */
6562         if (IS_GEN(dev_priv, 2))
6563                 intel_wait_for_vblank(dev_priv, pipe);
6564
6565         intel_encoders_disable(crtc, old_crtc_state, old_state);
6566
6567         drm_crtc_vblank_off(crtc);
6568         assert_vblank_disabled(crtc);
6569
6570         intel_disable_pipe(old_crtc_state);
6571
6572         i9xx_pfit_disable(old_crtc_state);
6573
6574         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
6575
6576         if (!intel_crtc_has_type(old_crtc_state, INTEL_OUTPUT_DSI)) {
6577                 if (IS_CHERRYVIEW(dev_priv))
6578                         chv_disable_pll(dev_priv, pipe);
6579                 else if (IS_VALLEYVIEW(dev_priv))
6580                         vlv_disable_pll(dev_priv, pipe);
6581                 else
6582                         i9xx_disable_pll(old_crtc_state);
6583         }
6584
6585         intel_encoders_post_pll_disable(crtc, old_crtc_state, old_state);
6586
6587         if (!IS_GEN(dev_priv, 2))
6588                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6589
6590         if (!dev_priv->display.initial_watermarks)
6591                 intel_update_watermarks(intel_crtc);
6592
6593         /* clock the pipe down to 640x480@60 to potentially save power */
6594         if (IS_I830(dev_priv))
6595                 i830_enable_pipe(dev_priv, pipe);
6596 }
6597
6598 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc,
6599                                         struct drm_modeset_acquire_ctx *ctx)
6600 {
6601         struct intel_encoder *encoder;
6602         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6603         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6604         enum intel_display_power_domain domain;
6605         struct intel_plane *plane;
6606         u64 domains;
6607         struct drm_atomic_state *state;
6608         struct intel_crtc_state *crtc_state;
6609         int ret;
6610
6611         if (!intel_crtc->active)
6612                 return;
6613
6614         for_each_intel_plane_on_crtc(&dev_priv->drm, intel_crtc, plane) {
6615                 const struct intel_plane_state *plane_state =
6616                         to_intel_plane_state(plane->base.state);
6617
6618                 if (plane_state->base.visible)
6619                         intel_plane_disable_noatomic(intel_crtc, plane);
6620         }
6621
6622         state = drm_atomic_state_alloc(crtc->dev);
6623         if (!state) {
6624                 DRM_DEBUG_KMS("failed to disable [CRTC:%d:%s], out of memory",
6625                               crtc->base.id, crtc->name);
6626                 return;
6627         }
6628
6629         state->acquire_ctx = ctx;
6630
6631         /* Everything's already locked, -EDEADLK can't happen. */
6632         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
6633         ret = drm_atomic_add_affected_connectors(state, crtc);
6634
6635         WARN_ON(IS_ERR(crtc_state) || ret);
6636
6637         dev_priv->display.crtc_disable(crtc_state, state);
6638
6639         drm_atomic_state_put(state);
6640
6641         DRM_DEBUG_KMS("[CRTC:%d:%s] hw state adjusted, was enabled, now disabled\n",
6642                       crtc->base.id, crtc->name);
6643
6644         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
6645         crtc->state->active = false;
6646         intel_crtc->active = false;
6647         crtc->enabled = false;
6648         crtc->state->connector_mask = 0;
6649         crtc->state->encoder_mask = 0;
6650
6651         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
6652                 encoder->base.crtc = NULL;
6653
6654         intel_fbc_disable(intel_crtc);
6655         intel_update_watermarks(intel_crtc);
6656         intel_disable_shared_dpll(to_intel_crtc_state(crtc->state));
6657
6658         domains = intel_crtc->enabled_power_domains;
6659         for_each_power_domain(domain, domains)
6660                 intel_display_power_put_unchecked(dev_priv, domain);
6661         intel_crtc->enabled_power_domains = 0;
6662
6663         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6664         dev_priv->min_cdclk[intel_crtc->pipe] = 0;
6665         dev_priv->min_voltage_level[intel_crtc->pipe] = 0;
6666 }
6667
6668 /*
6669  * turn all crtc's off, but do not adjust state
6670  * This has to be paired with a call to intel_modeset_setup_hw_state.
6671  */
6672 int intel_display_suspend(struct drm_device *dev)
6673 {
6674         struct drm_i915_private *dev_priv = to_i915(dev);
6675         struct drm_atomic_state *state;
6676         int ret;
6677
6678         state = drm_atomic_helper_suspend(dev);
6679         ret = PTR_ERR_OR_ZERO(state);
6680         if (ret)
6681                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6682         else
6683                 dev_priv->modeset_restore_state = state;
6684         return ret;
6685 }
6686
6687 void intel_encoder_destroy(struct drm_encoder *encoder)
6688 {
6689         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6690
6691         drm_encoder_cleanup(encoder);
6692         kfree(intel_encoder);
6693 }
6694
6695 /* Cross check the actual hw state with our own modeset state tracking (and it's
6696  * internal consistency). */
6697 static void intel_connector_verify_state(struct drm_crtc_state *crtc_state,
6698                                          struct drm_connector_state *conn_state)
6699 {
6700         struct intel_connector *connector = to_intel_connector(conn_state->connector);
6701
6702         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6703                       connector->base.base.id,
6704                       connector->base.name);
6705
6706         if (connector->get_hw_state(connector)) {
6707                 struct intel_encoder *encoder = connector->encoder;
6708
6709                 I915_STATE_WARN(!crtc_state,
6710                          "connector enabled without attached crtc\n");
6711
6712                 if (!crtc_state)
6713                         return;
6714
6715                 I915_STATE_WARN(!crtc_state->active,
6716                       "connector is active, but attached crtc isn't\n");
6717
6718                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6719                         return;
6720
6721                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6722                         "atomic encoder doesn't match attached encoder\n");
6723
6724                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6725                         "attached encoder crtc differs from connector crtc\n");
6726         } else {
6727                 I915_STATE_WARN(crtc_state && crtc_state->active,
6728                         "attached crtc is active, but connector isn't\n");
6729                 I915_STATE_WARN(!crtc_state && conn_state->best_encoder,
6730                         "best encoder set without crtc!\n");
6731         }
6732 }
6733
6734 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6735 {
6736         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6737                 return crtc_state->fdi_lanes;
6738
6739         return 0;
6740 }
6741
6742 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6743                                      struct intel_crtc_state *pipe_config)
6744 {
6745         struct drm_i915_private *dev_priv = to_i915(dev);
6746         struct drm_atomic_state *state = pipe_config->base.state;
6747         struct intel_crtc *other_crtc;
6748         struct intel_crtc_state *other_crtc_state;
6749
6750         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6751                       pipe_name(pipe), pipe_config->fdi_lanes);
6752         if (pipe_config->fdi_lanes > 4) {
6753                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6754                               pipe_name(pipe), pipe_config->fdi_lanes);
6755                 return -EINVAL;
6756         }
6757
6758         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
6759                 if (pipe_config->fdi_lanes > 2) {
6760                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6761                                       pipe_config->fdi_lanes);
6762                         return -EINVAL;
6763                 } else {
6764                         return 0;
6765                 }
6766         }
6767
6768         if (INTEL_INFO(dev_priv)->num_pipes == 2)
6769                 return 0;
6770
6771         /* Ivybridge 3 pipe is really complicated */
6772         switch (pipe) {
6773         case PIPE_A:
6774                 return 0;
6775         case PIPE_B:
6776                 if (pipe_config->fdi_lanes <= 2)
6777                         return 0;
6778
6779                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_C);
6780                 other_crtc_state =
6781                         intel_atomic_get_crtc_state(state, other_crtc);
6782                 if (IS_ERR(other_crtc_state))
6783                         return PTR_ERR(other_crtc_state);
6784
6785                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6786                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6787                                       pipe_name(pipe), pipe_config->fdi_lanes);
6788                         return -EINVAL;
6789                 }
6790                 return 0;
6791         case PIPE_C:
6792                 if (pipe_config->fdi_lanes > 2) {
6793                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6794                                       pipe_name(pipe), pipe_config->fdi_lanes);
6795                         return -EINVAL;
6796                 }
6797
6798                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_B);
6799                 other_crtc_state =
6800                         intel_atomic_get_crtc_state(state, other_crtc);
6801                 if (IS_ERR(other_crtc_state))
6802                         return PTR_ERR(other_crtc_state);
6803
6804                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6805                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6806                         return -EINVAL;
6807                 }
6808                 return 0;
6809         default:
6810                 BUG();
6811         }
6812 }
6813
6814 #define RETRY 1
6815 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6816                                        struct intel_crtc_state *pipe_config)
6817 {
6818         struct drm_device *dev = intel_crtc->base.dev;
6819         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6820         int lane, link_bw, fdi_dotclock, ret;
6821         bool needs_recompute = false;
6822
6823 retry:
6824         /* FDI is a binary signal running at ~2.7GHz, encoding
6825          * each output octet as 10 bits. The actual frequency
6826          * is stored as a divider into a 100MHz clock, and the
6827          * mode pixel clock is stored in units of 1KHz.
6828          * Hence the bw of each lane in terms of the mode signal
6829          * is:
6830          */
6831         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
6832
6833         fdi_dotclock = adjusted_mode->crtc_clock;
6834
6835         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6836                                            pipe_config->pipe_bpp);
6837
6838         pipe_config->fdi_lanes = lane;
6839
6840         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6841                                link_bw, &pipe_config->fdi_m_n, false);
6842
6843         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
6844         if (ret == -EDEADLK)
6845                 return ret;
6846
6847         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6848                 pipe_config->pipe_bpp -= 2*3;
6849                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6850                               pipe_config->pipe_bpp);
6851                 needs_recompute = true;
6852                 pipe_config->bw_constrained = true;
6853
6854                 goto retry;
6855         }
6856
6857         if (needs_recompute)
6858                 return RETRY;
6859
6860         return ret;
6861 }
6862
6863 bool hsw_crtc_state_ips_capable(const struct intel_crtc_state *crtc_state)
6864 {
6865         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6866         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6867
6868         /* IPS only exists on ULT machines and is tied to pipe A. */
6869         if (!hsw_crtc_supports_ips(crtc))
6870                 return false;
6871
6872         if (!i915_modparams.enable_ips)
6873                 return false;
6874
6875         if (crtc_state->pipe_bpp > 24)
6876                 return false;
6877
6878         /*
6879          * We compare against max which means we must take
6880          * the increased cdclk requirement into account when
6881          * calculating the new cdclk.
6882          *
6883          * Should measure whether using a lower cdclk w/o IPS
6884          */
6885         if (IS_BROADWELL(dev_priv) &&
6886             crtc_state->pixel_rate > dev_priv->max_cdclk_freq * 95 / 100)
6887                 return false;
6888
6889         return true;
6890 }
6891
6892 static bool hsw_compute_ips_config(struct intel_crtc_state *crtc_state)
6893 {
6894         struct drm_i915_private *dev_priv =
6895                 to_i915(crtc_state->base.crtc->dev);
6896         struct intel_atomic_state *intel_state =
6897                 to_intel_atomic_state(crtc_state->base.state);
6898
6899         if (!hsw_crtc_state_ips_capable(crtc_state))
6900                 return false;
6901
6902         /*
6903          * When IPS gets enabled, the pipe CRC changes. Since IPS gets
6904          * enabled and disabled dynamically based on package C states,
6905          * user space can't make reliable use of the CRCs, so let's just
6906          * completely disable it.
6907          */
6908         if (crtc_state->crc_enabled)
6909                 return false;
6910
6911         /* IPS should be fine as long as at least one plane is enabled. */
6912         if (!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)))
6913                 return false;
6914
6915         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
6916         if (IS_BROADWELL(dev_priv) &&
6917             crtc_state->pixel_rate > intel_state->cdclk.logical.cdclk * 95 / 100)
6918                 return false;
6919
6920         return true;
6921 }
6922
6923 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
6924 {
6925         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6926
6927         /* GDG double wide on either pipe, otherwise pipe A only */
6928         return INTEL_GEN(dev_priv) < 4 &&
6929                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
6930 }
6931
6932 static u32 ilk_pipe_pixel_rate(const struct intel_crtc_state *pipe_config)
6933 {
6934         u32 pixel_rate;
6935
6936         pixel_rate = pipe_config->base.adjusted_mode.crtc_clock;
6937
6938         /*
6939          * We only use IF-ID interlacing. If we ever use
6940          * PF-ID we'll need to adjust the pixel_rate here.
6941          */
6942
6943         if (pipe_config->pch_pfit.enabled) {
6944                 u64 pipe_w, pipe_h, pfit_w, pfit_h;
6945                 u32 pfit_size = pipe_config->pch_pfit.size;
6946
6947                 pipe_w = pipe_config->pipe_src_w;
6948                 pipe_h = pipe_config->pipe_src_h;
6949
6950                 pfit_w = (pfit_size >> 16) & 0xFFFF;
6951                 pfit_h = pfit_size & 0xFFFF;
6952                 if (pipe_w < pfit_w)
6953                         pipe_w = pfit_w;
6954                 if (pipe_h < pfit_h)
6955                         pipe_h = pfit_h;
6956
6957                 if (WARN_ON(!pfit_w || !pfit_h))
6958                         return pixel_rate;
6959
6960                 pixel_rate = div_u64(mul_u32_u32(pixel_rate, pipe_w * pipe_h),
6961                                      pfit_w * pfit_h);
6962         }
6963
6964         return pixel_rate;
6965 }
6966
6967 static void intel_crtc_compute_pixel_rate(struct intel_crtc_state *crtc_state)
6968 {
6969         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
6970
6971         if (HAS_GMCH(dev_priv))
6972                 /* FIXME calculate proper pipe pixel rate for GMCH pfit */
6973                 crtc_state->pixel_rate =
6974                         crtc_state->base.adjusted_mode.crtc_clock;
6975         else
6976                 crtc_state->pixel_rate =
6977                         ilk_pipe_pixel_rate(crtc_state);
6978 }
6979
6980 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6981                                      struct intel_crtc_state *pipe_config)
6982 {
6983         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6984         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6985         int clock_limit = dev_priv->max_dotclk_freq;
6986
6987         if (INTEL_GEN(dev_priv) < 4) {
6988                 clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
6989
6990                 /*
6991                  * Enable double wide mode when the dot clock
6992                  * is > 90% of the (display) core speed.
6993                  */
6994                 if (intel_crtc_supports_double_wide(crtc) &&
6995                     adjusted_mode->crtc_clock > clock_limit) {
6996                         clock_limit = dev_priv->max_dotclk_freq;
6997                         pipe_config->double_wide = true;
6998                 }
6999         }
7000
7001         if (adjusted_mode->crtc_clock > clock_limit) {
7002                 DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
7003                               adjusted_mode->crtc_clock, clock_limit,
7004                               yesno(pipe_config->double_wide));
7005                 return -EINVAL;
7006         }
7007
7008         if ((pipe_config->output_format == INTEL_OUTPUT_FORMAT_YCBCR420 ||
7009              pipe_config->output_format == INTEL_OUTPUT_FORMAT_YCBCR444) &&
7010              pipe_config->base.ctm) {
7011                 /*
7012                  * There is only one pipe CSC unit per pipe, and we need that
7013                  * for output conversion from RGB->YCBCR. So if CTM is already
7014                  * applied we can't support YCBCR420 output.
7015                  */
7016                 DRM_DEBUG_KMS("YCBCR420 and CTM together are not possible\n");
7017                 return -EINVAL;
7018         }
7019
7020         /*
7021          * Pipe horizontal size must be even in:
7022          * - DVO ganged mode
7023          * - LVDS dual channel mode
7024          * - Double wide pipe
7025          */
7026         if (pipe_config->pipe_src_w & 1) {
7027                 if (pipe_config->double_wide) {
7028                         DRM_DEBUG_KMS("Odd pipe source width not supported with double wide pipe\n");
7029                         return -EINVAL;
7030                 }
7031
7032                 if (intel_crtc_has_type(pipe_config, INTEL_OUTPUT_LVDS) &&
7033                     intel_is_dual_link_lvds(dev_priv)) {
7034                         DRM_DEBUG_KMS("Odd pipe source width not supported with dual link LVDS\n");
7035                         return -EINVAL;
7036                 }
7037         }
7038
7039         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
7040          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
7041          */
7042         if ((INTEL_GEN(dev_priv) > 4 || IS_G4X(dev_priv)) &&
7043                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
7044                 return -EINVAL;
7045
7046         intel_crtc_compute_pixel_rate(pipe_config);
7047
7048         if (pipe_config->has_pch_encoder)
7049                 return ironlake_fdi_compute_config(crtc, pipe_config);
7050
7051         return 0;
7052 }
7053
7054 static void
7055 intel_reduce_m_n_ratio(u32 *num, u32 *den)
7056 {
7057         while (*num > DATA_LINK_M_N_MASK ||
7058                *den > DATA_LINK_M_N_MASK) {
7059                 *num >>= 1;
7060                 *den >>= 1;
7061         }
7062 }
7063
7064 static void compute_m_n(unsigned int m, unsigned int n,
7065                         u32 *ret_m, u32 *ret_n,
7066                         bool constant_n)
7067 {
7068         /*
7069          * Several DP dongles in particular seem to be fussy about
7070          * too large link M/N values. Give N value as 0x8000 that
7071          * should be acceptable by specific devices. 0x8000 is the
7072          * specified fixed N value for asynchronous clock mode,
7073          * which the devices expect also in synchronous clock mode.
7074          */
7075         if (constant_n)
7076                 *ret_n = 0x8000;
7077         else
7078                 *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
7079
7080         *ret_m = div_u64(mul_u32_u32(m, *ret_n), n);
7081         intel_reduce_m_n_ratio(ret_m, ret_n);
7082 }
7083
7084 void
7085 intel_link_compute_m_n(u16 bits_per_pixel, int nlanes,
7086                        int pixel_clock, int link_clock,
7087                        struct intel_link_m_n *m_n,
7088                        bool constant_n)
7089 {
7090         m_n->tu = 64;
7091
7092         compute_m_n(bits_per_pixel * pixel_clock,
7093                     link_clock * nlanes * 8,
7094                     &m_n->gmch_m, &m_n->gmch_n,
7095                     constant_n);
7096
7097         compute_m_n(pixel_clock, link_clock,
7098                     &m_n->link_m, &m_n->link_n,
7099                     constant_n);
7100 }
7101
7102 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
7103 {
7104         if (i915_modparams.panel_use_ssc >= 0)
7105                 return i915_modparams.panel_use_ssc != 0;
7106         return dev_priv->vbt.lvds_use_ssc
7107                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
7108 }
7109
7110 static u32 pnv_dpll_compute_fp(struct dpll *dpll)
7111 {
7112         return (1 << dpll->n) << 16 | dpll->m2;
7113 }
7114
7115 static u32 i9xx_dpll_compute_fp(struct dpll *dpll)
7116 {
7117         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
7118 }
7119
7120 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
7121                                      struct intel_crtc_state *crtc_state,
7122                                      struct dpll *reduced_clock)
7123 {
7124         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7125         u32 fp, fp2 = 0;
7126
7127         if (IS_PINEVIEW(dev_priv)) {
7128                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
7129                 if (reduced_clock)
7130                         fp2 = pnv_dpll_compute_fp(reduced_clock);
7131         } else {
7132                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
7133                 if (reduced_clock)
7134                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
7135         }
7136
7137         crtc_state->dpll_hw_state.fp0 = fp;
7138
7139         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7140             reduced_clock) {
7141                 crtc_state->dpll_hw_state.fp1 = fp2;
7142         } else {
7143                 crtc_state->dpll_hw_state.fp1 = fp;
7144         }
7145 }
7146
7147 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
7148                 pipe)
7149 {
7150         u32 reg_val;
7151
7152         /*
7153          * PLLB opamp always calibrates to max value of 0x3f, force enable it
7154          * and set it to a reasonable value instead.
7155          */
7156         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7157         reg_val &= 0xffffff00;
7158         reg_val |= 0x00000030;
7159         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7160
7161         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7162         reg_val &= 0x00ffffff;
7163         reg_val |= 0x8c000000;
7164         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7165
7166         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7167         reg_val &= 0xffffff00;
7168         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7169
7170         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7171         reg_val &= 0x00ffffff;
7172         reg_val |= 0xb0000000;
7173         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7174 }
7175
7176 static void intel_pch_transcoder_set_m_n(const struct intel_crtc_state *crtc_state,
7177                                          const struct intel_link_m_n *m_n)
7178 {
7179         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
7180         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7181         enum pipe pipe = crtc->pipe;
7182
7183         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7184         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
7185         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
7186         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
7187 }
7188
7189 static bool transcoder_has_m2_n2(struct drm_i915_private *dev_priv,
7190                                  enum transcoder transcoder)
7191 {
7192         if (IS_HASWELL(dev_priv))
7193                 return transcoder == TRANSCODER_EDP;
7194
7195         /*
7196          * Strictly speaking some registers are available before
7197          * gen7, but we only support DRRS on gen7+
7198          */
7199         return IS_GEN(dev_priv, 7) || IS_CHERRYVIEW(dev_priv);
7200 }
7201
7202 static void intel_cpu_transcoder_set_m_n(const struct intel_crtc_state *crtc_state,
7203                                          const struct intel_link_m_n *m_n,
7204                                          const struct intel_link_m_n *m2_n2)
7205 {
7206         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
7207         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7208         enum pipe pipe = crtc->pipe;
7209         enum transcoder transcoder = crtc_state->cpu_transcoder;
7210
7211         if (INTEL_GEN(dev_priv) >= 5) {
7212                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
7213                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
7214                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
7215                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
7216                 /*
7217                  *  M2_N2 registers are set only if DRRS is supported
7218                  * (to make sure the registers are not unnecessarily accessed).
7219                  */
7220                 if (m2_n2 && crtc_state->has_drrs &&
7221                     transcoder_has_m2_n2(dev_priv, transcoder)) {
7222                         I915_WRITE(PIPE_DATA_M2(transcoder),
7223                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
7224                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
7225                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
7226                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
7227                 }
7228         } else {
7229                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7230                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
7231                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
7232                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
7233         }
7234 }
7235
7236 void intel_dp_set_m_n(const struct intel_crtc_state *crtc_state, enum link_m_n_set m_n)
7237 {
7238         const struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
7239
7240         if (m_n == M1_N1) {
7241                 dp_m_n = &crtc_state->dp_m_n;
7242                 dp_m2_n2 = &crtc_state->dp_m2_n2;
7243         } else if (m_n == M2_N2) {
7244
7245                 /*
7246                  * M2_N2 registers are not supported. Hence m2_n2 divider value
7247                  * needs to be programmed into M1_N1.
7248                  */
7249                 dp_m_n = &crtc_state->dp_m2_n2;
7250         } else {
7251                 DRM_ERROR("Unsupported divider value\n");
7252                 return;
7253         }
7254
7255         if (crtc_state->has_pch_encoder)
7256                 intel_pch_transcoder_set_m_n(crtc_state, &crtc_state->dp_m_n);
7257         else
7258                 intel_cpu_transcoder_set_m_n(crtc_state, dp_m_n, dp_m2_n2);
7259 }
7260
7261 static void vlv_compute_dpll(struct intel_crtc *crtc,
7262                              struct intel_crtc_state *pipe_config)
7263 {
7264         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
7265                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7266         if (crtc->pipe != PIPE_A)
7267                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7268
7269         /* DPLL not used with DSI, but still need the rest set up */
7270         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
7271                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
7272                         DPLL_EXT_BUFFER_ENABLE_VLV;
7273
7274         pipe_config->dpll_hw_state.dpll_md =
7275                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7276 }
7277
7278 static void chv_compute_dpll(struct intel_crtc *crtc,
7279                              struct intel_crtc_state *pipe_config)
7280 {
7281         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
7282                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7283         if (crtc->pipe != PIPE_A)
7284                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7285
7286         /* DPLL not used with DSI, but still need the rest set up */
7287         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
7288                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE;
7289
7290         pipe_config->dpll_hw_state.dpll_md =
7291                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7292 }
7293
7294 static void vlv_prepare_pll(struct intel_crtc *crtc,
7295                             const struct intel_crtc_state *pipe_config)
7296 {
7297         struct drm_device *dev = crtc->base.dev;
7298         struct drm_i915_private *dev_priv = to_i915(dev);
7299         enum pipe pipe = crtc->pipe;
7300         u32 mdiv;
7301         u32 bestn, bestm1, bestm2, bestp1, bestp2;
7302         u32 coreclk, reg_val;
7303
7304         /* Enable Refclk */
7305         I915_WRITE(DPLL(pipe),
7306                    pipe_config->dpll_hw_state.dpll &
7307                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
7308
7309         /* No need to actually set up the DPLL with DSI */
7310         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7311                 return;
7312
7313         vlv_dpio_get(dev_priv);
7314
7315         bestn = pipe_config->dpll.n;
7316         bestm1 = pipe_config->dpll.m1;
7317         bestm2 = pipe_config->dpll.m2;
7318         bestp1 = pipe_config->dpll.p1;
7319         bestp2 = pipe_config->dpll.p2;
7320
7321         /* See eDP HDMI DPIO driver vbios notes doc */
7322
7323         /* PLL B needs special handling */
7324         if (pipe == PIPE_B)
7325                 vlv_pllb_recal_opamp(dev_priv, pipe);
7326
7327         /* Set up Tx target for periodic Rcomp update */
7328         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
7329
7330         /* Disable target IRef on PLL */
7331         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
7332         reg_val &= 0x00ffffff;
7333         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
7334
7335         /* Disable fast lock */
7336         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
7337
7338         /* Set idtafcrecal before PLL is enabled */
7339         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
7340         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
7341         mdiv |= ((bestn << DPIO_N_SHIFT));
7342         mdiv |= (1 << DPIO_K_SHIFT);
7343
7344         /*
7345          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
7346          * but we don't support that).
7347          * Note: don't use the DAC post divider as it seems unstable.
7348          */
7349         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
7350         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7351
7352         mdiv |= DPIO_ENABLE_CALIBRATION;
7353         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7354
7355         /* Set HBR and RBR LPF coefficients */
7356         if (pipe_config->port_clock == 162000 ||
7357             intel_crtc_has_type(pipe_config, INTEL_OUTPUT_ANALOG) ||
7358             intel_crtc_has_type(pipe_config, INTEL_OUTPUT_HDMI))
7359                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7360                                  0x009f0003);
7361         else
7362                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7363                                  0x00d0000f);
7364
7365         if (intel_crtc_has_dp_encoder(pipe_config)) {
7366                 /* Use SSC source */
7367                 if (pipe == PIPE_A)
7368                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7369                                          0x0df40000);
7370                 else
7371                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7372                                          0x0df70000);
7373         } else { /* HDMI or VGA */
7374                 /* Use bend source */
7375                 if (pipe == PIPE_A)
7376                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7377                                          0x0df70000);
7378                 else
7379                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7380                                          0x0df40000);
7381         }
7382
7383         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
7384         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
7385         if (intel_crtc_has_dp_encoder(pipe_config))
7386                 coreclk |= 0x01000000;
7387         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
7388
7389         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
7390
7391         vlv_dpio_put(dev_priv);
7392 }
7393
7394 static void chv_prepare_pll(struct intel_crtc *crtc,
7395                             const struct intel_crtc_state *pipe_config)
7396 {
7397         struct drm_device *dev = crtc->base.dev;
7398         struct drm_i915_private *dev_priv = to_i915(dev);
7399         enum pipe pipe = crtc->pipe;
7400         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7401         u32 loopfilter, tribuf_calcntr;
7402         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
7403         u32 dpio_val;
7404         int vco;
7405
7406         /* Enable Refclk and SSC */
7407         I915_WRITE(DPLL(pipe),
7408                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
7409
7410         /* No need to actually set up the DPLL with DSI */
7411         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7412                 return;
7413
7414         bestn = pipe_config->dpll.n;
7415         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
7416         bestm1 = pipe_config->dpll.m1;
7417         bestm2 = pipe_config->dpll.m2 >> 22;
7418         bestp1 = pipe_config->dpll.p1;
7419         bestp2 = pipe_config->dpll.p2;
7420         vco = pipe_config->dpll.vco;
7421         dpio_val = 0;
7422         loopfilter = 0;
7423
7424         vlv_dpio_get(dev_priv);
7425
7426         /* p1 and p2 divider */
7427         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
7428                         5 << DPIO_CHV_S1_DIV_SHIFT |
7429                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
7430                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
7431                         1 << DPIO_CHV_K_DIV_SHIFT);
7432
7433         /* Feedback post-divider - m2 */
7434         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
7435
7436         /* Feedback refclk divider - n and m1 */
7437         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
7438                         DPIO_CHV_M1_DIV_BY_2 |
7439                         1 << DPIO_CHV_N_DIV_SHIFT);
7440
7441         /* M2 fraction division */
7442         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
7443
7444         /* M2 fraction division enable */
7445         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7446         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
7447         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
7448         if (bestm2_frac)
7449                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
7450         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
7451
7452         /* Program digital lock detect threshold */
7453         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
7454         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
7455                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
7456         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
7457         if (!bestm2_frac)
7458                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
7459         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
7460
7461         /* Loop filter */
7462         if (vco == 5400000) {
7463                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
7464                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
7465                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
7466                 tribuf_calcntr = 0x9;
7467         } else if (vco <= 6200000) {
7468                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
7469                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
7470                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7471                 tribuf_calcntr = 0x9;
7472         } else if (vco <= 6480000) {
7473                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7474                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7475                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7476                 tribuf_calcntr = 0x8;
7477         } else {
7478                 /* Not supported. Apply the same limits as in the max case */
7479                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7480                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7481                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7482                 tribuf_calcntr = 0;
7483         }
7484         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
7485
7486         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
7487         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
7488         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
7489         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
7490
7491         /* AFC Recal */
7492         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
7493                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
7494                         DPIO_AFC_RECAL);
7495
7496         vlv_dpio_put(dev_priv);
7497 }
7498
7499 /**
7500  * vlv_force_pll_on - forcibly enable just the PLL
7501  * @dev_priv: i915 private structure
7502  * @pipe: pipe PLL to enable
7503  * @dpll: PLL configuration
7504  *
7505  * Enable the PLL for @pipe using the supplied @dpll config. To be used
7506  * in cases where we need the PLL enabled even when @pipe is not going to
7507  * be enabled.
7508  */
7509 int vlv_force_pll_on(struct drm_i915_private *dev_priv, enum pipe pipe,
7510                      const struct dpll *dpll)
7511 {
7512         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
7513         struct intel_crtc_state *pipe_config;
7514
7515         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
7516         if (!pipe_config)
7517                 return -ENOMEM;
7518
7519         pipe_config->base.crtc = &crtc->base;
7520         pipe_config->pixel_multiplier = 1;
7521         pipe_config->dpll = *dpll;
7522
7523         if (IS_CHERRYVIEW(dev_priv)) {
7524                 chv_compute_dpll(crtc, pipe_config);
7525                 chv_prepare_pll(crtc, pipe_config);
7526                 chv_enable_pll(crtc, pipe_config);
7527         } else {
7528                 vlv_compute_dpll(crtc, pipe_config);
7529                 vlv_prepare_pll(crtc, pipe_config);
7530                 vlv_enable_pll(crtc, pipe_config);
7531         }
7532
7533         kfree(pipe_config);
7534
7535         return 0;
7536 }
7537
7538 /**
7539  * vlv_force_pll_off - forcibly disable just the PLL
7540  * @dev_priv: i915 private structure
7541  * @pipe: pipe PLL to disable
7542  *
7543  * Disable the PLL for @pipe. To be used in cases where we need
7544  * the PLL enabled even when @pipe is not going to be enabled.
7545  */
7546 void vlv_force_pll_off(struct drm_i915_private *dev_priv, enum pipe pipe)
7547 {
7548         if (IS_CHERRYVIEW(dev_priv))
7549                 chv_disable_pll(dev_priv, pipe);
7550         else
7551                 vlv_disable_pll(dev_priv, pipe);
7552 }
7553
7554 static void i9xx_compute_dpll(struct intel_crtc *crtc,
7555                               struct intel_crtc_state *crtc_state,
7556                               struct dpll *reduced_clock)
7557 {
7558         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7559         u32 dpll;
7560         struct dpll *clock = &crtc_state->dpll;
7561
7562         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7563
7564         dpll = DPLL_VGA_MODE_DIS;
7565
7566         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
7567                 dpll |= DPLLB_MODE_LVDS;
7568         else
7569                 dpll |= DPLLB_MODE_DAC_SERIAL;
7570
7571         if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
7572             IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
7573                 dpll |= (crtc_state->pixel_multiplier - 1)
7574                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7575         }
7576
7577         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7578             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
7579                 dpll |= DPLL_SDVO_HIGH_SPEED;
7580
7581         if (intel_crtc_has_dp_encoder(crtc_state))
7582                 dpll |= DPLL_SDVO_HIGH_SPEED;
7583
7584         /* compute bitmask from p1 value */
7585         if (IS_PINEVIEW(dev_priv))
7586                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7587         else {
7588                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7589                 if (IS_G4X(dev_priv) && reduced_clock)
7590                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7591         }
7592         switch (clock->p2) {
7593         case 5:
7594                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7595                 break;
7596         case 7:
7597                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7598                 break;
7599         case 10:
7600                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7601                 break;
7602         case 14:
7603                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7604                 break;
7605         }
7606         if (INTEL_GEN(dev_priv) >= 4)
7607                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7608
7609         if (crtc_state->sdvo_tv_clock)
7610                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7611         else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7612                  intel_panel_use_ssc(dev_priv))
7613                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7614         else
7615                 dpll |= PLL_REF_INPUT_DREFCLK;
7616
7617         dpll |= DPLL_VCO_ENABLE;
7618         crtc_state->dpll_hw_state.dpll = dpll;
7619
7620         if (INTEL_GEN(dev_priv) >= 4) {
7621                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7622                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7623                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7624         }
7625 }
7626
7627 static void i8xx_compute_dpll(struct intel_crtc *crtc,
7628                               struct intel_crtc_state *crtc_state,
7629                               struct dpll *reduced_clock)
7630 {
7631         struct drm_device *dev = crtc->base.dev;
7632         struct drm_i915_private *dev_priv = to_i915(dev);
7633         u32 dpll;
7634         struct dpll *clock = &crtc_state->dpll;
7635
7636         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7637
7638         dpll = DPLL_VGA_MODE_DIS;
7639
7640         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7641                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7642         } else {
7643                 if (clock->p1 == 2)
7644                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7645                 else
7646                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7647                 if (clock->p2 == 4)
7648                         dpll |= PLL_P2_DIVIDE_BY_4;
7649         }
7650
7651         /*
7652          * Bspec:
7653          * "[Almador Errata}: For the correct operation of the muxed DVO pins
7654          *  (GDEVSELB/I2Cdata, GIRDBY/I2CClk) and (GFRAMEB/DVI_Data,
7655          *  GTRDYB/DVI_Clk): Bit 31 (DPLL VCO Enable) and Bit 30 (2X Clock
7656          *  Enable) must be set to “1” in both the DPLL A Control Register
7657          *  (06014h-06017h) and DPLL B Control Register (06018h-0601Bh)."
7658          *
7659          * For simplicity We simply keep both bits always enabled in
7660          * both DPLLS. The spec says we should disable the DVO 2X clock
7661          * when not needed, but this seems to work fine in practice.
7662          */
7663         if (IS_I830(dev_priv) ||
7664             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO))
7665                 dpll |= DPLL_DVO_2X_MODE;
7666
7667         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7668             intel_panel_use_ssc(dev_priv))
7669                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7670         else
7671                 dpll |= PLL_REF_INPUT_DREFCLK;
7672
7673         dpll |= DPLL_VCO_ENABLE;
7674         crtc_state->dpll_hw_state.dpll = dpll;
7675 }
7676
7677 static void intel_set_pipe_timings(const struct intel_crtc_state *crtc_state)
7678 {
7679         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
7680         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7681         enum pipe pipe = crtc->pipe;
7682         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
7683         const struct drm_display_mode *adjusted_mode = &crtc_state->base.adjusted_mode;
7684         u32 crtc_vtotal, crtc_vblank_end;
7685         int vsyncshift = 0;
7686
7687         /* We need to be careful not to changed the adjusted mode, for otherwise
7688          * the hw state checker will get angry at the mismatch. */
7689         crtc_vtotal = adjusted_mode->crtc_vtotal;
7690         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7691
7692         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7693                 /* the chip adds 2 halflines automatically */
7694                 crtc_vtotal -= 1;
7695                 crtc_vblank_end -= 1;
7696
7697                 if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO))
7698                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7699                 else
7700                         vsyncshift = adjusted_mode->crtc_hsync_start -
7701                                 adjusted_mode->crtc_htotal / 2;
7702                 if (vsyncshift < 0)
7703                         vsyncshift += adjusted_mode->crtc_htotal;
7704         }
7705
7706         if (INTEL_GEN(dev_priv) > 3)
7707                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7708
7709         I915_WRITE(HTOTAL(cpu_transcoder),
7710                    (adjusted_mode->crtc_hdisplay - 1) |
7711                    ((adjusted_mode->crtc_htotal - 1) << 16));
7712         I915_WRITE(HBLANK(cpu_transcoder),
7713                    (adjusted_mode->crtc_hblank_start - 1) |
7714                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7715         I915_WRITE(HSYNC(cpu_transcoder),
7716                    (adjusted_mode->crtc_hsync_start - 1) |
7717                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7718
7719         I915_WRITE(VTOTAL(cpu_transcoder),
7720                    (adjusted_mode->crtc_vdisplay - 1) |
7721                    ((crtc_vtotal - 1) << 16));
7722         I915_WRITE(VBLANK(cpu_transcoder),
7723                    (adjusted_mode->crtc_vblank_start - 1) |
7724                    ((crtc_vblank_end - 1) << 16));
7725         I915_WRITE(VSYNC(cpu_transcoder),
7726                    (adjusted_mode->crtc_vsync_start - 1) |
7727                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7728
7729         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7730          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7731          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7732          * bits. */
7733         if (IS_HASWELL(dev_priv) && cpu_transcoder == TRANSCODER_EDP &&
7734             (pipe == PIPE_B || pipe == PIPE_C))
7735                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7736
7737 }
7738
7739 static void intel_set_pipe_src_size(const struct intel_crtc_state *crtc_state)
7740 {
7741         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
7742         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7743         enum pipe pipe = crtc->pipe;
7744
7745         /* pipesrc controls the size that is scaled from, which should
7746          * always be the user's requested size.
7747          */
7748         I915_WRITE(PIPESRC(pipe),
7749                    ((crtc_state->pipe_src_w - 1) << 16) |
7750                    (crtc_state->pipe_src_h - 1));
7751 }
7752
7753 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7754                                    struct intel_crtc_state *pipe_config)
7755 {
7756         struct drm_device *dev = crtc->base.dev;
7757         struct drm_i915_private *dev_priv = to_i915(dev);
7758         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7759         u32 tmp;
7760
7761         tmp = I915_READ(HTOTAL(cpu_transcoder));
7762         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7763         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7764
7765         if (!transcoder_is_dsi(cpu_transcoder)) {
7766                 tmp = I915_READ(HBLANK(cpu_transcoder));
7767                 pipe_config->base.adjusted_mode.crtc_hblank_start =
7768                                                         (tmp & 0xffff) + 1;
7769                 pipe_config->base.adjusted_mode.crtc_hblank_end =
7770                                                 ((tmp >> 16) & 0xffff) + 1;
7771         }
7772         tmp = I915_READ(HSYNC(cpu_transcoder));
7773         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7774         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7775
7776         tmp = I915_READ(VTOTAL(cpu_transcoder));
7777         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7778         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7779
7780         if (!transcoder_is_dsi(cpu_transcoder)) {
7781                 tmp = I915_READ(VBLANK(cpu_transcoder));
7782                 pipe_config->base.adjusted_mode.crtc_vblank_start =
7783                                                         (tmp & 0xffff) + 1;
7784                 pipe_config->base.adjusted_mode.crtc_vblank_end =
7785                                                 ((tmp >> 16) & 0xffff) + 1;
7786         }
7787         tmp = I915_READ(VSYNC(cpu_transcoder));
7788         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7789         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7790
7791         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7792                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7793                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7794                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7795         }
7796 }
7797
7798 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
7799                                     struct intel_crtc_state *pipe_config)
7800 {
7801         struct drm_device *dev = crtc->base.dev;
7802         struct drm_i915_private *dev_priv = to_i915(dev);
7803         u32 tmp;
7804
7805         tmp = I915_READ(PIPESRC(crtc->pipe));
7806         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7807         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7808
7809         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7810         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7811 }
7812
7813 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7814                                  struct intel_crtc_state *pipe_config)
7815 {
7816         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7817         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7818         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7819         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7820
7821         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7822         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7823         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7824         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7825
7826         mode->flags = pipe_config->base.adjusted_mode.flags;
7827         mode->type = DRM_MODE_TYPE_DRIVER;
7828
7829         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7830
7831         mode->hsync = drm_mode_hsync(mode);
7832         mode->vrefresh = drm_mode_vrefresh(mode);
7833         drm_mode_set_name(mode);
7834 }
7835
7836 static void i9xx_set_pipeconf(const struct intel_crtc_state *crtc_state)
7837 {
7838         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
7839         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7840         u32 pipeconf;
7841
7842         pipeconf = 0;
7843
7844         /* we keep both pipes enabled on 830 */
7845         if (IS_I830(dev_priv))
7846                 pipeconf |= I915_READ(PIPECONF(crtc->pipe)) & PIPECONF_ENABLE;
7847
7848         if (crtc_state->double_wide)
7849                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7850
7851         /* only g4x and later have fancy bpc/dither controls */
7852         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7853             IS_CHERRYVIEW(dev_priv)) {
7854                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7855                 if (crtc_state->dither && crtc_state->pipe_bpp != 30)
7856                         pipeconf |= PIPECONF_DITHER_EN |
7857                                     PIPECONF_DITHER_TYPE_SP;
7858
7859                 switch (crtc_state->pipe_bpp) {
7860                 case 18:
7861                         pipeconf |= PIPECONF_6BPC;
7862                         break;
7863                 case 24:
7864                         pipeconf |= PIPECONF_8BPC;
7865                         break;
7866                 case 30:
7867                         pipeconf |= PIPECONF_10BPC;
7868                         break;
7869                 default:
7870                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7871                         BUG();
7872                 }
7873         }
7874
7875         if (crtc_state->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7876                 if (INTEL_GEN(dev_priv) < 4 ||
7877                     intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO))
7878                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7879                 else
7880                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7881         } else {
7882                 pipeconf |= PIPECONF_PROGRESSIVE;
7883         }
7884
7885         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7886              crtc_state->limited_color_range)
7887                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7888
7889         pipeconf |= PIPECONF_GAMMA_MODE(crtc_state->gamma_mode);
7890
7891         I915_WRITE(PIPECONF(crtc->pipe), pipeconf);
7892         POSTING_READ(PIPECONF(crtc->pipe));
7893 }
7894
7895 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
7896                                    struct intel_crtc_state *crtc_state)
7897 {
7898         struct drm_device *dev = crtc->base.dev;
7899         struct drm_i915_private *dev_priv = to_i915(dev);
7900         const struct intel_limit *limit;
7901         int refclk = 48000;
7902
7903         memset(&crtc_state->dpll_hw_state, 0,
7904                sizeof(crtc_state->dpll_hw_state));
7905
7906         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7907                 if (intel_panel_use_ssc(dev_priv)) {
7908                         refclk = dev_priv->vbt.lvds_ssc_freq;
7909                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7910                 }
7911
7912                 limit = &intel_limits_i8xx_lvds;
7913         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO)) {
7914                 limit = &intel_limits_i8xx_dvo;
7915         } else {
7916                 limit = &intel_limits_i8xx_dac;
7917         }
7918
7919         if (!crtc_state->clock_set &&
7920             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7921                                  refclk, NULL, &crtc_state->dpll)) {
7922                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7923                 return -EINVAL;
7924         }
7925
7926         i8xx_compute_dpll(crtc, crtc_state, NULL);
7927
7928         return 0;
7929 }
7930
7931 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
7932                                   struct intel_crtc_state *crtc_state)
7933 {
7934         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7935         const struct intel_limit *limit;
7936         int refclk = 96000;
7937
7938         memset(&crtc_state->dpll_hw_state, 0,
7939                sizeof(crtc_state->dpll_hw_state));
7940
7941         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7942                 if (intel_panel_use_ssc(dev_priv)) {
7943                         refclk = dev_priv->vbt.lvds_ssc_freq;
7944                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7945                 }
7946
7947                 if (intel_is_dual_link_lvds(dev_priv))
7948                         limit = &intel_limits_g4x_dual_channel_lvds;
7949                 else
7950                         limit = &intel_limits_g4x_single_channel_lvds;
7951         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI) ||
7952                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
7953                 limit = &intel_limits_g4x_hdmi;
7954         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO)) {
7955                 limit = &intel_limits_g4x_sdvo;
7956         } else {
7957                 /* The option is for other outputs */
7958                 limit = &intel_limits_i9xx_sdvo;
7959         }
7960
7961         if (!crtc_state->clock_set &&
7962             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7963                                 refclk, NULL, &crtc_state->dpll)) {
7964                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7965                 return -EINVAL;
7966         }
7967
7968         i9xx_compute_dpll(crtc, crtc_state, NULL);
7969
7970         return 0;
7971 }
7972
7973 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
7974                                   struct intel_crtc_state *crtc_state)
7975 {
7976         struct drm_device *dev = crtc->base.dev;
7977         struct drm_i915_private *dev_priv = to_i915(dev);
7978         const struct intel_limit *limit;
7979         int refclk = 96000;
7980
7981         memset(&crtc_state->dpll_hw_state, 0,
7982                sizeof(crtc_state->dpll_hw_state));
7983
7984         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7985                 if (intel_panel_use_ssc(dev_priv)) {
7986                         refclk = dev_priv->vbt.lvds_ssc_freq;
7987                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7988                 }
7989
7990                 limit = &intel_limits_pineview_lvds;
7991         } else {
7992                 limit = &intel_limits_pineview_sdvo;
7993         }
7994
7995         if (!crtc_state->clock_set &&
7996             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7997                                 refclk, NULL, &crtc_state->dpll)) {
7998                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7999                 return -EINVAL;
8000         }
8001
8002         i9xx_compute_dpll(crtc, crtc_state, NULL);
8003
8004         return 0;
8005 }
8006
8007 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
8008                                    struct intel_crtc_state *crtc_state)
8009 {
8010         struct drm_device *dev = crtc->base.dev;
8011         struct drm_i915_private *dev_priv = to_i915(dev);
8012         const struct intel_limit *limit;
8013         int refclk = 96000;
8014
8015         memset(&crtc_state->dpll_hw_state, 0,
8016                sizeof(crtc_state->dpll_hw_state));
8017
8018         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8019                 if (intel_panel_use_ssc(dev_priv)) {
8020                         refclk = dev_priv->vbt.lvds_ssc_freq;
8021                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8022                 }
8023
8024                 limit = &intel_limits_i9xx_lvds;
8025         } else {
8026                 limit = &intel_limits_i9xx_sdvo;
8027         }
8028
8029         if (!crtc_state->clock_set &&
8030             !i9xx_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         i9xx_compute_dpll(crtc, crtc_state, NULL);
8037
8038         return 0;
8039 }
8040
8041 static int chv_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_chv;
8046
8047         memset(&crtc_state->dpll_hw_state, 0,
8048                sizeof(crtc_state->dpll_hw_state));
8049
8050         if (!crtc_state->clock_set &&
8051             !chv_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         chv_compute_dpll(crtc, crtc_state);
8058
8059         return 0;
8060 }
8061
8062 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
8063                                   struct intel_crtc_state *crtc_state)
8064 {
8065         int refclk = 100000;
8066         const struct intel_limit *limit = &intel_limits_vlv;
8067
8068         memset(&crtc_state->dpll_hw_state, 0,
8069                sizeof(crtc_state->dpll_hw_state));
8070
8071         if (!crtc_state->clock_set &&
8072             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8073                                 refclk, NULL, &crtc_state->dpll)) {
8074                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8075                 return -EINVAL;
8076         }
8077
8078         vlv_compute_dpll(crtc, crtc_state);
8079
8080         return 0;
8081 }
8082
8083 static bool i9xx_has_pfit(struct drm_i915_private *dev_priv)
8084 {
8085         if (IS_I830(dev_priv))
8086                 return false;
8087
8088         return INTEL_GEN(dev_priv) >= 4 ||
8089                 IS_PINEVIEW(dev_priv) || IS_MOBILE(dev_priv);
8090 }
8091
8092 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
8093                                  struct intel_crtc_state *pipe_config)
8094 {
8095         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8096         u32 tmp;
8097
8098         if (!i9xx_has_pfit(dev_priv))
8099                 return;
8100
8101         tmp = I915_READ(PFIT_CONTROL);
8102         if (!(tmp & PFIT_ENABLE))
8103                 return;
8104
8105         /* Check whether the pfit is attached to our pipe. */
8106         if (INTEL_GEN(dev_priv) < 4) {
8107                 if (crtc->pipe != PIPE_B)
8108                         return;
8109         } else {
8110                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
8111                         return;
8112         }
8113
8114         pipe_config->gmch_pfit.control = tmp;
8115         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
8116 }
8117
8118 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
8119                                struct intel_crtc_state *pipe_config)
8120 {
8121         struct drm_device *dev = crtc->base.dev;
8122         struct drm_i915_private *dev_priv = to_i915(dev);
8123         int pipe = pipe_config->cpu_transcoder;
8124         struct dpll clock;
8125         u32 mdiv;
8126         int refclk = 100000;
8127
8128         /* In case of DSI, DPLL will not be used */
8129         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
8130                 return;
8131
8132         vlv_dpio_get(dev_priv);
8133         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
8134         vlv_dpio_put(dev_priv);
8135
8136         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
8137         clock.m2 = mdiv & DPIO_M2DIV_MASK;
8138         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
8139         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
8140         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
8141
8142         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
8143 }
8144
8145 static void
8146 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
8147                               struct intel_initial_plane_config *plane_config)
8148 {
8149         struct drm_device *dev = crtc->base.dev;
8150         struct drm_i915_private *dev_priv = to_i915(dev);
8151         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
8152         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
8153         enum pipe pipe;
8154         u32 val, base, offset;
8155         int fourcc, pixel_format;
8156         unsigned int aligned_height;
8157         struct drm_framebuffer *fb;
8158         struct intel_framebuffer *intel_fb;
8159
8160         if (!plane->get_hw_state(plane, &pipe))
8161                 return;
8162
8163         WARN_ON(pipe != crtc->pipe);
8164
8165         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8166         if (!intel_fb) {
8167                 DRM_DEBUG_KMS("failed to alloc fb\n");
8168                 return;
8169         }
8170
8171         fb = &intel_fb->base;
8172
8173         fb->dev = dev;
8174
8175         val = I915_READ(DSPCNTR(i9xx_plane));
8176
8177         if (INTEL_GEN(dev_priv) >= 4) {
8178                 if (val & DISPPLANE_TILED) {
8179                         plane_config->tiling = I915_TILING_X;
8180                         fb->modifier = I915_FORMAT_MOD_X_TILED;
8181                 }
8182
8183                 if (val & DISPPLANE_ROTATE_180)
8184                         plane_config->rotation = DRM_MODE_ROTATE_180;
8185         }
8186
8187         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B &&
8188             val & DISPPLANE_MIRROR)
8189                 plane_config->rotation |= DRM_MODE_REFLECT_X;
8190
8191         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
8192         fourcc = i9xx_format_to_fourcc(pixel_format);
8193         fb->format = drm_format_info(fourcc);
8194
8195         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
8196                 offset = I915_READ(DSPOFFSET(i9xx_plane));
8197                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
8198         } else if (INTEL_GEN(dev_priv) >= 4) {
8199                 if (plane_config->tiling)
8200                         offset = I915_READ(DSPTILEOFF(i9xx_plane));
8201                 else
8202                         offset = I915_READ(DSPLINOFF(i9xx_plane));
8203                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
8204         } else {
8205                 base = I915_READ(DSPADDR(i9xx_plane));
8206         }
8207         plane_config->base = base;
8208
8209         val = I915_READ(PIPESRC(pipe));
8210         fb->width = ((val >> 16) & 0xfff) + 1;
8211         fb->height = ((val >> 0) & 0xfff) + 1;
8212
8213         val = I915_READ(DSPSTRIDE(i9xx_plane));
8214         fb->pitches[0] = val & 0xffffffc0;
8215
8216         aligned_height = intel_fb_align_height(fb, 0, fb->height);
8217
8218         plane_config->size = fb->pitches[0] * aligned_height;
8219
8220         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8221                       crtc->base.name, plane->base.name, fb->width, fb->height,
8222                       fb->format->cpp[0] * 8, base, fb->pitches[0],
8223                       plane_config->size);
8224
8225         plane_config->fb = intel_fb;
8226 }
8227
8228 static void chv_crtc_clock_get(struct intel_crtc *crtc,
8229                                struct intel_crtc_state *pipe_config)
8230 {
8231         struct drm_device *dev = crtc->base.dev;
8232         struct drm_i915_private *dev_priv = to_i915(dev);
8233         int pipe = pipe_config->cpu_transcoder;
8234         enum dpio_channel port = vlv_pipe_to_channel(pipe);
8235         struct dpll clock;
8236         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
8237         int refclk = 100000;
8238
8239         /* In case of DSI, DPLL will not be used */
8240         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
8241                 return;
8242
8243         vlv_dpio_get(dev_priv);
8244         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
8245         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
8246         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
8247         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
8248         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
8249         vlv_dpio_put(dev_priv);
8250
8251         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
8252         clock.m2 = (pll_dw0 & 0xff) << 22;
8253         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
8254                 clock.m2 |= pll_dw2 & 0x3fffff;
8255         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
8256         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
8257         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
8258
8259         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
8260 }
8261
8262 static void intel_get_crtc_ycbcr_config(struct intel_crtc *crtc,
8263                                         struct intel_crtc_state *pipe_config)
8264 {
8265         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8266         enum intel_output_format output = INTEL_OUTPUT_FORMAT_RGB;
8267
8268         pipe_config->lspcon_downsampling = false;
8269
8270         if (IS_BROADWELL(dev_priv) || INTEL_GEN(dev_priv) >= 9) {
8271                 u32 tmp = I915_READ(PIPEMISC(crtc->pipe));
8272
8273                 if (tmp & PIPEMISC_OUTPUT_COLORSPACE_YUV) {
8274                         bool ycbcr420_enabled = tmp & PIPEMISC_YUV420_ENABLE;
8275                         bool blend = tmp & PIPEMISC_YUV420_MODE_FULL_BLEND;
8276
8277                         if (ycbcr420_enabled) {
8278                                 /* We support 4:2:0 in full blend mode only */
8279                                 if (!blend)
8280                                         output = INTEL_OUTPUT_FORMAT_INVALID;
8281                                 else if (!(IS_GEMINILAKE(dev_priv) ||
8282                                            INTEL_GEN(dev_priv) >= 10))
8283                                         output = INTEL_OUTPUT_FORMAT_INVALID;
8284                                 else
8285                                         output = INTEL_OUTPUT_FORMAT_YCBCR420;
8286                         } else {
8287                                 /*
8288                                  * Currently there is no interface defined to
8289                                  * check user preference between RGB/YCBCR444
8290                                  * or YCBCR420. So the only possible case for
8291                                  * YCBCR444 usage is driving YCBCR420 output
8292                                  * with LSPCON, when pipe is configured for
8293                                  * YCBCR444 output and LSPCON takes care of
8294                                  * downsampling it.
8295                                  */
8296                                 pipe_config->lspcon_downsampling = true;
8297                                 output = INTEL_OUTPUT_FORMAT_YCBCR444;
8298                         }
8299                 }
8300         }
8301
8302         pipe_config->output_format = output;
8303 }
8304
8305 static void i9xx_get_pipe_color_config(struct intel_crtc_state *crtc_state)
8306 {
8307         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
8308         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
8309         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8310         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
8311         u32 tmp;
8312
8313         tmp = I915_READ(DSPCNTR(i9xx_plane));
8314
8315         if (tmp & DISPPLANE_GAMMA_ENABLE)
8316                 crtc_state->gamma_enable = true;
8317
8318         if (!HAS_GMCH(dev_priv) &&
8319             tmp & DISPPLANE_PIPE_CSC_ENABLE)
8320                 crtc_state->csc_enable = true;
8321 }
8322
8323 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
8324                                  struct intel_crtc_state *pipe_config)
8325 {
8326         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8327         enum intel_display_power_domain power_domain;
8328         intel_wakeref_t wakeref;
8329         u32 tmp;
8330         bool ret;
8331
8332         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8333         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
8334         if (!wakeref)
8335                 return false;
8336
8337         pipe_config->output_format = INTEL_OUTPUT_FORMAT_RGB;
8338         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8339         pipe_config->shared_dpll = NULL;
8340
8341         ret = false;
8342
8343         tmp = I915_READ(PIPECONF(crtc->pipe));
8344         if (!(tmp & PIPECONF_ENABLE))
8345                 goto out;
8346
8347         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
8348             IS_CHERRYVIEW(dev_priv)) {
8349                 switch (tmp & PIPECONF_BPC_MASK) {
8350                 case PIPECONF_6BPC:
8351                         pipe_config->pipe_bpp = 18;
8352                         break;
8353                 case PIPECONF_8BPC:
8354                         pipe_config->pipe_bpp = 24;
8355                         break;
8356                 case PIPECONF_10BPC:
8357                         pipe_config->pipe_bpp = 30;
8358                         break;
8359                 default:
8360                         break;
8361                 }
8362         }
8363
8364         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
8365             (tmp & PIPECONF_COLOR_RANGE_SELECT))
8366                 pipe_config->limited_color_range = true;
8367
8368         pipe_config->gamma_mode = (tmp & PIPECONF_GAMMA_MODE_MASK_I9XX) >>
8369                 PIPECONF_GAMMA_MODE_SHIFT;
8370
8371         if (IS_CHERRYVIEW(dev_priv))
8372                 pipe_config->cgm_mode = I915_READ(CGM_PIPE_MODE(crtc->pipe));
8373
8374         i9xx_get_pipe_color_config(pipe_config);
8375
8376         if (INTEL_GEN(dev_priv) < 4)
8377                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
8378
8379         intel_get_pipe_timings(crtc, pipe_config);
8380         intel_get_pipe_src_size(crtc, pipe_config);
8381
8382         i9xx_get_pfit_config(crtc, pipe_config);
8383
8384         if (INTEL_GEN(dev_priv) >= 4) {
8385                 /* No way to read it out on pipes B and C */
8386                 if (IS_CHERRYVIEW(dev_priv) && crtc->pipe != PIPE_A)
8387                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
8388                 else
8389                         tmp = I915_READ(DPLL_MD(crtc->pipe));
8390                 pipe_config->pixel_multiplier =
8391                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
8392                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
8393                 pipe_config->dpll_hw_state.dpll_md = tmp;
8394         } else if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
8395                    IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
8396                 tmp = I915_READ(DPLL(crtc->pipe));
8397                 pipe_config->pixel_multiplier =
8398                         ((tmp & SDVO_MULTIPLIER_MASK)
8399                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
8400         } else {
8401                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
8402                  * port and will be fixed up in the encoder->get_config
8403                  * function. */
8404                 pipe_config->pixel_multiplier = 1;
8405         }
8406         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
8407         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
8408                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
8409                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
8410         } else {
8411                 /* Mask out read-only status bits. */
8412                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
8413                                                      DPLL_PORTC_READY_MASK |
8414                                                      DPLL_PORTB_READY_MASK);
8415         }
8416
8417         if (IS_CHERRYVIEW(dev_priv))
8418                 chv_crtc_clock_get(crtc, pipe_config);
8419         else if (IS_VALLEYVIEW(dev_priv))
8420                 vlv_crtc_clock_get(crtc, pipe_config);
8421         else
8422                 i9xx_crtc_clock_get(crtc, pipe_config);
8423
8424         /*
8425          * Normally the dotclock is filled in by the encoder .get_config()
8426          * but in case the pipe is enabled w/o any ports we need a sane
8427          * default.
8428          */
8429         pipe_config->base.adjusted_mode.crtc_clock =
8430                 pipe_config->port_clock / pipe_config->pixel_multiplier;
8431
8432         ret = true;
8433
8434 out:
8435         intel_display_power_put(dev_priv, power_domain, wakeref);
8436
8437         return ret;
8438 }
8439
8440 static void ironlake_init_pch_refclk(struct drm_i915_private *dev_priv)
8441 {
8442         struct intel_encoder *encoder;
8443         int i;
8444         u32 val, final;
8445         bool has_lvds = false;
8446         bool has_cpu_edp = false;
8447         bool has_panel = false;
8448         bool has_ck505 = false;
8449         bool can_ssc = false;
8450         bool using_ssc_source = false;
8451
8452         /* We need to take the global config into account */
8453         for_each_intel_encoder(&dev_priv->drm, encoder) {
8454                 switch (encoder->type) {
8455                 case INTEL_OUTPUT_LVDS:
8456                         has_panel = true;
8457                         has_lvds = true;
8458                         break;
8459                 case INTEL_OUTPUT_EDP:
8460                         has_panel = true;
8461                         if (encoder->port == PORT_A)
8462                                 has_cpu_edp = true;
8463                         break;
8464                 default:
8465                         break;
8466                 }
8467         }
8468
8469         if (HAS_PCH_IBX(dev_priv)) {
8470                 has_ck505 = dev_priv->vbt.display_clock_mode;
8471                 can_ssc = has_ck505;
8472         } else {
8473                 has_ck505 = false;
8474                 can_ssc = true;
8475         }
8476
8477         /* Check if any DPLLs are using the SSC source */
8478         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
8479                 u32 temp = I915_READ(PCH_DPLL(i));
8480
8481                 if (!(temp & DPLL_VCO_ENABLE))
8482                         continue;
8483
8484                 if ((temp & PLL_REF_INPUT_MASK) ==
8485                     PLLB_REF_INPUT_SPREADSPECTRUMIN) {
8486                         using_ssc_source = true;
8487                         break;
8488                 }
8489         }
8490
8491         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d using_ssc_source %d\n",
8492                       has_panel, has_lvds, has_ck505, using_ssc_source);
8493
8494         /* Ironlake: try to setup display ref clock before DPLL
8495          * enabling. This is only under driver's control after
8496          * PCH B stepping, previous chipset stepping should be
8497          * ignoring this setting.
8498          */
8499         val = I915_READ(PCH_DREF_CONTROL);
8500
8501         /* As we must carefully and slowly disable/enable each source in turn,
8502          * compute the final state we want first and check if we need to
8503          * make any changes at all.
8504          */
8505         final = val;
8506         final &= ~DREF_NONSPREAD_SOURCE_MASK;
8507         if (has_ck505)
8508                 final |= DREF_NONSPREAD_CK505_ENABLE;
8509         else
8510                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
8511
8512         final &= ~DREF_SSC_SOURCE_MASK;
8513         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8514         final &= ~DREF_SSC1_ENABLE;
8515
8516         if (has_panel) {
8517                 final |= DREF_SSC_SOURCE_ENABLE;
8518
8519                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
8520                         final |= DREF_SSC1_ENABLE;
8521
8522                 if (has_cpu_edp) {
8523                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
8524                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8525                         else
8526                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8527                 } else
8528                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8529         } else if (using_ssc_source) {
8530                 final |= DREF_SSC_SOURCE_ENABLE;
8531                 final |= DREF_SSC1_ENABLE;
8532         }
8533
8534         if (final == val)
8535                 return;
8536
8537         /* Always enable nonspread source */
8538         val &= ~DREF_NONSPREAD_SOURCE_MASK;
8539
8540         if (has_ck505)
8541                 val |= DREF_NONSPREAD_CK505_ENABLE;
8542         else
8543                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
8544
8545         if (has_panel) {
8546                 val &= ~DREF_SSC_SOURCE_MASK;
8547                 val |= DREF_SSC_SOURCE_ENABLE;
8548
8549                 /* SSC must be turned on before enabling the CPU output  */
8550                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8551                         DRM_DEBUG_KMS("Using SSC on panel\n");
8552                         val |= DREF_SSC1_ENABLE;
8553                 } else
8554                         val &= ~DREF_SSC1_ENABLE;
8555
8556                 /* Get SSC going before enabling the outputs */
8557                 I915_WRITE(PCH_DREF_CONTROL, val);
8558                 POSTING_READ(PCH_DREF_CONTROL);
8559                 udelay(200);
8560
8561                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8562
8563                 /* Enable CPU source on CPU attached eDP */
8564                 if (has_cpu_edp) {
8565                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8566                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
8567                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8568                         } else
8569                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8570                 } else
8571                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8572
8573                 I915_WRITE(PCH_DREF_CONTROL, val);
8574                 POSTING_READ(PCH_DREF_CONTROL);
8575                 udelay(200);
8576         } else {
8577                 DRM_DEBUG_KMS("Disabling CPU source output\n");
8578
8579                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8580
8581                 /* Turn off CPU output */
8582                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8583
8584                 I915_WRITE(PCH_DREF_CONTROL, val);
8585                 POSTING_READ(PCH_DREF_CONTROL);
8586                 udelay(200);
8587
8588                 if (!using_ssc_source) {
8589                         DRM_DEBUG_KMS("Disabling SSC source\n");
8590
8591                         /* Turn off the SSC source */
8592                         val &= ~DREF_SSC_SOURCE_MASK;
8593                         val |= DREF_SSC_SOURCE_DISABLE;
8594
8595                         /* Turn off SSC1 */
8596                         val &= ~DREF_SSC1_ENABLE;
8597
8598                         I915_WRITE(PCH_DREF_CONTROL, val);
8599                         POSTING_READ(PCH_DREF_CONTROL);
8600                         udelay(200);
8601                 }
8602         }
8603
8604         BUG_ON(val != final);
8605 }
8606
8607 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
8608 {
8609         u32 tmp;
8610
8611         tmp = I915_READ(SOUTH_CHICKEN2);
8612         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
8613         I915_WRITE(SOUTH_CHICKEN2, tmp);
8614
8615         if (wait_for_us(I915_READ(SOUTH_CHICKEN2) &
8616                         FDI_MPHY_IOSFSB_RESET_STATUS, 100))
8617                 DRM_ERROR("FDI mPHY reset assert timeout\n");
8618
8619         tmp = I915_READ(SOUTH_CHICKEN2);
8620         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
8621         I915_WRITE(SOUTH_CHICKEN2, tmp);
8622
8623         if (wait_for_us((I915_READ(SOUTH_CHICKEN2) &
8624                          FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
8625                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
8626 }
8627
8628 /* WaMPhyProgramming:hsw */
8629 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
8630 {
8631         u32 tmp;
8632
8633         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
8634         tmp &= ~(0xFF << 24);
8635         tmp |= (0x12 << 24);
8636         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
8637
8638         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
8639         tmp |= (1 << 11);
8640         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
8641
8642         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
8643         tmp |= (1 << 11);
8644         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
8645
8646         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
8647         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8648         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
8649
8650         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
8651         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8652         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
8653
8654         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
8655         tmp &= ~(7 << 13);
8656         tmp |= (5 << 13);
8657         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
8658
8659         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
8660         tmp &= ~(7 << 13);
8661         tmp |= (5 << 13);
8662         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
8663
8664         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
8665         tmp &= ~0xFF;
8666         tmp |= 0x1C;
8667         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
8668
8669         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
8670         tmp &= ~0xFF;
8671         tmp |= 0x1C;
8672         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
8673
8674         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
8675         tmp &= ~(0xFF << 16);
8676         tmp |= (0x1C << 16);
8677         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
8678
8679         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
8680         tmp &= ~(0xFF << 16);
8681         tmp |= (0x1C << 16);
8682         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
8683
8684         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8685         tmp |= (1 << 27);
8686         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8687
8688         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8689         tmp |= (1 << 27);
8690         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8691
8692         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8693         tmp &= ~(0xF << 28);
8694         tmp |= (4 << 28);
8695         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8696
8697         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
8698         tmp &= ~(0xF << 28);
8699         tmp |= (4 << 28);
8700         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
8701 }
8702
8703 /* Implements 3 different sequences from BSpec chapter "Display iCLK
8704  * Programming" based on the parameters passed:
8705  * - Sequence to enable CLKOUT_DP
8706  * - Sequence to enable CLKOUT_DP without spread
8707  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
8708  */
8709 static void lpt_enable_clkout_dp(struct drm_i915_private *dev_priv,
8710                                  bool with_spread, bool with_fdi)
8711 {
8712         u32 reg, tmp;
8713
8714         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
8715                 with_spread = true;
8716         if (WARN(HAS_PCH_LPT_LP(dev_priv) &&
8717             with_fdi, "LP PCH doesn't have FDI\n"))
8718                 with_fdi = false;
8719
8720         mutex_lock(&dev_priv->sb_lock);
8721
8722         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8723         tmp &= ~SBI_SSCCTL_DISABLE;
8724         tmp |= SBI_SSCCTL_PATHALT;
8725         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8726
8727         udelay(24);
8728
8729         if (with_spread) {
8730                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8731                 tmp &= ~SBI_SSCCTL_PATHALT;
8732                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8733
8734                 if (with_fdi) {
8735                         lpt_reset_fdi_mphy(dev_priv);
8736                         lpt_program_fdi_mphy(dev_priv);
8737                 }
8738         }
8739
8740         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
8741         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8742         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8743         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8744
8745         mutex_unlock(&dev_priv->sb_lock);
8746 }
8747
8748 /* Sequence to disable CLKOUT_DP */
8749 void lpt_disable_clkout_dp(struct drm_i915_private *dev_priv)
8750 {
8751         u32 reg, tmp;
8752
8753         mutex_lock(&dev_priv->sb_lock);
8754
8755         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
8756         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8757         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8758         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8759
8760         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8761         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8762                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8763                         tmp |= SBI_SSCCTL_PATHALT;
8764                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8765                         udelay(32);
8766                 }
8767                 tmp |= SBI_SSCCTL_DISABLE;
8768                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8769         }
8770
8771         mutex_unlock(&dev_priv->sb_lock);
8772 }
8773
8774 #define BEND_IDX(steps) ((50 + (steps)) / 5)
8775
8776 static const u16 sscdivintphase[] = {
8777         [BEND_IDX( 50)] = 0x3B23,
8778         [BEND_IDX( 45)] = 0x3B23,
8779         [BEND_IDX( 40)] = 0x3C23,
8780         [BEND_IDX( 35)] = 0x3C23,
8781         [BEND_IDX( 30)] = 0x3D23,
8782         [BEND_IDX( 25)] = 0x3D23,
8783         [BEND_IDX( 20)] = 0x3E23,
8784         [BEND_IDX( 15)] = 0x3E23,
8785         [BEND_IDX( 10)] = 0x3F23,
8786         [BEND_IDX(  5)] = 0x3F23,
8787         [BEND_IDX(  0)] = 0x0025,
8788         [BEND_IDX( -5)] = 0x0025,
8789         [BEND_IDX(-10)] = 0x0125,
8790         [BEND_IDX(-15)] = 0x0125,
8791         [BEND_IDX(-20)] = 0x0225,
8792         [BEND_IDX(-25)] = 0x0225,
8793         [BEND_IDX(-30)] = 0x0325,
8794         [BEND_IDX(-35)] = 0x0325,
8795         [BEND_IDX(-40)] = 0x0425,
8796         [BEND_IDX(-45)] = 0x0425,
8797         [BEND_IDX(-50)] = 0x0525,
8798 };
8799
8800 /*
8801  * Bend CLKOUT_DP
8802  * steps -50 to 50 inclusive, in steps of 5
8803  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
8804  * change in clock period = -(steps / 10) * 5.787 ps
8805  */
8806 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
8807 {
8808         u32 tmp;
8809         int idx = BEND_IDX(steps);
8810
8811         if (WARN_ON(steps % 5 != 0))
8812                 return;
8813
8814         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
8815                 return;
8816
8817         mutex_lock(&dev_priv->sb_lock);
8818
8819         if (steps % 10 != 0)
8820                 tmp = 0xAAAAAAAB;
8821         else
8822                 tmp = 0x00000000;
8823         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
8824
8825         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
8826         tmp &= 0xffff0000;
8827         tmp |= sscdivintphase[idx];
8828         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
8829
8830         mutex_unlock(&dev_priv->sb_lock);
8831 }
8832
8833 #undef BEND_IDX
8834
8835 static void lpt_init_pch_refclk(struct drm_i915_private *dev_priv)
8836 {
8837         struct intel_encoder *encoder;
8838         bool has_vga = false;
8839
8840         for_each_intel_encoder(&dev_priv->drm, encoder) {
8841                 switch (encoder->type) {
8842                 case INTEL_OUTPUT_ANALOG:
8843                         has_vga = true;
8844                         break;
8845                 default:
8846                         break;
8847                 }
8848         }
8849
8850         if (has_vga) {
8851                 lpt_bend_clkout_dp(dev_priv, 0);
8852                 lpt_enable_clkout_dp(dev_priv, true, true);
8853         } else {
8854                 lpt_disable_clkout_dp(dev_priv);
8855         }
8856 }
8857
8858 /*
8859  * Initialize reference clocks when the driver loads
8860  */
8861 void intel_init_pch_refclk(struct drm_i915_private *dev_priv)
8862 {
8863         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv))
8864                 ironlake_init_pch_refclk(dev_priv);
8865         else if (HAS_PCH_LPT(dev_priv))
8866                 lpt_init_pch_refclk(dev_priv);
8867 }
8868
8869 static void ironlake_set_pipeconf(const struct intel_crtc_state *crtc_state)
8870 {
8871         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
8872         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8873         enum pipe pipe = crtc->pipe;
8874         u32 val;
8875
8876         val = 0;
8877
8878         switch (crtc_state->pipe_bpp) {
8879         case 18:
8880                 val |= PIPECONF_6BPC;
8881                 break;
8882         case 24:
8883                 val |= PIPECONF_8BPC;
8884                 break;
8885         case 30:
8886                 val |= PIPECONF_10BPC;
8887                 break;
8888         case 36:
8889                 val |= PIPECONF_12BPC;
8890                 break;
8891         default:
8892                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8893                 BUG();
8894         }
8895
8896         if (crtc_state->dither)
8897                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8898
8899         if (crtc_state->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8900                 val |= PIPECONF_INTERLACED_ILK;
8901         else
8902                 val |= PIPECONF_PROGRESSIVE;
8903
8904         if (crtc_state->limited_color_range)
8905                 val |= PIPECONF_COLOR_RANGE_SELECT;
8906
8907         val |= PIPECONF_GAMMA_MODE(crtc_state->gamma_mode);
8908
8909         I915_WRITE(PIPECONF(pipe), val);
8910         POSTING_READ(PIPECONF(pipe));
8911 }
8912
8913 static void haswell_set_pipeconf(const struct intel_crtc_state *crtc_state)
8914 {
8915         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
8916         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8917         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
8918         u32 val = 0;
8919
8920         if (IS_HASWELL(dev_priv) && crtc_state->dither)
8921                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8922
8923         if (crtc_state->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8924                 val |= PIPECONF_INTERLACED_ILK;
8925         else
8926                 val |= PIPECONF_PROGRESSIVE;
8927
8928         I915_WRITE(PIPECONF(cpu_transcoder), val);
8929         POSTING_READ(PIPECONF(cpu_transcoder));
8930 }
8931
8932 static void bdw_set_pipemisc(const struct intel_crtc_state *crtc_state)
8933 {
8934         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
8935         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8936         u32 val = 0;
8937
8938         switch (crtc_state->pipe_bpp) {
8939         case 18:
8940                 val |= PIPEMISC_DITHER_6_BPC;
8941                 break;
8942         case 24:
8943                 val |= PIPEMISC_DITHER_8_BPC;
8944                 break;
8945         case 30:
8946                 val |= PIPEMISC_DITHER_10_BPC;
8947                 break;
8948         case 36:
8949                 val |= PIPEMISC_DITHER_12_BPC;
8950                 break;
8951         default:
8952                 MISSING_CASE(crtc_state->pipe_bpp);
8953                 break;
8954         }
8955
8956         if (crtc_state->dither)
8957                 val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8958
8959         if (crtc_state->output_format == INTEL_OUTPUT_FORMAT_YCBCR420 ||
8960             crtc_state->output_format == INTEL_OUTPUT_FORMAT_YCBCR444)
8961                 val |= PIPEMISC_OUTPUT_COLORSPACE_YUV;
8962
8963         if (crtc_state->output_format == INTEL_OUTPUT_FORMAT_YCBCR420)
8964                 val |= PIPEMISC_YUV420_ENABLE |
8965                         PIPEMISC_YUV420_MODE_FULL_BLEND;
8966
8967         if (INTEL_GEN(dev_priv) >= 11 &&
8968             (crtc_state->active_planes & ~(icl_hdr_plane_mask() |
8969                                            BIT(PLANE_CURSOR))) == 0)
8970                 val |= PIPEMISC_HDR_MODE_PRECISION;
8971
8972         I915_WRITE(PIPEMISC(crtc->pipe), val);
8973 }
8974
8975 int bdw_get_pipemisc_bpp(struct intel_crtc *crtc)
8976 {
8977         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8978         u32 tmp;
8979
8980         tmp = I915_READ(PIPEMISC(crtc->pipe));
8981
8982         switch (tmp & PIPEMISC_DITHER_BPC_MASK) {
8983         case PIPEMISC_DITHER_6_BPC:
8984                 return 18;
8985         case PIPEMISC_DITHER_8_BPC:
8986                 return 24;
8987         case PIPEMISC_DITHER_10_BPC:
8988                 return 30;
8989         case PIPEMISC_DITHER_12_BPC:
8990                 return 36;
8991         default:
8992                 MISSING_CASE(tmp);
8993                 return 0;
8994         }
8995 }
8996
8997 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8998 {
8999         /*
9000          * Account for spread spectrum to avoid
9001          * oversubscribing the link. Max center spread
9002          * is 2.5%; use 5% for safety's sake.
9003          */
9004         u32 bps = target_clock * bpp * 21 / 20;
9005         return DIV_ROUND_UP(bps, link_bw * 8);
9006 }
9007
9008 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
9009 {
9010         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
9011 }
9012
9013 static void ironlake_compute_dpll(struct intel_crtc *crtc,
9014                                   struct intel_crtc_state *crtc_state,
9015                                   struct dpll *reduced_clock)
9016 {
9017         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9018         u32 dpll, fp, fp2;
9019         int factor;
9020
9021         /* Enable autotuning of the PLL clock (if permissible) */
9022         factor = 21;
9023         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
9024                 if ((intel_panel_use_ssc(dev_priv) &&
9025                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
9026                     (HAS_PCH_IBX(dev_priv) &&
9027                      intel_is_dual_link_lvds(dev_priv)))
9028                         factor = 25;
9029         } else if (crtc_state->sdvo_tv_clock) {
9030                 factor = 20;
9031         }
9032
9033         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
9034
9035         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
9036                 fp |= FP_CB_TUNE;
9037
9038         if (reduced_clock) {
9039                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
9040
9041                 if (reduced_clock->m < factor * reduced_clock->n)
9042                         fp2 |= FP_CB_TUNE;
9043         } else {
9044                 fp2 = fp;
9045         }
9046
9047         dpll = 0;
9048
9049         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
9050                 dpll |= DPLLB_MODE_LVDS;
9051         else
9052                 dpll |= DPLLB_MODE_DAC_SERIAL;
9053
9054         dpll |= (crtc_state->pixel_multiplier - 1)
9055                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
9056
9057         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
9058             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
9059                 dpll |= DPLL_SDVO_HIGH_SPEED;
9060
9061         if (intel_crtc_has_dp_encoder(crtc_state))
9062                 dpll |= DPLL_SDVO_HIGH_SPEED;
9063
9064         /*
9065          * The high speed IO clock is only really required for
9066          * SDVO/HDMI/DP, but we also enable it for CRT to make it
9067          * possible to share the DPLL between CRT and HDMI. Enabling
9068          * the clock needlessly does no real harm, except use up a
9069          * bit of power potentially.
9070          *
9071          * We'll limit this to IVB with 3 pipes, since it has only two
9072          * DPLLs and so DPLL sharing is the only way to get three pipes
9073          * driving PCH ports at the same time. On SNB we could do this,
9074          * and potentially avoid enabling the second DPLL, but it's not
9075          * clear if it''s a win or loss power wise. No point in doing
9076          * this on ILK at all since it has a fixed DPLL<->pipe mapping.
9077          */
9078         if (INTEL_INFO(dev_priv)->num_pipes == 3 &&
9079             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG))
9080                 dpll |= DPLL_SDVO_HIGH_SPEED;
9081
9082         /* compute bitmask from p1 value */
9083         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
9084         /* also FPA1 */
9085         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
9086
9087         switch (crtc_state->dpll.p2) {
9088         case 5:
9089                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
9090                 break;
9091         case 7:
9092                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
9093                 break;
9094         case 10:
9095                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
9096                 break;
9097         case 14:
9098                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
9099                 break;
9100         }
9101
9102         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
9103             intel_panel_use_ssc(dev_priv))
9104                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
9105         else
9106                 dpll |= PLL_REF_INPUT_DREFCLK;
9107
9108         dpll |= DPLL_VCO_ENABLE;
9109
9110         crtc_state->dpll_hw_state.dpll = dpll;
9111         crtc_state->dpll_hw_state.fp0 = fp;
9112         crtc_state->dpll_hw_state.fp1 = fp2;
9113 }
9114
9115 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
9116                                        struct intel_crtc_state *crtc_state)
9117 {
9118         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9119         const struct intel_limit *limit;
9120         int refclk = 120000;
9121
9122         memset(&crtc_state->dpll_hw_state, 0,
9123                sizeof(crtc_state->dpll_hw_state));
9124
9125         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
9126         if (!crtc_state->has_pch_encoder)
9127                 return 0;
9128
9129         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
9130                 if (intel_panel_use_ssc(dev_priv)) {
9131                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
9132                                       dev_priv->vbt.lvds_ssc_freq);
9133                         refclk = dev_priv->vbt.lvds_ssc_freq;
9134                 }
9135
9136                 if (intel_is_dual_link_lvds(dev_priv)) {
9137                         if (refclk == 100000)
9138                                 limit = &intel_limits_ironlake_dual_lvds_100m;
9139                         else
9140                                 limit = &intel_limits_ironlake_dual_lvds;
9141                 } else {
9142                         if (refclk == 100000)
9143                                 limit = &intel_limits_ironlake_single_lvds_100m;
9144                         else
9145                                 limit = &intel_limits_ironlake_single_lvds;
9146                 }
9147         } else {
9148                 limit = &intel_limits_ironlake_dac;
9149         }
9150
9151         if (!crtc_state->clock_set &&
9152             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
9153                                 refclk, NULL, &crtc_state->dpll)) {
9154                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
9155                 return -EINVAL;
9156         }
9157
9158         ironlake_compute_dpll(crtc, crtc_state, NULL);
9159
9160         if (!intel_get_shared_dpll(crtc_state, NULL)) {
9161                 DRM_DEBUG_KMS("failed to find PLL for pipe %c\n",
9162                               pipe_name(crtc->pipe));
9163                 return -EINVAL;
9164         }
9165
9166         return 0;
9167 }
9168
9169 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
9170                                          struct intel_link_m_n *m_n)
9171 {
9172         struct drm_device *dev = crtc->base.dev;
9173         struct drm_i915_private *dev_priv = to_i915(dev);
9174         enum pipe pipe = crtc->pipe;
9175
9176         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
9177         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
9178         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
9179                 & ~TU_SIZE_MASK;
9180         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
9181         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
9182                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9183 }
9184
9185 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
9186                                          enum transcoder transcoder,
9187                                          struct intel_link_m_n *m_n,
9188                                          struct intel_link_m_n *m2_n2)
9189 {
9190         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9191         enum pipe pipe = crtc->pipe;
9192
9193         if (INTEL_GEN(dev_priv) >= 5) {
9194                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
9195                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
9196                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
9197                         & ~TU_SIZE_MASK;
9198                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
9199                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
9200                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9201
9202                 if (m2_n2 && transcoder_has_m2_n2(dev_priv, transcoder)) {
9203                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
9204                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
9205                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
9206                                         & ~TU_SIZE_MASK;
9207                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
9208                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
9209                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9210                 }
9211         } else {
9212                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
9213                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
9214                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
9215                         & ~TU_SIZE_MASK;
9216                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
9217                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
9218                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9219         }
9220 }
9221
9222 void intel_dp_get_m_n(struct intel_crtc *crtc,
9223                       struct intel_crtc_state *pipe_config)
9224 {
9225         if (pipe_config->has_pch_encoder)
9226                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
9227         else
9228                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9229                                              &pipe_config->dp_m_n,
9230                                              &pipe_config->dp_m2_n2);
9231 }
9232
9233 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
9234                                         struct intel_crtc_state *pipe_config)
9235 {
9236         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9237                                      &pipe_config->fdi_m_n, NULL);
9238 }
9239
9240 static void skylake_get_pfit_config(struct intel_crtc *crtc,
9241                                     struct intel_crtc_state *pipe_config)
9242 {
9243         struct drm_device *dev = crtc->base.dev;
9244         struct drm_i915_private *dev_priv = to_i915(dev);
9245         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
9246         u32 ps_ctrl = 0;
9247         int id = -1;
9248         int i;
9249
9250         /* find scaler attached to this pipe */
9251         for (i = 0; i < crtc->num_scalers; i++) {
9252                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
9253                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
9254                         id = i;
9255                         pipe_config->pch_pfit.enabled = true;
9256                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
9257                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
9258                         scaler_state->scalers[i].in_use = true;
9259                         break;
9260                 }
9261         }
9262
9263         scaler_state->scaler_id = id;
9264         if (id >= 0) {
9265                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
9266         } else {
9267                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
9268         }
9269 }
9270
9271 static void
9272 skylake_get_initial_plane_config(struct intel_crtc *crtc,
9273                                  struct intel_initial_plane_config *plane_config)
9274 {
9275         struct drm_device *dev = crtc->base.dev;
9276         struct drm_i915_private *dev_priv = to_i915(dev);
9277         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
9278         enum plane_id plane_id = plane->id;
9279         enum pipe pipe;
9280         u32 val, base, offset, stride_mult, tiling, alpha;
9281         int fourcc, pixel_format;
9282         unsigned int aligned_height;
9283         struct drm_framebuffer *fb;
9284         struct intel_framebuffer *intel_fb;
9285
9286         if (!plane->get_hw_state(plane, &pipe))
9287                 return;
9288
9289         WARN_ON(pipe != crtc->pipe);
9290
9291         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9292         if (!intel_fb) {
9293                 DRM_DEBUG_KMS("failed to alloc fb\n");
9294                 return;
9295         }
9296
9297         fb = &intel_fb->base;
9298
9299         fb->dev = dev;
9300
9301         val = I915_READ(PLANE_CTL(pipe, plane_id));
9302
9303         if (INTEL_GEN(dev_priv) >= 11)
9304                 pixel_format = val & ICL_PLANE_CTL_FORMAT_MASK;
9305         else
9306                 pixel_format = val & PLANE_CTL_FORMAT_MASK;
9307
9308         if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv)) {
9309                 alpha = I915_READ(PLANE_COLOR_CTL(pipe, plane_id));
9310                 alpha &= PLANE_COLOR_ALPHA_MASK;
9311         } else {
9312                 alpha = val & PLANE_CTL_ALPHA_MASK;
9313         }
9314
9315         fourcc = skl_format_to_fourcc(pixel_format,
9316                                       val & PLANE_CTL_ORDER_RGBX, alpha);
9317         fb->format = drm_format_info(fourcc);
9318
9319         tiling = val & PLANE_CTL_TILED_MASK;
9320         switch (tiling) {
9321         case PLANE_CTL_TILED_LINEAR:
9322                 fb->modifier = DRM_FORMAT_MOD_LINEAR;
9323                 break;
9324         case PLANE_CTL_TILED_X:
9325                 plane_config->tiling = I915_TILING_X;
9326                 fb->modifier = I915_FORMAT_MOD_X_TILED;
9327                 break;
9328         case PLANE_CTL_TILED_Y:
9329                 plane_config->tiling = I915_TILING_Y;
9330                 if (val & PLANE_CTL_RENDER_DECOMPRESSION_ENABLE)
9331                         fb->modifier = I915_FORMAT_MOD_Y_TILED_CCS;
9332                 else
9333                         fb->modifier = I915_FORMAT_MOD_Y_TILED;
9334                 break;
9335         case PLANE_CTL_TILED_YF:
9336                 if (val & PLANE_CTL_RENDER_DECOMPRESSION_ENABLE)
9337                         fb->modifier = I915_FORMAT_MOD_Yf_TILED_CCS;
9338                 else
9339                         fb->modifier = I915_FORMAT_MOD_Yf_TILED;
9340                 break;
9341         default:
9342                 MISSING_CASE(tiling);
9343                 goto error;
9344         }
9345
9346         /*
9347          * DRM_MODE_ROTATE_ is counter clockwise to stay compatible with Xrandr
9348          * while i915 HW rotation is clockwise, thats why this swapping.
9349          */
9350         switch (val & PLANE_CTL_ROTATE_MASK) {
9351         case PLANE_CTL_ROTATE_0:
9352                 plane_config->rotation = DRM_MODE_ROTATE_0;
9353                 break;
9354         case PLANE_CTL_ROTATE_90:
9355                 plane_config->rotation = DRM_MODE_ROTATE_270;
9356                 break;
9357         case PLANE_CTL_ROTATE_180:
9358                 plane_config->rotation = DRM_MODE_ROTATE_180;
9359                 break;
9360         case PLANE_CTL_ROTATE_270:
9361                 plane_config->rotation = DRM_MODE_ROTATE_90;
9362                 break;
9363         }
9364
9365         if (INTEL_GEN(dev_priv) >= 10 &&
9366             val & PLANE_CTL_FLIP_HORIZONTAL)
9367                 plane_config->rotation |= DRM_MODE_REFLECT_X;
9368
9369         base = I915_READ(PLANE_SURF(pipe, plane_id)) & 0xfffff000;
9370         plane_config->base = base;
9371
9372         offset = I915_READ(PLANE_OFFSET(pipe, plane_id));
9373
9374         val = I915_READ(PLANE_SIZE(pipe, plane_id));
9375         fb->height = ((val >> 16) & 0xfff) + 1;
9376         fb->width = ((val >> 0) & 0x1fff) + 1;
9377
9378         val = I915_READ(PLANE_STRIDE(pipe, plane_id));
9379         stride_mult = skl_plane_stride_mult(fb, 0, DRM_MODE_ROTATE_0);
9380         fb->pitches[0] = (val & 0x3ff) * stride_mult;
9381
9382         aligned_height = intel_fb_align_height(fb, 0, fb->height);
9383
9384         plane_config->size = fb->pitches[0] * aligned_height;
9385
9386         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9387                       crtc->base.name, plane->base.name, fb->width, fb->height,
9388                       fb->format->cpp[0] * 8, base, fb->pitches[0],
9389                       plane_config->size);
9390
9391         plane_config->fb = intel_fb;
9392         return;
9393
9394 error:
9395         kfree(intel_fb);
9396 }
9397
9398 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
9399                                      struct intel_crtc_state *pipe_config)
9400 {
9401         struct drm_device *dev = crtc->base.dev;
9402         struct drm_i915_private *dev_priv = to_i915(dev);
9403         u32 tmp;
9404
9405         tmp = I915_READ(PF_CTL(crtc->pipe));
9406
9407         if (tmp & PF_ENABLE) {
9408                 pipe_config->pch_pfit.enabled = true;
9409                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
9410                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
9411
9412                 /* We currently do not free assignements of panel fitters on
9413                  * ivb/hsw (since we don't use the higher upscaling modes which
9414                  * differentiates them) so just WARN about this case for now. */
9415                 if (IS_GEN(dev_priv, 7)) {
9416                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
9417                                 PF_PIPE_SEL_IVB(crtc->pipe));
9418                 }
9419         }
9420 }
9421
9422 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
9423                                      struct intel_crtc_state *pipe_config)
9424 {
9425         struct drm_device *dev = crtc->base.dev;
9426         struct drm_i915_private *dev_priv = to_i915(dev);
9427         enum intel_display_power_domain power_domain;
9428         intel_wakeref_t wakeref;
9429         u32 tmp;
9430         bool ret;
9431
9432         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9433         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
9434         if (!wakeref)
9435                 return false;
9436
9437         pipe_config->output_format = INTEL_OUTPUT_FORMAT_RGB;
9438         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9439         pipe_config->shared_dpll = NULL;
9440
9441         ret = false;
9442         tmp = I915_READ(PIPECONF(crtc->pipe));
9443         if (!(tmp & PIPECONF_ENABLE))
9444                 goto out;
9445
9446         switch (tmp & PIPECONF_BPC_MASK) {
9447         case PIPECONF_6BPC:
9448                 pipe_config->pipe_bpp = 18;
9449                 break;
9450         case PIPECONF_8BPC:
9451                 pipe_config->pipe_bpp = 24;
9452                 break;
9453         case PIPECONF_10BPC:
9454                 pipe_config->pipe_bpp = 30;
9455                 break;
9456         case PIPECONF_12BPC:
9457                 pipe_config->pipe_bpp = 36;
9458                 break;
9459         default:
9460                 break;
9461         }
9462
9463         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
9464                 pipe_config->limited_color_range = true;
9465
9466         pipe_config->gamma_mode = (tmp & PIPECONF_GAMMA_MODE_MASK_ILK) >>
9467                 PIPECONF_GAMMA_MODE_SHIFT;
9468
9469         pipe_config->csc_mode = I915_READ(PIPE_CSC_MODE(crtc->pipe));
9470
9471         i9xx_get_pipe_color_config(pipe_config);
9472
9473         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
9474                 struct intel_shared_dpll *pll;
9475                 enum intel_dpll_id pll_id;
9476
9477                 pipe_config->has_pch_encoder = true;
9478
9479                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
9480                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9481                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9482
9483                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9484
9485                 if (HAS_PCH_IBX(dev_priv)) {
9486                         /*
9487                          * The pipe->pch transcoder and pch transcoder->pll
9488                          * mapping is fixed.
9489                          */
9490                         pll_id = (enum intel_dpll_id) crtc->pipe;
9491                 } else {
9492                         tmp = I915_READ(PCH_DPLL_SEL);
9493                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
9494                                 pll_id = DPLL_ID_PCH_PLL_B;
9495                         else
9496                                 pll_id= DPLL_ID_PCH_PLL_A;
9497                 }
9498
9499                 pipe_config->shared_dpll =
9500                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
9501                 pll = pipe_config->shared_dpll;
9502
9503                 WARN_ON(!pll->info->funcs->get_hw_state(dev_priv, pll,
9504                                                 &pipe_config->dpll_hw_state));
9505
9506                 tmp = pipe_config->dpll_hw_state.dpll;
9507                 pipe_config->pixel_multiplier =
9508                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
9509                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
9510
9511                 ironlake_pch_clock_get(crtc, pipe_config);
9512         } else {
9513                 pipe_config->pixel_multiplier = 1;
9514         }
9515
9516         intel_get_pipe_timings(crtc, pipe_config);
9517         intel_get_pipe_src_size(crtc, pipe_config);
9518
9519         ironlake_get_pfit_config(crtc, pipe_config);
9520
9521         ret = true;
9522
9523 out:
9524         intel_display_power_put(dev_priv, power_domain, wakeref);
9525
9526         return ret;
9527 }
9528 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9529                                       struct intel_crtc_state *crtc_state)
9530 {
9531         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9532         struct intel_atomic_state *state =
9533                 to_intel_atomic_state(crtc_state->base.state);
9534
9535         if (!intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DSI) ||
9536             INTEL_GEN(dev_priv) >= 11) {
9537                 struct intel_encoder *encoder =
9538                         intel_get_crtc_new_encoder(state, crtc_state);
9539
9540                 if (!intel_get_shared_dpll(crtc_state, encoder)) {
9541                         DRM_DEBUG_KMS("failed to find PLL for pipe %c\n",
9542                                       pipe_name(crtc->pipe));
9543                         return -EINVAL;
9544                 }
9545         }
9546
9547         return 0;
9548 }
9549
9550 static void cannonlake_get_ddi_pll(struct drm_i915_private *dev_priv,
9551                                    enum port port,
9552                                    struct intel_crtc_state *pipe_config)
9553 {
9554         enum intel_dpll_id id;
9555         u32 temp;
9556
9557         temp = I915_READ(DPCLKA_CFGCR0) & DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
9558         id = temp >> DPCLKA_CFGCR0_DDI_CLK_SEL_SHIFT(port);
9559
9560         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL2))
9561                 return;
9562
9563         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9564 }
9565
9566 static void icelake_get_ddi_pll(struct drm_i915_private *dev_priv,
9567                                 enum port port,
9568                                 struct intel_crtc_state *pipe_config)
9569 {
9570         enum intel_dpll_id id;
9571         u32 temp;
9572
9573         /* TODO: TBT pll not implemented. */
9574         if (intel_port_is_combophy(dev_priv, port)) {
9575                 temp = I915_READ(DPCLKA_CFGCR0_ICL) &
9576                        DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
9577                 id = temp >> DPCLKA_CFGCR0_DDI_CLK_SEL_SHIFT(port);
9578         } else if (intel_port_is_tc(dev_priv, port)) {
9579                 id = icl_tc_port_to_pll_id(intel_port_to_tc(dev_priv, port));
9580         } else {
9581                 WARN(1, "Invalid port %x\n", port);
9582                 return;
9583         }
9584
9585         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9586 }
9587
9588 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9589                                 enum port port,
9590                                 struct intel_crtc_state *pipe_config)
9591 {
9592         enum intel_dpll_id id;
9593
9594         switch (port) {
9595         case PORT_A:
9596                 id = DPLL_ID_SKL_DPLL0;
9597                 break;
9598         case PORT_B:
9599                 id = DPLL_ID_SKL_DPLL1;
9600                 break;
9601         case PORT_C:
9602                 id = DPLL_ID_SKL_DPLL2;
9603                 break;
9604         default:
9605                 DRM_ERROR("Incorrect port type\n");
9606                 return;
9607         }
9608
9609         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9610 }
9611
9612 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9613                                 enum port port,
9614                                 struct intel_crtc_state *pipe_config)
9615 {
9616         enum intel_dpll_id id;
9617         u32 temp;
9618
9619         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9620         id = temp >> (port * 3 + 1);
9621
9622         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL3))
9623                 return;
9624
9625         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9626 }
9627
9628 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9629                                 enum port port,
9630                                 struct intel_crtc_state *pipe_config)
9631 {
9632         enum intel_dpll_id id;
9633         u32 ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9634
9635         switch (ddi_pll_sel) {
9636         case PORT_CLK_SEL_WRPLL1:
9637                 id = DPLL_ID_WRPLL1;
9638                 break;
9639         case PORT_CLK_SEL_WRPLL2:
9640                 id = DPLL_ID_WRPLL2;
9641                 break;
9642         case PORT_CLK_SEL_SPLL:
9643                 id = DPLL_ID_SPLL;
9644                 break;
9645         case PORT_CLK_SEL_LCPLL_810:
9646                 id = DPLL_ID_LCPLL_810;
9647                 break;
9648         case PORT_CLK_SEL_LCPLL_1350:
9649                 id = DPLL_ID_LCPLL_1350;
9650                 break;
9651         case PORT_CLK_SEL_LCPLL_2700:
9652                 id = DPLL_ID_LCPLL_2700;
9653                 break;
9654         default:
9655                 MISSING_CASE(ddi_pll_sel);
9656                 /* fall through */
9657         case PORT_CLK_SEL_NONE:
9658                 return;
9659         }
9660
9661         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9662 }
9663
9664 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
9665                                      struct intel_crtc_state *pipe_config,
9666                                      u64 *power_domain_mask,
9667                                      intel_wakeref_t *wakerefs)
9668 {
9669         struct drm_device *dev = crtc->base.dev;
9670         struct drm_i915_private *dev_priv = to_i915(dev);
9671         enum intel_display_power_domain power_domain;
9672         unsigned long panel_transcoder_mask = 0;
9673         unsigned long enabled_panel_transcoders = 0;
9674         enum transcoder panel_transcoder;
9675         intel_wakeref_t wf;
9676         u32 tmp;
9677
9678         if (INTEL_GEN(dev_priv) >= 11)
9679                 panel_transcoder_mask |=
9680                         BIT(TRANSCODER_DSI_0) | BIT(TRANSCODER_DSI_1);
9681
9682         if (HAS_TRANSCODER_EDP(dev_priv))
9683                 panel_transcoder_mask |= BIT(TRANSCODER_EDP);
9684
9685         /*
9686          * The pipe->transcoder mapping is fixed with the exception of the eDP
9687          * and DSI transcoders handled below.
9688          */
9689         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9690
9691         /*
9692          * XXX: Do intel_display_power_get_if_enabled before reading this (for
9693          * consistency and less surprising code; it's in always on power).
9694          */
9695         for_each_set_bit(panel_transcoder,
9696                          &panel_transcoder_mask,
9697                          ARRAY_SIZE(INTEL_INFO(dev_priv)->trans_offsets)) {
9698                 bool force_thru = false;
9699                 enum pipe trans_pipe;
9700
9701                 tmp = I915_READ(TRANS_DDI_FUNC_CTL(panel_transcoder));
9702                 if (!(tmp & TRANS_DDI_FUNC_ENABLE))
9703                         continue;
9704
9705                 /*
9706                  * Log all enabled ones, only use the first one.
9707                  *
9708                  * FIXME: This won't work for two separate DSI displays.
9709                  */
9710                 enabled_panel_transcoders |= BIT(panel_transcoder);
9711                 if (enabled_panel_transcoders != BIT(panel_transcoder))
9712                         continue;
9713
9714                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9715                 default:
9716                         WARN(1, "unknown pipe linked to transcoder %s\n",
9717                              transcoder_name(panel_transcoder));
9718                         /* fall through */
9719                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9720                         force_thru = true;
9721                         /* fall through */
9722                 case TRANS_DDI_EDP_INPUT_A_ON:
9723                         trans_pipe = PIPE_A;
9724                         break;
9725                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
9726                         trans_pipe = PIPE_B;
9727                         break;
9728                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
9729                         trans_pipe = PIPE_C;
9730                         break;
9731                 }
9732
9733                 if (trans_pipe == crtc->pipe) {
9734                         pipe_config->cpu_transcoder = panel_transcoder;
9735                         pipe_config->pch_pfit.force_thru = force_thru;
9736                 }
9737         }
9738
9739         /*
9740          * Valid combos: none, eDP, DSI0, DSI1, DSI0+DSI1
9741          */
9742         WARN_ON((enabled_panel_transcoders & BIT(TRANSCODER_EDP)) &&
9743                 enabled_panel_transcoders != BIT(TRANSCODER_EDP));
9744
9745         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
9746         WARN_ON(*power_domain_mask & BIT_ULL(power_domain));
9747
9748         wf = intel_display_power_get_if_enabled(dev_priv, power_domain);
9749         if (!wf)
9750                 return false;
9751
9752         wakerefs[power_domain] = wf;
9753         *power_domain_mask |= BIT_ULL(power_domain);
9754
9755         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
9756
9757         return tmp & PIPECONF_ENABLE;
9758 }
9759
9760 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
9761                                          struct intel_crtc_state *pipe_config,
9762                                          u64 *power_domain_mask,
9763                                          intel_wakeref_t *wakerefs)
9764 {
9765         struct drm_device *dev = crtc->base.dev;
9766         struct drm_i915_private *dev_priv = to_i915(dev);
9767         enum intel_display_power_domain power_domain;
9768         enum transcoder cpu_transcoder;
9769         intel_wakeref_t wf;
9770         enum port port;
9771         u32 tmp;
9772
9773         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
9774                 if (port == PORT_A)
9775                         cpu_transcoder = TRANSCODER_DSI_A;
9776                 else
9777                         cpu_transcoder = TRANSCODER_DSI_C;
9778
9779                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
9780                 WARN_ON(*power_domain_mask & BIT_ULL(power_domain));
9781
9782                 wf = intel_display_power_get_if_enabled(dev_priv, power_domain);
9783                 if (!wf)
9784                         continue;
9785
9786                 wakerefs[power_domain] = wf;
9787                 *power_domain_mask |= BIT_ULL(power_domain);
9788
9789                 /*
9790                  * The PLL needs to be enabled with a valid divider
9791                  * configuration, otherwise accessing DSI registers will hang
9792                  * the machine. See BSpec North Display Engine
9793                  * registers/MIPI[BXT]. We can break out here early, since we
9794                  * need the same DSI PLL to be enabled for both DSI ports.
9795                  */
9796                 if (!bxt_dsi_pll_is_enabled(dev_priv))
9797                         break;
9798
9799                 /* XXX: this works for video mode only */
9800                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
9801                 if (!(tmp & DPI_ENABLE))
9802                         continue;
9803
9804                 tmp = I915_READ(MIPI_CTRL(port));
9805                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
9806                         continue;
9807
9808                 pipe_config->cpu_transcoder = cpu_transcoder;
9809                 break;
9810         }
9811
9812         return transcoder_is_dsi(pipe_config->cpu_transcoder);
9813 }
9814
9815 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9816                                        struct intel_crtc_state *pipe_config)
9817 {
9818         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9819         struct intel_shared_dpll *pll;
9820         enum port port;
9821         u32 tmp;
9822
9823         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9824
9825         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9826
9827         if (INTEL_GEN(dev_priv) >= 11)
9828                 icelake_get_ddi_pll(dev_priv, port, pipe_config);
9829         else if (IS_CANNONLAKE(dev_priv))
9830                 cannonlake_get_ddi_pll(dev_priv, port, pipe_config);
9831         else if (IS_GEN9_BC(dev_priv))
9832                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
9833         else if (IS_GEN9_LP(dev_priv))
9834                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
9835         else
9836                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
9837
9838         pll = pipe_config->shared_dpll;
9839         if (pll) {
9840                 WARN_ON(!pll->info->funcs->get_hw_state(dev_priv, pll,
9841                                                 &pipe_config->dpll_hw_state));
9842         }
9843
9844         /*
9845          * Haswell has only FDI/PCH transcoder A. It is which is connected to
9846          * DDI E. So just check whether this pipe is wired to DDI E and whether
9847          * the PCH transcoder is on.
9848          */
9849         if (INTEL_GEN(dev_priv) < 9 &&
9850             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
9851                 pipe_config->has_pch_encoder = true;
9852
9853                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
9854                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9855                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9856
9857                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9858         }
9859 }
9860
9861 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
9862                                     struct intel_crtc_state *pipe_config)
9863 {
9864         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9865         intel_wakeref_t wakerefs[POWER_DOMAIN_NUM], wf;
9866         enum intel_display_power_domain power_domain;
9867         u64 power_domain_mask;
9868         bool active;
9869
9870         intel_crtc_init_scalers(crtc, pipe_config);
9871
9872         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9873         wf = intel_display_power_get_if_enabled(dev_priv, power_domain);
9874         if (!wf)
9875                 return false;
9876
9877         wakerefs[power_domain] = wf;
9878         power_domain_mask = BIT_ULL(power_domain);
9879
9880         pipe_config->shared_dpll = NULL;
9881
9882         active = hsw_get_transcoder_state(crtc, pipe_config,
9883                                           &power_domain_mask, wakerefs);
9884
9885         if (IS_GEN9_LP(dev_priv) &&
9886             bxt_get_dsi_transcoder_state(crtc, pipe_config,
9887                                          &power_domain_mask, wakerefs)) {
9888                 WARN_ON(active);
9889                 active = true;
9890         }
9891
9892         if (!active)
9893                 goto out;
9894
9895         if (!transcoder_is_dsi(pipe_config->cpu_transcoder) ||
9896             INTEL_GEN(dev_priv) >= 11) {
9897                 haswell_get_ddi_port_state(crtc, pipe_config);
9898                 intel_get_pipe_timings(crtc, pipe_config);
9899         }
9900
9901         intel_get_pipe_src_size(crtc, pipe_config);
9902         intel_get_crtc_ycbcr_config(crtc, pipe_config);
9903
9904         pipe_config->gamma_mode = I915_READ(GAMMA_MODE(crtc->pipe));
9905
9906         pipe_config->csc_mode = I915_READ(PIPE_CSC_MODE(crtc->pipe));
9907
9908         if (INTEL_GEN(dev_priv) >= 9) {
9909                 u32 tmp = I915_READ(SKL_BOTTOM_COLOR(crtc->pipe));
9910
9911                 if (tmp & SKL_BOTTOM_COLOR_GAMMA_ENABLE)
9912                         pipe_config->gamma_enable = true;
9913
9914                 if (tmp & SKL_BOTTOM_COLOR_CSC_ENABLE)
9915                         pipe_config->csc_enable = true;
9916         } else {
9917                 i9xx_get_pipe_color_config(pipe_config);
9918         }
9919
9920         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
9921         WARN_ON(power_domain_mask & BIT_ULL(power_domain));
9922
9923         wf = intel_display_power_get_if_enabled(dev_priv, power_domain);
9924         if (wf) {
9925                 wakerefs[power_domain] = wf;
9926                 power_domain_mask |= BIT_ULL(power_domain);
9927
9928                 if (INTEL_GEN(dev_priv) >= 9)
9929                         skylake_get_pfit_config(crtc, pipe_config);
9930                 else
9931                         ironlake_get_pfit_config(crtc, pipe_config);
9932         }
9933
9934         if (hsw_crtc_supports_ips(crtc)) {
9935                 if (IS_HASWELL(dev_priv))
9936                         pipe_config->ips_enabled = I915_READ(IPS_CTL) & IPS_ENABLE;
9937                 else {
9938                         /*
9939                          * We cannot readout IPS state on broadwell, set to
9940                          * true so we can set it to a defined state on first
9941                          * commit.
9942                          */
9943                         pipe_config->ips_enabled = true;
9944                 }
9945         }
9946
9947         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
9948             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9949                 pipe_config->pixel_multiplier =
9950                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
9951         } else {
9952                 pipe_config->pixel_multiplier = 1;
9953         }
9954
9955 out:
9956         for_each_power_domain(power_domain, power_domain_mask)
9957                 intel_display_power_put(dev_priv,
9958                                         power_domain, wakerefs[power_domain]);
9959
9960         return active;
9961 }
9962
9963 static u32 intel_cursor_base(const struct intel_plane_state *plane_state)
9964 {
9965         struct drm_i915_private *dev_priv =
9966                 to_i915(plane_state->base.plane->dev);
9967         const struct drm_framebuffer *fb = plane_state->base.fb;
9968         const struct drm_i915_gem_object *obj = intel_fb_obj(fb);
9969         u32 base;
9970
9971         if (INTEL_INFO(dev_priv)->display.cursor_needs_physical)
9972                 base = obj->phys_handle->busaddr;
9973         else
9974                 base = intel_plane_ggtt_offset(plane_state);
9975
9976         base += plane_state->color_plane[0].offset;
9977
9978         /* ILK+ do this automagically */
9979         if (HAS_GMCH(dev_priv) &&
9980             plane_state->base.rotation & DRM_MODE_ROTATE_180)
9981                 base += (plane_state->base.crtc_h *
9982                          plane_state->base.crtc_w - 1) * fb->format->cpp[0];
9983
9984         return base;
9985 }
9986
9987 static u32 intel_cursor_position(const struct intel_plane_state *plane_state)
9988 {
9989         int x = plane_state->base.crtc_x;
9990         int y = plane_state->base.crtc_y;
9991         u32 pos = 0;
9992
9993         if (x < 0) {
9994                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
9995                 x = -x;
9996         }
9997         pos |= x << CURSOR_X_SHIFT;
9998
9999         if (y < 0) {
10000                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
10001                 y = -y;
10002         }
10003         pos |= y << CURSOR_Y_SHIFT;
10004
10005         return pos;
10006 }
10007
10008 static bool intel_cursor_size_ok(const struct intel_plane_state *plane_state)
10009 {
10010         const struct drm_mode_config *config =
10011                 &plane_state->base.plane->dev->mode_config;
10012         int width = plane_state->base.crtc_w;
10013         int height = plane_state->base.crtc_h;
10014
10015         return width > 0 && width <= config->cursor_width &&
10016                 height > 0 && height <= config->cursor_height;
10017 }
10018
10019 static int intel_cursor_check_surface(struct intel_plane_state *plane_state)
10020 {
10021         const struct drm_framebuffer *fb = plane_state->base.fb;
10022         unsigned int rotation = plane_state->base.rotation;
10023         int src_x, src_y;
10024         u32 offset;
10025         int ret;
10026
10027         intel_fill_fb_ggtt_view(&plane_state->view, fb, rotation);
10028         plane_state->color_plane[0].stride = intel_fb_pitch(fb, 0, rotation);
10029
10030         ret = intel_plane_check_stride(plane_state);
10031         if (ret)
10032                 return ret;
10033
10034         src_x = plane_state->base.src_x >> 16;
10035         src_y = plane_state->base.src_y >> 16;
10036
10037         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
10038         offset = intel_plane_compute_aligned_offset(&src_x, &src_y,
10039                                                     plane_state, 0);
10040
10041         if (src_x != 0 || src_y != 0) {
10042                 DRM_DEBUG_KMS("Arbitrary cursor panning not supported\n");
10043                 return -EINVAL;
10044         }
10045
10046         plane_state->color_plane[0].offset = offset;
10047
10048         return 0;
10049 }
10050
10051 static int intel_check_cursor(struct intel_crtc_state *crtc_state,
10052                               struct intel_plane_state *plane_state)
10053 {
10054         const struct drm_framebuffer *fb = plane_state->base.fb;
10055         int ret;
10056
10057         if (fb && fb->modifier != DRM_FORMAT_MOD_LINEAR) {
10058                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
10059                 return -EINVAL;
10060         }
10061
10062         ret = drm_atomic_helper_check_plane_state(&plane_state->base,
10063                                                   &crtc_state->base,
10064                                                   DRM_PLANE_HELPER_NO_SCALING,
10065                                                   DRM_PLANE_HELPER_NO_SCALING,
10066                                                   true, true);
10067         if (ret)
10068                 return ret;
10069
10070         if (!plane_state->base.visible)
10071                 return 0;
10072
10073         ret = intel_plane_check_src_coordinates(plane_state);
10074         if (ret)
10075                 return ret;
10076
10077         ret = intel_cursor_check_surface(plane_state);
10078         if (ret)
10079                 return ret;
10080
10081         return 0;
10082 }
10083
10084 static unsigned int
10085 i845_cursor_max_stride(struct intel_plane *plane,
10086                        u32 pixel_format, u64 modifier,
10087                        unsigned int rotation)
10088 {
10089         return 2048;
10090 }
10091
10092 static u32 i845_cursor_ctl_crtc(const struct intel_crtc_state *crtc_state)
10093 {
10094         u32 cntl = 0;
10095
10096         if (crtc_state->gamma_enable)
10097                 cntl |= CURSOR_GAMMA_ENABLE;
10098
10099         return cntl;
10100 }
10101
10102 static u32 i845_cursor_ctl(const struct intel_crtc_state *crtc_state,
10103                            const struct intel_plane_state *plane_state)
10104 {
10105         return CURSOR_ENABLE |
10106                 CURSOR_FORMAT_ARGB |
10107                 CURSOR_STRIDE(plane_state->color_plane[0].stride);
10108 }
10109
10110 static bool i845_cursor_size_ok(const struct intel_plane_state *plane_state)
10111 {
10112         int width = plane_state->base.crtc_w;
10113
10114         /*
10115          * 845g/865g are only limited by the width of their cursors,
10116          * the height is arbitrary up to the precision of the register.
10117          */
10118         return intel_cursor_size_ok(plane_state) && IS_ALIGNED(width, 64);
10119 }
10120
10121 static int i845_check_cursor(struct intel_crtc_state *crtc_state,
10122                              struct intel_plane_state *plane_state)
10123 {
10124         const struct drm_framebuffer *fb = plane_state->base.fb;
10125         int ret;
10126
10127         ret = intel_check_cursor(crtc_state, plane_state);
10128         if (ret)
10129                 return ret;
10130
10131         /* if we want to turn off the cursor ignore width and height */
10132         if (!fb)
10133                 return 0;
10134
10135         /* Check for which cursor types we support */
10136         if (!i845_cursor_size_ok(plane_state)) {
10137                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
10138                           plane_state->base.crtc_w,
10139                           plane_state->base.crtc_h);
10140                 return -EINVAL;
10141         }
10142
10143         WARN_ON(plane_state->base.visible &&
10144                 plane_state->color_plane[0].stride != fb->pitches[0]);
10145
10146         switch (fb->pitches[0]) {
10147         case 256:
10148         case 512:
10149         case 1024:
10150         case 2048:
10151                 break;
10152         default:
10153                 DRM_DEBUG_KMS("Invalid cursor stride (%u)\n",
10154                               fb->pitches[0]);
10155                 return -EINVAL;
10156         }
10157
10158         plane_state->ctl = i845_cursor_ctl(crtc_state, plane_state);
10159
10160         return 0;
10161 }
10162
10163 static void i845_update_cursor(struct intel_plane *plane,
10164                                const struct intel_crtc_state *crtc_state,
10165                                const struct intel_plane_state *plane_state)
10166 {
10167         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10168         u32 cntl = 0, base = 0, pos = 0, size = 0;
10169         unsigned long irqflags;
10170
10171         if (plane_state && plane_state->base.visible) {
10172                 unsigned int width = plane_state->base.crtc_w;
10173                 unsigned int height = plane_state->base.crtc_h;
10174
10175                 cntl = plane_state->ctl |
10176                         i845_cursor_ctl_crtc(crtc_state);
10177
10178                 size = (height << 12) | width;
10179
10180                 base = intel_cursor_base(plane_state);
10181                 pos = intel_cursor_position(plane_state);
10182         }
10183
10184         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
10185
10186         /* On these chipsets we can only modify the base/size/stride
10187          * whilst the cursor is disabled.
10188          */
10189         if (plane->cursor.base != base ||
10190             plane->cursor.size != size ||
10191             plane->cursor.cntl != cntl) {
10192                 I915_WRITE_FW(CURCNTR(PIPE_A), 0);
10193                 I915_WRITE_FW(CURBASE(PIPE_A), base);
10194                 I915_WRITE_FW(CURSIZE, size);
10195                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
10196                 I915_WRITE_FW(CURCNTR(PIPE_A), cntl);
10197
10198                 plane->cursor.base = base;
10199                 plane->cursor.size = size;
10200                 plane->cursor.cntl = cntl;
10201         } else {
10202                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
10203         }
10204
10205         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
10206 }
10207
10208 static void i845_disable_cursor(struct intel_plane *plane,
10209                                 const struct intel_crtc_state *crtc_state)
10210 {
10211         i845_update_cursor(plane, crtc_state, NULL);
10212 }
10213
10214 static bool i845_cursor_get_hw_state(struct intel_plane *plane,
10215                                      enum pipe *pipe)
10216 {
10217         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10218         enum intel_display_power_domain power_domain;
10219         intel_wakeref_t wakeref;
10220         bool ret;
10221
10222         power_domain = POWER_DOMAIN_PIPE(PIPE_A);
10223         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
10224         if (!wakeref)
10225                 return false;
10226
10227         ret = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
10228
10229         *pipe = PIPE_A;
10230
10231         intel_display_power_put(dev_priv, power_domain, wakeref);
10232
10233         return ret;
10234 }
10235
10236 static unsigned int
10237 i9xx_cursor_max_stride(struct intel_plane *plane,
10238                        u32 pixel_format, u64 modifier,
10239                        unsigned int rotation)
10240 {
10241         return plane->base.dev->mode_config.cursor_width * 4;
10242 }
10243
10244 static u32 i9xx_cursor_ctl_crtc(const struct intel_crtc_state *crtc_state)
10245 {
10246         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
10247         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10248         u32 cntl = 0;
10249
10250         if (INTEL_GEN(dev_priv) >= 11)
10251                 return cntl;
10252
10253         if (crtc_state->gamma_enable)
10254                 cntl = MCURSOR_GAMMA_ENABLE;
10255
10256         if (crtc_state->csc_enable)
10257                 cntl |= MCURSOR_PIPE_CSC_ENABLE;
10258
10259         if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10260                 cntl |= MCURSOR_PIPE_SELECT(crtc->pipe);
10261
10262         return cntl;
10263 }
10264
10265 static u32 i9xx_cursor_ctl(const struct intel_crtc_state *crtc_state,
10266                            const struct intel_plane_state *plane_state)
10267 {
10268         struct drm_i915_private *dev_priv =
10269                 to_i915(plane_state->base.plane->dev);
10270         u32 cntl = 0;
10271
10272         if (IS_GEN(dev_priv, 6) || IS_IVYBRIDGE(dev_priv))
10273                 cntl |= MCURSOR_TRICKLE_FEED_DISABLE;
10274
10275         switch (plane_state->base.crtc_w) {
10276         case 64:
10277                 cntl |= MCURSOR_MODE_64_ARGB_AX;
10278                 break;
10279         case 128:
10280                 cntl |= MCURSOR_MODE_128_ARGB_AX;
10281                 break;
10282         case 256:
10283                 cntl |= MCURSOR_MODE_256_ARGB_AX;
10284                 break;
10285         default:
10286                 MISSING_CASE(plane_state->base.crtc_w);
10287                 return 0;
10288         }
10289
10290         if (plane_state->base.rotation & DRM_MODE_ROTATE_180)
10291                 cntl |= MCURSOR_ROTATE_180;
10292
10293         return cntl;
10294 }
10295
10296 static bool i9xx_cursor_size_ok(const struct intel_plane_state *plane_state)
10297 {
10298         struct drm_i915_private *dev_priv =
10299                 to_i915(plane_state->base.plane->dev);
10300         int width = plane_state->base.crtc_w;
10301         int height = plane_state->base.crtc_h;
10302
10303         if (!intel_cursor_size_ok(plane_state))
10304                 return false;
10305
10306         /* Cursor width is limited to a few power-of-two sizes */
10307         switch (width) {
10308         case 256:
10309         case 128:
10310         case 64:
10311                 break;
10312         default:
10313                 return false;
10314         }
10315
10316         /*
10317          * IVB+ have CUR_FBC_CTL which allows an arbitrary cursor
10318          * height from 8 lines up to the cursor width, when the
10319          * cursor is not rotated. Everything else requires square
10320          * cursors.
10321          */
10322         if (HAS_CUR_FBC(dev_priv) &&
10323             plane_state->base.rotation & DRM_MODE_ROTATE_0) {
10324                 if (height < 8 || height > width)
10325                         return false;
10326         } else {
10327                 if (height != width)
10328                         return false;
10329         }
10330
10331         return true;
10332 }
10333
10334 static int i9xx_check_cursor(struct intel_crtc_state *crtc_state,
10335                              struct intel_plane_state *plane_state)
10336 {
10337         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
10338         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10339         const struct drm_framebuffer *fb = plane_state->base.fb;
10340         enum pipe pipe = plane->pipe;
10341         int ret;
10342
10343         ret = intel_check_cursor(crtc_state, plane_state);
10344         if (ret)
10345                 return ret;
10346
10347         /* if we want to turn off the cursor ignore width and height */
10348         if (!fb)
10349                 return 0;
10350
10351         /* Check for which cursor types we support */
10352         if (!i9xx_cursor_size_ok(plane_state)) {
10353                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
10354                           plane_state->base.crtc_w,
10355                           plane_state->base.crtc_h);
10356                 return -EINVAL;
10357         }
10358
10359         WARN_ON(plane_state->base.visible &&
10360                 plane_state->color_plane[0].stride != fb->pitches[0]);
10361
10362         if (fb->pitches[0] != plane_state->base.crtc_w * fb->format->cpp[0]) {
10363                 DRM_DEBUG_KMS("Invalid cursor stride (%u) (cursor width %d)\n",
10364                               fb->pitches[0], plane_state->base.crtc_w);
10365                 return -EINVAL;
10366         }
10367
10368         /*
10369          * There's something wrong with the cursor on CHV pipe C.
10370          * If it straddles the left edge of the screen then
10371          * moving it away from the edge or disabling it often
10372          * results in a pipe underrun, and often that can lead to
10373          * dead pipe (constant underrun reported, and it scans
10374          * out just a solid color). To recover from that, the
10375          * display power well must be turned off and on again.
10376          * Refuse the put the cursor into that compromised position.
10377          */
10378         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_C &&
10379             plane_state->base.visible && plane_state->base.crtc_x < 0) {
10380                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
10381                 return -EINVAL;
10382         }
10383
10384         plane_state->ctl = i9xx_cursor_ctl(crtc_state, plane_state);
10385
10386         return 0;
10387 }
10388
10389 static void i9xx_update_cursor(struct intel_plane *plane,
10390                                const struct intel_crtc_state *crtc_state,
10391                                const struct intel_plane_state *plane_state)
10392 {
10393         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10394         enum pipe pipe = plane->pipe;
10395         u32 cntl = 0, base = 0, pos = 0, fbc_ctl = 0;
10396         unsigned long irqflags;
10397
10398         if (plane_state && plane_state->base.visible) {
10399                 cntl = plane_state->ctl |
10400                         i9xx_cursor_ctl_crtc(crtc_state);
10401
10402                 if (plane_state->base.crtc_h != plane_state->base.crtc_w)
10403                         fbc_ctl = CUR_FBC_CTL_EN | (plane_state->base.crtc_h - 1);
10404
10405                 base = intel_cursor_base(plane_state);
10406                 pos = intel_cursor_position(plane_state);
10407         }
10408
10409         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
10410
10411         /*
10412          * On some platforms writing CURCNTR first will also
10413          * cause CURPOS to be armed by the CURBASE write.
10414          * Without the CURCNTR write the CURPOS write would
10415          * arm itself. Thus we always update CURCNTR before
10416          * CURPOS.
10417          *
10418          * On other platforms CURPOS always requires the
10419          * CURBASE write to arm the update. Additonally
10420          * a write to any of the cursor register will cancel
10421          * an already armed cursor update. Thus leaving out
10422          * the CURBASE write after CURPOS could lead to a
10423          * cursor that doesn't appear to move, or even change
10424          * shape. Thus we always write CURBASE.
10425          *
10426          * The other registers are armed by by the CURBASE write
10427          * except when the plane is getting enabled at which time
10428          * the CURCNTR write arms the update.
10429          */
10430
10431         if (INTEL_GEN(dev_priv) >= 9)
10432                 skl_write_cursor_wm(plane, crtc_state);
10433
10434         if (plane->cursor.base != base ||
10435             plane->cursor.size != fbc_ctl ||
10436             plane->cursor.cntl != cntl) {
10437                 if (HAS_CUR_FBC(dev_priv))
10438                         I915_WRITE_FW(CUR_FBC_CTL(pipe), fbc_ctl);
10439                 I915_WRITE_FW(CURCNTR(pipe), cntl);
10440                 I915_WRITE_FW(CURPOS(pipe), pos);
10441                 I915_WRITE_FW(CURBASE(pipe), base);
10442
10443                 plane->cursor.base = base;
10444                 plane->cursor.size = fbc_ctl;
10445                 plane->cursor.cntl = cntl;
10446         } else {
10447                 I915_WRITE_FW(CURPOS(pipe), pos);
10448                 I915_WRITE_FW(CURBASE(pipe), base);
10449         }
10450
10451         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
10452 }
10453
10454 static void i9xx_disable_cursor(struct intel_plane *plane,
10455                                 const struct intel_crtc_state *crtc_state)
10456 {
10457         i9xx_update_cursor(plane, crtc_state, NULL);
10458 }
10459
10460 static bool i9xx_cursor_get_hw_state(struct intel_plane *plane,
10461                                      enum pipe *pipe)
10462 {
10463         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10464         enum intel_display_power_domain power_domain;
10465         intel_wakeref_t wakeref;
10466         bool ret;
10467         u32 val;
10468
10469         /*
10470          * Not 100% correct for planes that can move between pipes,
10471          * but that's only the case for gen2-3 which don't have any
10472          * display power wells.
10473          */
10474         power_domain = POWER_DOMAIN_PIPE(plane->pipe);
10475         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
10476         if (!wakeref)
10477                 return false;
10478
10479         val = I915_READ(CURCNTR(plane->pipe));
10480
10481         ret = val & MCURSOR_MODE;
10482
10483         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
10484                 *pipe = plane->pipe;
10485         else
10486                 *pipe = (val & MCURSOR_PIPE_SELECT_MASK) >>
10487                         MCURSOR_PIPE_SELECT_SHIFT;
10488
10489         intel_display_power_put(dev_priv, power_domain, wakeref);
10490
10491         return ret;
10492 }
10493
10494 /* VESA 640x480x72Hz mode to set on the pipe */
10495 static const struct drm_display_mode load_detect_mode = {
10496         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10497                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10498 };
10499
10500 struct drm_framebuffer *
10501 intel_framebuffer_create(struct drm_i915_gem_object *obj,
10502                          struct drm_mode_fb_cmd2 *mode_cmd)
10503 {
10504         struct intel_framebuffer *intel_fb;
10505         int ret;
10506
10507         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10508         if (!intel_fb)
10509                 return ERR_PTR(-ENOMEM);
10510
10511         ret = intel_framebuffer_init(intel_fb, obj, mode_cmd);
10512         if (ret)
10513                 goto err;
10514
10515         return &intel_fb->base;
10516
10517 err:
10518         kfree(intel_fb);
10519         return ERR_PTR(ret);
10520 }
10521
10522 static int intel_modeset_disable_planes(struct drm_atomic_state *state,
10523                                         struct drm_crtc *crtc)
10524 {
10525         struct drm_plane *plane;
10526         struct drm_plane_state *plane_state;
10527         int ret, i;
10528
10529         ret = drm_atomic_add_affected_planes(state, crtc);
10530         if (ret)
10531                 return ret;
10532
10533         for_each_new_plane_in_state(state, plane, plane_state, i) {
10534                 if (plane_state->crtc != crtc)
10535                         continue;
10536
10537                 ret = drm_atomic_set_crtc_for_plane(plane_state, NULL);
10538                 if (ret)
10539                         return ret;
10540
10541                 drm_atomic_set_fb_for_plane(plane_state, NULL);
10542         }
10543
10544         return 0;
10545 }
10546
10547 int intel_get_load_detect_pipe(struct drm_connector *connector,
10548                                const struct drm_display_mode *mode,
10549                                struct intel_load_detect_pipe *old,
10550                                struct drm_modeset_acquire_ctx *ctx)
10551 {
10552         struct intel_crtc *intel_crtc;
10553         struct intel_encoder *intel_encoder =
10554                 intel_attached_encoder(connector);
10555         struct drm_crtc *possible_crtc;
10556         struct drm_encoder *encoder = &intel_encoder->base;
10557         struct drm_crtc *crtc = NULL;
10558         struct drm_device *dev = encoder->dev;
10559         struct drm_i915_private *dev_priv = to_i915(dev);
10560         struct drm_mode_config *config = &dev->mode_config;
10561         struct drm_atomic_state *state = NULL, *restore_state = NULL;
10562         struct drm_connector_state *connector_state;
10563         struct intel_crtc_state *crtc_state;
10564         int ret, i = -1;
10565
10566         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10567                       connector->base.id, connector->name,
10568                       encoder->base.id, encoder->name);
10569
10570         old->restore_state = NULL;
10571
10572         WARN_ON(!drm_modeset_is_locked(&config->connection_mutex));
10573
10574         /*
10575          * Algorithm gets a little messy:
10576          *
10577          *   - if the connector already has an assigned crtc, use it (but make
10578          *     sure it's on first)
10579          *
10580          *   - try to find the first unused crtc that can drive this connector,
10581          *     and use that if we find one
10582          */
10583
10584         /* See if we already have a CRTC for this connector */
10585         if (connector->state->crtc) {
10586                 crtc = connector->state->crtc;
10587
10588                 ret = drm_modeset_lock(&crtc->mutex, ctx);
10589                 if (ret)
10590                         goto fail;
10591
10592                 /* Make sure the crtc and connector are running */
10593                 goto found;
10594         }
10595
10596         /* Find an unused one (if possible) */
10597         for_each_crtc(dev, possible_crtc) {
10598                 i++;
10599                 if (!(encoder->possible_crtcs & (1 << i)))
10600                         continue;
10601
10602                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
10603                 if (ret)
10604                         goto fail;
10605
10606                 if (possible_crtc->state->enable) {
10607                         drm_modeset_unlock(&possible_crtc->mutex);
10608                         continue;
10609                 }
10610
10611                 crtc = possible_crtc;
10612                 break;
10613         }
10614
10615         /*
10616          * If we didn't find an unused CRTC, don't use any.
10617          */
10618         if (!crtc) {
10619                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
10620                 ret = -ENODEV;
10621                 goto fail;
10622         }
10623
10624 found:
10625         intel_crtc = to_intel_crtc(crtc);
10626
10627         state = drm_atomic_state_alloc(dev);
10628         restore_state = drm_atomic_state_alloc(dev);
10629         if (!state || !restore_state) {
10630                 ret = -ENOMEM;
10631                 goto fail;
10632         }
10633
10634         state->acquire_ctx = ctx;
10635         restore_state->acquire_ctx = ctx;
10636
10637         connector_state = drm_atomic_get_connector_state(state, connector);
10638         if (IS_ERR(connector_state)) {
10639                 ret = PTR_ERR(connector_state);
10640                 goto fail;
10641         }
10642
10643         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
10644         if (ret)
10645                 goto fail;
10646
10647         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10648         if (IS_ERR(crtc_state)) {
10649                 ret = PTR_ERR(crtc_state);
10650                 goto fail;
10651         }
10652
10653         crtc_state->base.active = crtc_state->base.enable = true;
10654
10655         if (!mode)
10656                 mode = &load_detect_mode;
10657
10658         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
10659         if (ret)
10660                 goto fail;
10661
10662         ret = intel_modeset_disable_planes(state, crtc);
10663         if (ret)
10664                 goto fail;
10665
10666         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
10667         if (!ret)
10668                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
10669         if (!ret)
10670                 ret = drm_atomic_add_affected_planes(restore_state, crtc);
10671         if (ret) {
10672                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
10673                 goto fail;
10674         }
10675
10676         ret = drm_atomic_commit(state);
10677         if (ret) {
10678                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
10679                 goto fail;
10680         }
10681
10682         old->restore_state = restore_state;
10683         drm_atomic_state_put(state);
10684
10685         /* let the connector get through one full cycle before testing */
10686         intel_wait_for_vblank(dev_priv, intel_crtc->pipe);
10687         return true;
10688
10689 fail:
10690         if (state) {
10691                 drm_atomic_state_put(state);
10692                 state = NULL;
10693         }
10694         if (restore_state) {
10695                 drm_atomic_state_put(restore_state);
10696                 restore_state = NULL;
10697         }
10698
10699         if (ret == -EDEADLK)
10700                 return ret;
10701
10702         return false;
10703 }
10704
10705 void intel_release_load_detect_pipe(struct drm_connector *connector,
10706                                     struct intel_load_detect_pipe *old,
10707                                     struct drm_modeset_acquire_ctx *ctx)
10708 {
10709         struct intel_encoder *intel_encoder =
10710                 intel_attached_encoder(connector);
10711         struct drm_encoder *encoder = &intel_encoder->base;
10712         struct drm_atomic_state *state = old->restore_state;
10713         int ret;
10714
10715         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10716                       connector->base.id, connector->name,
10717                       encoder->base.id, encoder->name);
10718
10719         if (!state)
10720                 return;
10721
10722         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
10723         if (ret)
10724                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
10725         drm_atomic_state_put(state);
10726 }
10727
10728 static int i9xx_pll_refclk(struct drm_device *dev,
10729                            const struct intel_crtc_state *pipe_config)
10730 {
10731         struct drm_i915_private *dev_priv = to_i915(dev);
10732         u32 dpll = pipe_config->dpll_hw_state.dpll;
10733
10734         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10735                 return dev_priv->vbt.lvds_ssc_freq;
10736         else if (HAS_PCH_SPLIT(dev_priv))
10737                 return 120000;
10738         else if (!IS_GEN(dev_priv, 2))
10739                 return 96000;
10740         else
10741                 return 48000;
10742 }
10743
10744 /* Returns the clock of the currently programmed mode of the given pipe. */
10745 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
10746                                 struct intel_crtc_state *pipe_config)
10747 {
10748         struct drm_device *dev = crtc->base.dev;
10749         struct drm_i915_private *dev_priv = to_i915(dev);
10750         int pipe = pipe_config->cpu_transcoder;
10751         u32 dpll = pipe_config->dpll_hw_state.dpll;
10752         u32 fp;
10753         struct dpll clock;
10754         int port_clock;
10755         int refclk = i9xx_pll_refclk(dev, pipe_config);
10756
10757         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10758                 fp = pipe_config->dpll_hw_state.fp0;
10759         else
10760                 fp = pipe_config->dpll_hw_state.fp1;
10761
10762         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10763         if (IS_PINEVIEW(dev_priv)) {
10764                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10765                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10766         } else {
10767                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10768                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10769         }
10770
10771         if (!IS_GEN(dev_priv, 2)) {
10772                 if (IS_PINEVIEW(dev_priv))
10773                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10774                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10775                 else
10776                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10777                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10778
10779                 switch (dpll & DPLL_MODE_MASK) {
10780                 case DPLLB_MODE_DAC_SERIAL:
10781                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10782                                 5 : 10;
10783                         break;
10784                 case DPLLB_MODE_LVDS:
10785                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10786                                 7 : 14;
10787                         break;
10788                 default:
10789                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10790                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10791                         return;
10792                 }
10793
10794                 if (IS_PINEVIEW(dev_priv))
10795                         port_clock = pnv_calc_dpll_params(refclk, &clock);
10796                 else
10797                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
10798         } else {
10799                 u32 lvds = IS_I830(dev_priv) ? 0 : I915_READ(LVDS);
10800                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10801
10802                 if (is_lvds) {
10803                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10804                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10805
10806                         if (lvds & LVDS_CLKB_POWER_UP)
10807                                 clock.p2 = 7;
10808                         else
10809                                 clock.p2 = 14;
10810                 } else {
10811                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10812                                 clock.p1 = 2;
10813                         else {
10814                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10815                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10816                         }
10817                         if (dpll & PLL_P2_DIVIDE_BY_4)
10818                                 clock.p2 = 4;
10819                         else
10820                                 clock.p2 = 2;
10821                 }
10822
10823                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10824         }
10825
10826         /*
10827          * This value includes pixel_multiplier. We will use
10828          * port_clock to compute adjusted_mode.crtc_clock in the
10829          * encoder's get_config() function.
10830          */
10831         pipe_config->port_clock = port_clock;
10832 }
10833
10834 int intel_dotclock_calculate(int link_freq,
10835                              const struct intel_link_m_n *m_n)
10836 {
10837         /*
10838          * The calculation for the data clock is:
10839          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10840          * But we want to avoid losing precison if possible, so:
10841          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10842          *
10843          * and the link clock is simpler:
10844          * link_clock = (m * link_clock) / n
10845          */
10846
10847         if (!m_n->link_n)
10848                 return 0;
10849
10850         return div_u64(mul_u32_u32(m_n->link_m, link_freq), m_n->link_n);
10851 }
10852
10853 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10854                                    struct intel_crtc_state *pipe_config)
10855 {
10856         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10857
10858         /* read out port_clock from the DPLL */
10859         i9xx_crtc_clock_get(crtc, pipe_config);
10860
10861         /*
10862          * In case there is an active pipe without active ports,
10863          * we may need some idea for the dotclock anyway.
10864          * Calculate one based on the FDI configuration.
10865          */
10866         pipe_config->base.adjusted_mode.crtc_clock =
10867                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
10868                                          &pipe_config->fdi_m_n);
10869 }
10870
10871 /* Returns the currently programmed mode of the given encoder. */
10872 struct drm_display_mode *
10873 intel_encoder_current_mode(struct intel_encoder *encoder)
10874 {
10875         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
10876         struct intel_crtc_state *crtc_state;
10877         struct drm_display_mode *mode;
10878         struct intel_crtc *crtc;
10879         enum pipe pipe;
10880
10881         if (!encoder->get_hw_state(encoder, &pipe))
10882                 return NULL;
10883
10884         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
10885
10886         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10887         if (!mode)
10888                 return NULL;
10889
10890         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
10891         if (!crtc_state) {
10892                 kfree(mode);
10893                 return NULL;
10894         }
10895
10896         crtc_state->base.crtc = &crtc->base;
10897
10898         if (!dev_priv->display.get_pipe_config(crtc, crtc_state)) {
10899                 kfree(crtc_state);
10900                 kfree(mode);
10901                 return NULL;
10902         }
10903
10904         encoder->get_config(encoder, crtc_state);
10905
10906         intel_mode_from_pipe_config(mode, crtc_state);
10907
10908         kfree(crtc_state);
10909
10910         return mode;
10911 }
10912
10913 static void intel_crtc_destroy(struct drm_crtc *crtc)
10914 {
10915         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10916
10917         drm_crtc_cleanup(crtc);
10918         kfree(intel_crtc);
10919 }
10920
10921 /**
10922  * intel_wm_need_update - Check whether watermarks need updating
10923  * @cur: current plane state
10924  * @new: new plane state
10925  *
10926  * Check current plane state versus the new one to determine whether
10927  * watermarks need to be recalculated.
10928  *
10929  * Returns true or false.
10930  */
10931 static bool intel_wm_need_update(struct intel_plane_state *cur,
10932                                  struct intel_plane_state *new)
10933 {
10934         /* Update watermarks on tiling or size changes. */
10935         if (new->base.visible != cur->base.visible)
10936                 return true;
10937
10938         if (!cur->base.fb || !new->base.fb)
10939                 return false;
10940
10941         if (cur->base.fb->modifier != new->base.fb->modifier ||
10942             cur->base.rotation != new->base.rotation ||
10943             drm_rect_width(&new->base.src) != drm_rect_width(&cur->base.src) ||
10944             drm_rect_height(&new->base.src) != drm_rect_height(&cur->base.src) ||
10945             drm_rect_width(&new->base.dst) != drm_rect_width(&cur->base.dst) ||
10946             drm_rect_height(&new->base.dst) != drm_rect_height(&cur->base.dst))
10947                 return true;
10948
10949         return false;
10950 }
10951
10952 static bool needs_scaling(const struct intel_plane_state *state)
10953 {
10954         int src_w = drm_rect_width(&state->base.src) >> 16;
10955         int src_h = drm_rect_height(&state->base.src) >> 16;
10956         int dst_w = drm_rect_width(&state->base.dst);
10957         int dst_h = drm_rect_height(&state->base.dst);
10958
10959         return (src_w != dst_w || src_h != dst_h);
10960 }
10961
10962 int intel_plane_atomic_calc_changes(const struct intel_crtc_state *old_crtc_state,
10963                                     struct drm_crtc_state *crtc_state,
10964                                     const struct intel_plane_state *old_plane_state,
10965                                     struct drm_plane_state *plane_state)
10966 {
10967         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
10968         struct drm_crtc *crtc = crtc_state->crtc;
10969         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10970         struct intel_plane *plane = to_intel_plane(plane_state->plane);
10971         struct drm_device *dev = crtc->dev;
10972         struct drm_i915_private *dev_priv = to_i915(dev);
10973         bool mode_changed = needs_modeset(crtc_state);
10974         bool was_crtc_enabled = old_crtc_state->base.active;
10975         bool is_crtc_enabled = crtc_state->active;
10976         bool turn_off, turn_on, visible, was_visible;
10977         struct drm_framebuffer *fb = plane_state->fb;
10978         int ret;
10979
10980         if (INTEL_GEN(dev_priv) >= 9 && plane->id != PLANE_CURSOR) {
10981                 ret = skl_update_scaler_plane(
10982                         to_intel_crtc_state(crtc_state),
10983                         to_intel_plane_state(plane_state));
10984                 if (ret)
10985                         return ret;
10986         }
10987
10988         was_visible = old_plane_state->base.visible;
10989         visible = plane_state->visible;
10990
10991         if (!was_crtc_enabled && WARN_ON(was_visible))
10992                 was_visible = false;
10993
10994         /*
10995          * Visibility is calculated as if the crtc was on, but
10996          * after scaler setup everything depends on it being off
10997          * when the crtc isn't active.
10998          *
10999          * FIXME this is wrong for watermarks. Watermarks should also
11000          * be computed as if the pipe would be active. Perhaps move
11001          * per-plane wm computation to the .check_plane() hook, and
11002          * only combine the results from all planes in the current place?
11003          */
11004         if (!is_crtc_enabled) {
11005                 plane_state->visible = visible = false;
11006                 to_intel_crtc_state(crtc_state)->active_planes &= ~BIT(plane->id);
11007         }
11008
11009         if (!was_visible && !visible)
11010                 return 0;
11011
11012         if (fb != old_plane_state->base.fb)
11013                 pipe_config->fb_changed = true;
11014
11015         turn_off = was_visible && (!visible || mode_changed);
11016         turn_on = visible && (!was_visible || mode_changed);
11017
11018         DRM_DEBUG_ATOMIC("[CRTC:%d:%s] has [PLANE:%d:%s] with fb %i\n",
11019                          intel_crtc->base.base.id, intel_crtc->base.name,
11020                          plane->base.base.id, plane->base.name,
11021                          fb ? fb->base.id : -1);
11022
11023         DRM_DEBUG_ATOMIC("[PLANE:%d:%s] visible %i -> %i, off %i, on %i, ms %i\n",
11024                          plane->base.base.id, plane->base.name,
11025                          was_visible, visible,
11026                          turn_off, turn_on, mode_changed);
11027
11028         if (turn_on) {
11029                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
11030                         pipe_config->update_wm_pre = true;
11031
11032                 /* must disable cxsr around plane enable/disable */
11033                 if (plane->id != PLANE_CURSOR)
11034                         pipe_config->disable_cxsr = true;
11035         } else if (turn_off) {
11036                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
11037                         pipe_config->update_wm_post = true;
11038
11039                 /* must disable cxsr around plane enable/disable */
11040                 if (plane->id != PLANE_CURSOR)
11041                         pipe_config->disable_cxsr = true;
11042         } else if (intel_wm_need_update(to_intel_plane_state(plane->base.state),
11043                                         to_intel_plane_state(plane_state))) {
11044                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
11045                         /* FIXME bollocks */
11046                         pipe_config->update_wm_pre = true;
11047                         pipe_config->update_wm_post = true;
11048                 }
11049         }
11050
11051         if (visible || was_visible)
11052                 pipe_config->fb_bits |= plane->frontbuffer_bit;
11053
11054         /*
11055          * ILK/SNB DVSACNTR/Sprite Enable
11056          * IVB SPR_CTL/Sprite Enable
11057          * "When in Self Refresh Big FIFO mode, a write to enable the
11058          *  plane will be internally buffered and delayed while Big FIFO
11059          *  mode is exiting."
11060          *
11061          * Which means that enabling the sprite can take an extra frame
11062          * when we start in big FIFO mode (LP1+). Thus we need to drop
11063          * down to LP0 and wait for vblank in order to make sure the
11064          * sprite gets enabled on the next vblank after the register write.
11065          * Doing otherwise would risk enabling the sprite one frame after
11066          * we've already signalled flip completion. We can resume LP1+
11067          * once the sprite has been enabled.
11068          *
11069          *
11070          * WaCxSRDisabledForSpriteScaling:ivb
11071          * IVB SPR_SCALE/Scaling Enable
11072          * "Low Power watermarks must be disabled for at least one
11073          *  frame before enabling sprite scaling, and kept disabled
11074          *  until sprite scaling is disabled."
11075          *
11076          * ILK/SNB DVSASCALE/Scaling Enable
11077          * "When in Self Refresh Big FIFO mode, scaling enable will be
11078          *  masked off while Big FIFO mode is exiting."
11079          *
11080          * Despite the w/a only being listed for IVB we assume that
11081          * the ILK/SNB note has similar ramifications, hence we apply
11082          * the w/a on all three platforms.
11083          *
11084          * With experimental results seems this is needed also for primary
11085          * plane, not only sprite plane.
11086          */
11087         if (plane->id != PLANE_CURSOR &&
11088             (IS_GEN_RANGE(dev_priv, 5, 6) ||
11089              IS_IVYBRIDGE(dev_priv)) &&
11090             (turn_on || (!needs_scaling(old_plane_state) &&
11091                          needs_scaling(to_intel_plane_state(plane_state)))))
11092                 pipe_config->disable_lp_wm = true;
11093
11094         return 0;
11095 }
11096
11097 static bool encoders_cloneable(const struct intel_encoder *a,
11098                                const struct intel_encoder *b)
11099 {
11100         /* masks could be asymmetric, so check both ways */
11101         return a == b || (a->cloneable & (1 << b->type) &&
11102                           b->cloneable & (1 << a->type));
11103 }
11104
11105 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
11106                                          struct intel_crtc *crtc,
11107                                          struct intel_encoder *encoder)
11108 {
11109         struct intel_encoder *source_encoder;
11110         struct drm_connector *connector;
11111         struct drm_connector_state *connector_state;
11112         int i;
11113
11114         for_each_new_connector_in_state(state, connector, connector_state, i) {
11115                 if (connector_state->crtc != &crtc->base)
11116                         continue;
11117
11118                 source_encoder =
11119                         to_intel_encoder(connector_state->best_encoder);
11120                 if (!encoders_cloneable(encoder, source_encoder))
11121                         return false;
11122         }
11123
11124         return true;
11125 }
11126
11127 static int icl_add_linked_planes(struct intel_atomic_state *state)
11128 {
11129         struct intel_plane *plane, *linked;
11130         struct intel_plane_state *plane_state, *linked_plane_state;
11131         int i;
11132
11133         for_each_new_intel_plane_in_state(state, plane, plane_state, i) {
11134                 linked = plane_state->linked_plane;
11135
11136                 if (!linked)
11137                         continue;
11138
11139                 linked_plane_state = intel_atomic_get_plane_state(state, linked);
11140                 if (IS_ERR(linked_plane_state))
11141                         return PTR_ERR(linked_plane_state);
11142
11143                 WARN_ON(linked_plane_state->linked_plane != plane);
11144                 WARN_ON(linked_plane_state->slave == plane_state->slave);
11145         }
11146
11147         return 0;
11148 }
11149
11150 static int icl_check_nv12_planes(struct intel_crtc_state *crtc_state)
11151 {
11152         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
11153         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11154         struct intel_atomic_state *state = to_intel_atomic_state(crtc_state->base.state);
11155         struct intel_plane *plane, *linked;
11156         struct intel_plane_state *plane_state;
11157         int i;
11158
11159         if (INTEL_GEN(dev_priv) < 11)
11160                 return 0;
11161
11162         /*
11163          * Destroy all old plane links and make the slave plane invisible
11164          * in the crtc_state->active_planes mask.
11165          */
11166         for_each_new_intel_plane_in_state(state, plane, plane_state, i) {
11167                 if (plane->pipe != crtc->pipe || !plane_state->linked_plane)
11168                         continue;
11169
11170                 plane_state->linked_plane = NULL;
11171                 if (plane_state->slave && !plane_state->base.visible) {
11172                         crtc_state->active_planes &= ~BIT(plane->id);
11173                         crtc_state->update_planes |= BIT(plane->id);
11174                 }
11175
11176                 plane_state->slave = false;
11177         }
11178
11179         if (!crtc_state->nv12_planes)
11180                 return 0;
11181
11182         for_each_new_intel_plane_in_state(state, plane, plane_state, i) {
11183                 struct intel_plane_state *linked_state = NULL;
11184
11185                 if (plane->pipe != crtc->pipe ||
11186                     !(crtc_state->nv12_planes & BIT(plane->id)))
11187                         continue;
11188
11189                 for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, linked) {
11190                         if (!icl_is_nv12_y_plane(linked->id))
11191                                 continue;
11192
11193                         if (crtc_state->active_planes & BIT(linked->id))
11194                                 continue;
11195
11196                         linked_state = intel_atomic_get_plane_state(state, linked);
11197                         if (IS_ERR(linked_state))
11198                                 return PTR_ERR(linked_state);
11199
11200                         break;
11201                 }
11202
11203                 if (!linked_state) {
11204                         DRM_DEBUG_KMS("Need %d free Y planes for planar YUV\n",
11205                                       hweight8(crtc_state->nv12_planes));
11206
11207                         return -EINVAL;
11208                 }
11209
11210                 plane_state->linked_plane = linked;
11211
11212                 linked_state->slave = true;
11213                 linked_state->linked_plane = plane;
11214                 crtc_state->active_planes |= BIT(linked->id);
11215                 crtc_state->update_planes |= BIT(linked->id);
11216                 DRM_DEBUG_KMS("Using %s as Y plane for %s\n", linked->base.name, plane->base.name);
11217         }
11218
11219         return 0;
11220 }
11221
11222 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
11223                                    struct drm_crtc_state *crtc_state)
11224 {
11225         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
11226         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11227         struct intel_crtc_state *pipe_config =
11228                 to_intel_crtc_state(crtc_state);
11229         int ret;
11230         bool mode_changed = needs_modeset(crtc_state);
11231
11232         if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv) &&
11233             mode_changed && !crtc_state->active)
11234                 pipe_config->update_wm_post = true;
11235
11236         if (mode_changed && crtc_state->enable &&
11237             dev_priv->display.crtc_compute_clock &&
11238             !WARN_ON(pipe_config->shared_dpll)) {
11239                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
11240                                                            pipe_config);
11241                 if (ret)
11242                         return ret;
11243         }
11244
11245         if (mode_changed || pipe_config->update_pipe ||
11246             crtc_state->color_mgmt_changed) {
11247                 ret = intel_color_check(pipe_config);
11248                 if (ret)
11249                         return ret;
11250         }
11251
11252         ret = 0;
11253         if (dev_priv->display.compute_pipe_wm) {
11254                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
11255                 if (ret) {
11256                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
11257                         return ret;
11258                 }
11259         }
11260
11261         if (dev_priv->display.compute_intermediate_wm) {
11262                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
11263                         return 0;
11264
11265                 /*
11266                  * Calculate 'intermediate' watermarks that satisfy both the
11267                  * old state and the new state.  We can program these
11268                  * immediately.
11269                  */
11270                 ret = dev_priv->display.compute_intermediate_wm(pipe_config);
11271                 if (ret) {
11272                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
11273                         return ret;
11274                 }
11275         }
11276
11277         if (INTEL_GEN(dev_priv) >= 9) {
11278                 if (mode_changed || pipe_config->update_pipe)
11279                         ret = skl_update_scaler_crtc(pipe_config);
11280
11281                 if (!ret)
11282                         ret = icl_check_nv12_planes(pipe_config);
11283                 if (!ret)
11284                         ret = skl_check_pipe_max_pixel_rate(intel_crtc,
11285                                                             pipe_config);
11286                 if (!ret)
11287                         ret = intel_atomic_setup_scalers(dev_priv, intel_crtc,
11288                                                          pipe_config);
11289         }
11290
11291         if (HAS_IPS(dev_priv))
11292                 pipe_config->ips_enabled = hsw_compute_ips_config(pipe_config);
11293
11294         return ret;
11295 }
11296
11297 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
11298         .atomic_check = intel_crtc_atomic_check,
11299 };
11300
11301 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
11302 {
11303         struct intel_connector *connector;
11304         struct drm_connector_list_iter conn_iter;
11305
11306         drm_connector_list_iter_begin(dev, &conn_iter);
11307         for_each_intel_connector_iter(connector, &conn_iter) {
11308                 if (connector->base.state->crtc)
11309                         drm_connector_put(&connector->base);
11310
11311                 if (connector->base.encoder) {
11312                         connector->base.state->best_encoder =
11313                                 connector->base.encoder;
11314                         connector->base.state->crtc =
11315                                 connector->base.encoder->crtc;
11316
11317                         drm_connector_get(&connector->base);
11318                 } else {
11319                         connector->base.state->best_encoder = NULL;
11320                         connector->base.state->crtc = NULL;
11321                 }
11322         }
11323         drm_connector_list_iter_end(&conn_iter);
11324 }
11325
11326 static int
11327 compute_sink_pipe_bpp(const struct drm_connector_state *conn_state,
11328                       struct intel_crtc_state *pipe_config)
11329 {
11330         struct drm_connector *connector = conn_state->connector;
11331         const struct drm_display_info *info = &connector->display_info;
11332         int bpp;
11333
11334         switch (conn_state->max_bpc) {
11335         case 6 ... 7:
11336                 bpp = 6 * 3;
11337                 break;
11338         case 8 ... 9:
11339                 bpp = 8 * 3;
11340                 break;
11341         case 10 ... 11:
11342                 bpp = 10 * 3;
11343                 break;
11344         case 12:
11345                 bpp = 12 * 3;
11346                 break;
11347         default:
11348                 return -EINVAL;
11349         }
11350
11351         if (bpp < pipe_config->pipe_bpp) {
11352                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] Limiting display bpp to %d instead of "
11353                               "EDID bpp %d, requested bpp %d, max platform bpp %d\n",
11354                               connector->base.id, connector->name,
11355                               bpp, 3 * info->bpc, 3 * conn_state->max_requested_bpc,
11356                               pipe_config->pipe_bpp);
11357
11358                 pipe_config->pipe_bpp = bpp;
11359         }
11360
11361         return 0;
11362 }
11363
11364 static int
11365 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
11366                           struct intel_crtc_state *pipe_config)
11367 {
11368         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11369         struct drm_atomic_state *state = pipe_config->base.state;
11370         struct drm_connector *connector;
11371         struct drm_connector_state *connector_state;
11372         int bpp, i;
11373
11374         if ((IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
11375             IS_CHERRYVIEW(dev_priv)))
11376                 bpp = 10*3;
11377         else if (INTEL_GEN(dev_priv) >= 5)
11378                 bpp = 12*3;
11379         else
11380                 bpp = 8*3;
11381
11382         pipe_config->pipe_bpp = bpp;
11383
11384         /* Clamp display bpp to connector max bpp */
11385         for_each_new_connector_in_state(state, connector, connector_state, i) {
11386                 int ret;
11387
11388                 if (connector_state->crtc != &crtc->base)
11389                         continue;
11390
11391                 ret = compute_sink_pipe_bpp(connector_state, pipe_config);
11392                 if (ret)
11393                         return ret;
11394         }
11395
11396         return 0;
11397 }
11398
11399 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
11400 {
11401         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
11402                         "type: 0x%x flags: 0x%x\n",
11403                 mode->crtc_clock,
11404                 mode->crtc_hdisplay, mode->crtc_hsync_start,
11405                 mode->crtc_hsync_end, mode->crtc_htotal,
11406                 mode->crtc_vdisplay, mode->crtc_vsync_start,
11407                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
11408 }
11409
11410 static inline void
11411 intel_dump_m_n_config(struct intel_crtc_state *pipe_config, char *id,
11412                       unsigned int lane_count, struct intel_link_m_n *m_n)
11413 {
11414         DRM_DEBUG_KMS("%s: lanes: %i; gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
11415                       id, lane_count,
11416                       m_n->gmch_m, m_n->gmch_n,
11417                       m_n->link_m, m_n->link_n, m_n->tu);
11418 }
11419
11420 static void
11421 intel_dump_infoframe(struct drm_i915_private *dev_priv,
11422                      const union hdmi_infoframe *frame)
11423 {
11424         if ((drm_debug & DRM_UT_KMS) == 0)
11425                 return;
11426
11427         hdmi_infoframe_log(KERN_DEBUG, dev_priv->drm.dev, frame);
11428 }
11429
11430 #define OUTPUT_TYPE(x) [INTEL_OUTPUT_ ## x] = #x
11431
11432 static const char * const output_type_str[] = {
11433         OUTPUT_TYPE(UNUSED),
11434         OUTPUT_TYPE(ANALOG),
11435         OUTPUT_TYPE(DVO),
11436         OUTPUT_TYPE(SDVO),
11437         OUTPUT_TYPE(LVDS),
11438         OUTPUT_TYPE(TVOUT),
11439         OUTPUT_TYPE(HDMI),
11440         OUTPUT_TYPE(DP),
11441         OUTPUT_TYPE(EDP),
11442         OUTPUT_TYPE(DSI),
11443         OUTPUT_TYPE(DDI),
11444         OUTPUT_TYPE(DP_MST),
11445 };
11446
11447 #undef OUTPUT_TYPE
11448
11449 static void snprintf_output_types(char *buf, size_t len,
11450                                   unsigned int output_types)
11451 {
11452         char *str = buf;
11453         int i;
11454
11455         str[0] = '\0';
11456
11457         for (i = 0; i < ARRAY_SIZE(output_type_str); i++) {
11458                 int r;
11459
11460                 if ((output_types & BIT(i)) == 0)
11461                         continue;
11462
11463                 r = snprintf(str, len, "%s%s",
11464                              str != buf ? "," : "", output_type_str[i]);
11465                 if (r >= len)
11466                         break;
11467                 str += r;
11468                 len -= r;
11469
11470                 output_types &= ~BIT(i);
11471         }
11472
11473         WARN_ON_ONCE(output_types != 0);
11474 }
11475
11476 static const char * const output_format_str[] = {
11477         [INTEL_OUTPUT_FORMAT_INVALID] = "Invalid",
11478         [INTEL_OUTPUT_FORMAT_RGB] = "RGB",
11479         [INTEL_OUTPUT_FORMAT_YCBCR420] = "YCBCR4:2:0",
11480         [INTEL_OUTPUT_FORMAT_YCBCR444] = "YCBCR4:4:4",
11481 };
11482
11483 static const char *output_formats(enum intel_output_format format)
11484 {
11485         if (format >= ARRAY_SIZE(output_format_str))
11486                 format = INTEL_OUTPUT_FORMAT_INVALID;
11487         return output_format_str[format];
11488 }
11489
11490 static void intel_dump_pipe_config(struct intel_crtc *crtc,
11491                                    struct intel_crtc_state *pipe_config,
11492                                    const char *context)
11493 {
11494         struct drm_device *dev = crtc->base.dev;
11495         struct drm_i915_private *dev_priv = to_i915(dev);
11496         struct drm_plane *plane;
11497         struct intel_plane *intel_plane;
11498         struct intel_plane_state *state;
11499         struct drm_framebuffer *fb;
11500         char buf[64];
11501
11502         DRM_DEBUG_KMS("[CRTC:%d:%s]%s\n",
11503                       crtc->base.base.id, crtc->base.name, context);
11504
11505         snprintf_output_types(buf, sizeof(buf), pipe_config->output_types);
11506         DRM_DEBUG_KMS("output_types: %s (0x%x)\n",
11507                       buf, pipe_config->output_types);
11508
11509         DRM_DEBUG_KMS("output format: %s\n",
11510                       output_formats(pipe_config->output_format));
11511
11512         DRM_DEBUG_KMS("cpu_transcoder: %s, pipe bpp: %i, dithering: %i\n",
11513                       transcoder_name(pipe_config->cpu_transcoder),
11514                       pipe_config->pipe_bpp, pipe_config->dither);
11515
11516         if (pipe_config->has_pch_encoder)
11517                 intel_dump_m_n_config(pipe_config, "fdi",
11518                                       pipe_config->fdi_lanes,
11519                                       &pipe_config->fdi_m_n);
11520
11521         if (intel_crtc_has_dp_encoder(pipe_config)) {
11522                 intel_dump_m_n_config(pipe_config, "dp m_n",
11523                                 pipe_config->lane_count, &pipe_config->dp_m_n);
11524                 if (pipe_config->has_drrs)
11525                         intel_dump_m_n_config(pipe_config, "dp m2_n2",
11526                                               pipe_config->lane_count,
11527                                               &pipe_config->dp_m2_n2);
11528         }
11529
11530         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
11531                       pipe_config->has_audio, pipe_config->has_infoframe);
11532
11533         DRM_DEBUG_KMS("infoframes enabled: 0x%x\n",
11534                       pipe_config->infoframes.enable);
11535
11536         if (pipe_config->infoframes.enable &
11537             intel_hdmi_infoframe_enable(HDMI_PACKET_TYPE_GENERAL_CONTROL))
11538                 DRM_DEBUG_KMS("GCP: 0x%x\n", pipe_config->infoframes.gcp);
11539         if (pipe_config->infoframes.enable &
11540             intel_hdmi_infoframe_enable(HDMI_INFOFRAME_TYPE_AVI))
11541                 intel_dump_infoframe(dev_priv, &pipe_config->infoframes.avi);
11542         if (pipe_config->infoframes.enable &
11543             intel_hdmi_infoframe_enable(HDMI_INFOFRAME_TYPE_SPD))
11544                 intel_dump_infoframe(dev_priv, &pipe_config->infoframes.spd);
11545         if (pipe_config->infoframes.enable &
11546             intel_hdmi_infoframe_enable(HDMI_INFOFRAME_TYPE_VENDOR))
11547                 intel_dump_infoframe(dev_priv, &pipe_config->infoframes.hdmi);
11548
11549         DRM_DEBUG_KMS("requested mode:\n");
11550         drm_mode_debug_printmodeline(&pipe_config->base.mode);
11551         DRM_DEBUG_KMS("adjusted mode:\n");
11552         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
11553         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
11554         DRM_DEBUG_KMS("port clock: %d, pipe src size: %dx%d, pixel rate %d\n",
11555                       pipe_config->port_clock,
11556                       pipe_config->pipe_src_w, pipe_config->pipe_src_h,
11557                       pipe_config->pixel_rate);
11558
11559         if (INTEL_GEN(dev_priv) >= 9)
11560                 DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
11561                               crtc->num_scalers,
11562                               pipe_config->scaler_state.scaler_users,
11563                               pipe_config->scaler_state.scaler_id);
11564
11565         if (HAS_GMCH(dev_priv))
11566                 DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
11567                               pipe_config->gmch_pfit.control,
11568                               pipe_config->gmch_pfit.pgm_ratios,
11569                               pipe_config->gmch_pfit.lvds_border_bits);
11570         else
11571                 DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s, force thru: %s\n",
11572                               pipe_config->pch_pfit.pos,
11573                               pipe_config->pch_pfit.size,
11574                               enableddisabled(pipe_config->pch_pfit.enabled),
11575                               yesno(pipe_config->pch_pfit.force_thru));
11576
11577         DRM_DEBUG_KMS("ips: %i, double wide: %i\n",
11578                       pipe_config->ips_enabled, pipe_config->double_wide);
11579
11580         intel_dpll_dump_hw_state(dev_priv, &pipe_config->dpll_hw_state);
11581
11582         DRM_DEBUG_KMS("planes on this crtc\n");
11583         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
11584                 struct drm_format_name_buf format_name;
11585                 intel_plane = to_intel_plane(plane);
11586                 if (intel_plane->pipe != crtc->pipe)
11587                         continue;
11588
11589                 state = to_intel_plane_state(plane->state);
11590                 fb = state->base.fb;
11591                 if (!fb) {
11592                         DRM_DEBUG_KMS("[PLANE:%d:%s] disabled, scaler_id = %d\n",
11593                                       plane->base.id, plane->name, state->scaler_id);
11594                         continue;
11595                 }
11596
11597                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d, fb = %ux%u format = %s\n",
11598                               plane->base.id, plane->name,
11599                               fb->base.id, fb->width, fb->height,
11600                               drm_get_format_name(fb->format->format, &format_name));
11601                 if (INTEL_GEN(dev_priv) >= 9)
11602                         DRM_DEBUG_KMS("\tscaler:%d src %dx%d+%d+%d dst %dx%d+%d+%d\n",
11603                                       state->scaler_id,
11604                                       state->base.src.x1 >> 16,
11605                                       state->base.src.y1 >> 16,
11606                                       drm_rect_width(&state->base.src) >> 16,
11607                                       drm_rect_height(&state->base.src) >> 16,
11608                                       state->base.dst.x1, state->base.dst.y1,
11609                                       drm_rect_width(&state->base.dst),
11610                                       drm_rect_height(&state->base.dst));
11611         }
11612 }
11613
11614 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
11615 {
11616         struct drm_device *dev = state->dev;
11617         struct drm_connector *connector;
11618         struct drm_connector_list_iter conn_iter;
11619         unsigned int used_ports = 0;
11620         unsigned int used_mst_ports = 0;
11621         bool ret = true;
11622
11623         /*
11624          * Walk the connector list instead of the encoder
11625          * list to detect the problem on ddi platforms
11626          * where there's just one encoder per digital port.
11627          */
11628         drm_connector_list_iter_begin(dev, &conn_iter);
11629         drm_for_each_connector_iter(connector, &conn_iter) {
11630                 struct drm_connector_state *connector_state;
11631                 struct intel_encoder *encoder;
11632
11633                 connector_state = drm_atomic_get_new_connector_state(state, connector);
11634                 if (!connector_state)
11635                         connector_state = connector->state;
11636
11637                 if (!connector_state->best_encoder)
11638                         continue;
11639
11640                 encoder = to_intel_encoder(connector_state->best_encoder);
11641
11642                 WARN_ON(!connector_state->crtc);
11643
11644                 switch (encoder->type) {
11645                         unsigned int port_mask;
11646                 case INTEL_OUTPUT_DDI:
11647                         if (WARN_ON(!HAS_DDI(to_i915(dev))))
11648                                 break;
11649                         /* else: fall through */
11650                 case INTEL_OUTPUT_DP:
11651                 case INTEL_OUTPUT_HDMI:
11652                 case INTEL_OUTPUT_EDP:
11653                         port_mask = 1 << encoder->port;
11654
11655                         /* the same port mustn't appear more than once */
11656                         if (used_ports & port_mask)
11657                                 ret = false;
11658
11659                         used_ports |= port_mask;
11660                         break;
11661                 case INTEL_OUTPUT_DP_MST:
11662                         used_mst_ports |=
11663                                 1 << encoder->port;
11664                         break;
11665                 default:
11666                         break;
11667                 }
11668         }
11669         drm_connector_list_iter_end(&conn_iter);
11670
11671         /* can't mix MST and SST/HDMI on the same port */
11672         if (used_ports & used_mst_ports)
11673                 return false;
11674
11675         return ret;
11676 }
11677
11678 static int
11679 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
11680 {
11681         struct drm_i915_private *dev_priv =
11682                 to_i915(crtc_state->base.crtc->dev);
11683         struct intel_crtc_state *saved_state;
11684
11685         saved_state = kzalloc(sizeof(*saved_state), GFP_KERNEL);
11686         if (!saved_state)
11687                 return -ENOMEM;
11688
11689         /* FIXME: before the switch to atomic started, a new pipe_config was
11690          * kzalloc'd. Code that depends on any field being zero should be
11691          * fixed, so that the crtc_state can be safely duplicated. For now,
11692          * only fields that are know to not cause problems are preserved. */
11693
11694         saved_state->scaler_state = crtc_state->scaler_state;
11695         saved_state->shared_dpll = crtc_state->shared_dpll;
11696         saved_state->dpll_hw_state = crtc_state->dpll_hw_state;
11697         saved_state->crc_enabled = crtc_state->crc_enabled;
11698         if (IS_G4X(dev_priv) ||
11699             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11700                 saved_state->wm = crtc_state->wm;
11701
11702         /* Keep base drm_crtc_state intact, only clear our extended struct */
11703         BUILD_BUG_ON(offsetof(struct intel_crtc_state, base));
11704         memcpy(&crtc_state->base + 1, &saved_state->base + 1,
11705                sizeof(*crtc_state) - sizeof(crtc_state->base));
11706
11707         kfree(saved_state);
11708         return 0;
11709 }
11710
11711 static int
11712 intel_modeset_pipe_config(struct drm_crtc *crtc,
11713                           struct intel_crtc_state *pipe_config)
11714 {
11715         struct drm_atomic_state *state = pipe_config->base.state;
11716         struct intel_encoder *encoder;
11717         struct drm_connector *connector;
11718         struct drm_connector_state *connector_state;
11719         int base_bpp, ret;
11720         int i;
11721         bool retry = true;
11722
11723         ret = clear_intel_crtc_state(pipe_config);
11724         if (ret)
11725                 return ret;
11726
11727         pipe_config->cpu_transcoder =
11728                 (enum transcoder) to_intel_crtc(crtc)->pipe;
11729
11730         /*
11731          * Sanitize sync polarity flags based on requested ones. If neither
11732          * positive or negative polarity is requested, treat this as meaning
11733          * negative polarity.
11734          */
11735         if (!(pipe_config->base.adjusted_mode.flags &
11736               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
11737                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
11738
11739         if (!(pipe_config->base.adjusted_mode.flags &
11740               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
11741                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
11742
11743         ret = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
11744                                         pipe_config);
11745         if (ret)
11746                 return ret;
11747
11748         base_bpp = pipe_config->pipe_bpp;
11749
11750         /*
11751          * Determine the real pipe dimensions. Note that stereo modes can
11752          * increase the actual pipe size due to the frame doubling and
11753          * insertion of additional space for blanks between the frame. This
11754          * is stored in the crtc timings. We use the requested mode to do this
11755          * computation to clearly distinguish it from the adjusted mode, which
11756          * can be changed by the connectors in the below retry loop.
11757          */
11758         drm_mode_get_hv_timing(&pipe_config->base.mode,
11759                                &pipe_config->pipe_src_w,
11760                                &pipe_config->pipe_src_h);
11761
11762         for_each_new_connector_in_state(state, connector, connector_state, i) {
11763                 if (connector_state->crtc != crtc)
11764                         continue;
11765
11766                 encoder = to_intel_encoder(connector_state->best_encoder);
11767
11768                 if (!check_single_encoder_cloning(state, to_intel_crtc(crtc), encoder)) {
11769                         DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
11770                         return -EINVAL;
11771                 }
11772
11773                 /*
11774                  * Determine output_types before calling the .compute_config()
11775                  * hooks so that the hooks can use this information safely.
11776                  */
11777                 if (encoder->compute_output_type)
11778                         pipe_config->output_types |=
11779                                 BIT(encoder->compute_output_type(encoder, pipe_config,
11780                                                                  connector_state));
11781                 else
11782                         pipe_config->output_types |= BIT(encoder->type);
11783         }
11784
11785 encoder_retry:
11786         /* Ensure the port clock defaults are reset when retrying. */
11787         pipe_config->port_clock = 0;
11788         pipe_config->pixel_multiplier = 1;
11789
11790         /* Fill in default crtc timings, allow encoders to overwrite them. */
11791         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
11792                               CRTC_STEREO_DOUBLE);
11793
11794         /* Pass our mode to the connectors and the CRTC to give them a chance to
11795          * adjust it according to limitations or connector properties, and also
11796          * a chance to reject the mode entirely.
11797          */
11798         for_each_new_connector_in_state(state, connector, connector_state, i) {
11799                 if (connector_state->crtc != crtc)
11800                         continue;
11801
11802                 encoder = to_intel_encoder(connector_state->best_encoder);
11803                 ret = encoder->compute_config(encoder, pipe_config,
11804                                               connector_state);
11805                 if (ret < 0) {
11806                         if (ret != -EDEADLK)
11807                                 DRM_DEBUG_KMS("Encoder config failure: %d\n",
11808                                               ret);
11809                         return ret;
11810                 }
11811         }
11812
11813         /* Set default port clock if not overwritten by the encoder. Needs to be
11814          * done afterwards in case the encoder adjusts the mode. */
11815         if (!pipe_config->port_clock)
11816                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
11817                         * pipe_config->pixel_multiplier;
11818
11819         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
11820         if (ret == -EDEADLK)
11821                 return ret;
11822         if (ret < 0) {
11823                 DRM_DEBUG_KMS("CRTC fixup failed\n");
11824                 return ret;
11825         }
11826
11827         if (ret == RETRY) {
11828                 if (WARN(!retry, "loop in pipe configuration computation\n"))
11829                         return -EINVAL;
11830
11831                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
11832                 retry = false;
11833                 goto encoder_retry;
11834         }
11835
11836         /* Dithering seems to not pass-through bits correctly when it should, so
11837          * only enable it on 6bpc panels and when its not a compliance
11838          * test requesting 6bpc video pattern.
11839          */
11840         pipe_config->dither = (pipe_config->pipe_bpp == 6*3) &&
11841                 !pipe_config->dither_force_disable;
11842         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
11843                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
11844
11845         return 0;
11846 }
11847
11848 static bool intel_fuzzy_clock_check(int clock1, int clock2)
11849 {
11850         int diff;
11851
11852         if (clock1 == clock2)
11853                 return true;
11854
11855         if (!clock1 || !clock2)
11856                 return false;
11857
11858         diff = abs(clock1 - clock2);
11859
11860         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
11861                 return true;
11862
11863         return false;
11864 }
11865
11866 static bool
11867 intel_compare_m_n(unsigned int m, unsigned int n,
11868                   unsigned int m2, unsigned int n2,
11869                   bool exact)
11870 {
11871         if (m == m2 && n == n2)
11872                 return true;
11873
11874         if (exact || !m || !n || !m2 || !n2)
11875                 return false;
11876
11877         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
11878
11879         if (n > n2) {
11880                 while (n > n2) {
11881                         m2 <<= 1;
11882                         n2 <<= 1;
11883                 }
11884         } else if (n < n2) {
11885                 while (n < n2) {
11886                         m <<= 1;
11887                         n <<= 1;
11888                 }
11889         }
11890
11891         if (n != n2)
11892                 return false;
11893
11894         return intel_fuzzy_clock_check(m, m2);
11895 }
11896
11897 static bool
11898 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
11899                        struct intel_link_m_n *m2_n2,
11900                        bool adjust)
11901 {
11902         if (m_n->tu == m2_n2->tu &&
11903             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
11904                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
11905             intel_compare_m_n(m_n->link_m, m_n->link_n,
11906                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
11907                 if (adjust)
11908                         *m2_n2 = *m_n;
11909
11910                 return true;
11911         }
11912
11913         return false;
11914 }
11915
11916 static bool
11917 intel_compare_infoframe(const union hdmi_infoframe *a,
11918                         const union hdmi_infoframe *b)
11919 {
11920         return memcmp(a, b, sizeof(*a)) == 0;
11921 }
11922
11923 static void
11924 pipe_config_infoframe_err(struct drm_i915_private *dev_priv,
11925                           bool adjust, const char *name,
11926                           const union hdmi_infoframe *a,
11927                           const union hdmi_infoframe *b)
11928 {
11929         if (adjust) {
11930                 if ((drm_debug & DRM_UT_KMS) == 0)
11931                         return;
11932
11933                 drm_dbg(DRM_UT_KMS, "mismatch in %s infoframe", name);
11934                 drm_dbg(DRM_UT_KMS, "expected:");
11935                 hdmi_infoframe_log(KERN_DEBUG, dev_priv->drm.dev, a);
11936                 drm_dbg(DRM_UT_KMS, "found");
11937                 hdmi_infoframe_log(KERN_DEBUG, dev_priv->drm.dev, b);
11938         } else {
11939                 drm_err("mismatch in %s infoframe", name);
11940                 drm_err("expected:");
11941                 hdmi_infoframe_log(KERN_ERR, dev_priv->drm.dev, a);
11942                 drm_err("found");
11943                 hdmi_infoframe_log(KERN_ERR, dev_priv->drm.dev, b);
11944         }
11945 }
11946
11947 static void __printf(3, 4)
11948 pipe_config_err(bool adjust, const char *name, const char *format, ...)
11949 {
11950         struct va_format vaf;
11951         va_list args;
11952
11953         va_start(args, format);
11954         vaf.fmt = format;
11955         vaf.va = &args;
11956
11957         if (adjust)
11958                 drm_dbg(DRM_UT_KMS, "mismatch in %s %pV", name, &vaf);
11959         else
11960                 drm_err("mismatch in %s %pV", name, &vaf);
11961
11962         va_end(args);
11963 }
11964
11965 static bool fastboot_enabled(struct drm_i915_private *dev_priv)
11966 {
11967         if (i915_modparams.fastboot != -1)
11968                 return i915_modparams.fastboot;
11969
11970         /* Enable fastboot by default on Skylake and newer */
11971         if (INTEL_GEN(dev_priv) >= 9)
11972                 return true;
11973
11974         /* Enable fastboot by default on VLV and CHV */
11975         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11976                 return true;
11977
11978         /* Disabled by default on all others */
11979         return false;
11980 }
11981
11982 static bool
11983 intel_pipe_config_compare(struct drm_i915_private *dev_priv,
11984                           struct intel_crtc_state *current_config,
11985                           struct intel_crtc_state *pipe_config,
11986                           bool adjust)
11987 {
11988         bool ret = true;
11989         bool fixup_inherited = adjust &&
11990                 (current_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED) &&
11991                 !(pipe_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED);
11992
11993         if (fixup_inherited && !fastboot_enabled(dev_priv)) {
11994                 DRM_DEBUG_KMS("initial modeset and fastboot not set\n");
11995                 ret = false;
11996         }
11997
11998 #define PIPE_CONF_CHECK_X(name) do { \
11999         if (current_config->name != pipe_config->name) { \
12000                 pipe_config_err(adjust, __stringify(name), \
12001                           "(expected 0x%08x, found 0x%08x)\n", \
12002                           current_config->name, \
12003                           pipe_config->name); \
12004                 ret = false; \
12005         } \
12006 } while (0)
12007
12008 #define PIPE_CONF_CHECK_I(name) do { \
12009         if (current_config->name != pipe_config->name) { \
12010                 pipe_config_err(adjust, __stringify(name), \
12011                           "(expected %i, found %i)\n", \
12012                           current_config->name, \
12013                           pipe_config->name); \
12014                 ret = false; \
12015         } \
12016 } while (0)
12017
12018 #define PIPE_CONF_CHECK_BOOL(name) do { \
12019         if (current_config->name != pipe_config->name) { \
12020                 pipe_config_err(adjust, __stringify(name), \
12021                           "(expected %s, found %s)\n", \
12022                           yesno(current_config->name), \
12023                           yesno(pipe_config->name)); \
12024                 ret = false; \
12025         } \
12026 } while (0)
12027
12028 /*
12029  * Checks state where we only read out the enabling, but not the entire
12030  * state itself (like full infoframes or ELD for audio). These states
12031  * require a full modeset on bootup to fix up.
12032  */
12033 #define PIPE_CONF_CHECK_BOOL_INCOMPLETE(name) do { \
12034         if (!fixup_inherited || (!current_config->name && !pipe_config->name)) { \
12035                 PIPE_CONF_CHECK_BOOL(name); \
12036         } else { \
12037                 pipe_config_err(adjust, __stringify(name), \
12038                           "unable to verify whether state matches exactly, forcing modeset (expected %s, found %s)\n", \
12039                           yesno(current_config->name), \
12040                           yesno(pipe_config->name)); \
12041                 ret = false; \
12042         } \
12043 } while (0)
12044
12045 #define PIPE_CONF_CHECK_P(name) do { \
12046         if (current_config->name != pipe_config->name) { \
12047                 pipe_config_err(adjust, __stringify(name), \
12048                           "(expected %p, found %p)\n", \
12049                           current_config->name, \
12050                           pipe_config->name); \
12051                 ret = false; \
12052         } \
12053 } while (0)
12054
12055 #define PIPE_CONF_CHECK_M_N(name) do { \
12056         if (!intel_compare_link_m_n(&current_config->name, \
12057                                     &pipe_config->name,\
12058                                     adjust)) { \
12059                 pipe_config_err(adjust, __stringify(name), \
12060                           "(expected tu %i gmch %i/%i link %i/%i, " \
12061                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12062                           current_config->name.tu, \
12063                           current_config->name.gmch_m, \
12064                           current_config->name.gmch_n, \
12065                           current_config->name.link_m, \
12066                           current_config->name.link_n, \
12067                           pipe_config->name.tu, \
12068                           pipe_config->name.gmch_m, \
12069                           pipe_config->name.gmch_n, \
12070                           pipe_config->name.link_m, \
12071                           pipe_config->name.link_n); \
12072                 ret = false; \
12073         } \
12074 } while (0)
12075
12076 /* This is required for BDW+ where there is only one set of registers for
12077  * switching between high and low RR.
12078  * This macro can be used whenever a comparison has to be made between one
12079  * hw state and multiple sw state variables.
12080  */
12081 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) do { \
12082         if (!intel_compare_link_m_n(&current_config->name, \
12083                                     &pipe_config->name, adjust) && \
12084             !intel_compare_link_m_n(&current_config->alt_name, \
12085                                     &pipe_config->name, adjust)) { \
12086                 pipe_config_err(adjust, __stringify(name), \
12087                           "(expected tu %i gmch %i/%i link %i/%i, " \
12088                           "or tu %i gmch %i/%i link %i/%i, " \
12089                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12090                           current_config->name.tu, \
12091                           current_config->name.gmch_m, \
12092                           current_config->name.gmch_n, \
12093                           current_config->name.link_m, \
12094                           current_config->name.link_n, \
12095                           current_config->alt_name.tu, \
12096                           current_config->alt_name.gmch_m, \
12097                           current_config->alt_name.gmch_n, \
12098                           current_config->alt_name.link_m, \
12099                           current_config->alt_name.link_n, \
12100                           pipe_config->name.tu, \
12101                           pipe_config->name.gmch_m, \
12102                           pipe_config->name.gmch_n, \
12103                           pipe_config->name.link_m, \
12104                           pipe_config->name.link_n); \
12105                 ret = false; \
12106         } \
12107 } while (0)
12108
12109 #define PIPE_CONF_CHECK_FLAGS(name, mask) do { \
12110         if ((current_config->name ^ pipe_config->name) & (mask)) { \
12111                 pipe_config_err(adjust, __stringify(name), \
12112                           "(%x) (expected %i, found %i)\n", \
12113                           (mask), \
12114                           current_config->name & (mask), \
12115                           pipe_config->name & (mask)); \
12116                 ret = false; \
12117         } \
12118 } while (0)
12119
12120 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) do { \
12121         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
12122                 pipe_config_err(adjust, __stringify(name), \
12123                           "(expected %i, found %i)\n", \
12124                           current_config->name, \
12125                           pipe_config->name); \
12126                 ret = false; \
12127         } \
12128 } while (0)
12129
12130 #define PIPE_CONF_CHECK_INFOFRAME(name) do { \
12131         if (!intel_compare_infoframe(&current_config->infoframes.name, \
12132                                      &pipe_config->infoframes.name)) { \
12133                 pipe_config_infoframe_err(dev_priv, adjust, __stringify(name), \
12134                                           &current_config->infoframes.name, \
12135                                           &pipe_config->infoframes.name); \
12136                 ret = false; \
12137         } \
12138 } while (0)
12139
12140 #define PIPE_CONF_QUIRK(quirk) \
12141         ((current_config->quirks | pipe_config->quirks) & (quirk))
12142
12143         PIPE_CONF_CHECK_I(cpu_transcoder);
12144
12145         PIPE_CONF_CHECK_BOOL(has_pch_encoder);
12146         PIPE_CONF_CHECK_I(fdi_lanes);
12147         PIPE_CONF_CHECK_M_N(fdi_m_n);
12148
12149         PIPE_CONF_CHECK_I(lane_count);
12150         PIPE_CONF_CHECK_X(lane_lat_optim_mask);
12151
12152         if (INTEL_GEN(dev_priv) < 8) {
12153                 PIPE_CONF_CHECK_M_N(dp_m_n);
12154
12155                 if (current_config->has_drrs)
12156                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
12157         } else
12158                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
12159
12160         PIPE_CONF_CHECK_X(output_types);
12161
12162         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
12163         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
12164         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
12165         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
12166         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
12167         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
12168
12169         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
12170         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
12171         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
12172         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
12173         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
12174         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
12175
12176         PIPE_CONF_CHECK_I(pixel_multiplier);
12177         PIPE_CONF_CHECK_I(output_format);
12178         PIPE_CONF_CHECK_BOOL(has_hdmi_sink);
12179         if ((INTEL_GEN(dev_priv) < 8 && !IS_HASWELL(dev_priv)) ||
12180             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
12181                 PIPE_CONF_CHECK_BOOL(limited_color_range);
12182
12183         PIPE_CONF_CHECK_BOOL(hdmi_scrambling);
12184         PIPE_CONF_CHECK_BOOL(hdmi_high_tmds_clock_ratio);
12185         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_infoframe);
12186
12187         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_audio);
12188
12189         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12190                               DRM_MODE_FLAG_INTERLACE);
12191
12192         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
12193                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12194                                       DRM_MODE_FLAG_PHSYNC);
12195                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12196                                       DRM_MODE_FLAG_NHSYNC);
12197                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12198                                       DRM_MODE_FLAG_PVSYNC);
12199                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12200                                       DRM_MODE_FLAG_NVSYNC);
12201         }
12202
12203         PIPE_CONF_CHECK_X(gmch_pfit.control);
12204         /* pfit ratios are autocomputed by the hw on gen4+ */
12205         if (INTEL_GEN(dev_priv) < 4)
12206                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
12207         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
12208
12209         /*
12210          * Changing the EDP transcoder input mux
12211          * (A_ONOFF vs. A_ON) requires a full modeset.
12212          */
12213         PIPE_CONF_CHECK_BOOL(pch_pfit.force_thru);
12214
12215         if (!adjust) {
12216                 PIPE_CONF_CHECK_I(pipe_src_w);
12217                 PIPE_CONF_CHECK_I(pipe_src_h);
12218
12219                 PIPE_CONF_CHECK_BOOL(pch_pfit.enabled);
12220                 if (current_config->pch_pfit.enabled) {
12221                         PIPE_CONF_CHECK_X(pch_pfit.pos);
12222                         PIPE_CONF_CHECK_X(pch_pfit.size);
12223                 }
12224
12225                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
12226                 PIPE_CONF_CHECK_CLOCK_FUZZY(pixel_rate);
12227
12228                 PIPE_CONF_CHECK_X(gamma_mode);
12229                 if (IS_CHERRYVIEW(dev_priv))
12230                         PIPE_CONF_CHECK_X(cgm_mode);
12231                 else
12232                         PIPE_CONF_CHECK_X(csc_mode);
12233                 PIPE_CONF_CHECK_BOOL(gamma_enable);
12234                 PIPE_CONF_CHECK_BOOL(csc_enable);
12235         }
12236
12237         PIPE_CONF_CHECK_BOOL(double_wide);
12238
12239         PIPE_CONF_CHECK_P(shared_dpll);
12240         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
12241         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
12242         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
12243         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
12244         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
12245         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
12246         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
12247         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
12248         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
12249         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr0);
12250         PIPE_CONF_CHECK_X(dpll_hw_state.ebb0);
12251         PIPE_CONF_CHECK_X(dpll_hw_state.ebb4);
12252         PIPE_CONF_CHECK_X(dpll_hw_state.pll0);
12253         PIPE_CONF_CHECK_X(dpll_hw_state.pll1);
12254         PIPE_CONF_CHECK_X(dpll_hw_state.pll2);
12255         PIPE_CONF_CHECK_X(dpll_hw_state.pll3);
12256         PIPE_CONF_CHECK_X(dpll_hw_state.pll6);
12257         PIPE_CONF_CHECK_X(dpll_hw_state.pll8);
12258         PIPE_CONF_CHECK_X(dpll_hw_state.pll9);
12259         PIPE_CONF_CHECK_X(dpll_hw_state.pll10);
12260         PIPE_CONF_CHECK_X(dpll_hw_state.pcsdw12);
12261         PIPE_CONF_CHECK_X(dpll_hw_state.mg_refclkin_ctl);
12262         PIPE_CONF_CHECK_X(dpll_hw_state.mg_clktop2_coreclkctl1);
12263         PIPE_CONF_CHECK_X(dpll_hw_state.mg_clktop2_hsclkctl);
12264         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_div0);
12265         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_div1);
12266         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_lf);
12267         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_frac_lock);
12268         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_ssc);
12269         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_bias);
12270         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_tdc_coldst_bias);
12271
12272         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
12273         PIPE_CONF_CHECK_X(dsi_pll.div);
12274
12275         if (IS_G4X(dev_priv) || INTEL_GEN(dev_priv) >= 5)
12276                 PIPE_CONF_CHECK_I(pipe_bpp);
12277
12278         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
12279         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
12280
12281         PIPE_CONF_CHECK_I(min_voltage_level);
12282
12283         PIPE_CONF_CHECK_X(infoframes.enable);
12284         PIPE_CONF_CHECK_X(infoframes.gcp);
12285         PIPE_CONF_CHECK_INFOFRAME(avi);
12286         PIPE_CONF_CHECK_INFOFRAME(spd);
12287         PIPE_CONF_CHECK_INFOFRAME(hdmi);
12288
12289 #undef PIPE_CONF_CHECK_X
12290 #undef PIPE_CONF_CHECK_I
12291 #undef PIPE_CONF_CHECK_BOOL
12292 #undef PIPE_CONF_CHECK_BOOL_INCOMPLETE
12293 #undef PIPE_CONF_CHECK_P
12294 #undef PIPE_CONF_CHECK_FLAGS
12295 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
12296 #undef PIPE_CONF_QUIRK
12297
12298         return ret;
12299 }
12300
12301 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
12302                                            const struct intel_crtc_state *pipe_config)
12303 {
12304         if (pipe_config->has_pch_encoder) {
12305                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
12306                                                             &pipe_config->fdi_m_n);
12307                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
12308
12309                 /*
12310                  * FDI already provided one idea for the dotclock.
12311                  * Yell if the encoder disagrees.
12312                  */
12313                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
12314                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
12315                      fdi_dotclock, dotclock);
12316         }
12317 }
12318
12319 static void verify_wm_state(struct drm_crtc *crtc,
12320                             struct drm_crtc_state *new_state)
12321 {
12322         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
12323         struct skl_hw_state {
12324                 struct skl_ddb_entry ddb_y[I915_MAX_PLANES];
12325                 struct skl_ddb_entry ddb_uv[I915_MAX_PLANES];
12326                 struct skl_ddb_allocation ddb;
12327                 struct skl_pipe_wm wm;
12328         } *hw;
12329         struct skl_ddb_allocation *sw_ddb;
12330         struct skl_pipe_wm *sw_wm;
12331         struct skl_ddb_entry *hw_ddb_entry, *sw_ddb_entry;
12332         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12333         const enum pipe pipe = intel_crtc->pipe;
12334         int plane, level, max_level = ilk_wm_max_level(dev_priv);
12335
12336         if (INTEL_GEN(dev_priv) < 9 || !new_state->active)
12337                 return;
12338
12339         hw = kzalloc(sizeof(*hw), GFP_KERNEL);
12340         if (!hw)
12341                 return;
12342
12343         skl_pipe_wm_get_hw_state(intel_crtc, &hw->wm);
12344         sw_wm = &to_intel_crtc_state(new_state)->wm.skl.optimal;
12345
12346         skl_pipe_ddb_get_hw_state(intel_crtc, hw->ddb_y, hw->ddb_uv);
12347
12348         skl_ddb_get_hw_state(dev_priv, &hw->ddb);
12349         sw_ddb = &dev_priv->wm.skl_hw.ddb;
12350
12351         if (INTEL_GEN(dev_priv) >= 11 &&
12352             hw->ddb.enabled_slices != sw_ddb->enabled_slices)
12353                 DRM_ERROR("mismatch in DBUF Slices (expected %u, got %u)\n",
12354                           sw_ddb->enabled_slices,
12355                           hw->ddb.enabled_slices);
12356
12357         /* planes */
12358         for_each_universal_plane(dev_priv, pipe, plane) {
12359                 struct skl_plane_wm *hw_plane_wm, *sw_plane_wm;
12360
12361                 hw_plane_wm = &hw->wm.planes[plane];
12362                 sw_plane_wm = &sw_wm->planes[plane];
12363
12364                 /* Watermarks */
12365                 for (level = 0; level <= max_level; level++) {
12366                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
12367                                                 &sw_plane_wm->wm[level]))
12368                                 continue;
12369
12370                         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",
12371                                   pipe_name(pipe), plane + 1, level,
12372                                   sw_plane_wm->wm[level].plane_en,
12373                                   sw_plane_wm->wm[level].plane_res_b,
12374                                   sw_plane_wm->wm[level].plane_res_l,
12375                                   hw_plane_wm->wm[level].plane_en,
12376                                   hw_plane_wm->wm[level].plane_res_b,
12377                                   hw_plane_wm->wm[level].plane_res_l);
12378                 }
12379
12380                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
12381                                          &sw_plane_wm->trans_wm)) {
12382                         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",
12383                                   pipe_name(pipe), plane + 1,
12384                                   sw_plane_wm->trans_wm.plane_en,
12385                                   sw_plane_wm->trans_wm.plane_res_b,
12386                                   sw_plane_wm->trans_wm.plane_res_l,
12387                                   hw_plane_wm->trans_wm.plane_en,
12388                                   hw_plane_wm->trans_wm.plane_res_b,
12389                                   hw_plane_wm->trans_wm.plane_res_l);
12390                 }
12391
12392                 /* DDB */
12393                 hw_ddb_entry = &hw->ddb_y[plane];
12394                 sw_ddb_entry = &to_intel_crtc_state(new_state)->wm.skl.plane_ddb_y[plane];
12395
12396                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
12397                         DRM_ERROR("mismatch in DDB state pipe %c plane %d (expected (%u,%u), found (%u,%u))\n",
12398                                   pipe_name(pipe), plane + 1,
12399                                   sw_ddb_entry->start, sw_ddb_entry->end,
12400                                   hw_ddb_entry->start, hw_ddb_entry->end);
12401                 }
12402         }
12403
12404         /*
12405          * cursor
12406          * If the cursor plane isn't active, we may not have updated it's ddb
12407          * allocation. In that case since the ddb allocation will be updated
12408          * once the plane becomes visible, we can skip this check
12409          */
12410         if (1) {
12411                 struct skl_plane_wm *hw_plane_wm, *sw_plane_wm;
12412
12413                 hw_plane_wm = &hw->wm.planes[PLANE_CURSOR];
12414                 sw_plane_wm = &sw_wm->planes[PLANE_CURSOR];
12415
12416                 /* Watermarks */
12417                 for (level = 0; level <= max_level; level++) {
12418                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
12419                                                 &sw_plane_wm->wm[level]))
12420                                 continue;
12421
12422                         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",
12423                                   pipe_name(pipe), level,
12424                                   sw_plane_wm->wm[level].plane_en,
12425                                   sw_plane_wm->wm[level].plane_res_b,
12426                                   sw_plane_wm->wm[level].plane_res_l,
12427                                   hw_plane_wm->wm[level].plane_en,
12428                                   hw_plane_wm->wm[level].plane_res_b,
12429                                   hw_plane_wm->wm[level].plane_res_l);
12430                 }
12431
12432                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
12433                                          &sw_plane_wm->trans_wm)) {
12434                         DRM_ERROR("mismatch in trans WM pipe %c cursor (expected e=%d b=%u l=%u, got e=%d b=%u l=%u)\n",
12435                                   pipe_name(pipe),
12436                                   sw_plane_wm->trans_wm.plane_en,
12437                                   sw_plane_wm->trans_wm.plane_res_b,
12438                                   sw_plane_wm->trans_wm.plane_res_l,
12439                                   hw_plane_wm->trans_wm.plane_en,
12440                                   hw_plane_wm->trans_wm.plane_res_b,
12441                                   hw_plane_wm->trans_wm.plane_res_l);
12442                 }
12443
12444                 /* DDB */
12445                 hw_ddb_entry = &hw->ddb_y[PLANE_CURSOR];
12446                 sw_ddb_entry = &to_intel_crtc_state(new_state)->wm.skl.plane_ddb_y[PLANE_CURSOR];
12447
12448                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
12449                         DRM_ERROR("mismatch in DDB state pipe %c cursor (expected (%u,%u), found (%u,%u))\n",
12450                                   pipe_name(pipe),
12451                                   sw_ddb_entry->start, sw_ddb_entry->end,
12452                                   hw_ddb_entry->start, hw_ddb_entry->end);
12453                 }
12454         }
12455
12456         kfree(hw);
12457 }
12458
12459 static void
12460 verify_connector_state(struct drm_device *dev,
12461                        struct drm_atomic_state *state,
12462                        struct drm_crtc *crtc)
12463 {
12464         struct drm_connector *connector;
12465         struct drm_connector_state *new_conn_state;
12466         int i;
12467
12468         for_each_new_connector_in_state(state, connector, new_conn_state, i) {
12469                 struct drm_encoder *encoder = connector->encoder;
12470                 struct drm_crtc_state *crtc_state = NULL;
12471
12472                 if (new_conn_state->crtc != crtc)
12473                         continue;
12474
12475                 if (crtc)
12476                         crtc_state = drm_atomic_get_new_crtc_state(state, new_conn_state->crtc);
12477
12478                 intel_connector_verify_state(crtc_state, new_conn_state);
12479
12480                 I915_STATE_WARN(new_conn_state->best_encoder != encoder,
12481                      "connector's atomic encoder doesn't match legacy encoder\n");
12482         }
12483 }
12484
12485 static void
12486 verify_encoder_state(struct drm_device *dev, struct drm_atomic_state *state)
12487 {
12488         struct intel_encoder *encoder;
12489         struct drm_connector *connector;
12490         struct drm_connector_state *old_conn_state, *new_conn_state;
12491         int i;
12492
12493         for_each_intel_encoder(dev, encoder) {
12494                 bool enabled = false, found = false;
12495                 enum pipe pipe;
12496
12497                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
12498                               encoder->base.base.id,
12499                               encoder->base.name);
12500
12501                 for_each_oldnew_connector_in_state(state, connector, old_conn_state,
12502                                                    new_conn_state, i) {
12503                         if (old_conn_state->best_encoder == &encoder->base)
12504                                 found = true;
12505
12506                         if (new_conn_state->best_encoder != &encoder->base)
12507                                 continue;
12508                         found = enabled = true;
12509
12510                         I915_STATE_WARN(new_conn_state->crtc !=
12511                                         encoder->base.crtc,
12512                              "connector's crtc doesn't match encoder crtc\n");
12513                 }
12514
12515                 if (!found)
12516                         continue;
12517
12518                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
12519                      "encoder's enabled state mismatch "
12520                      "(expected %i, found %i)\n",
12521                      !!encoder->base.crtc, enabled);
12522
12523                 if (!encoder->base.crtc) {
12524                         bool active;
12525
12526                         active = encoder->get_hw_state(encoder, &pipe);
12527                         I915_STATE_WARN(active,
12528                              "encoder detached but still enabled on pipe %c.\n",
12529                              pipe_name(pipe));
12530                 }
12531         }
12532 }
12533
12534 static void
12535 verify_crtc_state(struct drm_crtc *crtc,
12536                   struct drm_crtc_state *old_crtc_state,
12537                   struct drm_crtc_state *new_crtc_state)
12538 {
12539         struct drm_device *dev = crtc->dev;
12540         struct drm_i915_private *dev_priv = to_i915(dev);
12541         struct intel_encoder *encoder;
12542         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12543         struct intel_crtc_state *pipe_config, *sw_config;
12544         struct drm_atomic_state *old_state;
12545         bool active;
12546
12547         old_state = old_crtc_state->state;
12548         __drm_atomic_helper_crtc_destroy_state(old_crtc_state);
12549         pipe_config = to_intel_crtc_state(old_crtc_state);
12550         memset(pipe_config, 0, sizeof(*pipe_config));
12551         pipe_config->base.crtc = crtc;
12552         pipe_config->base.state = old_state;
12553
12554         DRM_DEBUG_KMS("[CRTC:%d:%s]\n", crtc->base.id, crtc->name);
12555
12556         active = dev_priv->display.get_pipe_config(intel_crtc, pipe_config);
12557
12558         /* we keep both pipes enabled on 830 */
12559         if (IS_I830(dev_priv))
12560                 active = new_crtc_state->active;
12561
12562         I915_STATE_WARN(new_crtc_state->active != active,
12563              "crtc active state doesn't match with hw state "
12564              "(expected %i, found %i)\n", new_crtc_state->active, active);
12565
12566         I915_STATE_WARN(intel_crtc->active != new_crtc_state->active,
12567              "transitional active state does not match atomic hw state "
12568              "(expected %i, found %i)\n", new_crtc_state->active, intel_crtc->active);
12569
12570         for_each_encoder_on_crtc(dev, crtc, encoder) {
12571                 enum pipe pipe;
12572
12573                 active = encoder->get_hw_state(encoder, &pipe);
12574                 I915_STATE_WARN(active != new_crtc_state->active,
12575                         "[ENCODER:%i] active %i with crtc active %i\n",
12576                         encoder->base.base.id, active, new_crtc_state->active);
12577
12578                 I915_STATE_WARN(active && intel_crtc->pipe != pipe,
12579                                 "Encoder connected to wrong pipe %c\n",
12580                                 pipe_name(pipe));
12581
12582                 if (active)
12583                         encoder->get_config(encoder, pipe_config);
12584         }
12585
12586         intel_crtc_compute_pixel_rate(pipe_config);
12587
12588         if (!new_crtc_state->active)
12589                 return;
12590
12591         intel_pipe_config_sanity_check(dev_priv, pipe_config);
12592
12593         sw_config = to_intel_crtc_state(new_crtc_state);
12594         if (!intel_pipe_config_compare(dev_priv, sw_config,
12595                                        pipe_config, false)) {
12596                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
12597                 intel_dump_pipe_config(intel_crtc, pipe_config,
12598                                        "[hw state]");
12599                 intel_dump_pipe_config(intel_crtc, sw_config,
12600                                        "[sw state]");
12601         }
12602 }
12603
12604 static void
12605 intel_verify_planes(struct intel_atomic_state *state)
12606 {
12607         struct intel_plane *plane;
12608         const struct intel_plane_state *plane_state;
12609         int i;
12610
12611         for_each_new_intel_plane_in_state(state, plane,
12612                                           plane_state, i)
12613                 assert_plane(plane, plane_state->slave ||
12614                              plane_state->base.visible);
12615 }
12616
12617 static void
12618 verify_single_dpll_state(struct drm_i915_private *dev_priv,
12619                          struct intel_shared_dpll *pll,
12620                          struct drm_crtc *crtc,
12621                          struct drm_crtc_state *new_state)
12622 {
12623         struct intel_dpll_hw_state dpll_hw_state;
12624         unsigned int crtc_mask;
12625         bool active;
12626
12627         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
12628
12629         DRM_DEBUG_KMS("%s\n", pll->info->name);
12630
12631         active = pll->info->funcs->get_hw_state(dev_priv, pll, &dpll_hw_state);
12632
12633         if (!(pll->info->flags & INTEL_DPLL_ALWAYS_ON)) {
12634                 I915_STATE_WARN(!pll->on && pll->active_mask,
12635                      "pll in active use but not on in sw tracking\n");
12636                 I915_STATE_WARN(pll->on && !pll->active_mask,
12637                      "pll is on but not used by any active crtc\n");
12638                 I915_STATE_WARN(pll->on != active,
12639                      "pll on state mismatch (expected %i, found %i)\n",
12640                      pll->on, active);
12641         }
12642
12643         if (!crtc) {
12644                 I915_STATE_WARN(pll->active_mask & ~pll->state.crtc_mask,
12645                                 "more active pll users than references: %x vs %x\n",
12646                                 pll->active_mask, pll->state.crtc_mask);
12647
12648                 return;
12649         }
12650
12651         crtc_mask = drm_crtc_mask(crtc);
12652
12653         if (new_state->active)
12654                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
12655                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
12656                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
12657         else
12658                 I915_STATE_WARN(pll->active_mask & crtc_mask,
12659                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
12660                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
12661
12662         I915_STATE_WARN(!(pll->state.crtc_mask & crtc_mask),
12663                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
12664                         crtc_mask, pll->state.crtc_mask);
12665
12666         I915_STATE_WARN(pll->on && memcmp(&pll->state.hw_state,
12667                                           &dpll_hw_state,
12668                                           sizeof(dpll_hw_state)),
12669                         "pll hw state mismatch\n");
12670 }
12671
12672 static void
12673 verify_shared_dpll_state(struct drm_device *dev, struct drm_crtc *crtc,
12674                          struct drm_crtc_state *old_crtc_state,
12675                          struct drm_crtc_state *new_crtc_state)
12676 {
12677         struct drm_i915_private *dev_priv = to_i915(dev);
12678         struct intel_crtc_state *old_state = to_intel_crtc_state(old_crtc_state);
12679         struct intel_crtc_state *new_state = to_intel_crtc_state(new_crtc_state);
12680
12681         if (new_state->shared_dpll)
12682                 verify_single_dpll_state(dev_priv, new_state->shared_dpll, crtc, new_crtc_state);
12683
12684         if (old_state->shared_dpll &&
12685             old_state->shared_dpll != new_state->shared_dpll) {
12686                 unsigned int crtc_mask = drm_crtc_mask(crtc);
12687                 struct intel_shared_dpll *pll = old_state->shared_dpll;
12688
12689                 I915_STATE_WARN(pll->active_mask & crtc_mask,
12690                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
12691                                 pipe_name(drm_crtc_index(crtc)));
12692                 I915_STATE_WARN(pll->state.crtc_mask & crtc_mask,
12693                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
12694                                 pipe_name(drm_crtc_index(crtc)));
12695         }
12696 }
12697
12698 static void
12699 intel_modeset_verify_crtc(struct drm_crtc *crtc,
12700                           struct drm_atomic_state *state,
12701                           struct drm_crtc_state *old_state,
12702                           struct drm_crtc_state *new_state)
12703 {
12704         if (!needs_modeset(new_state) &&
12705             !to_intel_crtc_state(new_state)->update_pipe)
12706                 return;
12707
12708         verify_wm_state(crtc, new_state);
12709         verify_connector_state(crtc->dev, state, crtc);
12710         verify_crtc_state(crtc, old_state, new_state);
12711         verify_shared_dpll_state(crtc->dev, crtc, old_state, new_state);
12712 }
12713
12714 static void
12715 verify_disabled_dpll_state(struct drm_device *dev)
12716 {
12717         struct drm_i915_private *dev_priv = to_i915(dev);
12718         int i;
12719
12720         for (i = 0; i < dev_priv->num_shared_dpll; i++)
12721                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
12722 }
12723
12724 static void
12725 intel_modeset_verify_disabled(struct drm_device *dev,
12726                               struct drm_atomic_state *state)
12727 {
12728         verify_encoder_state(dev, state);
12729         verify_connector_state(dev, state, NULL);
12730         verify_disabled_dpll_state(dev);
12731 }
12732
12733 static void update_scanline_offset(const struct intel_crtc_state *crtc_state)
12734 {
12735         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
12736         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
12737
12738         /*
12739          * The scanline counter increments at the leading edge of hsync.
12740          *
12741          * On most platforms it starts counting from vtotal-1 on the
12742          * first active line. That means the scanline counter value is
12743          * always one less than what we would expect. Ie. just after
12744          * start of vblank, which also occurs at start of hsync (on the
12745          * last active line), the scanline counter will read vblank_start-1.
12746          *
12747          * On gen2 the scanline counter starts counting from 1 instead
12748          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
12749          * to keep the value positive), instead of adding one.
12750          *
12751          * On HSW+ the behaviour of the scanline counter depends on the output
12752          * type. For DP ports it behaves like most other platforms, but on HDMI
12753          * there's an extra 1 line difference. So we need to add two instead of
12754          * one to the value.
12755          *
12756          * On VLV/CHV DSI the scanline counter would appear to increment
12757          * approx. 1/3 of a scanline before start of vblank. Unfortunately
12758          * that means we can't tell whether we're in vblank or not while
12759          * we're on that particular line. We must still set scanline_offset
12760          * to 1 so that the vblank timestamps come out correct when we query
12761          * the scanline counter from within the vblank interrupt handler.
12762          * However if queried just before the start of vblank we'll get an
12763          * answer that's slightly in the future.
12764          */
12765         if (IS_GEN(dev_priv, 2)) {
12766                 const struct drm_display_mode *adjusted_mode = &crtc_state->base.adjusted_mode;
12767                 int vtotal;
12768
12769                 vtotal = adjusted_mode->crtc_vtotal;
12770                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
12771                         vtotal /= 2;
12772
12773                 crtc->scanline_offset = vtotal - 1;
12774         } else if (HAS_DDI(dev_priv) &&
12775                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI)) {
12776                 crtc->scanline_offset = 2;
12777         } else
12778                 crtc->scanline_offset = 1;
12779 }
12780
12781 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
12782 {
12783         struct drm_device *dev = state->dev;
12784         struct drm_i915_private *dev_priv = to_i915(dev);
12785         struct drm_crtc *crtc;
12786         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12787         int i;
12788
12789         if (!dev_priv->display.crtc_compute_clock)
12790                 return;
12791
12792         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12793                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12794                 struct intel_shared_dpll *old_dpll =
12795                         to_intel_crtc_state(old_crtc_state)->shared_dpll;
12796
12797                 if (!needs_modeset(new_crtc_state))
12798                         continue;
12799
12800                 to_intel_crtc_state(new_crtc_state)->shared_dpll = NULL;
12801
12802                 if (!old_dpll)
12803                         continue;
12804
12805                 intel_release_shared_dpll(old_dpll, intel_crtc, state);
12806         }
12807 }
12808
12809 /*
12810  * This implements the workaround described in the "notes" section of the mode
12811  * set sequence documentation. When going from no pipes or single pipe to
12812  * multiple pipes, and planes are enabled after the pipe, we need to wait at
12813  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
12814  */
12815 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
12816 {
12817         struct drm_crtc_state *crtc_state;
12818         struct intel_crtc *intel_crtc;
12819         struct drm_crtc *crtc;
12820         struct intel_crtc_state *first_crtc_state = NULL;
12821         struct intel_crtc_state *other_crtc_state = NULL;
12822         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
12823         int i;
12824
12825         /* look at all crtc's that are going to be enabled in during modeset */
12826         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
12827                 intel_crtc = to_intel_crtc(crtc);
12828
12829                 if (!crtc_state->active || !needs_modeset(crtc_state))
12830                         continue;
12831
12832                 if (first_crtc_state) {
12833                         other_crtc_state = to_intel_crtc_state(crtc_state);
12834                         break;
12835                 } else {
12836                         first_crtc_state = to_intel_crtc_state(crtc_state);
12837                         first_pipe = intel_crtc->pipe;
12838                 }
12839         }
12840
12841         /* No workaround needed? */
12842         if (!first_crtc_state)
12843                 return 0;
12844
12845         /* w/a possibly needed, check how many crtc's are already enabled. */
12846         for_each_intel_crtc(state->dev, intel_crtc) {
12847                 struct intel_crtc_state *pipe_config;
12848
12849                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
12850                 if (IS_ERR(pipe_config))
12851                         return PTR_ERR(pipe_config);
12852
12853                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
12854
12855                 if (!pipe_config->base.active ||
12856                     needs_modeset(&pipe_config->base))
12857                         continue;
12858
12859                 /* 2 or more enabled crtcs means no need for w/a */
12860                 if (enabled_pipe != INVALID_PIPE)
12861                         return 0;
12862
12863                 enabled_pipe = intel_crtc->pipe;
12864         }
12865
12866         if (enabled_pipe != INVALID_PIPE)
12867                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
12868         else if (other_crtc_state)
12869                 other_crtc_state->hsw_workaround_pipe = first_pipe;
12870
12871         return 0;
12872 }
12873
12874 static int intel_lock_all_pipes(struct drm_atomic_state *state)
12875 {
12876         struct drm_crtc *crtc;
12877
12878         /* Add all pipes to the state */
12879         for_each_crtc(state->dev, crtc) {
12880                 struct drm_crtc_state *crtc_state;
12881
12882                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
12883                 if (IS_ERR(crtc_state))
12884                         return PTR_ERR(crtc_state);
12885         }
12886
12887         return 0;
12888 }
12889
12890 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
12891 {
12892         struct drm_crtc *crtc;
12893
12894         /*
12895          * Add all pipes to the state, and force
12896          * a modeset on all the active ones.
12897          */
12898         for_each_crtc(state->dev, crtc) {
12899                 struct drm_crtc_state *crtc_state;
12900                 int ret;
12901
12902                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
12903                 if (IS_ERR(crtc_state))
12904                         return PTR_ERR(crtc_state);
12905
12906                 if (!crtc_state->active || needs_modeset(crtc_state))
12907                         continue;
12908
12909                 crtc_state->mode_changed = true;
12910
12911                 ret = drm_atomic_add_affected_connectors(state, crtc);
12912                 if (ret)
12913                         return ret;
12914
12915                 ret = drm_atomic_add_affected_planes(state, crtc);
12916                 if (ret)
12917                         return ret;
12918         }
12919
12920         return 0;
12921 }
12922
12923 static int intel_modeset_checks(struct drm_atomic_state *state)
12924 {
12925         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12926         struct drm_i915_private *dev_priv = to_i915(state->dev);
12927         struct drm_crtc *crtc;
12928         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12929         int ret = 0, i;
12930
12931         if (!check_digital_port_conflicts(state)) {
12932                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
12933                 return -EINVAL;
12934         }
12935
12936         /* keep the current setting */
12937         if (!intel_state->cdclk.force_min_cdclk_changed)
12938                 intel_state->cdclk.force_min_cdclk =
12939                         dev_priv->cdclk.force_min_cdclk;
12940
12941         intel_state->modeset = true;
12942         intel_state->active_crtcs = dev_priv->active_crtcs;
12943         intel_state->cdclk.logical = dev_priv->cdclk.logical;
12944         intel_state->cdclk.actual = dev_priv->cdclk.actual;
12945         intel_state->cdclk.pipe = INVALID_PIPE;
12946
12947         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12948                 if (new_crtc_state->active)
12949                         intel_state->active_crtcs |= 1 << i;
12950                 else
12951                         intel_state->active_crtcs &= ~(1 << i);
12952
12953                 if (old_crtc_state->active != new_crtc_state->active)
12954                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
12955         }
12956
12957         /*
12958          * See if the config requires any additional preparation, e.g.
12959          * to adjust global state with pipes off.  We need to do this
12960          * here so we can get the modeset_pipe updated config for the new
12961          * mode set on this crtc.  For other crtcs we need to use the
12962          * adjusted_mode bits in the crtc directly.
12963          */
12964         if (dev_priv->display.modeset_calc_cdclk) {
12965                 enum pipe pipe;
12966
12967                 ret = dev_priv->display.modeset_calc_cdclk(state);
12968                 if (ret < 0)
12969                         return ret;
12970
12971                 /*
12972                  * Writes to dev_priv->cdclk.logical must protected by
12973                  * holding all the crtc locks, even if we don't end up
12974                  * touching the hardware
12975                  */
12976                 if (intel_cdclk_changed(&dev_priv->cdclk.logical,
12977                                         &intel_state->cdclk.logical)) {
12978                         ret = intel_lock_all_pipes(state);
12979                         if (ret < 0)
12980                                 return ret;
12981                 }
12982
12983                 if (is_power_of_2(intel_state->active_crtcs)) {
12984                         struct drm_crtc *crtc;
12985                         struct drm_crtc_state *crtc_state;
12986
12987                         pipe = ilog2(intel_state->active_crtcs);
12988                         crtc = &intel_get_crtc_for_pipe(dev_priv, pipe)->base;
12989                         crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
12990                         if (crtc_state && needs_modeset(crtc_state))
12991                                 pipe = INVALID_PIPE;
12992                 } else {
12993                         pipe = INVALID_PIPE;
12994                 }
12995
12996                 /* All pipes must be switched off while we change the cdclk. */
12997                 if (pipe != INVALID_PIPE &&
12998                     intel_cdclk_needs_cd2x_update(dev_priv,
12999                                                   &dev_priv->cdclk.actual,
13000                                                   &intel_state->cdclk.actual)) {
13001                         ret = intel_lock_all_pipes(state);
13002                         if (ret < 0)
13003                                 return ret;
13004
13005                         intel_state->cdclk.pipe = pipe;
13006                 } else if (intel_cdclk_needs_modeset(&dev_priv->cdclk.actual,
13007                                                      &intel_state->cdclk.actual)) {
13008                         ret = intel_modeset_all_pipes(state);
13009                         if (ret < 0)
13010                                 return ret;
13011
13012                         intel_state->cdclk.pipe = INVALID_PIPE;
13013                 }
13014
13015                 DRM_DEBUG_KMS("New cdclk calculated to be logical %u kHz, actual %u kHz\n",
13016                               intel_state->cdclk.logical.cdclk,
13017                               intel_state->cdclk.actual.cdclk);
13018                 DRM_DEBUG_KMS("New voltage level calculated to be logical %u, actual %u\n",
13019                               intel_state->cdclk.logical.voltage_level,
13020                               intel_state->cdclk.actual.voltage_level);
13021         }
13022
13023         intel_modeset_clear_plls(state);
13024
13025         if (IS_HASWELL(dev_priv))
13026                 return haswell_mode_set_planes_workaround(state);
13027
13028         return 0;
13029 }
13030
13031 /*
13032  * Handle calculation of various watermark data at the end of the atomic check
13033  * phase.  The code here should be run after the per-crtc and per-plane 'check'
13034  * handlers to ensure that all derived state has been updated.
13035  */
13036 static int calc_watermark_data(struct intel_atomic_state *state)
13037 {
13038         struct drm_device *dev = state->base.dev;
13039         struct drm_i915_private *dev_priv = to_i915(dev);
13040
13041         /* Is there platform-specific watermark information to calculate? */
13042         if (dev_priv->display.compute_global_watermarks)
13043                 return dev_priv->display.compute_global_watermarks(state);
13044
13045         return 0;
13046 }
13047
13048 /**
13049  * intel_atomic_check - validate state object
13050  * @dev: drm device
13051  * @state: state to validate
13052  */
13053 static int intel_atomic_check(struct drm_device *dev,
13054                               struct drm_atomic_state *state)
13055 {
13056         struct drm_i915_private *dev_priv = to_i915(dev);
13057         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13058         struct drm_crtc *crtc;
13059         struct drm_crtc_state *old_crtc_state, *crtc_state;
13060         int ret, i;
13061         bool any_ms = intel_state->cdclk.force_min_cdclk_changed;
13062
13063         /* Catch I915_MODE_FLAG_INHERITED */
13064         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
13065                                       crtc_state, i) {
13066                 if (crtc_state->mode.private_flags !=
13067                     old_crtc_state->mode.private_flags)
13068                         crtc_state->mode_changed = true;
13069         }
13070
13071         ret = drm_atomic_helper_check_modeset(dev, state);
13072         if (ret)
13073                 return ret;
13074
13075         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, crtc_state, i) {
13076                 struct intel_crtc_state *pipe_config =
13077                         to_intel_crtc_state(crtc_state);
13078
13079                 if (!needs_modeset(crtc_state))
13080                         continue;
13081
13082                 if (!crtc_state->enable) {
13083                         any_ms = true;
13084                         continue;
13085                 }
13086
13087                 ret = intel_modeset_pipe_config(crtc, pipe_config);
13088                 if (ret == -EDEADLK)
13089                         return ret;
13090                 if (ret) {
13091                         intel_dump_pipe_config(to_intel_crtc(crtc),
13092                                                pipe_config, "[failed]");
13093                         return ret;
13094                 }
13095
13096                 if (intel_pipe_config_compare(dev_priv,
13097                                         to_intel_crtc_state(old_crtc_state),
13098                                         pipe_config, true)) {
13099                         crtc_state->mode_changed = false;
13100                         pipe_config->update_pipe = true;
13101                 }
13102
13103                 if (needs_modeset(crtc_state))
13104                         any_ms = true;
13105
13106                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
13107                                        needs_modeset(crtc_state) ?
13108                                        "[modeset]" : "[fastset]");
13109         }
13110
13111         ret = drm_dp_mst_atomic_check(state);
13112         if (ret)
13113                 return ret;
13114
13115         if (any_ms) {
13116                 ret = intel_modeset_checks(state);
13117
13118                 if (ret)
13119                         return ret;
13120         } else {
13121                 intel_state->cdclk.logical = dev_priv->cdclk.logical;
13122         }
13123
13124         ret = icl_add_linked_planes(intel_state);
13125         if (ret)
13126                 return ret;
13127
13128         ret = drm_atomic_helper_check_planes(dev, state);
13129         if (ret)
13130                 return ret;
13131
13132         intel_fbc_choose_crtc(dev_priv, intel_state);
13133         return calc_watermark_data(intel_state);
13134 }
13135
13136 static int intel_atomic_prepare_commit(struct drm_device *dev,
13137                                        struct drm_atomic_state *state)
13138 {
13139         return drm_atomic_helper_prepare_planes(dev, state);
13140 }
13141
13142 u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc)
13143 {
13144         struct drm_device *dev = crtc->base.dev;
13145         struct drm_vblank_crtc *vblank = &dev->vblank[drm_crtc_index(&crtc->base)];
13146
13147         if (!vblank->max_vblank_count)
13148                 return (u32)drm_crtc_accurate_vblank_count(&crtc->base);
13149
13150         return dev->driver->get_vblank_counter(dev, crtc->pipe);
13151 }
13152
13153 static void intel_update_crtc(struct drm_crtc *crtc,
13154                               struct drm_atomic_state *state,
13155                               struct drm_crtc_state *old_crtc_state,
13156                               struct drm_crtc_state *new_crtc_state)
13157 {
13158         struct drm_device *dev = crtc->dev;
13159         struct drm_i915_private *dev_priv = to_i915(dev);
13160         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13161         struct intel_crtc_state *pipe_config = to_intel_crtc_state(new_crtc_state);
13162         bool modeset = needs_modeset(new_crtc_state);
13163         struct intel_plane_state *new_plane_state =
13164                 intel_atomic_get_new_plane_state(to_intel_atomic_state(state),
13165                                                  to_intel_plane(crtc->primary));
13166
13167         if (modeset) {
13168                 update_scanline_offset(pipe_config);
13169                 dev_priv->display.crtc_enable(pipe_config, state);
13170
13171                 /* vblanks work again, re-enable pipe CRC. */
13172                 intel_crtc_enable_pipe_crc(intel_crtc);
13173         } else {
13174                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
13175                                        pipe_config);
13176
13177                 if (pipe_config->update_pipe)
13178                         intel_encoders_update_pipe(crtc, pipe_config, state);
13179         }
13180
13181         if (pipe_config->update_pipe && !pipe_config->enable_fbc)
13182                 intel_fbc_disable(intel_crtc);
13183         else if (new_plane_state)
13184                 intel_fbc_enable(intel_crtc, pipe_config, new_plane_state);
13185
13186         intel_begin_crtc_commit(to_intel_atomic_state(state), intel_crtc);
13187
13188         if (INTEL_GEN(dev_priv) >= 9)
13189                 skl_update_planes_on_crtc(to_intel_atomic_state(state), intel_crtc);
13190         else
13191                 i9xx_update_planes_on_crtc(to_intel_atomic_state(state), intel_crtc);
13192
13193         intel_finish_crtc_commit(to_intel_atomic_state(state), intel_crtc);
13194 }
13195
13196 static void intel_update_crtcs(struct drm_atomic_state *state)
13197 {
13198         struct drm_crtc *crtc;
13199         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
13200         int i;
13201
13202         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13203                 if (!new_crtc_state->active)
13204                         continue;
13205
13206                 intel_update_crtc(crtc, state, old_crtc_state,
13207                                   new_crtc_state);
13208         }
13209 }
13210
13211 static void skl_update_crtcs(struct drm_atomic_state *state)
13212 {
13213         struct drm_i915_private *dev_priv = to_i915(state->dev);
13214         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13215         struct drm_crtc *crtc;
13216         struct intel_crtc *intel_crtc;
13217         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
13218         struct intel_crtc_state *cstate;
13219         unsigned int updated = 0;
13220         bool progress;
13221         enum pipe pipe;
13222         int i;
13223         u8 hw_enabled_slices = dev_priv->wm.skl_hw.ddb.enabled_slices;
13224         u8 required_slices = intel_state->wm_results.ddb.enabled_slices;
13225         struct skl_ddb_entry entries[I915_MAX_PIPES] = {};
13226
13227         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i)
13228                 /* ignore allocations for crtc's that have been turned off. */
13229                 if (new_crtc_state->active)
13230                         entries[i] = to_intel_crtc_state(old_crtc_state)->wm.skl.ddb;
13231
13232         /* If 2nd DBuf slice required, enable it here */
13233         if (INTEL_GEN(dev_priv) >= 11 && required_slices > hw_enabled_slices)
13234                 icl_dbuf_slices_update(dev_priv, required_slices);
13235
13236         /*
13237          * Whenever the number of active pipes changes, we need to make sure we
13238          * update the pipes in the right order so that their ddb allocations
13239          * never overlap with eachother inbetween CRTC updates. Otherwise we'll
13240          * cause pipe underruns and other bad stuff.
13241          */
13242         do {
13243                 progress = false;
13244
13245                 for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13246                         bool vbl_wait = false;
13247                         unsigned int cmask = drm_crtc_mask(crtc);
13248
13249                         intel_crtc = to_intel_crtc(crtc);
13250                         cstate = to_intel_crtc_state(new_crtc_state);
13251                         pipe = intel_crtc->pipe;
13252
13253                         if (updated & cmask || !cstate->base.active)
13254                                 continue;
13255
13256                         if (skl_ddb_allocation_overlaps(&cstate->wm.skl.ddb,
13257                                                         entries,
13258                                                         INTEL_INFO(dev_priv)->num_pipes, i))
13259                                 continue;
13260
13261                         updated |= cmask;
13262                         entries[i] = cstate->wm.skl.ddb;
13263
13264                         /*
13265                          * If this is an already active pipe, it's DDB changed,
13266                          * and this isn't the last pipe that needs updating
13267                          * then we need to wait for a vblank to pass for the
13268                          * new ddb allocation to take effect.
13269                          */
13270                         if (!skl_ddb_entry_equal(&cstate->wm.skl.ddb,
13271                                                  &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb) &&
13272                             !new_crtc_state->active_changed &&
13273                             intel_state->wm_results.dirty_pipes != updated)
13274                                 vbl_wait = true;
13275
13276                         intel_update_crtc(crtc, state, old_crtc_state,
13277                                           new_crtc_state);
13278
13279                         if (vbl_wait)
13280                                 intel_wait_for_vblank(dev_priv, pipe);
13281
13282                         progress = true;
13283                 }
13284         } while (progress);
13285
13286         /* If 2nd DBuf slice is no more required disable it */
13287         if (INTEL_GEN(dev_priv) >= 11 && required_slices < hw_enabled_slices)
13288                 icl_dbuf_slices_update(dev_priv, required_slices);
13289 }
13290
13291 static void intel_atomic_helper_free_state(struct drm_i915_private *dev_priv)
13292 {
13293         struct intel_atomic_state *state, *next;
13294         struct llist_node *freed;
13295
13296         freed = llist_del_all(&dev_priv->atomic_helper.free_list);
13297         llist_for_each_entry_safe(state, next, freed, freed)
13298                 drm_atomic_state_put(&state->base);
13299 }
13300
13301 static void intel_atomic_helper_free_state_worker(struct work_struct *work)
13302 {
13303         struct drm_i915_private *dev_priv =
13304                 container_of(work, typeof(*dev_priv), atomic_helper.free_work);
13305
13306         intel_atomic_helper_free_state(dev_priv);
13307 }
13308
13309 static void intel_atomic_commit_fence_wait(struct intel_atomic_state *intel_state)
13310 {
13311         struct wait_queue_entry wait_fence, wait_reset;
13312         struct drm_i915_private *dev_priv = to_i915(intel_state->base.dev);
13313
13314         init_wait_entry(&wait_fence, 0);
13315         init_wait_entry(&wait_reset, 0);
13316         for (;;) {
13317                 prepare_to_wait(&intel_state->commit_ready.wait,
13318                                 &wait_fence, TASK_UNINTERRUPTIBLE);
13319                 prepare_to_wait(&dev_priv->gpu_error.wait_queue,
13320                                 &wait_reset, TASK_UNINTERRUPTIBLE);
13321
13322
13323                 if (i915_sw_fence_done(&intel_state->commit_ready)
13324                     || test_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags))
13325                         break;
13326
13327                 schedule();
13328         }
13329         finish_wait(&intel_state->commit_ready.wait, &wait_fence);
13330         finish_wait(&dev_priv->gpu_error.wait_queue, &wait_reset);
13331 }
13332
13333 static void intel_atomic_cleanup_work(struct work_struct *work)
13334 {
13335         struct drm_atomic_state *state =
13336                 container_of(work, struct drm_atomic_state, commit_work);
13337         struct drm_i915_private *i915 = to_i915(state->dev);
13338
13339         drm_atomic_helper_cleanup_planes(&i915->drm, state);
13340         drm_atomic_helper_commit_cleanup_done(state);
13341         drm_atomic_state_put(state);
13342
13343         intel_atomic_helper_free_state(i915);
13344 }
13345
13346 static void intel_atomic_commit_tail(struct drm_atomic_state *state)
13347 {
13348         struct drm_device *dev = state->dev;
13349         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13350         struct drm_i915_private *dev_priv = to_i915(dev);
13351         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
13352         struct intel_crtc_state *new_intel_crtc_state, *old_intel_crtc_state;
13353         struct drm_crtc *crtc;
13354         struct intel_crtc *intel_crtc;
13355         u64 put_domains[I915_MAX_PIPES] = {};
13356         intel_wakeref_t wakeref = 0;
13357         int i;
13358
13359         intel_atomic_commit_fence_wait(intel_state);
13360
13361         drm_atomic_helper_wait_for_dependencies(state);
13362
13363         if (intel_state->modeset)
13364                 wakeref = intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
13365
13366         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13367                 old_intel_crtc_state = to_intel_crtc_state(old_crtc_state);
13368                 new_intel_crtc_state = to_intel_crtc_state(new_crtc_state);
13369                 intel_crtc = to_intel_crtc(crtc);
13370
13371                 if (needs_modeset(new_crtc_state) ||
13372                     to_intel_crtc_state(new_crtc_state)->update_pipe) {
13373
13374                         put_domains[intel_crtc->pipe] =
13375                                 modeset_get_crtc_power_domains(crtc,
13376                                         new_intel_crtc_state);
13377                 }
13378
13379                 if (!needs_modeset(new_crtc_state))
13380                         continue;
13381
13382                 intel_pre_plane_update(old_intel_crtc_state, new_intel_crtc_state);
13383
13384                 if (old_crtc_state->active) {
13385                         intel_crtc_disable_planes(intel_state, intel_crtc);
13386
13387                         /*
13388                          * We need to disable pipe CRC before disabling the pipe,
13389                          * or we race against vblank off.
13390                          */
13391                         intel_crtc_disable_pipe_crc(intel_crtc);
13392
13393                         dev_priv->display.crtc_disable(old_intel_crtc_state, state);
13394                         intel_crtc->active = false;
13395                         intel_fbc_disable(intel_crtc);
13396                         intel_disable_shared_dpll(old_intel_crtc_state);
13397
13398                         /*
13399                          * Underruns don't always raise
13400                          * interrupts, so check manually.
13401                          */
13402                         intel_check_cpu_fifo_underruns(dev_priv);
13403                         intel_check_pch_fifo_underruns(dev_priv);
13404
13405                         /* FIXME unify this for all platforms */
13406                         if (!new_crtc_state->active &&
13407                             !HAS_GMCH(dev_priv) &&
13408                             dev_priv->display.initial_watermarks)
13409                                 dev_priv->display.initial_watermarks(intel_state,
13410                                                                      new_intel_crtc_state);
13411                 }
13412         }
13413
13414         /* FIXME: Eventually get rid of our intel_crtc->config pointer */
13415         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i)
13416                 to_intel_crtc(crtc)->config = to_intel_crtc_state(new_crtc_state);
13417
13418         if (intel_state->modeset) {
13419                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
13420
13421                 intel_set_cdclk_pre_plane_update(dev_priv,
13422                                                  &intel_state->cdclk.actual,
13423                                                  &dev_priv->cdclk.actual,
13424                                                  intel_state->cdclk.pipe);
13425
13426                 /*
13427                  * SKL workaround: bspec recommends we disable the SAGV when we
13428                  * have more then one pipe enabled
13429                  */
13430                 if (!intel_can_enable_sagv(state))
13431                         intel_disable_sagv(dev_priv);
13432
13433                 intel_modeset_verify_disabled(dev, state);
13434         }
13435
13436         /* Complete the events for pipes that have now been disabled */
13437         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13438                 bool modeset = needs_modeset(new_crtc_state);
13439
13440                 /* Complete events for now disable pipes here. */
13441                 if (modeset && !new_crtc_state->active && new_crtc_state->event) {
13442                         spin_lock_irq(&dev->event_lock);
13443                         drm_crtc_send_vblank_event(crtc, new_crtc_state->event);
13444                         spin_unlock_irq(&dev->event_lock);
13445
13446                         new_crtc_state->event = NULL;
13447                 }
13448         }
13449
13450         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
13451         dev_priv->display.update_crtcs(state);
13452
13453         if (intel_state->modeset)
13454                 intel_set_cdclk_post_plane_update(dev_priv,
13455                                                   &intel_state->cdclk.actual,
13456                                                   &dev_priv->cdclk.actual,
13457                                                   intel_state->cdclk.pipe);
13458
13459         /* FIXME: We should call drm_atomic_helper_commit_hw_done() here
13460          * already, but still need the state for the delayed optimization. To
13461          * fix this:
13462          * - wrap the optimization/post_plane_update stuff into a per-crtc work.
13463          * - schedule that vblank worker _before_ calling hw_done
13464          * - at the start of commit_tail, cancel it _synchrously
13465          * - switch over to the vblank wait helper in the core after that since
13466          *   we don't need out special handling any more.
13467          */
13468         drm_atomic_helper_wait_for_flip_done(dev, state);
13469
13470         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13471                 new_intel_crtc_state = to_intel_crtc_state(new_crtc_state);
13472
13473                 if (new_crtc_state->active &&
13474                     !needs_modeset(new_crtc_state) &&
13475                     (new_intel_crtc_state->base.color_mgmt_changed ||
13476                      new_intel_crtc_state->update_pipe))
13477                         intel_color_load_luts(new_intel_crtc_state);
13478         }
13479
13480         /*
13481          * Now that the vblank has passed, we can go ahead and program the
13482          * optimal watermarks on platforms that need two-step watermark
13483          * programming.
13484          *
13485          * TODO: Move this (and other cleanup) to an async worker eventually.
13486          */
13487         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13488                 new_intel_crtc_state = to_intel_crtc_state(new_crtc_state);
13489
13490                 if (dev_priv->display.optimize_watermarks)
13491                         dev_priv->display.optimize_watermarks(intel_state,
13492                                                               new_intel_crtc_state);
13493         }
13494
13495         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13496                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
13497
13498                 if (put_domains[i])
13499                         modeset_put_power_domains(dev_priv, put_domains[i]);
13500
13501                 intel_modeset_verify_crtc(crtc, state, old_crtc_state, new_crtc_state);
13502         }
13503
13504         if (intel_state->modeset)
13505                 intel_verify_planes(intel_state);
13506
13507         if (intel_state->modeset && intel_can_enable_sagv(state))
13508                 intel_enable_sagv(dev_priv);
13509
13510         drm_atomic_helper_commit_hw_done(state);
13511
13512         if (intel_state->modeset) {
13513                 /* As one of the primary mmio accessors, KMS has a high
13514                  * likelihood of triggering bugs in unclaimed access. After we
13515                  * finish modesetting, see if an error has been flagged, and if
13516                  * so enable debugging for the next modeset - and hope we catch
13517                  * the culprit.
13518                  */
13519                 intel_uncore_arm_unclaimed_mmio_detection(&dev_priv->uncore);
13520                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET, wakeref);
13521         }
13522
13523         /*
13524          * Defer the cleanup of the old state to a separate worker to not
13525          * impede the current task (userspace for blocking modesets) that
13526          * are executed inline. For out-of-line asynchronous modesets/flips,
13527          * deferring to a new worker seems overkill, but we would place a
13528          * schedule point (cond_resched()) here anyway to keep latencies
13529          * down.
13530          */
13531         INIT_WORK(&state->commit_work, intel_atomic_cleanup_work);
13532         queue_work(system_highpri_wq, &state->commit_work);
13533 }
13534
13535 static void intel_atomic_commit_work(struct work_struct *work)
13536 {
13537         struct drm_atomic_state *state =
13538                 container_of(work, struct drm_atomic_state, commit_work);
13539
13540         intel_atomic_commit_tail(state);
13541 }
13542
13543 static int __i915_sw_fence_call
13544 intel_atomic_commit_ready(struct i915_sw_fence *fence,
13545                           enum i915_sw_fence_notify notify)
13546 {
13547         struct intel_atomic_state *state =
13548                 container_of(fence, struct intel_atomic_state, commit_ready);
13549
13550         switch (notify) {
13551         case FENCE_COMPLETE:
13552                 /* we do blocking waits in the worker, nothing to do here */
13553                 break;
13554         case FENCE_FREE:
13555                 {
13556                         struct intel_atomic_helper *helper =
13557                                 &to_i915(state->base.dev)->atomic_helper;
13558
13559                         if (llist_add(&state->freed, &helper->free_list))
13560                                 schedule_work(&helper->free_work);
13561                         break;
13562                 }
13563         }
13564
13565         return NOTIFY_DONE;
13566 }
13567
13568 static void intel_atomic_track_fbs(struct drm_atomic_state *state)
13569 {
13570         struct drm_plane_state *old_plane_state, *new_plane_state;
13571         struct drm_plane *plane;
13572         int i;
13573
13574         for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i)
13575                 i915_gem_track_fb(intel_fb_obj(old_plane_state->fb),
13576                                   intel_fb_obj(new_plane_state->fb),
13577                                   to_intel_plane(plane)->frontbuffer_bit);
13578 }
13579
13580 /**
13581  * intel_atomic_commit - commit validated state object
13582  * @dev: DRM device
13583  * @state: the top-level driver state object
13584  * @nonblock: nonblocking commit
13585  *
13586  * This function commits a top-level state object that has been validated
13587  * with drm_atomic_helper_check().
13588  *
13589  * RETURNS
13590  * Zero for success or -errno.
13591  */
13592 static int intel_atomic_commit(struct drm_device *dev,
13593                                struct drm_atomic_state *state,
13594                                bool nonblock)
13595 {
13596         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13597         struct drm_i915_private *dev_priv = to_i915(dev);
13598         int ret = 0;
13599
13600         drm_atomic_state_get(state);
13601         i915_sw_fence_init(&intel_state->commit_ready,
13602                            intel_atomic_commit_ready);
13603
13604         /*
13605          * The intel_legacy_cursor_update() fast path takes care
13606          * of avoiding the vblank waits for simple cursor
13607          * movement and flips. For cursor on/off and size changes,
13608          * we want to perform the vblank waits so that watermark
13609          * updates happen during the correct frames. Gen9+ have
13610          * double buffered watermarks and so shouldn't need this.
13611          *
13612          * Unset state->legacy_cursor_update before the call to
13613          * drm_atomic_helper_setup_commit() because otherwise
13614          * drm_atomic_helper_wait_for_flip_done() is a noop and
13615          * we get FIFO underruns because we didn't wait
13616          * for vblank.
13617          *
13618          * FIXME doing watermarks and fb cleanup from a vblank worker
13619          * (assuming we had any) would solve these problems.
13620          */
13621         if (INTEL_GEN(dev_priv) < 9 && state->legacy_cursor_update) {
13622                 struct intel_crtc_state *new_crtc_state;
13623                 struct intel_crtc *crtc;
13624                 int i;
13625
13626                 for_each_new_intel_crtc_in_state(intel_state, crtc, new_crtc_state, i)
13627                         if (new_crtc_state->wm.need_postvbl_update ||
13628                             new_crtc_state->update_wm_post)
13629                                 state->legacy_cursor_update = false;
13630         }
13631
13632         ret = intel_atomic_prepare_commit(dev, state);
13633         if (ret) {
13634                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
13635                 i915_sw_fence_commit(&intel_state->commit_ready);
13636                 return ret;
13637         }
13638
13639         ret = drm_atomic_helper_setup_commit(state, nonblock);
13640         if (!ret)
13641                 ret = drm_atomic_helper_swap_state(state, true);
13642
13643         if (ret) {
13644                 i915_sw_fence_commit(&intel_state->commit_ready);
13645
13646                 drm_atomic_helper_cleanup_planes(dev, state);
13647                 return ret;
13648         }
13649         dev_priv->wm.distrust_bios_wm = false;
13650         intel_shared_dpll_swap_state(state);
13651         intel_atomic_track_fbs(state);
13652
13653         if (intel_state->modeset) {
13654                 memcpy(dev_priv->min_cdclk, intel_state->min_cdclk,
13655                        sizeof(intel_state->min_cdclk));
13656                 memcpy(dev_priv->min_voltage_level,
13657                        intel_state->min_voltage_level,
13658                        sizeof(intel_state->min_voltage_level));
13659                 dev_priv->active_crtcs = intel_state->active_crtcs;
13660                 dev_priv->cdclk.force_min_cdclk =
13661                         intel_state->cdclk.force_min_cdclk;
13662
13663                 intel_cdclk_swap_state(intel_state);
13664         }
13665
13666         drm_atomic_state_get(state);
13667         INIT_WORK(&state->commit_work, intel_atomic_commit_work);
13668
13669         i915_sw_fence_commit(&intel_state->commit_ready);
13670         if (nonblock && intel_state->modeset) {
13671                 queue_work(dev_priv->modeset_wq, &state->commit_work);
13672         } else if (nonblock) {
13673                 queue_work(system_unbound_wq, &state->commit_work);
13674         } else {
13675                 if (intel_state->modeset)
13676                         flush_workqueue(dev_priv->modeset_wq);
13677                 intel_atomic_commit_tail(state);
13678         }
13679
13680         return 0;
13681 }
13682
13683 static const struct drm_crtc_funcs intel_crtc_funcs = {
13684         .gamma_set = drm_atomic_helper_legacy_gamma_set,
13685         .set_config = drm_atomic_helper_set_config,
13686         .destroy = intel_crtc_destroy,
13687         .page_flip = drm_atomic_helper_page_flip,
13688         .atomic_duplicate_state = intel_crtc_duplicate_state,
13689         .atomic_destroy_state = intel_crtc_destroy_state,
13690         .set_crc_source = intel_crtc_set_crc_source,
13691         .verify_crc_source = intel_crtc_verify_crc_source,
13692         .get_crc_sources = intel_crtc_get_crc_sources,
13693 };
13694
13695 struct wait_rps_boost {
13696         struct wait_queue_entry wait;
13697
13698         struct drm_crtc *crtc;
13699         struct i915_request *request;
13700 };
13701
13702 static int do_rps_boost(struct wait_queue_entry *_wait,
13703                         unsigned mode, int sync, void *key)
13704 {
13705         struct wait_rps_boost *wait = container_of(_wait, typeof(*wait), wait);
13706         struct i915_request *rq = wait->request;
13707
13708         /*
13709          * If we missed the vblank, but the request is already running it
13710          * is reasonable to assume that it will complete before the next
13711          * vblank without our intervention, so leave RPS alone.
13712          */
13713         if (!i915_request_started(rq))
13714                 gen6_rps_boost(rq);
13715         i915_request_put(rq);
13716
13717         drm_crtc_vblank_put(wait->crtc);
13718
13719         list_del(&wait->wait.entry);
13720         kfree(wait);
13721         return 1;
13722 }
13723
13724 static void add_rps_boost_after_vblank(struct drm_crtc *crtc,
13725                                        struct dma_fence *fence)
13726 {
13727         struct wait_rps_boost *wait;
13728
13729         if (!dma_fence_is_i915(fence))
13730                 return;
13731
13732         if (INTEL_GEN(to_i915(crtc->dev)) < 6)
13733                 return;
13734
13735         if (drm_crtc_vblank_get(crtc))
13736                 return;
13737
13738         wait = kmalloc(sizeof(*wait), GFP_KERNEL);
13739         if (!wait) {
13740                 drm_crtc_vblank_put(crtc);
13741                 return;
13742         }
13743
13744         wait->request = to_request(dma_fence_get(fence));
13745         wait->crtc = crtc;
13746
13747         wait->wait.func = do_rps_boost;
13748         wait->wait.flags = 0;
13749
13750         add_wait_queue(drm_crtc_vblank_waitqueue(crtc), &wait->wait);
13751 }
13752
13753 static int intel_plane_pin_fb(struct intel_plane_state *plane_state)
13754 {
13755         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
13756         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
13757         struct drm_framebuffer *fb = plane_state->base.fb;
13758         struct i915_vma *vma;
13759
13760         if (plane->id == PLANE_CURSOR &&
13761             INTEL_INFO(dev_priv)->display.cursor_needs_physical) {
13762                 struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13763                 const int align = intel_cursor_alignment(dev_priv);
13764                 int err;
13765
13766                 err = i915_gem_object_attach_phys(obj, align);
13767                 if (err)
13768                         return err;
13769         }
13770
13771         vma = intel_pin_and_fence_fb_obj(fb,
13772                                          &plane_state->view,
13773                                          intel_plane_uses_fence(plane_state),
13774                                          &plane_state->flags);
13775         if (IS_ERR(vma))
13776                 return PTR_ERR(vma);
13777
13778         plane_state->vma = vma;
13779
13780         return 0;
13781 }
13782
13783 static void intel_plane_unpin_fb(struct intel_plane_state *old_plane_state)
13784 {
13785         struct i915_vma *vma;
13786
13787         vma = fetch_and_zero(&old_plane_state->vma);
13788         if (vma)
13789                 intel_unpin_fb_vma(vma, old_plane_state->flags);
13790 }
13791
13792 static void fb_obj_bump_render_priority(struct drm_i915_gem_object *obj)
13793 {
13794         struct i915_sched_attr attr = {
13795                 .priority = I915_PRIORITY_DISPLAY,
13796         };
13797
13798         i915_gem_object_wait_priority(obj, 0, &attr);
13799 }
13800
13801 /**
13802  * intel_prepare_plane_fb - Prepare fb for usage on plane
13803  * @plane: drm plane to prepare for
13804  * @new_state: the plane state being prepared
13805  *
13806  * Prepares a framebuffer for usage on a display plane.  Generally this
13807  * involves pinning the underlying object and updating the frontbuffer tracking
13808  * bits.  Some older platforms need special physical address handling for
13809  * cursor planes.
13810  *
13811  * Must be called with struct_mutex held.
13812  *
13813  * Returns 0 on success, negative error code on failure.
13814  */
13815 int
13816 intel_prepare_plane_fb(struct drm_plane *plane,
13817                        struct drm_plane_state *new_state)
13818 {
13819         struct intel_atomic_state *intel_state =
13820                 to_intel_atomic_state(new_state->state);
13821         struct drm_i915_private *dev_priv = to_i915(plane->dev);
13822         struct drm_framebuffer *fb = new_state->fb;
13823         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13824         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
13825         int ret;
13826
13827         if (old_obj) {
13828                 struct drm_crtc_state *crtc_state =
13829                         drm_atomic_get_new_crtc_state(new_state->state,
13830                                                       plane->state->crtc);
13831
13832                 /* Big Hammer, we also need to ensure that any pending
13833                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
13834                  * current scanout is retired before unpinning the old
13835                  * framebuffer. Note that we rely on userspace rendering
13836                  * into the buffer attached to the pipe they are waiting
13837                  * on. If not, userspace generates a GPU hang with IPEHR
13838                  * point to the MI_WAIT_FOR_EVENT.
13839                  *
13840                  * This should only fail upon a hung GPU, in which case we
13841                  * can safely continue.
13842                  */
13843                 if (needs_modeset(crtc_state)) {
13844                         ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
13845                                                               old_obj->resv, NULL,
13846                                                               false, 0,
13847                                                               GFP_KERNEL);
13848                         if (ret < 0)
13849                                 return ret;
13850                 }
13851         }
13852
13853         if (new_state->fence) { /* explicit fencing */
13854                 ret = i915_sw_fence_await_dma_fence(&intel_state->commit_ready,
13855                                                     new_state->fence,
13856                                                     I915_FENCE_TIMEOUT,
13857                                                     GFP_KERNEL);
13858                 if (ret < 0)
13859                         return ret;
13860         }
13861
13862         if (!obj)
13863                 return 0;
13864
13865         ret = i915_gem_object_pin_pages(obj);
13866         if (ret)
13867                 return ret;
13868
13869         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
13870         if (ret) {
13871                 i915_gem_object_unpin_pages(obj);
13872                 return ret;
13873         }
13874
13875         ret = intel_plane_pin_fb(to_intel_plane_state(new_state));
13876
13877         mutex_unlock(&dev_priv->drm.struct_mutex);
13878         i915_gem_object_unpin_pages(obj);
13879         if (ret)
13880                 return ret;
13881
13882         fb_obj_bump_render_priority(obj);
13883         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
13884
13885         if (!new_state->fence) { /* implicit fencing */
13886                 struct dma_fence *fence;
13887
13888                 ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
13889                                                       obj->resv, NULL,
13890                                                       false, I915_FENCE_TIMEOUT,
13891                                                       GFP_KERNEL);
13892                 if (ret < 0)
13893                         return ret;
13894
13895                 fence = reservation_object_get_excl_rcu(obj->resv);
13896                 if (fence) {
13897                         add_rps_boost_after_vblank(new_state->crtc, fence);
13898                         dma_fence_put(fence);
13899                 }
13900         } else {
13901                 add_rps_boost_after_vblank(new_state->crtc, new_state->fence);
13902         }
13903
13904         /*
13905          * We declare pageflips to be interactive and so merit a small bias
13906          * towards upclocking to deliver the frame on time. By only changing
13907          * the RPS thresholds to sample more regularly and aim for higher
13908          * clocks we can hopefully deliver low power workloads (like kodi)
13909          * that are not quite steady state without resorting to forcing
13910          * maximum clocks following a vblank miss (see do_rps_boost()).
13911          */
13912         if (!intel_state->rps_interactive) {
13913                 intel_rps_mark_interactive(dev_priv, true);
13914                 intel_state->rps_interactive = true;
13915         }
13916
13917         return 0;
13918 }
13919
13920 /**
13921  * intel_cleanup_plane_fb - Cleans up an fb after plane use
13922  * @plane: drm plane to clean up for
13923  * @old_state: the state from the previous modeset
13924  *
13925  * Cleans up a framebuffer that has just been removed from a plane.
13926  *
13927  * Must be called with struct_mutex held.
13928  */
13929 void
13930 intel_cleanup_plane_fb(struct drm_plane *plane,
13931                        struct drm_plane_state *old_state)
13932 {
13933         struct intel_atomic_state *intel_state =
13934                 to_intel_atomic_state(old_state->state);
13935         struct drm_i915_private *dev_priv = to_i915(plane->dev);
13936
13937         if (intel_state->rps_interactive) {
13938                 intel_rps_mark_interactive(dev_priv, false);
13939                 intel_state->rps_interactive = false;
13940         }
13941
13942         /* Should only be called after a successful intel_prepare_plane_fb()! */
13943         mutex_lock(&dev_priv->drm.struct_mutex);
13944         intel_plane_unpin_fb(to_intel_plane_state(old_state));
13945         mutex_unlock(&dev_priv->drm.struct_mutex);
13946 }
13947
13948 int
13949 skl_max_scale(const struct intel_crtc_state *crtc_state,
13950               u32 pixel_format)
13951 {
13952         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
13953         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13954         int max_scale, mult;
13955         int crtc_clock, max_dotclk, tmpclk1, tmpclk2;
13956
13957         if (!crtc_state->base.enable)
13958                 return DRM_PLANE_HELPER_NO_SCALING;
13959
13960         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
13961         max_dotclk = to_intel_atomic_state(crtc_state->base.state)->cdclk.logical.cdclk;
13962
13963         if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) >= 10)
13964                 max_dotclk *= 2;
13965
13966         if (WARN_ON_ONCE(!crtc_clock || max_dotclk < crtc_clock))
13967                 return DRM_PLANE_HELPER_NO_SCALING;
13968
13969         /*
13970          * skl max scale is lower of:
13971          *    close to 3 but not 3, -1 is for that purpose
13972          *            or
13973          *    cdclk/crtc_clock
13974          */
13975         mult = is_planar_yuv_format(pixel_format) ? 2 : 3;
13976         tmpclk1 = (1 << 16) * mult - 1;
13977         tmpclk2 = (1 << 8) * ((max_dotclk << 8) / crtc_clock);
13978         max_scale = min(tmpclk1, tmpclk2);
13979
13980         return max_scale;
13981 }
13982
13983 static void intel_begin_crtc_commit(struct intel_atomic_state *state,
13984                                     struct intel_crtc *crtc)
13985 {
13986         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13987         struct intel_crtc_state *old_crtc_state =
13988                 intel_atomic_get_old_crtc_state(state, crtc);
13989         struct intel_crtc_state *new_crtc_state =
13990                 intel_atomic_get_new_crtc_state(state, crtc);
13991         bool modeset = needs_modeset(&new_crtc_state->base);
13992
13993         /* Perform vblank evasion around commit operation */
13994         intel_pipe_update_start(new_crtc_state);
13995
13996         if (modeset)
13997                 goto out;
13998
13999         if (new_crtc_state->base.color_mgmt_changed ||
14000             new_crtc_state->update_pipe)
14001                 intel_color_commit(new_crtc_state);
14002
14003         if (new_crtc_state->update_pipe)
14004                 intel_update_pipe_config(old_crtc_state, new_crtc_state);
14005         else if (INTEL_GEN(dev_priv) >= 9)
14006                 skl_detach_scalers(new_crtc_state);
14007
14008         if (INTEL_GEN(dev_priv) >= 9 || IS_BROADWELL(dev_priv))
14009                 bdw_set_pipemisc(new_crtc_state);
14010
14011 out:
14012         if (dev_priv->display.atomic_update_watermarks)
14013                 dev_priv->display.atomic_update_watermarks(state,
14014                                                            new_crtc_state);
14015 }
14016
14017 void intel_crtc_arm_fifo_underrun(struct intel_crtc *crtc,
14018                                   struct intel_crtc_state *crtc_state)
14019 {
14020         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
14021
14022         if (!IS_GEN(dev_priv, 2))
14023                 intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, true);
14024
14025         if (crtc_state->has_pch_encoder) {
14026                 enum pipe pch_transcoder =
14027                         intel_crtc_pch_transcoder(crtc);
14028
14029                 intel_set_pch_fifo_underrun_reporting(dev_priv, pch_transcoder, true);
14030         }
14031 }
14032
14033 static void intel_finish_crtc_commit(struct intel_atomic_state *state,
14034                                      struct intel_crtc *crtc)
14035 {
14036         struct intel_crtc_state *old_crtc_state =
14037                 intel_atomic_get_old_crtc_state(state, crtc);
14038         struct intel_crtc_state *new_crtc_state =
14039                 intel_atomic_get_new_crtc_state(state, crtc);
14040
14041         intel_pipe_update_end(new_crtc_state);
14042
14043         if (new_crtc_state->update_pipe &&
14044             !needs_modeset(&new_crtc_state->base) &&
14045             old_crtc_state->base.mode.private_flags & I915_MODE_FLAG_INHERITED)
14046                 intel_crtc_arm_fifo_underrun(crtc, new_crtc_state);
14047 }
14048
14049 /**
14050  * intel_plane_destroy - destroy a plane
14051  * @plane: plane to destroy
14052  *
14053  * Common destruction function for all types of planes (primary, cursor,
14054  * sprite).
14055  */
14056 void intel_plane_destroy(struct drm_plane *plane)
14057 {
14058         drm_plane_cleanup(plane);
14059         kfree(to_intel_plane(plane));
14060 }
14061
14062 static bool i8xx_plane_format_mod_supported(struct drm_plane *_plane,
14063                                             u32 format, u64 modifier)
14064 {
14065         switch (modifier) {
14066         case DRM_FORMAT_MOD_LINEAR:
14067         case I915_FORMAT_MOD_X_TILED:
14068                 break;
14069         default:
14070                 return false;
14071         }
14072
14073         switch (format) {
14074         case DRM_FORMAT_C8:
14075         case DRM_FORMAT_RGB565:
14076         case DRM_FORMAT_XRGB1555:
14077         case DRM_FORMAT_XRGB8888:
14078                 return modifier == DRM_FORMAT_MOD_LINEAR ||
14079                         modifier == I915_FORMAT_MOD_X_TILED;
14080         default:
14081                 return false;
14082         }
14083 }
14084
14085 static bool i965_plane_format_mod_supported(struct drm_plane *_plane,
14086                                             u32 format, u64 modifier)
14087 {
14088         switch (modifier) {
14089         case DRM_FORMAT_MOD_LINEAR:
14090         case I915_FORMAT_MOD_X_TILED:
14091                 break;
14092         default:
14093                 return false;
14094         }
14095
14096         switch (format) {
14097         case DRM_FORMAT_C8:
14098         case DRM_FORMAT_RGB565:
14099         case DRM_FORMAT_XRGB8888:
14100         case DRM_FORMAT_XBGR8888:
14101         case DRM_FORMAT_XRGB2101010:
14102         case DRM_FORMAT_XBGR2101010:
14103                 return modifier == DRM_FORMAT_MOD_LINEAR ||
14104                         modifier == I915_FORMAT_MOD_X_TILED;
14105         default:
14106                 return false;
14107         }
14108 }
14109
14110 static bool intel_cursor_format_mod_supported(struct drm_plane *_plane,
14111                                               u32 format, u64 modifier)
14112 {
14113         return modifier == DRM_FORMAT_MOD_LINEAR &&
14114                 format == DRM_FORMAT_ARGB8888;
14115 }
14116
14117 static const struct drm_plane_funcs i965_plane_funcs = {
14118         .update_plane = drm_atomic_helper_update_plane,
14119         .disable_plane = drm_atomic_helper_disable_plane,
14120         .destroy = intel_plane_destroy,
14121         .atomic_get_property = intel_plane_atomic_get_property,
14122         .atomic_set_property = intel_plane_atomic_set_property,
14123         .atomic_duplicate_state = intel_plane_duplicate_state,
14124         .atomic_destroy_state = intel_plane_destroy_state,
14125         .format_mod_supported = i965_plane_format_mod_supported,
14126 };
14127
14128 static const struct drm_plane_funcs i8xx_plane_funcs = {
14129         .update_plane = drm_atomic_helper_update_plane,
14130         .disable_plane = drm_atomic_helper_disable_plane,
14131         .destroy = intel_plane_destroy,
14132         .atomic_get_property = intel_plane_atomic_get_property,
14133         .atomic_set_property = intel_plane_atomic_set_property,
14134         .atomic_duplicate_state = intel_plane_duplicate_state,
14135         .atomic_destroy_state = intel_plane_destroy_state,
14136         .format_mod_supported = i8xx_plane_format_mod_supported,
14137 };
14138
14139 static int
14140 intel_legacy_cursor_update(struct drm_plane *plane,
14141                            struct drm_crtc *crtc,
14142                            struct drm_framebuffer *fb,
14143                            int crtc_x, int crtc_y,
14144                            unsigned int crtc_w, unsigned int crtc_h,
14145                            u32 src_x, u32 src_y,
14146                            u32 src_w, u32 src_h,
14147                            struct drm_modeset_acquire_ctx *ctx)
14148 {
14149         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
14150         int ret;
14151         struct drm_plane_state *old_plane_state, *new_plane_state;
14152         struct intel_plane *intel_plane = to_intel_plane(plane);
14153         struct drm_framebuffer *old_fb;
14154         struct intel_crtc_state *crtc_state =
14155                 to_intel_crtc_state(crtc->state);
14156         struct intel_crtc_state *new_crtc_state;
14157
14158         /*
14159          * When crtc is inactive or there is a modeset pending,
14160          * wait for it to complete in the slowpath
14161          */
14162         if (!crtc_state->base.active || needs_modeset(&crtc_state->base) ||
14163             crtc_state->update_pipe)
14164                 goto slow;
14165
14166         old_plane_state = plane->state;
14167         /*
14168          * Don't do an async update if there is an outstanding commit modifying
14169          * the plane.  This prevents our async update's changes from getting
14170          * overridden by a previous synchronous update's state.
14171          */
14172         if (old_plane_state->commit &&
14173             !try_wait_for_completion(&old_plane_state->commit->hw_done))
14174                 goto slow;
14175
14176         /*
14177          * If any parameters change that may affect watermarks,
14178          * take the slowpath. Only changing fb or position should be
14179          * in the fastpath.
14180          */
14181         if (old_plane_state->crtc != crtc ||
14182             old_plane_state->src_w != src_w ||
14183             old_plane_state->src_h != src_h ||
14184             old_plane_state->crtc_w != crtc_w ||
14185             old_plane_state->crtc_h != crtc_h ||
14186             !old_plane_state->fb != !fb)
14187                 goto slow;
14188
14189         new_plane_state = intel_plane_duplicate_state(plane);
14190         if (!new_plane_state)
14191                 return -ENOMEM;
14192
14193         new_crtc_state = to_intel_crtc_state(intel_crtc_duplicate_state(crtc));
14194         if (!new_crtc_state) {
14195                 ret = -ENOMEM;
14196                 goto out_free;
14197         }
14198
14199         drm_atomic_set_fb_for_plane(new_plane_state, fb);
14200
14201         new_plane_state->src_x = src_x;
14202         new_plane_state->src_y = src_y;
14203         new_plane_state->src_w = src_w;
14204         new_plane_state->src_h = src_h;
14205         new_plane_state->crtc_x = crtc_x;
14206         new_plane_state->crtc_y = crtc_y;
14207         new_plane_state->crtc_w = crtc_w;
14208         new_plane_state->crtc_h = crtc_h;
14209
14210         ret = intel_plane_atomic_check_with_state(crtc_state, new_crtc_state,
14211                                                   to_intel_plane_state(old_plane_state),
14212                                                   to_intel_plane_state(new_plane_state));
14213         if (ret)
14214                 goto out_free;
14215
14216         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
14217         if (ret)
14218                 goto out_free;
14219
14220         ret = intel_plane_pin_fb(to_intel_plane_state(new_plane_state));
14221         if (ret)
14222                 goto out_unlock;
14223
14224         intel_fb_obj_flush(intel_fb_obj(fb), ORIGIN_FLIP);
14225
14226         old_fb = old_plane_state->fb;
14227         i915_gem_track_fb(intel_fb_obj(old_fb), intel_fb_obj(fb),
14228                           intel_plane->frontbuffer_bit);
14229
14230         /* Swap plane state */
14231         plane->state = new_plane_state;
14232
14233         /*
14234          * We cannot swap crtc_state as it may be in use by an atomic commit or
14235          * page flip that's running simultaneously. If we swap crtc_state and
14236          * destroy the old state, we will cause a use-after-free there.
14237          *
14238          * Only update active_planes, which is needed for our internal
14239          * bookkeeping. Either value will do the right thing when updating
14240          * planes atomically. If the cursor was part of the atomic update then
14241          * we would have taken the slowpath.
14242          */
14243         crtc_state->active_planes = new_crtc_state->active_planes;
14244
14245         if (plane->state->visible)
14246                 intel_update_plane(intel_plane, crtc_state,
14247                                    to_intel_plane_state(plane->state));
14248         else
14249                 intel_disable_plane(intel_plane, crtc_state);
14250
14251         intel_plane_unpin_fb(to_intel_plane_state(old_plane_state));
14252
14253 out_unlock:
14254         mutex_unlock(&dev_priv->drm.struct_mutex);
14255 out_free:
14256         if (new_crtc_state)
14257                 intel_crtc_destroy_state(crtc, &new_crtc_state->base);
14258         if (ret)
14259                 intel_plane_destroy_state(plane, new_plane_state);
14260         else
14261                 intel_plane_destroy_state(plane, old_plane_state);
14262         return ret;
14263
14264 slow:
14265         return drm_atomic_helper_update_plane(plane, crtc, fb,
14266                                               crtc_x, crtc_y, crtc_w, crtc_h,
14267                                               src_x, src_y, src_w, src_h, ctx);
14268 }
14269
14270 static const struct drm_plane_funcs intel_cursor_plane_funcs = {
14271         .update_plane = intel_legacy_cursor_update,
14272         .disable_plane = drm_atomic_helper_disable_plane,
14273         .destroy = intel_plane_destroy,
14274         .atomic_get_property = intel_plane_atomic_get_property,
14275         .atomic_set_property = intel_plane_atomic_set_property,
14276         .atomic_duplicate_state = intel_plane_duplicate_state,
14277         .atomic_destroy_state = intel_plane_destroy_state,
14278         .format_mod_supported = intel_cursor_format_mod_supported,
14279 };
14280
14281 static bool i9xx_plane_has_fbc(struct drm_i915_private *dev_priv,
14282                                enum i9xx_plane_id i9xx_plane)
14283 {
14284         if (!HAS_FBC(dev_priv))
14285                 return false;
14286
14287         if (IS_BROADWELL(dev_priv) || IS_HASWELL(dev_priv))
14288                 return i9xx_plane == PLANE_A; /* tied to pipe A */
14289         else if (IS_IVYBRIDGE(dev_priv))
14290                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B ||
14291                         i9xx_plane == PLANE_C;
14292         else if (INTEL_GEN(dev_priv) >= 4)
14293                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B;
14294         else
14295                 return i9xx_plane == PLANE_A;
14296 }
14297
14298 static struct intel_plane *
14299 intel_primary_plane_create(struct drm_i915_private *dev_priv, enum pipe pipe)
14300 {
14301         struct intel_plane *plane;
14302         const struct drm_plane_funcs *plane_funcs;
14303         unsigned int supported_rotations;
14304         unsigned int possible_crtcs;
14305         const u64 *modifiers;
14306         const u32 *formats;
14307         int num_formats;
14308         int ret;
14309
14310         if (INTEL_GEN(dev_priv) >= 9)
14311                 return skl_universal_plane_create(dev_priv, pipe,
14312                                                   PLANE_PRIMARY);
14313
14314         plane = intel_plane_alloc();
14315         if (IS_ERR(plane))
14316                 return plane;
14317
14318         plane->pipe = pipe;
14319         /*
14320          * On gen2/3 only plane A can do FBC, but the panel fitter and LVDS
14321          * port is hooked to pipe B. Hence we want plane A feeding pipe B.
14322          */
14323         if (HAS_FBC(dev_priv) && INTEL_GEN(dev_priv) < 4)
14324                 plane->i9xx_plane = (enum i9xx_plane_id) !pipe;
14325         else
14326                 plane->i9xx_plane = (enum i9xx_plane_id) pipe;
14327         plane->id = PLANE_PRIMARY;
14328         plane->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, plane->id);
14329
14330         plane->has_fbc = i9xx_plane_has_fbc(dev_priv, plane->i9xx_plane);
14331         if (plane->has_fbc) {
14332                 struct intel_fbc *fbc = &dev_priv->fbc;
14333
14334                 fbc->possible_framebuffer_bits |= plane->frontbuffer_bit;
14335         }
14336
14337         if (INTEL_GEN(dev_priv) >= 4) {
14338                 formats = i965_primary_formats;
14339                 num_formats = ARRAY_SIZE(i965_primary_formats);
14340                 modifiers = i9xx_format_modifiers;
14341
14342                 plane->max_stride = i9xx_plane_max_stride;
14343                 plane->update_plane = i9xx_update_plane;
14344                 plane->disable_plane = i9xx_disable_plane;
14345                 plane->get_hw_state = i9xx_plane_get_hw_state;
14346                 plane->check_plane = i9xx_plane_check;
14347
14348                 plane_funcs = &i965_plane_funcs;
14349         } else {
14350                 formats = i8xx_primary_formats;
14351                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
14352                 modifiers = i9xx_format_modifiers;
14353
14354                 plane->max_stride = i9xx_plane_max_stride;
14355                 plane->update_plane = i9xx_update_plane;
14356                 plane->disable_plane = i9xx_disable_plane;
14357                 plane->get_hw_state = i9xx_plane_get_hw_state;
14358                 plane->check_plane = i9xx_plane_check;
14359
14360                 plane_funcs = &i8xx_plane_funcs;
14361         }
14362
14363         possible_crtcs = BIT(pipe);
14364
14365         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
14366                 ret = drm_universal_plane_init(&dev_priv->drm, &plane->base,
14367                                                possible_crtcs, plane_funcs,
14368                                                formats, num_formats, modifiers,
14369                                                DRM_PLANE_TYPE_PRIMARY,
14370                                                "primary %c", pipe_name(pipe));
14371         else
14372                 ret = drm_universal_plane_init(&dev_priv->drm, &plane->base,
14373                                                possible_crtcs, plane_funcs,
14374                                                formats, num_formats, modifiers,
14375                                                DRM_PLANE_TYPE_PRIMARY,
14376                                                "plane %c",
14377                                                plane_name(plane->i9xx_plane));
14378         if (ret)
14379                 goto fail;
14380
14381         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
14382                 supported_rotations =
14383                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180 |
14384                         DRM_MODE_REFLECT_X;
14385         } else if (INTEL_GEN(dev_priv) >= 4) {
14386                 supported_rotations =
14387                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180;
14388         } else {
14389                 supported_rotations = DRM_MODE_ROTATE_0;
14390         }
14391
14392         if (INTEL_GEN(dev_priv) >= 4)
14393                 drm_plane_create_rotation_property(&plane->base,
14394                                                    DRM_MODE_ROTATE_0,
14395                                                    supported_rotations);
14396
14397         drm_plane_helper_add(&plane->base, &intel_plane_helper_funcs);
14398
14399         return plane;
14400
14401 fail:
14402         intel_plane_free(plane);
14403
14404         return ERR_PTR(ret);
14405 }
14406
14407 static struct intel_plane *
14408 intel_cursor_plane_create(struct drm_i915_private *dev_priv,
14409                           enum pipe pipe)
14410 {
14411         unsigned int possible_crtcs;
14412         struct intel_plane *cursor;
14413         int ret;
14414
14415         cursor = intel_plane_alloc();
14416         if (IS_ERR(cursor))
14417                 return cursor;
14418
14419         cursor->pipe = pipe;
14420         cursor->i9xx_plane = (enum i9xx_plane_id) pipe;
14421         cursor->id = PLANE_CURSOR;
14422         cursor->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, cursor->id);
14423
14424         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
14425                 cursor->max_stride = i845_cursor_max_stride;
14426                 cursor->update_plane = i845_update_cursor;
14427                 cursor->disable_plane = i845_disable_cursor;
14428                 cursor->get_hw_state = i845_cursor_get_hw_state;
14429                 cursor->check_plane = i845_check_cursor;
14430         } else {
14431                 cursor->max_stride = i9xx_cursor_max_stride;
14432                 cursor->update_plane = i9xx_update_cursor;
14433                 cursor->disable_plane = i9xx_disable_cursor;
14434                 cursor->get_hw_state = i9xx_cursor_get_hw_state;
14435                 cursor->check_plane = i9xx_check_cursor;
14436         }
14437
14438         cursor->cursor.base = ~0;
14439         cursor->cursor.cntl = ~0;
14440
14441         if (IS_I845G(dev_priv) || IS_I865G(dev_priv) || HAS_CUR_FBC(dev_priv))
14442                 cursor->cursor.size = ~0;
14443
14444         possible_crtcs = BIT(pipe);
14445
14446         ret = drm_universal_plane_init(&dev_priv->drm, &cursor->base,
14447                                        possible_crtcs, &intel_cursor_plane_funcs,
14448                                        intel_cursor_formats,
14449                                        ARRAY_SIZE(intel_cursor_formats),
14450                                        cursor_format_modifiers,
14451                                        DRM_PLANE_TYPE_CURSOR,
14452                                        "cursor %c", pipe_name(pipe));
14453         if (ret)
14454                 goto fail;
14455
14456         if (INTEL_GEN(dev_priv) >= 4)
14457                 drm_plane_create_rotation_property(&cursor->base,
14458                                                    DRM_MODE_ROTATE_0,
14459                                                    DRM_MODE_ROTATE_0 |
14460                                                    DRM_MODE_ROTATE_180);
14461
14462         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
14463
14464         return cursor;
14465
14466 fail:
14467         intel_plane_free(cursor);
14468
14469         return ERR_PTR(ret);
14470 }
14471
14472 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
14473                                     struct intel_crtc_state *crtc_state)
14474 {
14475         struct intel_crtc_scaler_state *scaler_state =
14476                 &crtc_state->scaler_state;
14477         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
14478         int i;
14479
14480         crtc->num_scalers = RUNTIME_INFO(dev_priv)->num_scalers[crtc->pipe];
14481         if (!crtc->num_scalers)
14482                 return;
14483
14484         for (i = 0; i < crtc->num_scalers; i++) {
14485                 struct intel_scaler *scaler = &scaler_state->scalers[i];
14486
14487                 scaler->in_use = 0;
14488                 scaler->mode = 0;
14489         }
14490
14491         scaler_state->scaler_id = -1;
14492 }
14493
14494 static int intel_crtc_init(struct drm_i915_private *dev_priv, enum pipe pipe)
14495 {
14496         struct intel_crtc *intel_crtc;
14497         struct intel_crtc_state *crtc_state = NULL;
14498         struct intel_plane *primary = NULL;
14499         struct intel_plane *cursor = NULL;
14500         int sprite, ret;
14501
14502         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
14503         if (!intel_crtc)
14504                 return -ENOMEM;
14505
14506         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
14507         if (!crtc_state) {
14508                 ret = -ENOMEM;
14509                 goto fail;
14510         }
14511         intel_crtc->config = crtc_state;
14512         intel_crtc->base.state = &crtc_state->base;
14513         crtc_state->base.crtc = &intel_crtc->base;
14514
14515         primary = intel_primary_plane_create(dev_priv, pipe);
14516         if (IS_ERR(primary)) {
14517                 ret = PTR_ERR(primary);
14518                 goto fail;
14519         }
14520         intel_crtc->plane_ids_mask |= BIT(primary->id);
14521
14522         for_each_sprite(dev_priv, pipe, sprite) {
14523                 struct intel_plane *plane;
14524
14525                 plane = intel_sprite_plane_create(dev_priv, pipe, sprite);
14526                 if (IS_ERR(plane)) {
14527                         ret = PTR_ERR(plane);
14528                         goto fail;
14529                 }
14530                 intel_crtc->plane_ids_mask |= BIT(plane->id);
14531         }
14532
14533         cursor = intel_cursor_plane_create(dev_priv, pipe);
14534         if (IS_ERR(cursor)) {
14535                 ret = PTR_ERR(cursor);
14536                 goto fail;
14537         }
14538         intel_crtc->plane_ids_mask |= BIT(cursor->id);
14539
14540         ret = drm_crtc_init_with_planes(&dev_priv->drm, &intel_crtc->base,
14541                                         &primary->base, &cursor->base,
14542                                         &intel_crtc_funcs,
14543                                         "pipe %c", pipe_name(pipe));
14544         if (ret)
14545                 goto fail;
14546
14547         intel_crtc->pipe = pipe;
14548
14549         /* initialize shared scalers */
14550         intel_crtc_init_scalers(intel_crtc, crtc_state);
14551
14552         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->pipe_to_crtc_mapping) ||
14553                dev_priv->pipe_to_crtc_mapping[pipe] != NULL);
14554         dev_priv->pipe_to_crtc_mapping[pipe] = intel_crtc;
14555
14556         if (INTEL_GEN(dev_priv) < 9) {
14557                 enum i9xx_plane_id i9xx_plane = primary->i9xx_plane;
14558
14559                 BUG_ON(i9xx_plane >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
14560                        dev_priv->plane_to_crtc_mapping[i9xx_plane] != NULL);
14561                 dev_priv->plane_to_crtc_mapping[i9xx_plane] = intel_crtc;
14562         }
14563
14564         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
14565
14566         intel_color_init(intel_crtc);
14567
14568         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
14569
14570         return 0;
14571
14572 fail:
14573         /*
14574          * drm_mode_config_cleanup() will free up any
14575          * crtcs/planes already initialized.
14576          */
14577         kfree(crtc_state);
14578         kfree(intel_crtc);
14579
14580         return ret;
14581 }
14582
14583 int intel_get_pipe_from_crtc_id_ioctl(struct drm_device *dev, void *data,
14584                                       struct drm_file *file)
14585 {
14586         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
14587         struct drm_crtc *drmmode_crtc;
14588         struct intel_crtc *crtc;
14589
14590         drmmode_crtc = drm_crtc_find(dev, file, pipe_from_crtc_id->crtc_id);
14591         if (!drmmode_crtc)
14592                 return -ENOENT;
14593
14594         crtc = to_intel_crtc(drmmode_crtc);
14595         pipe_from_crtc_id->pipe = crtc->pipe;
14596
14597         return 0;
14598 }
14599
14600 static int intel_encoder_clones(struct intel_encoder *encoder)
14601 {
14602         struct drm_device *dev = encoder->base.dev;
14603         struct intel_encoder *source_encoder;
14604         int index_mask = 0;
14605         int entry = 0;
14606
14607         for_each_intel_encoder(dev, source_encoder) {
14608                 if (encoders_cloneable(encoder, source_encoder))
14609                         index_mask |= (1 << entry);
14610
14611                 entry++;
14612         }
14613
14614         return index_mask;
14615 }
14616
14617 static bool ilk_has_edp_a(struct drm_i915_private *dev_priv)
14618 {
14619         if (!IS_MOBILE(dev_priv))
14620                 return false;
14621
14622         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
14623                 return false;
14624
14625         if (IS_GEN(dev_priv, 5) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
14626                 return false;
14627
14628         return true;
14629 }
14630
14631 static bool intel_ddi_crt_present(struct drm_i915_private *dev_priv)
14632 {
14633         if (INTEL_GEN(dev_priv) >= 9)
14634                 return false;
14635
14636         if (IS_HSW_ULT(dev_priv) || IS_BDW_ULT(dev_priv))
14637                 return false;
14638
14639         if (HAS_PCH_LPT_H(dev_priv) &&
14640             I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
14641                 return false;
14642
14643         /* DDI E can't be used if DDI A requires 4 lanes */
14644         if (I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
14645                 return false;
14646
14647         if (!dev_priv->vbt.int_crt_support)
14648                 return false;
14649
14650         return true;
14651 }
14652
14653 void intel_pps_unlock_regs_wa(struct drm_i915_private *dev_priv)
14654 {
14655         int pps_num;
14656         int pps_idx;
14657
14658         if (HAS_DDI(dev_priv))
14659                 return;
14660         /*
14661          * This w/a is needed at least on CPT/PPT, but to be sure apply it
14662          * everywhere where registers can be write protected.
14663          */
14664         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
14665                 pps_num = 2;
14666         else
14667                 pps_num = 1;
14668
14669         for (pps_idx = 0; pps_idx < pps_num; pps_idx++) {
14670                 u32 val = I915_READ(PP_CONTROL(pps_idx));
14671
14672                 val = (val & ~PANEL_UNLOCK_MASK) | PANEL_UNLOCK_REGS;
14673                 I915_WRITE(PP_CONTROL(pps_idx), val);
14674         }
14675 }
14676
14677 static void intel_pps_init(struct drm_i915_private *dev_priv)
14678 {
14679         if (HAS_PCH_SPLIT(dev_priv) || IS_GEN9_LP(dev_priv))
14680                 dev_priv->pps_mmio_base = PCH_PPS_BASE;
14681         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
14682                 dev_priv->pps_mmio_base = VLV_PPS_BASE;
14683         else
14684                 dev_priv->pps_mmio_base = PPS_BASE;
14685
14686         intel_pps_unlock_regs_wa(dev_priv);
14687 }
14688
14689 static void intel_setup_outputs(struct drm_i915_private *dev_priv)
14690 {
14691         struct intel_encoder *encoder;
14692         bool dpd_is_edp = false;
14693
14694         intel_pps_init(dev_priv);
14695
14696         if (!HAS_DISPLAY(dev_priv))
14697                 return;
14698
14699         if (IS_ELKHARTLAKE(dev_priv)) {
14700                 intel_ddi_init(dev_priv, PORT_A);
14701                 intel_ddi_init(dev_priv, PORT_B);
14702                 intel_ddi_init(dev_priv, PORT_C);
14703                 icl_dsi_init(dev_priv);
14704         } else if (INTEL_GEN(dev_priv) >= 11) {
14705                 intel_ddi_init(dev_priv, PORT_A);
14706                 intel_ddi_init(dev_priv, PORT_B);
14707                 intel_ddi_init(dev_priv, PORT_C);
14708                 intel_ddi_init(dev_priv, PORT_D);
14709                 intel_ddi_init(dev_priv, PORT_E);
14710                 /*
14711                  * On some ICL SKUs port F is not present. No strap bits for
14712                  * this, so rely on VBT.
14713                  * Work around broken VBTs on SKUs known to have no port F.
14714                  */
14715                 if (IS_ICL_WITH_PORT_F(dev_priv) &&
14716                     intel_bios_is_port_present(dev_priv, PORT_F))
14717                         intel_ddi_init(dev_priv, PORT_F);
14718
14719                 icl_dsi_init(dev_priv);
14720         } else if (IS_GEN9_LP(dev_priv)) {
14721                 /*
14722                  * FIXME: Broxton doesn't support port detection via the
14723                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
14724                  * detect the ports.
14725                  */
14726                 intel_ddi_init(dev_priv, PORT_A);
14727                 intel_ddi_init(dev_priv, PORT_B);
14728                 intel_ddi_init(dev_priv, PORT_C);
14729
14730                 vlv_dsi_init(dev_priv);
14731         } else if (HAS_DDI(dev_priv)) {
14732                 int found;
14733
14734                 if (intel_ddi_crt_present(dev_priv))
14735                         intel_crt_init(dev_priv);
14736
14737                 /*
14738                  * Haswell uses DDI functions to detect digital outputs.
14739                  * On SKL pre-D0 the strap isn't connected, so we assume
14740                  * it's there.
14741                  */
14742                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
14743                 /* WaIgnoreDDIAStrap: skl */
14744                 if (found || IS_GEN9_BC(dev_priv))
14745                         intel_ddi_init(dev_priv, PORT_A);
14746
14747                 /* DDI B, C, D, and F detection is indicated by the SFUSE_STRAP
14748                  * register */
14749                 found = I915_READ(SFUSE_STRAP);
14750
14751                 if (found & SFUSE_STRAP_DDIB_DETECTED)
14752                         intel_ddi_init(dev_priv, PORT_B);
14753                 if (found & SFUSE_STRAP_DDIC_DETECTED)
14754                         intel_ddi_init(dev_priv, PORT_C);
14755                 if (found & SFUSE_STRAP_DDID_DETECTED)
14756                         intel_ddi_init(dev_priv, PORT_D);
14757                 if (found & SFUSE_STRAP_DDIF_DETECTED)
14758                         intel_ddi_init(dev_priv, PORT_F);
14759                 /*
14760                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
14761                  */
14762                 if (IS_GEN9_BC(dev_priv) &&
14763                     intel_bios_is_port_present(dev_priv, PORT_E))
14764                         intel_ddi_init(dev_priv, PORT_E);
14765
14766         } else if (HAS_PCH_SPLIT(dev_priv)) {
14767                 int found;
14768
14769                 /*
14770                  * intel_edp_init_connector() depends on this completing first,
14771                  * to prevent the registration of both eDP and LVDS and the
14772                  * incorrect sharing of the PPS.
14773                  */
14774                 intel_lvds_init(dev_priv);
14775                 intel_crt_init(dev_priv);
14776
14777                 dpd_is_edp = intel_dp_is_port_edp(dev_priv, PORT_D);
14778
14779                 if (ilk_has_edp_a(dev_priv))
14780                         intel_dp_init(dev_priv, DP_A, PORT_A);
14781
14782                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
14783                         /* PCH SDVOB multiplex with HDMIB */
14784                         found = intel_sdvo_init(dev_priv, PCH_SDVOB, PORT_B);
14785                         if (!found)
14786                                 intel_hdmi_init(dev_priv, PCH_HDMIB, PORT_B);
14787                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
14788                                 intel_dp_init(dev_priv, PCH_DP_B, PORT_B);
14789                 }
14790
14791                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
14792                         intel_hdmi_init(dev_priv, PCH_HDMIC, PORT_C);
14793
14794                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
14795                         intel_hdmi_init(dev_priv, PCH_HDMID, PORT_D);
14796
14797                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
14798                         intel_dp_init(dev_priv, PCH_DP_C, PORT_C);
14799
14800                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
14801                         intel_dp_init(dev_priv, PCH_DP_D, PORT_D);
14802         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
14803                 bool has_edp, has_port;
14804
14805                 if (IS_VALLEYVIEW(dev_priv) && dev_priv->vbt.int_crt_support)
14806                         intel_crt_init(dev_priv);
14807
14808                 /*
14809                  * The DP_DETECTED bit is the latched state of the DDC
14810                  * SDA pin at boot. However since eDP doesn't require DDC
14811                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
14812                  * eDP ports may have been muxed to an alternate function.
14813                  * Thus we can't rely on the DP_DETECTED bit alone to detect
14814                  * eDP ports. Consult the VBT as well as DP_DETECTED to
14815                  * detect eDP ports.
14816                  *
14817                  * Sadly the straps seem to be missing sometimes even for HDMI
14818                  * ports (eg. on Voyo V3 - CHT x7-Z8700), so check both strap
14819                  * and VBT for the presence of the port. Additionally we can't
14820                  * trust the port type the VBT declares as we've seen at least
14821                  * HDMI ports that the VBT claim are DP or eDP.
14822                  */
14823                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_B);
14824                 has_port = intel_bios_is_port_present(dev_priv, PORT_B);
14825                 if (I915_READ(VLV_DP_B) & DP_DETECTED || has_port)
14826                         has_edp &= intel_dp_init(dev_priv, VLV_DP_B, PORT_B);
14827                 if ((I915_READ(VLV_HDMIB) & SDVO_DETECTED || has_port) && !has_edp)
14828                         intel_hdmi_init(dev_priv, VLV_HDMIB, PORT_B);
14829
14830                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_C);
14831                 has_port = intel_bios_is_port_present(dev_priv, PORT_C);
14832                 if (I915_READ(VLV_DP_C) & DP_DETECTED || has_port)
14833                         has_edp &= intel_dp_init(dev_priv, VLV_DP_C, PORT_C);
14834                 if ((I915_READ(VLV_HDMIC) & SDVO_DETECTED || has_port) && !has_edp)
14835                         intel_hdmi_init(dev_priv, VLV_HDMIC, PORT_C);
14836
14837                 if (IS_CHERRYVIEW(dev_priv)) {
14838                         /*
14839                          * eDP not supported on port D,
14840                          * so no need to worry about it
14841                          */
14842                         has_port = intel_bios_is_port_present(dev_priv, PORT_D);
14843                         if (I915_READ(CHV_DP_D) & DP_DETECTED || has_port)
14844                                 intel_dp_init(dev_priv, CHV_DP_D, PORT_D);
14845                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED || has_port)
14846                                 intel_hdmi_init(dev_priv, CHV_HDMID, PORT_D);
14847                 }
14848
14849                 vlv_dsi_init(dev_priv);
14850         } else if (IS_PINEVIEW(dev_priv)) {
14851                 intel_lvds_init(dev_priv);
14852                 intel_crt_init(dev_priv);
14853         } else if (IS_GEN_RANGE(dev_priv, 3, 4)) {
14854                 bool found = false;
14855
14856                 if (IS_MOBILE(dev_priv))
14857                         intel_lvds_init(dev_priv);
14858
14859                 intel_crt_init(dev_priv);
14860
14861                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14862                         DRM_DEBUG_KMS("probing SDVOB\n");
14863                         found = intel_sdvo_init(dev_priv, GEN3_SDVOB, PORT_B);
14864                         if (!found && IS_G4X(dev_priv)) {
14865                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
14866                                 intel_hdmi_init(dev_priv, GEN4_HDMIB, PORT_B);
14867                         }
14868
14869                         if (!found && IS_G4X(dev_priv))
14870                                 intel_dp_init(dev_priv, DP_B, PORT_B);
14871                 }
14872
14873                 /* Before G4X SDVOC doesn't have its own detect register */
14874
14875                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14876                         DRM_DEBUG_KMS("probing SDVOC\n");
14877                         found = intel_sdvo_init(dev_priv, GEN3_SDVOC, PORT_C);
14878                 }
14879
14880                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
14881
14882                         if (IS_G4X(dev_priv)) {
14883                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
14884                                 intel_hdmi_init(dev_priv, GEN4_HDMIC, PORT_C);
14885                         }
14886                         if (IS_G4X(dev_priv))
14887                                 intel_dp_init(dev_priv, DP_C, PORT_C);
14888                 }
14889
14890                 if (IS_G4X(dev_priv) && (I915_READ(DP_D) & DP_DETECTED))
14891                         intel_dp_init(dev_priv, DP_D, PORT_D);
14892
14893                 if (SUPPORTS_TV(dev_priv))
14894                         intel_tv_init(dev_priv);
14895         } else if (IS_GEN(dev_priv, 2)) {
14896                 if (IS_I85X(dev_priv))
14897                         intel_lvds_init(dev_priv);
14898
14899                 intel_crt_init(dev_priv);
14900                 intel_dvo_init(dev_priv);
14901         }
14902
14903         intel_psr_init(dev_priv);
14904
14905         for_each_intel_encoder(&dev_priv->drm, encoder) {
14906                 encoder->base.possible_crtcs = encoder->crtc_mask;
14907                 encoder->base.possible_clones =
14908                         intel_encoder_clones(encoder);
14909         }
14910
14911         intel_init_pch_refclk(dev_priv);
14912
14913         drm_helper_move_panel_connectors_to_head(&dev_priv->drm);
14914 }
14915
14916 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
14917 {
14918         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14919         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14920
14921         drm_framebuffer_cleanup(fb);
14922
14923         i915_gem_object_lock(obj);
14924         WARN_ON(!obj->framebuffer_references--);
14925         i915_gem_object_unlock(obj);
14926
14927         i915_gem_object_put(obj);
14928
14929         kfree(intel_fb);
14930 }
14931
14932 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
14933                                                 struct drm_file *file,
14934                                                 unsigned int *handle)
14935 {
14936         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14937
14938         if (obj->userptr.mm) {
14939                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
14940                 return -EINVAL;
14941         }
14942
14943         return drm_gem_handle_create(file, &obj->base, handle);
14944 }
14945
14946 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
14947                                         struct drm_file *file,
14948                                         unsigned flags, unsigned color,
14949                                         struct drm_clip_rect *clips,
14950                                         unsigned num_clips)
14951 {
14952         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14953
14954         i915_gem_object_flush_if_display(obj);
14955         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
14956
14957         return 0;
14958 }
14959
14960 static const struct drm_framebuffer_funcs intel_fb_funcs = {
14961         .destroy = intel_user_framebuffer_destroy,
14962         .create_handle = intel_user_framebuffer_create_handle,
14963         .dirty = intel_user_framebuffer_dirty,
14964 };
14965
14966 static
14967 u32 intel_fb_pitch_limit(struct drm_i915_private *dev_priv,
14968                          u32 pixel_format, u64 fb_modifier)
14969 {
14970         struct intel_crtc *crtc;
14971         struct intel_plane *plane;
14972
14973         /*
14974          * We assume the primary plane for pipe A has
14975          * the highest stride limits of them all.
14976          */
14977         crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_A);
14978         plane = to_intel_plane(crtc->base.primary);
14979
14980         return plane->max_stride(plane, pixel_format, fb_modifier,
14981                                  DRM_MODE_ROTATE_0);
14982 }
14983
14984 static int intel_framebuffer_init(struct intel_framebuffer *intel_fb,
14985                                   struct drm_i915_gem_object *obj,
14986                                   struct drm_mode_fb_cmd2 *mode_cmd)
14987 {
14988         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
14989         struct drm_framebuffer *fb = &intel_fb->base;
14990         u32 pitch_limit;
14991         unsigned int tiling, stride;
14992         int ret = -EINVAL;
14993         int i;
14994
14995         i915_gem_object_lock(obj);
14996         obj->framebuffer_references++;
14997         tiling = i915_gem_object_get_tiling(obj);
14998         stride = i915_gem_object_get_stride(obj);
14999         i915_gem_object_unlock(obj);
15000
15001         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
15002                 /*
15003                  * If there's a fence, enforce that
15004                  * the fb modifier and tiling mode match.
15005                  */
15006                 if (tiling != I915_TILING_NONE &&
15007                     tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
15008                         DRM_DEBUG_KMS("tiling_mode doesn't match fb modifier\n");
15009                         goto err;
15010                 }
15011         } else {
15012                 if (tiling == I915_TILING_X) {
15013                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
15014                 } else if (tiling == I915_TILING_Y) {
15015                         DRM_DEBUG_KMS("No Y tiling for legacy addfb\n");
15016                         goto err;
15017                 }
15018         }
15019
15020         if (!drm_any_plane_has_format(&dev_priv->drm,
15021                                       mode_cmd->pixel_format,
15022                                       mode_cmd->modifier[0])) {
15023                 struct drm_format_name_buf format_name;
15024
15025                 DRM_DEBUG_KMS("unsupported pixel format %s / modifier 0x%llx\n",
15026                               drm_get_format_name(mode_cmd->pixel_format,
15027                                                   &format_name),
15028                               mode_cmd->modifier[0]);
15029                 goto err;
15030         }
15031
15032         /*
15033          * gen2/3 display engine uses the fence if present,
15034          * so the tiling mode must match the fb modifier exactly.
15035          */
15036         if (INTEL_GEN(dev_priv) < 4 &&
15037             tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
15038                 DRM_DEBUG_KMS("tiling_mode must match fb modifier exactly on gen2/3\n");
15039                 goto err;
15040         }
15041
15042         pitch_limit = intel_fb_pitch_limit(dev_priv, mode_cmd->pixel_format,
15043                                            mode_cmd->modifier[0]);
15044         if (mode_cmd->pitches[0] > pitch_limit) {
15045                 DRM_DEBUG_KMS("%s pitch (%u) must be at most %d\n",
15046                               mode_cmd->modifier[0] != DRM_FORMAT_MOD_LINEAR ?
15047                               "tiled" : "linear",
15048                               mode_cmd->pitches[0], pitch_limit);
15049                 goto err;
15050         }
15051
15052         /*
15053          * If there's a fence, enforce that
15054          * the fb pitch and fence stride match.
15055          */
15056         if (tiling != I915_TILING_NONE && mode_cmd->pitches[0] != stride) {
15057                 DRM_DEBUG_KMS("pitch (%d) must match tiling stride (%d)\n",
15058                               mode_cmd->pitches[0], stride);
15059                 goto err;
15060         }
15061
15062         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
15063         if (mode_cmd->offsets[0] != 0)
15064                 goto err;
15065
15066         drm_helper_mode_fill_fb_struct(&dev_priv->drm, fb, mode_cmd);
15067
15068         for (i = 0; i < fb->format->num_planes; i++) {
15069                 u32 stride_alignment;
15070
15071                 if (mode_cmd->handles[i] != mode_cmd->handles[0]) {
15072                         DRM_DEBUG_KMS("bad plane %d handle\n", i);
15073                         goto err;
15074                 }
15075
15076                 stride_alignment = intel_fb_stride_alignment(fb, i);
15077
15078                 /*
15079                  * Display WA #0531: skl,bxt,kbl,glk
15080                  *
15081                  * Render decompression and plane width > 3840
15082                  * combined with horizontal panning requires the
15083                  * plane stride to be a multiple of 4. We'll just
15084                  * require the entire fb to accommodate that to avoid
15085                  * potential runtime errors at plane configuration time.
15086                  */
15087                 if (IS_GEN(dev_priv, 9) && i == 0 && fb->width > 3840 &&
15088                     is_ccs_modifier(fb->modifier))
15089                         stride_alignment *= 4;
15090
15091                 if (fb->pitches[i] & (stride_alignment - 1)) {
15092                         DRM_DEBUG_KMS("plane %d pitch (%d) must be at least %u byte aligned\n",
15093                                       i, fb->pitches[i], stride_alignment);
15094                         goto err;
15095                 }
15096
15097                 fb->obj[i] = &obj->base;
15098         }
15099
15100         ret = intel_fill_fb_info(dev_priv, fb);
15101         if (ret)
15102                 goto err;
15103
15104         ret = drm_framebuffer_init(&dev_priv->drm, fb, &intel_fb_funcs);
15105         if (ret) {
15106                 DRM_ERROR("framebuffer init failed %d\n", ret);
15107                 goto err;
15108         }
15109
15110         return 0;
15111
15112 err:
15113         i915_gem_object_lock(obj);
15114         obj->framebuffer_references--;
15115         i915_gem_object_unlock(obj);
15116         return ret;
15117 }
15118
15119 static struct drm_framebuffer *
15120 intel_user_framebuffer_create(struct drm_device *dev,
15121                               struct drm_file *filp,
15122                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
15123 {
15124         struct drm_framebuffer *fb;
15125         struct drm_i915_gem_object *obj;
15126         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
15127
15128         obj = i915_gem_object_lookup(filp, mode_cmd.handles[0]);
15129         if (!obj)
15130                 return ERR_PTR(-ENOENT);
15131
15132         fb = intel_framebuffer_create(obj, &mode_cmd);
15133         if (IS_ERR(fb))
15134                 i915_gem_object_put(obj);
15135
15136         return fb;
15137 }
15138
15139 static void intel_atomic_state_free(struct drm_atomic_state *state)
15140 {
15141         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
15142
15143         drm_atomic_state_default_release(state);
15144
15145         i915_sw_fence_fini(&intel_state->commit_ready);
15146
15147         kfree(state);
15148 }
15149
15150 static enum drm_mode_status
15151 intel_mode_valid(struct drm_device *dev,
15152                  const struct drm_display_mode *mode)
15153 {
15154         struct drm_i915_private *dev_priv = to_i915(dev);
15155         int hdisplay_max, htotal_max;
15156         int vdisplay_max, vtotal_max;
15157
15158         /*
15159          * Can't reject DBLSCAN here because Xorg ddxen can add piles
15160          * of DBLSCAN modes to the output's mode list when they detect
15161          * the scaling mode property on the connector. And they don't
15162          * ask the kernel to validate those modes in any way until
15163          * modeset time at which point the client gets a protocol error.
15164          * So in order to not upset those clients we silently ignore the
15165          * DBLSCAN flag on such connectors. For other connectors we will
15166          * reject modes with the DBLSCAN flag in encoder->compute_config().
15167          * And we always reject DBLSCAN modes in connector->mode_valid()
15168          * as we never want such modes on the connector's mode list.
15169          */
15170
15171         if (mode->vscan > 1)
15172                 return MODE_NO_VSCAN;
15173
15174         if (mode->flags & DRM_MODE_FLAG_HSKEW)
15175                 return MODE_H_ILLEGAL;
15176
15177         if (mode->flags & (DRM_MODE_FLAG_CSYNC |
15178                            DRM_MODE_FLAG_NCSYNC |
15179                            DRM_MODE_FLAG_PCSYNC))
15180                 return MODE_HSYNC;
15181
15182         if (mode->flags & (DRM_MODE_FLAG_BCAST |
15183                            DRM_MODE_FLAG_PIXMUX |
15184                            DRM_MODE_FLAG_CLKDIV2))
15185                 return MODE_BAD;
15186
15187         if (INTEL_GEN(dev_priv) >= 9 ||
15188             IS_BROADWELL(dev_priv) || IS_HASWELL(dev_priv)) {
15189                 hdisplay_max = 8192; /* FDI max 4096 handled elsewhere */
15190                 vdisplay_max = 4096;
15191                 htotal_max = 8192;
15192                 vtotal_max = 8192;
15193         } else if (INTEL_GEN(dev_priv) >= 3) {
15194                 hdisplay_max = 4096;
15195                 vdisplay_max = 4096;
15196                 htotal_max = 8192;
15197                 vtotal_max = 8192;
15198         } else {
15199                 hdisplay_max = 2048;
15200                 vdisplay_max = 2048;
15201                 htotal_max = 4096;
15202                 vtotal_max = 4096;
15203         }
15204
15205         if (mode->hdisplay > hdisplay_max ||
15206             mode->hsync_start > htotal_max ||
15207             mode->hsync_end > htotal_max ||
15208             mode->htotal > htotal_max)
15209                 return MODE_H_ILLEGAL;
15210
15211         if (mode->vdisplay > vdisplay_max ||
15212             mode->vsync_start > vtotal_max ||
15213             mode->vsync_end > vtotal_max ||
15214             mode->vtotal > vtotal_max)
15215                 return MODE_V_ILLEGAL;
15216
15217         return MODE_OK;
15218 }
15219
15220 static const struct drm_mode_config_funcs intel_mode_funcs = {
15221         .fb_create = intel_user_framebuffer_create,
15222         .get_format_info = intel_get_format_info,
15223         .output_poll_changed = intel_fbdev_output_poll_changed,
15224         .mode_valid = intel_mode_valid,
15225         .atomic_check = intel_atomic_check,
15226         .atomic_commit = intel_atomic_commit,
15227         .atomic_state_alloc = intel_atomic_state_alloc,
15228         .atomic_state_clear = intel_atomic_state_clear,
15229         .atomic_state_free = intel_atomic_state_free,
15230 };
15231
15232 /**
15233  * intel_init_display_hooks - initialize the display modesetting hooks
15234  * @dev_priv: device private
15235  */
15236 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
15237 {
15238         intel_init_cdclk_hooks(dev_priv);
15239
15240         if (INTEL_GEN(dev_priv) >= 9) {
15241                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
15242                 dev_priv->display.get_initial_plane_config =
15243                         skylake_get_initial_plane_config;
15244                 dev_priv->display.crtc_compute_clock =
15245                         haswell_crtc_compute_clock;
15246                 dev_priv->display.crtc_enable = haswell_crtc_enable;
15247                 dev_priv->display.crtc_disable = haswell_crtc_disable;
15248         } else if (HAS_DDI(dev_priv)) {
15249                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
15250                 dev_priv->display.get_initial_plane_config =
15251                         i9xx_get_initial_plane_config;
15252                 dev_priv->display.crtc_compute_clock =
15253                         haswell_crtc_compute_clock;
15254                 dev_priv->display.crtc_enable = haswell_crtc_enable;
15255                 dev_priv->display.crtc_disable = haswell_crtc_disable;
15256         } else if (HAS_PCH_SPLIT(dev_priv)) {
15257                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
15258                 dev_priv->display.get_initial_plane_config =
15259                         i9xx_get_initial_plane_config;
15260                 dev_priv->display.crtc_compute_clock =
15261                         ironlake_crtc_compute_clock;
15262                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
15263                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
15264         } else if (IS_CHERRYVIEW(dev_priv)) {
15265                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15266                 dev_priv->display.get_initial_plane_config =
15267                         i9xx_get_initial_plane_config;
15268                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
15269                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
15270                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15271         } else if (IS_VALLEYVIEW(dev_priv)) {
15272                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15273                 dev_priv->display.get_initial_plane_config =
15274                         i9xx_get_initial_plane_config;
15275                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
15276                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
15277                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15278         } else if (IS_G4X(dev_priv)) {
15279                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15280                 dev_priv->display.get_initial_plane_config =
15281                         i9xx_get_initial_plane_config;
15282                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
15283                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15284                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15285         } else if (IS_PINEVIEW(dev_priv)) {
15286                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15287                 dev_priv->display.get_initial_plane_config =
15288                         i9xx_get_initial_plane_config;
15289                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
15290                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15291                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15292         } else if (!IS_GEN(dev_priv, 2)) {
15293                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15294                 dev_priv->display.get_initial_plane_config =
15295                         i9xx_get_initial_plane_config;
15296                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
15297                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15298                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15299         } else {
15300                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15301                 dev_priv->display.get_initial_plane_config =
15302                         i9xx_get_initial_plane_config;
15303                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
15304                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15305                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15306         }
15307
15308         if (IS_GEN(dev_priv, 5)) {
15309                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
15310         } else if (IS_GEN(dev_priv, 6)) {
15311                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
15312         } else if (IS_IVYBRIDGE(dev_priv)) {
15313                 /* FIXME: detect B0+ stepping and use auto training */
15314                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
15315         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
15316                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
15317         }
15318
15319         if (INTEL_GEN(dev_priv) >= 9)
15320                 dev_priv->display.update_crtcs = skl_update_crtcs;
15321         else
15322                 dev_priv->display.update_crtcs = intel_update_crtcs;
15323 }
15324
15325 static i915_reg_t i915_vgacntrl_reg(struct drm_i915_private *dev_priv)
15326 {
15327         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
15328                 return VLV_VGACNTRL;
15329         else if (INTEL_GEN(dev_priv) >= 5)
15330                 return CPU_VGACNTRL;
15331         else
15332                 return VGACNTRL;
15333 }
15334
15335 /* Disable the VGA plane that we never use */
15336 static void i915_disable_vga(struct drm_i915_private *dev_priv)
15337 {
15338         struct pci_dev *pdev = dev_priv->drm.pdev;
15339         u8 sr1;
15340         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
15341
15342         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
15343         vga_get_uninterruptible(pdev, VGA_RSRC_LEGACY_IO);
15344         outb(SR01, VGA_SR_INDEX);
15345         sr1 = inb(VGA_SR_DATA);
15346         outb(sr1 | 1<<5, VGA_SR_DATA);
15347         vga_put(pdev, VGA_RSRC_LEGACY_IO);
15348         udelay(300);
15349
15350         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
15351         POSTING_READ(vga_reg);
15352 }
15353
15354 void intel_modeset_init_hw(struct drm_device *dev)
15355 {
15356         struct drm_i915_private *dev_priv = to_i915(dev);
15357
15358         intel_update_cdclk(dev_priv);
15359         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
15360         dev_priv->cdclk.logical = dev_priv->cdclk.actual = dev_priv->cdclk.hw;
15361 }
15362
15363 /*
15364  * Calculate what we think the watermarks should be for the state we've read
15365  * out of the hardware and then immediately program those watermarks so that
15366  * we ensure the hardware settings match our internal state.
15367  *
15368  * We can calculate what we think WM's should be by creating a duplicate of the
15369  * current state (which was constructed during hardware readout) and running it
15370  * through the atomic check code to calculate new watermark values in the
15371  * state object.
15372  */
15373 static void sanitize_watermarks(struct drm_device *dev)
15374 {
15375         struct drm_i915_private *dev_priv = to_i915(dev);
15376         struct drm_atomic_state *state;
15377         struct intel_atomic_state *intel_state;
15378         struct drm_crtc *crtc;
15379         struct drm_crtc_state *cstate;
15380         struct drm_modeset_acquire_ctx ctx;
15381         int ret;
15382         int i;
15383
15384         /* Only supported on platforms that use atomic watermark design */
15385         if (!dev_priv->display.optimize_watermarks)
15386                 return;
15387
15388         /*
15389          * We need to hold connection_mutex before calling duplicate_state so
15390          * that the connector loop is protected.
15391          */
15392         drm_modeset_acquire_init(&ctx, 0);
15393 retry:
15394         ret = drm_modeset_lock_all_ctx(dev, &ctx);
15395         if (ret == -EDEADLK) {
15396                 drm_modeset_backoff(&ctx);
15397                 goto retry;
15398         } else if (WARN_ON(ret)) {
15399                 goto fail;
15400         }
15401
15402         state = drm_atomic_helper_duplicate_state(dev, &ctx);
15403         if (WARN_ON(IS_ERR(state)))
15404                 goto fail;
15405
15406         intel_state = to_intel_atomic_state(state);
15407
15408         /*
15409          * Hardware readout is the only time we don't want to calculate
15410          * intermediate watermarks (since we don't trust the current
15411          * watermarks).
15412          */
15413         if (!HAS_GMCH(dev_priv))
15414                 intel_state->skip_intermediate_wm = true;
15415
15416         ret = intel_atomic_check(dev, state);
15417         if (ret) {
15418                 /*
15419                  * If we fail here, it means that the hardware appears to be
15420                  * programmed in a way that shouldn't be possible, given our
15421                  * understanding of watermark requirements.  This might mean a
15422                  * mistake in the hardware readout code or a mistake in the
15423                  * watermark calculations for a given platform.  Raise a WARN
15424                  * so that this is noticeable.
15425                  *
15426                  * If this actually happens, we'll have to just leave the
15427                  * BIOS-programmed watermarks untouched and hope for the best.
15428                  */
15429                 WARN(true, "Could not determine valid watermarks for inherited state\n");
15430                 goto put_state;
15431         }
15432
15433         /* Write calculated watermark values back */
15434         for_each_new_crtc_in_state(state, crtc, cstate, i) {
15435                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
15436
15437                 cs->wm.need_postvbl_update = true;
15438                 dev_priv->display.optimize_watermarks(intel_state, cs);
15439
15440                 to_intel_crtc_state(crtc->state)->wm = cs->wm;
15441         }
15442
15443 put_state:
15444         drm_atomic_state_put(state);
15445 fail:
15446         drm_modeset_drop_locks(&ctx);
15447         drm_modeset_acquire_fini(&ctx);
15448 }
15449
15450 static void intel_update_fdi_pll_freq(struct drm_i915_private *dev_priv)
15451 {
15452         if (IS_GEN(dev_priv, 5)) {
15453                 u32 fdi_pll_clk =
15454                         I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK;
15455
15456                 dev_priv->fdi_pll_freq = (fdi_pll_clk + 2) * 10000;
15457         } else if (IS_GEN(dev_priv, 6) || IS_IVYBRIDGE(dev_priv)) {
15458                 dev_priv->fdi_pll_freq = 270000;
15459         } else {
15460                 return;
15461         }
15462
15463         DRM_DEBUG_DRIVER("FDI PLL freq=%d\n", dev_priv->fdi_pll_freq);
15464 }
15465
15466 static int intel_initial_commit(struct drm_device *dev)
15467 {
15468         struct drm_atomic_state *state = NULL;
15469         struct drm_modeset_acquire_ctx ctx;
15470         struct drm_crtc *crtc;
15471         struct drm_crtc_state *crtc_state;
15472         int ret = 0;
15473
15474         state = drm_atomic_state_alloc(dev);
15475         if (!state)
15476                 return -ENOMEM;
15477
15478         drm_modeset_acquire_init(&ctx, 0);
15479
15480 retry:
15481         state->acquire_ctx = &ctx;
15482
15483         drm_for_each_crtc(crtc, dev) {
15484                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
15485                 if (IS_ERR(crtc_state)) {
15486                         ret = PTR_ERR(crtc_state);
15487                         goto out;
15488                 }
15489
15490                 if (crtc_state->active) {
15491                         ret = drm_atomic_add_affected_planes(state, crtc);
15492                         if (ret)
15493                                 goto out;
15494
15495                         /*
15496                          * FIXME hack to force a LUT update to avoid the
15497                          * plane update forcing the pipe gamma on without
15498                          * having a proper LUT loaded. Remove once we
15499                          * have readout for pipe gamma enable.
15500                          */
15501                         crtc_state->color_mgmt_changed = true;
15502                 }
15503         }
15504
15505         ret = drm_atomic_commit(state);
15506
15507 out:
15508         if (ret == -EDEADLK) {
15509                 drm_atomic_state_clear(state);
15510                 drm_modeset_backoff(&ctx);
15511                 goto retry;
15512         }
15513
15514         drm_atomic_state_put(state);
15515
15516         drm_modeset_drop_locks(&ctx);
15517         drm_modeset_acquire_fini(&ctx);
15518
15519         return ret;
15520 }
15521
15522 int intel_modeset_init(struct drm_device *dev)
15523 {
15524         struct drm_i915_private *dev_priv = to_i915(dev);
15525         struct i915_ggtt *ggtt = &dev_priv->ggtt;
15526         enum pipe pipe;
15527         struct intel_crtc *crtc;
15528         int ret;
15529
15530         dev_priv->modeset_wq = alloc_ordered_workqueue("i915_modeset", 0);
15531
15532         drm_mode_config_init(dev);
15533
15534         dev->mode_config.min_width = 0;
15535         dev->mode_config.min_height = 0;
15536
15537         dev->mode_config.preferred_depth = 24;
15538         dev->mode_config.prefer_shadow = 1;
15539
15540         dev->mode_config.allow_fb_modifiers = true;
15541
15542         dev->mode_config.funcs = &intel_mode_funcs;
15543
15544         init_llist_head(&dev_priv->atomic_helper.free_list);
15545         INIT_WORK(&dev_priv->atomic_helper.free_work,
15546                   intel_atomic_helper_free_state_worker);
15547
15548         intel_init_quirks(dev_priv);
15549
15550         intel_fbc_init(dev_priv);
15551
15552         intel_init_pm(dev_priv);
15553
15554         /*
15555          * There may be no VBT; and if the BIOS enabled SSC we can
15556          * just keep using it to avoid unnecessary flicker.  Whereas if the
15557          * BIOS isn't using it, don't assume it will work even if the VBT
15558          * indicates as much.
15559          */
15560         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv)) {
15561                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
15562                                             DREF_SSC1_ENABLE);
15563
15564                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
15565                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
15566                                      bios_lvds_use_ssc ? "en" : "dis",
15567                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
15568                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
15569                 }
15570         }
15571
15572         /* maximum framebuffer dimensions */
15573         if (IS_GEN(dev_priv, 2)) {
15574                 dev->mode_config.max_width = 2048;
15575                 dev->mode_config.max_height = 2048;
15576         } else if (IS_GEN(dev_priv, 3)) {
15577                 dev->mode_config.max_width = 4096;
15578                 dev->mode_config.max_height = 4096;
15579         } else {
15580                 dev->mode_config.max_width = 8192;
15581                 dev->mode_config.max_height = 8192;
15582         }
15583
15584         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
15585                 dev->mode_config.cursor_width = IS_I845G(dev_priv) ? 64 : 512;
15586                 dev->mode_config.cursor_height = 1023;
15587         } else if (IS_GEN(dev_priv, 2)) {
15588                 dev->mode_config.cursor_width = 64;
15589                 dev->mode_config.cursor_height = 64;
15590         } else {
15591                 dev->mode_config.cursor_width = 256;
15592                 dev->mode_config.cursor_height = 256;
15593         }
15594
15595         dev->mode_config.fb_base = ggtt->gmadr.start;
15596
15597         DRM_DEBUG_KMS("%d display pipe%s available.\n",
15598                       INTEL_INFO(dev_priv)->num_pipes,
15599                       INTEL_INFO(dev_priv)->num_pipes > 1 ? "s" : "");
15600
15601         for_each_pipe(dev_priv, pipe) {
15602                 ret = intel_crtc_init(dev_priv, pipe);
15603                 if (ret) {
15604                         drm_mode_config_cleanup(dev);
15605                         return ret;
15606                 }
15607         }
15608
15609         intel_shared_dpll_init(dev);
15610         intel_update_fdi_pll_freq(dev_priv);
15611
15612         intel_update_czclk(dev_priv);
15613         intel_modeset_init_hw(dev);
15614
15615         intel_hdcp_component_init(dev_priv);
15616
15617         if (dev_priv->max_cdclk_freq == 0)
15618                 intel_update_max_cdclk(dev_priv);
15619
15620         /* Just disable it once at startup */
15621         i915_disable_vga(dev_priv);
15622         intel_setup_outputs(dev_priv);
15623
15624         drm_modeset_lock_all(dev);
15625         intel_modeset_setup_hw_state(dev, dev->mode_config.acquire_ctx);
15626         drm_modeset_unlock_all(dev);
15627
15628         for_each_intel_crtc(dev, crtc) {
15629                 struct intel_initial_plane_config plane_config = {};
15630
15631                 if (!crtc->active)
15632                         continue;
15633
15634                 /*
15635                  * Note that reserving the BIOS fb up front prevents us
15636                  * from stuffing other stolen allocations like the ring
15637                  * on top.  This prevents some ugliness at boot time, and
15638                  * can even allow for smooth boot transitions if the BIOS
15639                  * fb is large enough for the active pipe configuration.
15640                  */
15641                 dev_priv->display.get_initial_plane_config(crtc,
15642                                                            &plane_config);
15643
15644                 /*
15645                  * If the fb is shared between multiple heads, we'll
15646                  * just get the first one.
15647                  */
15648                 intel_find_initial_plane_obj(crtc, &plane_config);
15649         }
15650
15651         /*
15652          * Make sure hardware watermarks really match the state we read out.
15653          * Note that we need to do this after reconstructing the BIOS fb's
15654          * since the watermark calculation done here will use pstate->fb.
15655          */
15656         if (!HAS_GMCH(dev_priv))
15657                 sanitize_watermarks(dev);
15658
15659         /*
15660          * Force all active planes to recompute their states. So that on
15661          * mode_setcrtc after probe, all the intel_plane_state variables
15662          * are already calculated and there is no assert_plane warnings
15663          * during bootup.
15664          */
15665         ret = intel_initial_commit(dev);
15666         if (ret)
15667                 DRM_DEBUG_KMS("Initial commit in probe failed.\n");
15668
15669         return 0;
15670 }
15671
15672 void i830_enable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
15673 {
15674         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15675         /* 640x480@60Hz, ~25175 kHz */
15676         struct dpll clock = {
15677                 .m1 = 18,
15678                 .m2 = 7,
15679                 .p1 = 13,
15680                 .p2 = 4,
15681                 .n = 2,
15682         };
15683         u32 dpll, fp;
15684         int i;
15685
15686         WARN_ON(i9xx_calc_dpll_params(48000, &clock) != 25154);
15687
15688         DRM_DEBUG_KMS("enabling pipe %c due to force quirk (vco=%d dot=%d)\n",
15689                       pipe_name(pipe), clock.vco, clock.dot);
15690
15691         fp = i9xx_dpll_compute_fp(&clock);
15692         dpll = DPLL_DVO_2X_MODE |
15693                 DPLL_VGA_MODE_DIS |
15694                 ((clock.p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT) |
15695                 PLL_P2_DIVIDE_BY_4 |
15696                 PLL_REF_INPUT_DREFCLK |
15697                 DPLL_VCO_ENABLE;
15698
15699         I915_WRITE(FP0(pipe), fp);
15700         I915_WRITE(FP1(pipe), fp);
15701
15702         I915_WRITE(HTOTAL(pipe), (640 - 1) | ((800 - 1) << 16));
15703         I915_WRITE(HBLANK(pipe), (640 - 1) | ((800 - 1) << 16));
15704         I915_WRITE(HSYNC(pipe), (656 - 1) | ((752 - 1) << 16));
15705         I915_WRITE(VTOTAL(pipe), (480 - 1) | ((525 - 1) << 16));
15706         I915_WRITE(VBLANK(pipe), (480 - 1) | ((525 - 1) << 16));
15707         I915_WRITE(VSYNC(pipe), (490 - 1) | ((492 - 1) << 16));
15708         I915_WRITE(PIPESRC(pipe), ((640 - 1) << 16) | (480 - 1));
15709
15710         /*
15711          * Apparently we need to have VGA mode enabled prior to changing
15712          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
15713          * dividers, even though the register value does change.
15714          */
15715         I915_WRITE(DPLL(pipe), dpll & ~DPLL_VGA_MODE_DIS);
15716         I915_WRITE(DPLL(pipe), dpll);
15717
15718         /* Wait for the clocks to stabilize. */
15719         POSTING_READ(DPLL(pipe));
15720         udelay(150);
15721
15722         /* The pixel multiplier can only be updated once the
15723          * DPLL is enabled and the clocks are stable.
15724          *
15725          * So write it again.
15726          */
15727         I915_WRITE(DPLL(pipe), dpll);
15728
15729         /* We do this three times for luck */
15730         for (i = 0; i < 3 ; i++) {
15731                 I915_WRITE(DPLL(pipe), dpll);
15732                 POSTING_READ(DPLL(pipe));
15733                 udelay(150); /* wait for warmup */
15734         }
15735
15736         I915_WRITE(PIPECONF(pipe), PIPECONF_ENABLE | PIPECONF_PROGRESSIVE);
15737         POSTING_READ(PIPECONF(pipe));
15738
15739         intel_wait_for_pipe_scanline_moving(crtc);
15740 }
15741
15742 void i830_disable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
15743 {
15744         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15745
15746         DRM_DEBUG_KMS("disabling pipe %c due to force quirk\n",
15747                       pipe_name(pipe));
15748
15749         WARN_ON(I915_READ(DSPCNTR(PLANE_A)) & DISPLAY_PLANE_ENABLE);
15750         WARN_ON(I915_READ(DSPCNTR(PLANE_B)) & DISPLAY_PLANE_ENABLE);
15751         WARN_ON(I915_READ(DSPCNTR(PLANE_C)) & DISPLAY_PLANE_ENABLE);
15752         WARN_ON(I915_READ(CURCNTR(PIPE_A)) & MCURSOR_MODE);
15753         WARN_ON(I915_READ(CURCNTR(PIPE_B)) & MCURSOR_MODE);
15754
15755         I915_WRITE(PIPECONF(pipe), 0);
15756         POSTING_READ(PIPECONF(pipe));
15757
15758         intel_wait_for_pipe_scanline_stopped(crtc);
15759
15760         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
15761         POSTING_READ(DPLL(pipe));
15762 }
15763
15764 static void
15765 intel_sanitize_plane_mapping(struct drm_i915_private *dev_priv)
15766 {
15767         struct intel_crtc *crtc;
15768
15769         if (INTEL_GEN(dev_priv) >= 4)
15770                 return;
15771
15772         for_each_intel_crtc(&dev_priv->drm, crtc) {
15773                 struct intel_plane *plane =
15774                         to_intel_plane(crtc->base.primary);
15775                 struct intel_crtc *plane_crtc;
15776                 enum pipe pipe;
15777
15778                 if (!plane->get_hw_state(plane, &pipe))
15779                         continue;
15780
15781                 if (pipe == crtc->pipe)
15782                         continue;
15783
15784                 DRM_DEBUG_KMS("[PLANE:%d:%s] attached to the wrong pipe, disabling plane\n",
15785                               plane->base.base.id, plane->base.name);
15786
15787                 plane_crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15788                 intel_plane_disable_noatomic(plane_crtc, plane);
15789         }
15790 }
15791
15792 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
15793 {
15794         struct drm_device *dev = crtc->base.dev;
15795         struct intel_encoder *encoder;
15796
15797         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
15798                 return true;
15799
15800         return false;
15801 }
15802
15803 static struct intel_connector *intel_encoder_find_connector(struct intel_encoder *encoder)
15804 {
15805         struct drm_device *dev = encoder->base.dev;
15806         struct intel_connector *connector;
15807
15808         for_each_connector_on_encoder(dev, &encoder->base, connector)
15809                 return connector;
15810
15811         return NULL;
15812 }
15813
15814 static bool has_pch_trancoder(struct drm_i915_private *dev_priv,
15815                               enum pipe pch_transcoder)
15816 {
15817         return HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv) ||
15818                 (HAS_PCH_LPT_H(dev_priv) && pch_transcoder == PIPE_A);
15819 }
15820
15821 static void intel_sanitize_crtc(struct intel_crtc *crtc,
15822                                 struct drm_modeset_acquire_ctx *ctx)
15823 {
15824         struct drm_device *dev = crtc->base.dev;
15825         struct drm_i915_private *dev_priv = to_i915(dev);
15826         struct intel_crtc_state *crtc_state = to_intel_crtc_state(crtc->base.state);
15827         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
15828
15829         /* Clear any frame start delays used for debugging left by the BIOS */
15830         if (crtc->active && !transcoder_is_dsi(cpu_transcoder)) {
15831                 i915_reg_t reg = PIPECONF(cpu_transcoder);
15832
15833                 I915_WRITE(reg,
15834                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
15835         }
15836
15837         if (crtc_state->base.active) {
15838                 struct intel_plane *plane;
15839
15840                 /* Disable everything but the primary plane */
15841                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
15842                         const struct intel_plane_state *plane_state =
15843                                 to_intel_plane_state(plane->base.state);
15844
15845                         if (plane_state->base.visible &&
15846                             plane->base.type != DRM_PLANE_TYPE_PRIMARY)
15847                                 intel_plane_disable_noatomic(crtc, plane);
15848                 }
15849
15850                 /*
15851                  * Disable any background color set by the BIOS, but enable the
15852                  * gamma and CSC to match how we program our planes.
15853                  */
15854                 if (INTEL_GEN(dev_priv) >= 9)
15855                         I915_WRITE(SKL_BOTTOM_COLOR(crtc->pipe),
15856                                    SKL_BOTTOM_COLOR_GAMMA_ENABLE |
15857                                    SKL_BOTTOM_COLOR_CSC_ENABLE);
15858         }
15859
15860         /* Adjust the state of the output pipe according to whether we
15861          * have active connectors/encoders. */
15862         if (crtc_state->base.active && !intel_crtc_has_encoders(crtc))
15863                 intel_crtc_disable_noatomic(&crtc->base, ctx);
15864
15865         if (crtc_state->base.active || HAS_GMCH(dev_priv)) {
15866                 /*
15867                  * We start out with underrun reporting disabled to avoid races.
15868                  * For correct bookkeeping mark this on active crtcs.
15869                  *
15870                  * Also on gmch platforms we dont have any hardware bits to
15871                  * disable the underrun reporting. Which means we need to start
15872                  * out with underrun reporting disabled also on inactive pipes,
15873                  * since otherwise we'll complain about the garbage we read when
15874                  * e.g. coming up after runtime pm.
15875                  *
15876                  * No protection against concurrent access is required - at
15877                  * worst a fifo underrun happens which also sets this to false.
15878                  */
15879                 crtc->cpu_fifo_underrun_disabled = true;
15880                 /*
15881                  * We track the PCH trancoder underrun reporting state
15882                  * within the crtc. With crtc for pipe A housing the underrun
15883                  * reporting state for PCH transcoder A, crtc for pipe B housing
15884                  * it for PCH transcoder B, etc. LPT-H has only PCH transcoder A,
15885                  * and marking underrun reporting as disabled for the non-existing
15886                  * PCH transcoders B and C would prevent enabling the south
15887                  * error interrupt (see cpt_can_enable_serr_int()).
15888                  */
15889                 if (has_pch_trancoder(dev_priv, crtc->pipe))
15890                         crtc->pch_fifo_underrun_disabled = true;
15891         }
15892 }
15893
15894 static bool has_bogus_dpll_config(const struct intel_crtc_state *crtc_state)
15895 {
15896         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
15897
15898         /*
15899          * Some SNB BIOSen (eg. ASUS K53SV) are known to misprogram
15900          * the hardware when a high res displays plugged in. DPLL P
15901          * divider is zero, and the pipe timings are bonkers. We'll
15902          * try to disable everything in that case.
15903          *
15904          * FIXME would be nice to be able to sanitize this state
15905          * without several WARNs, but for now let's take the easy
15906          * road.
15907          */
15908         return IS_GEN(dev_priv, 6) &&
15909                 crtc_state->base.active &&
15910                 crtc_state->shared_dpll &&
15911                 crtc_state->port_clock == 0;
15912 }
15913
15914 static void intel_sanitize_encoder(struct intel_encoder *encoder)
15915 {
15916         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
15917         struct intel_connector *connector;
15918         struct intel_crtc *crtc = to_intel_crtc(encoder->base.crtc);
15919         struct intel_crtc_state *crtc_state = crtc ?
15920                 to_intel_crtc_state(crtc->base.state) : NULL;
15921
15922         /* We need to check both for a crtc link (meaning that the
15923          * encoder is active and trying to read from a pipe) and the
15924          * pipe itself being active. */
15925         bool has_active_crtc = crtc_state &&
15926                 crtc_state->base.active;
15927
15928         if (crtc_state && has_bogus_dpll_config(crtc_state)) {
15929                 DRM_DEBUG_KMS("BIOS has misprogrammed the hardware. Disabling pipe %c\n",
15930                               pipe_name(crtc->pipe));
15931                 has_active_crtc = false;
15932         }
15933
15934         connector = intel_encoder_find_connector(encoder);
15935         if (connector && !has_active_crtc) {
15936                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
15937                               encoder->base.base.id,
15938                               encoder->base.name);
15939
15940                 /* Connector is active, but has no active pipe. This is
15941                  * fallout from our resume register restoring. Disable
15942                  * the encoder manually again. */
15943                 if (crtc_state) {
15944                         struct drm_encoder *best_encoder;
15945
15946                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
15947                                       encoder->base.base.id,
15948                                       encoder->base.name);
15949
15950                         /* avoid oopsing in case the hooks consult best_encoder */
15951                         best_encoder = connector->base.state->best_encoder;
15952                         connector->base.state->best_encoder = &encoder->base;
15953
15954                         if (encoder->disable)
15955                                 encoder->disable(encoder, crtc_state,
15956                                                  connector->base.state);
15957                         if (encoder->post_disable)
15958                                 encoder->post_disable(encoder, crtc_state,
15959                                                       connector->base.state);
15960
15961                         connector->base.state->best_encoder = best_encoder;
15962                 }
15963                 encoder->base.crtc = NULL;
15964
15965                 /* Inconsistent output/port/pipe state happens presumably due to
15966                  * a bug in one of the get_hw_state functions. Or someplace else
15967                  * in our code, like the register restore mess on resume. Clamp
15968                  * things to off as a safer default. */
15969
15970                 connector->base.dpms = DRM_MODE_DPMS_OFF;
15971                 connector->base.encoder = NULL;
15972         }
15973
15974         /* notify opregion of the sanitized encoder state */
15975         intel_opregion_notify_encoder(encoder, connector && has_active_crtc);
15976
15977         if (INTEL_GEN(dev_priv) >= 11)
15978                 icl_sanitize_encoder_pll_mapping(encoder);
15979 }
15980
15981 void i915_redisable_vga_power_on(struct drm_i915_private *dev_priv)
15982 {
15983         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
15984
15985         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
15986                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
15987                 i915_disable_vga(dev_priv);
15988         }
15989 }
15990
15991 void i915_redisable_vga(struct drm_i915_private *dev_priv)
15992 {
15993         intel_wakeref_t wakeref;
15994
15995         /*
15996          * This function can be called both from intel_modeset_setup_hw_state or
15997          * at a very early point in our resume sequence, where the power well
15998          * structures are not yet restored. Since this function is at a very
15999          * paranoid "someone might have enabled VGA while we were not looking"
16000          * level, just check if the power well is enabled instead of trying to
16001          * follow the "don't touch the power well if we don't need it" policy
16002          * the rest of the driver uses.
16003          */
16004         wakeref = intel_display_power_get_if_enabled(dev_priv,
16005                                                      POWER_DOMAIN_VGA);
16006         if (!wakeref)
16007                 return;
16008
16009         i915_redisable_vga_power_on(dev_priv);
16010
16011         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA, wakeref);
16012 }
16013
16014 /* FIXME read out full plane state for all planes */
16015 static void readout_plane_state(struct drm_i915_private *dev_priv)
16016 {
16017         struct intel_plane *plane;
16018         struct intel_crtc *crtc;
16019
16020         for_each_intel_plane(&dev_priv->drm, plane) {
16021                 struct intel_plane_state *plane_state =
16022                         to_intel_plane_state(plane->base.state);
16023                 struct intel_crtc_state *crtc_state;
16024                 enum pipe pipe = PIPE_A;
16025                 bool visible;
16026
16027                 visible = plane->get_hw_state(plane, &pipe);
16028
16029                 crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
16030                 crtc_state = to_intel_crtc_state(crtc->base.state);
16031
16032                 intel_set_plane_visible(crtc_state, plane_state, visible);
16033
16034                 DRM_DEBUG_KMS("[PLANE:%d:%s] hw state readout: %s, pipe %c\n",
16035                               plane->base.base.id, plane->base.name,
16036                               enableddisabled(visible), pipe_name(pipe));
16037         }
16038
16039         for_each_intel_crtc(&dev_priv->drm, crtc) {
16040                 struct intel_crtc_state *crtc_state =
16041                         to_intel_crtc_state(crtc->base.state);
16042
16043                 fixup_active_planes(crtc_state);
16044         }
16045 }
16046
16047 static void intel_modeset_readout_hw_state(struct drm_device *dev)
16048 {
16049         struct drm_i915_private *dev_priv = to_i915(dev);
16050         enum pipe pipe;
16051         struct intel_crtc *crtc;
16052         struct intel_encoder *encoder;
16053         struct intel_connector *connector;
16054         struct drm_connector_list_iter conn_iter;
16055         int i;
16056
16057         dev_priv->active_crtcs = 0;
16058
16059         for_each_intel_crtc(dev, crtc) {
16060                 struct intel_crtc_state *crtc_state =
16061                         to_intel_crtc_state(crtc->base.state);
16062
16063                 __drm_atomic_helper_crtc_destroy_state(&crtc_state->base);
16064                 memset(crtc_state, 0, sizeof(*crtc_state));
16065                 crtc_state->base.crtc = &crtc->base;
16066
16067                 crtc_state->base.active = crtc_state->base.enable =
16068                         dev_priv->display.get_pipe_config(crtc, crtc_state);
16069
16070                 crtc->base.enabled = crtc_state->base.enable;
16071                 crtc->active = crtc_state->base.active;
16072
16073                 if (crtc_state->base.active)
16074                         dev_priv->active_crtcs |= 1 << crtc->pipe;
16075
16076                 DRM_DEBUG_KMS("[CRTC:%d:%s] hw state readout: %s\n",
16077                               crtc->base.base.id, crtc->base.name,
16078                               enableddisabled(crtc_state->base.active));
16079         }
16080
16081         readout_plane_state(dev_priv);
16082
16083         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
16084                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
16085
16086                 pll->on = pll->info->funcs->get_hw_state(dev_priv, pll,
16087                                                         &pll->state.hw_state);
16088                 pll->state.crtc_mask = 0;
16089                 for_each_intel_crtc(dev, crtc) {
16090                         struct intel_crtc_state *crtc_state =
16091                                 to_intel_crtc_state(crtc->base.state);
16092
16093                         if (crtc_state->base.active &&
16094                             crtc_state->shared_dpll == pll)
16095                                 pll->state.crtc_mask |= 1 << crtc->pipe;
16096                 }
16097                 pll->active_mask = pll->state.crtc_mask;
16098
16099                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
16100                               pll->info->name, pll->state.crtc_mask, pll->on);
16101         }
16102
16103         for_each_intel_encoder(dev, encoder) {
16104                 pipe = 0;
16105
16106                 if (encoder->get_hw_state(encoder, &pipe)) {
16107                         struct intel_crtc_state *crtc_state;
16108
16109                         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
16110                         crtc_state = to_intel_crtc_state(crtc->base.state);
16111
16112                         encoder->base.crtc = &crtc->base;
16113                         encoder->get_config(encoder, crtc_state);
16114                 } else {
16115                         encoder->base.crtc = NULL;
16116                 }
16117
16118                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
16119                               encoder->base.base.id, encoder->base.name,
16120                               enableddisabled(encoder->base.crtc),
16121                               pipe_name(pipe));
16122         }
16123
16124         drm_connector_list_iter_begin(dev, &conn_iter);
16125         for_each_intel_connector_iter(connector, &conn_iter) {
16126                 if (connector->get_hw_state(connector)) {
16127                         connector->base.dpms = DRM_MODE_DPMS_ON;
16128
16129                         encoder = connector->encoder;
16130                         connector->base.encoder = &encoder->base;
16131
16132                         if (encoder->base.crtc &&
16133                             encoder->base.crtc->state->active) {
16134                                 /*
16135                                  * This has to be done during hardware readout
16136                                  * because anything calling .crtc_disable may
16137                                  * rely on the connector_mask being accurate.
16138                                  */
16139                                 encoder->base.crtc->state->connector_mask |=
16140                                         drm_connector_mask(&connector->base);
16141                                 encoder->base.crtc->state->encoder_mask |=
16142                                         drm_encoder_mask(&encoder->base);
16143                         }
16144
16145                 } else {
16146                         connector->base.dpms = DRM_MODE_DPMS_OFF;
16147                         connector->base.encoder = NULL;
16148                 }
16149                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
16150                               connector->base.base.id, connector->base.name,
16151                               enableddisabled(connector->base.encoder));
16152         }
16153         drm_connector_list_iter_end(&conn_iter);
16154
16155         for_each_intel_crtc(dev, crtc) {
16156                 struct intel_crtc_state *crtc_state =
16157                         to_intel_crtc_state(crtc->base.state);
16158                 int min_cdclk = 0;
16159
16160                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
16161                 if (crtc_state->base.active) {
16162                         intel_mode_from_pipe_config(&crtc->base.mode, crtc_state);
16163                         crtc->base.mode.hdisplay = crtc_state->pipe_src_w;
16164                         crtc->base.mode.vdisplay = crtc_state->pipe_src_h;
16165                         intel_mode_from_pipe_config(&crtc_state->base.adjusted_mode, crtc_state);
16166                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
16167
16168                         /*
16169                          * The initial mode needs to be set in order to keep
16170                          * the atomic core happy. It wants a valid mode if the
16171                          * crtc's enabled, so we do the above call.
16172                          *
16173                          * But we don't set all the derived state fully, hence
16174                          * set a flag to indicate that a full recalculation is
16175                          * needed on the next commit.
16176                          */
16177                         crtc_state->base.mode.private_flags = I915_MODE_FLAG_INHERITED;
16178
16179                         intel_crtc_compute_pixel_rate(crtc_state);
16180
16181                         if (dev_priv->display.modeset_calc_cdclk) {
16182                                 min_cdclk = intel_crtc_compute_min_cdclk(crtc_state);
16183                                 if (WARN_ON(min_cdclk < 0))
16184                                         min_cdclk = 0;
16185                         }
16186
16187                         drm_calc_timestamping_constants(&crtc->base,
16188                                                         &crtc_state->base.adjusted_mode);
16189                         update_scanline_offset(crtc_state);
16190                 }
16191
16192                 dev_priv->min_cdclk[crtc->pipe] = min_cdclk;
16193                 dev_priv->min_voltage_level[crtc->pipe] =
16194                         crtc_state->min_voltage_level;
16195
16196                 intel_pipe_config_sanity_check(dev_priv, crtc_state);
16197         }
16198 }
16199
16200 static void
16201 get_encoder_power_domains(struct drm_i915_private *dev_priv)
16202 {
16203         struct intel_encoder *encoder;
16204
16205         for_each_intel_encoder(&dev_priv->drm, encoder) {
16206                 struct intel_crtc_state *crtc_state;
16207
16208                 if (!encoder->get_power_domains)
16209                         continue;
16210
16211                 /*
16212                  * MST-primary and inactive encoders don't have a crtc state
16213                  * and neither of these require any power domain references.
16214                  */
16215                 if (!encoder->base.crtc)
16216                         continue;
16217
16218                 crtc_state = to_intel_crtc_state(encoder->base.crtc->state);
16219                 encoder->get_power_domains(encoder, crtc_state);
16220         }
16221 }
16222
16223 static void intel_early_display_was(struct drm_i915_private *dev_priv)
16224 {
16225         /* Display WA #1185 WaDisableDARBFClkGating:cnl,glk */
16226         if (IS_CANNONLAKE(dev_priv) || IS_GEMINILAKE(dev_priv))
16227                 I915_WRITE(GEN9_CLKGATE_DIS_0, I915_READ(GEN9_CLKGATE_DIS_0) |
16228                            DARBF_GATING_DIS);
16229
16230         if (IS_HASWELL(dev_priv)) {
16231                 /*
16232                  * WaRsPkgCStateDisplayPMReq:hsw
16233                  * System hang if this isn't done before disabling all planes!
16234                  */
16235                 I915_WRITE(CHICKEN_PAR1_1,
16236                            I915_READ(CHICKEN_PAR1_1) | FORCE_ARB_IDLE_PLANES);
16237         }
16238 }
16239
16240 static void ibx_sanitize_pch_hdmi_port(struct drm_i915_private *dev_priv,
16241                                        enum port port, i915_reg_t hdmi_reg)
16242 {
16243         u32 val = I915_READ(hdmi_reg);
16244
16245         if (val & SDVO_ENABLE ||
16246             (val & SDVO_PIPE_SEL_MASK) == SDVO_PIPE_SEL(PIPE_A))
16247                 return;
16248
16249         DRM_DEBUG_KMS("Sanitizing transcoder select for HDMI %c\n",
16250                       port_name(port));
16251
16252         val &= ~SDVO_PIPE_SEL_MASK;
16253         val |= SDVO_PIPE_SEL(PIPE_A);
16254
16255         I915_WRITE(hdmi_reg, val);
16256 }
16257
16258 static void ibx_sanitize_pch_dp_port(struct drm_i915_private *dev_priv,
16259                                      enum port port, i915_reg_t dp_reg)
16260 {
16261         u32 val = I915_READ(dp_reg);
16262
16263         if (val & DP_PORT_EN ||
16264             (val & DP_PIPE_SEL_MASK) == DP_PIPE_SEL(PIPE_A))
16265                 return;
16266
16267         DRM_DEBUG_KMS("Sanitizing transcoder select for DP %c\n",
16268                       port_name(port));
16269
16270         val &= ~DP_PIPE_SEL_MASK;
16271         val |= DP_PIPE_SEL(PIPE_A);
16272
16273         I915_WRITE(dp_reg, val);
16274 }
16275
16276 static void ibx_sanitize_pch_ports(struct drm_i915_private *dev_priv)
16277 {
16278         /*
16279          * The BIOS may select transcoder B on some of the PCH
16280          * ports even it doesn't enable the port. This would trip
16281          * assert_pch_dp_disabled() and assert_pch_hdmi_disabled().
16282          * Sanitize the transcoder select bits to prevent that. We
16283          * assume that the BIOS never actually enabled the port,
16284          * because if it did we'd actually have to toggle the port
16285          * on and back off to make the transcoder A select stick
16286          * (see. intel_dp_link_down(), intel_disable_hdmi(),
16287          * intel_disable_sdvo()).
16288          */
16289         ibx_sanitize_pch_dp_port(dev_priv, PORT_B, PCH_DP_B);
16290         ibx_sanitize_pch_dp_port(dev_priv, PORT_C, PCH_DP_C);
16291         ibx_sanitize_pch_dp_port(dev_priv, PORT_D, PCH_DP_D);
16292
16293         /* PCH SDVOB multiplex with HDMIB */
16294         ibx_sanitize_pch_hdmi_port(dev_priv, PORT_B, PCH_HDMIB);
16295         ibx_sanitize_pch_hdmi_port(dev_priv, PORT_C, PCH_HDMIC);
16296         ibx_sanitize_pch_hdmi_port(dev_priv, PORT_D, PCH_HDMID);
16297 }
16298
16299 /* Scan out the current hw modeset state,
16300  * and sanitizes it to the current state
16301  */
16302 static void
16303 intel_modeset_setup_hw_state(struct drm_device *dev,
16304                              struct drm_modeset_acquire_ctx *ctx)
16305 {
16306         struct drm_i915_private *dev_priv = to_i915(dev);
16307         struct intel_crtc_state *crtc_state;
16308         struct intel_encoder *encoder;
16309         struct intel_crtc *crtc;
16310         intel_wakeref_t wakeref;
16311         int i;
16312
16313         wakeref = intel_display_power_get(dev_priv, POWER_DOMAIN_INIT);
16314
16315         intel_early_display_was(dev_priv);
16316         intel_modeset_readout_hw_state(dev);
16317
16318         /* HW state is read out, now we need to sanitize this mess. */
16319         get_encoder_power_domains(dev_priv);
16320
16321         if (HAS_PCH_IBX(dev_priv))
16322                 ibx_sanitize_pch_ports(dev_priv);
16323
16324         /*
16325          * intel_sanitize_plane_mapping() may need to do vblank
16326          * waits, so we need vblank interrupts restored beforehand.
16327          */
16328         for_each_intel_crtc(&dev_priv->drm, crtc) {
16329                 crtc_state = to_intel_crtc_state(crtc->base.state);
16330
16331                 drm_crtc_vblank_reset(&crtc->base);
16332
16333                 if (crtc_state->base.active)
16334                         intel_crtc_vblank_on(crtc_state);
16335         }
16336
16337         intel_sanitize_plane_mapping(dev_priv);
16338
16339         for_each_intel_encoder(dev, encoder)
16340                 intel_sanitize_encoder(encoder);
16341
16342         for_each_intel_crtc(&dev_priv->drm, crtc) {
16343                 crtc_state = to_intel_crtc_state(crtc->base.state);
16344                 intel_sanitize_crtc(crtc, ctx);
16345                 intel_dump_pipe_config(crtc, crtc_state,
16346                                        "[setup_hw_state]");
16347         }
16348
16349         intel_modeset_update_connector_atomic_state(dev);
16350
16351         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
16352                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
16353
16354                 if (!pll->on || pll->active_mask)
16355                         continue;
16356
16357                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n",
16358                               pll->info->name);
16359
16360                 pll->info->funcs->disable(dev_priv, pll);
16361                 pll->on = false;
16362         }
16363
16364         if (IS_G4X(dev_priv)) {
16365                 g4x_wm_get_hw_state(dev_priv);
16366                 g4x_wm_sanitize(dev_priv);
16367         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
16368                 vlv_wm_get_hw_state(dev_priv);
16369                 vlv_wm_sanitize(dev_priv);
16370         } else if (INTEL_GEN(dev_priv) >= 9) {
16371                 skl_wm_get_hw_state(dev_priv);
16372         } else if (HAS_PCH_SPLIT(dev_priv)) {
16373                 ilk_wm_get_hw_state(dev_priv);
16374         }
16375
16376         for_each_intel_crtc(dev, crtc) {
16377                 u64 put_domains;
16378
16379                 crtc_state = to_intel_crtc_state(crtc->base.state);
16380                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc_state);
16381                 if (WARN_ON(put_domains))
16382                         modeset_put_power_domains(dev_priv, put_domains);
16383         }
16384
16385         intel_display_power_put(dev_priv, POWER_DOMAIN_INIT, wakeref);
16386
16387         intel_fbc_init_pipe_state(dev_priv);
16388 }
16389
16390 void intel_display_resume(struct drm_device *dev)
16391 {
16392         struct drm_i915_private *dev_priv = to_i915(dev);
16393         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
16394         struct drm_modeset_acquire_ctx ctx;
16395         int ret;
16396
16397         dev_priv->modeset_restore_state = NULL;
16398         if (state)
16399                 state->acquire_ctx = &ctx;
16400
16401         drm_modeset_acquire_init(&ctx, 0);
16402
16403         while (1) {
16404                 ret = drm_modeset_lock_all_ctx(dev, &ctx);
16405                 if (ret != -EDEADLK)
16406                         break;
16407
16408                 drm_modeset_backoff(&ctx);
16409         }
16410
16411         if (!ret)
16412                 ret = __intel_display_resume(dev, state, &ctx);
16413
16414         intel_enable_ipc(dev_priv);
16415         drm_modeset_drop_locks(&ctx);
16416         drm_modeset_acquire_fini(&ctx);
16417
16418         if (ret)
16419                 DRM_ERROR("Restoring old state failed with %i\n", ret);
16420         if (state)
16421                 drm_atomic_state_put(state);
16422 }
16423
16424 static void intel_hpd_poll_fini(struct drm_device *dev)
16425 {
16426         struct intel_connector *connector;
16427         struct drm_connector_list_iter conn_iter;
16428
16429         /* Kill all the work that may have been queued by hpd. */
16430         drm_connector_list_iter_begin(dev, &conn_iter);
16431         for_each_intel_connector_iter(connector, &conn_iter) {
16432                 if (connector->modeset_retry_work.func)
16433                         cancel_work_sync(&connector->modeset_retry_work);
16434                 if (connector->hdcp.shim) {
16435                         cancel_delayed_work_sync(&connector->hdcp.check_work);
16436                         cancel_work_sync(&connector->hdcp.prop_work);
16437                 }
16438         }
16439         drm_connector_list_iter_end(&conn_iter);
16440 }
16441
16442 void intel_modeset_cleanup(struct drm_device *dev)
16443 {
16444         struct drm_i915_private *dev_priv = to_i915(dev);
16445
16446         flush_workqueue(dev_priv->modeset_wq);
16447
16448         flush_work(&dev_priv->atomic_helper.free_work);
16449         WARN_ON(!llist_empty(&dev_priv->atomic_helper.free_list));
16450
16451         /*
16452          * Interrupts and polling as the first thing to avoid creating havoc.
16453          * Too much stuff here (turning of connectors, ...) would
16454          * experience fancy races otherwise.
16455          */
16456         intel_irq_uninstall(dev_priv);
16457
16458         /*
16459          * Due to the hpd irq storm handling the hotplug work can re-arm the
16460          * poll handlers. Hence disable polling after hpd handling is shut down.
16461          */
16462         intel_hpd_poll_fini(dev);
16463
16464         /* poll work can call into fbdev, hence clean that up afterwards */
16465         intel_fbdev_fini(dev_priv);
16466
16467         intel_unregister_dsm_handler();
16468
16469         intel_fbc_global_disable(dev_priv);
16470
16471         /* flush any delayed tasks or pending work */
16472         flush_scheduled_work();
16473
16474         intel_hdcp_component_fini(dev_priv);
16475
16476         drm_mode_config_cleanup(dev);
16477
16478         intel_overlay_cleanup(dev_priv);
16479
16480         intel_gmbus_teardown(dev_priv);
16481
16482         destroy_workqueue(dev_priv->modeset_wq);
16483
16484         intel_fbc_cleanup_cfb(dev_priv);
16485 }
16486
16487 /*
16488  * set vga decode state - true == enable VGA decode
16489  */
16490 int intel_modeset_vga_set_state(struct drm_i915_private *dev_priv, bool state)
16491 {
16492         unsigned reg = INTEL_GEN(dev_priv) >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
16493         u16 gmch_ctrl;
16494
16495         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
16496                 DRM_ERROR("failed to read control word\n");
16497                 return -EIO;
16498         }
16499
16500         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
16501                 return 0;
16502
16503         if (state)
16504                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
16505         else
16506                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
16507
16508         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
16509                 DRM_ERROR("failed to write control word\n");
16510                 return -EIO;
16511         }
16512
16513         return 0;
16514 }
16515
16516 #if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
16517
16518 struct intel_display_error_state {
16519
16520         u32 power_well_driver;
16521
16522         struct intel_cursor_error_state {
16523                 u32 control;
16524                 u32 position;
16525                 u32 base;
16526                 u32 size;
16527         } cursor[I915_MAX_PIPES];
16528
16529         struct intel_pipe_error_state {
16530                 bool power_domain_on;
16531                 u32 source;
16532                 u32 stat;
16533         } pipe[I915_MAX_PIPES];
16534
16535         struct intel_plane_error_state {
16536                 u32 control;
16537                 u32 stride;
16538                 u32 size;
16539                 u32 pos;
16540                 u32 addr;
16541                 u32 surface;
16542                 u32 tile_offset;
16543         } plane[I915_MAX_PIPES];
16544
16545         struct intel_transcoder_error_state {
16546                 bool available;
16547                 bool power_domain_on;
16548                 enum transcoder cpu_transcoder;
16549
16550                 u32 conf;
16551
16552                 u32 htotal;
16553                 u32 hblank;
16554                 u32 hsync;
16555                 u32 vtotal;
16556                 u32 vblank;
16557                 u32 vsync;
16558         } transcoder[4];
16559 };
16560
16561 struct intel_display_error_state *
16562 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
16563 {
16564         struct intel_display_error_state *error;
16565         int transcoders[] = {
16566                 TRANSCODER_A,
16567                 TRANSCODER_B,
16568                 TRANSCODER_C,
16569                 TRANSCODER_EDP,
16570         };
16571         int i;
16572
16573         BUILD_BUG_ON(ARRAY_SIZE(transcoders) != ARRAY_SIZE(error->transcoder));
16574
16575         if (!HAS_DISPLAY(dev_priv))
16576                 return NULL;
16577
16578         error = kzalloc(sizeof(*error), GFP_ATOMIC);
16579         if (error == NULL)
16580                 return NULL;
16581
16582         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
16583                 error->power_well_driver = I915_READ(HSW_PWR_WELL_CTL2);
16584
16585         for_each_pipe(dev_priv, i) {
16586                 error->pipe[i].power_domain_on =
16587                         __intel_display_power_is_enabled(dev_priv,
16588                                                          POWER_DOMAIN_PIPE(i));
16589                 if (!error->pipe[i].power_domain_on)
16590                         continue;
16591
16592                 error->cursor[i].control = I915_READ(CURCNTR(i));
16593                 error->cursor[i].position = I915_READ(CURPOS(i));
16594                 error->cursor[i].base = I915_READ(CURBASE(i));
16595
16596                 error->plane[i].control = I915_READ(DSPCNTR(i));
16597                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
16598                 if (INTEL_GEN(dev_priv) <= 3) {
16599                         error->plane[i].size = I915_READ(DSPSIZE(i));
16600                         error->plane[i].pos = I915_READ(DSPPOS(i));
16601                 }
16602                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
16603                         error->plane[i].addr = I915_READ(DSPADDR(i));
16604                 if (INTEL_GEN(dev_priv) >= 4) {
16605                         error->plane[i].surface = I915_READ(DSPSURF(i));
16606                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
16607                 }
16608
16609                 error->pipe[i].source = I915_READ(PIPESRC(i));
16610
16611                 if (HAS_GMCH(dev_priv))
16612                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
16613         }
16614
16615         for (i = 0; i < ARRAY_SIZE(error->transcoder); i++) {
16616                 enum transcoder cpu_transcoder = transcoders[i];
16617
16618                 if (!INTEL_INFO(dev_priv)->trans_offsets[cpu_transcoder])
16619                         continue;
16620
16621                 error->transcoder[i].available = true;
16622                 error->transcoder[i].power_domain_on =
16623                         __intel_display_power_is_enabled(dev_priv,
16624                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
16625                 if (!error->transcoder[i].power_domain_on)
16626                         continue;
16627
16628                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
16629
16630                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
16631                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
16632                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
16633                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
16634                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
16635                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
16636                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
16637         }
16638
16639         return error;
16640 }
16641
16642 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
16643
16644 void
16645 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
16646                                 struct intel_display_error_state *error)
16647 {
16648         struct drm_i915_private *dev_priv = m->i915;
16649         int i;
16650
16651         if (!error)
16652                 return;
16653
16654         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev_priv)->num_pipes);
16655         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
16656                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
16657                            error->power_well_driver);
16658         for_each_pipe(dev_priv, i) {
16659                 err_printf(m, "Pipe [%d]:\n", i);
16660                 err_printf(m, "  Power: %s\n",
16661                            onoff(error->pipe[i].power_domain_on));
16662                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
16663                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
16664
16665                 err_printf(m, "Plane [%d]:\n", i);
16666                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
16667                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
16668                 if (INTEL_GEN(dev_priv) <= 3) {
16669                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
16670                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
16671                 }
16672                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
16673                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
16674                 if (INTEL_GEN(dev_priv) >= 4) {
16675                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
16676                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
16677                 }
16678
16679                 err_printf(m, "Cursor [%d]:\n", i);
16680                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
16681                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
16682                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
16683         }
16684
16685         for (i = 0; i < ARRAY_SIZE(error->transcoder); i++) {
16686                 if (!error->transcoder[i].available)
16687                         continue;
16688
16689                 err_printf(m, "CPU transcoder: %s\n",
16690                            transcoder_name(error->transcoder[i].cpu_transcoder));
16691                 err_printf(m, "  Power: %s\n",
16692                            onoff(error->transcoder[i].power_domain_on));
16693                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
16694                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
16695                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
16696                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
16697                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
16698                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
16699                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
16700         }
16701 }
16702
16703 #endif