Merge tag 'drm-intel-next-2019-05-24' of git://anongit.freedesktop.org/drm/drm-intel...
[platform/kernel/linux-rpi.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 intel_tile_size(dev_priv);
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         return intel_tile_size(to_i915(fb->dev)) /
1962                 intel_tile_width_bytes(fb, color_plane);
1963 }
1964
1965 /* Return the tile dimensions in pixel units */
1966 static void intel_tile_dims(const struct drm_framebuffer *fb, int color_plane,
1967                             unsigned int *tile_width,
1968                             unsigned int *tile_height)
1969 {
1970         unsigned int tile_width_bytes = intel_tile_width_bytes(fb, color_plane);
1971         unsigned int cpp = fb->format->cpp[color_plane];
1972
1973         *tile_width = tile_width_bytes / cpp;
1974         *tile_height = intel_tile_size(to_i915(fb->dev)) / tile_width_bytes;
1975 }
1976
1977 unsigned int
1978 intel_fb_align_height(const struct drm_framebuffer *fb,
1979                       int color_plane, unsigned int height)
1980 {
1981         unsigned int tile_height = intel_tile_height(fb, color_plane);
1982
1983         return ALIGN(height, tile_height);
1984 }
1985
1986 unsigned int intel_rotation_info_size(const struct intel_rotation_info *rot_info)
1987 {
1988         unsigned int size = 0;
1989         int i;
1990
1991         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
1992                 size += rot_info->plane[i].width * rot_info->plane[i].height;
1993
1994         return size;
1995 }
1996
1997 unsigned int intel_remapped_info_size(const struct intel_remapped_info *rem_info)
1998 {
1999         unsigned int size = 0;
2000         int i;
2001
2002         for (i = 0 ; i < ARRAY_SIZE(rem_info->plane); i++)
2003                 size += rem_info->plane[i].width * rem_info->plane[i].height;
2004
2005         return size;
2006 }
2007
2008 static void
2009 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view,
2010                         const struct drm_framebuffer *fb,
2011                         unsigned int rotation)
2012 {
2013         view->type = I915_GGTT_VIEW_NORMAL;
2014         if (drm_rotation_90_or_270(rotation)) {
2015                 view->type = I915_GGTT_VIEW_ROTATED;
2016                 view->rotated = to_intel_framebuffer(fb)->rot_info;
2017         }
2018 }
2019
2020 static unsigned int intel_cursor_alignment(const struct drm_i915_private *dev_priv)
2021 {
2022         if (IS_I830(dev_priv))
2023                 return 16 * 1024;
2024         else if (IS_I85X(dev_priv))
2025                 return 256;
2026         else if (IS_I845G(dev_priv) || IS_I865G(dev_priv))
2027                 return 32;
2028         else
2029                 return 4 * 1024;
2030 }
2031
2032 static unsigned int intel_linear_alignment(const struct drm_i915_private *dev_priv)
2033 {
2034         if (INTEL_GEN(dev_priv) >= 9)
2035                 return 256 * 1024;
2036         else if (IS_I965G(dev_priv) || IS_I965GM(dev_priv) ||
2037                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
2038                 return 128 * 1024;
2039         else if (INTEL_GEN(dev_priv) >= 4)
2040                 return 4 * 1024;
2041         else
2042                 return 0;
2043 }
2044
2045 static unsigned int intel_surf_alignment(const struct drm_framebuffer *fb,
2046                                          int color_plane)
2047 {
2048         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2049
2050         /* AUX_DIST needs only 4K alignment */
2051         if (color_plane == 1)
2052                 return 4096;
2053
2054         switch (fb->modifier) {
2055         case DRM_FORMAT_MOD_LINEAR:
2056                 return intel_linear_alignment(dev_priv);
2057         case I915_FORMAT_MOD_X_TILED:
2058                 if (INTEL_GEN(dev_priv) >= 9)
2059                         return 256 * 1024;
2060                 return 0;
2061         case I915_FORMAT_MOD_Y_TILED_CCS:
2062         case I915_FORMAT_MOD_Yf_TILED_CCS:
2063         case I915_FORMAT_MOD_Y_TILED:
2064         case I915_FORMAT_MOD_Yf_TILED:
2065                 return 1 * 1024 * 1024;
2066         default:
2067                 MISSING_CASE(fb->modifier);
2068                 return 0;
2069         }
2070 }
2071
2072 static bool intel_plane_uses_fence(const struct intel_plane_state *plane_state)
2073 {
2074         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2075         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
2076
2077         return INTEL_GEN(dev_priv) < 4 ||
2078                 (plane->has_fbc &&
2079                  plane_state->view.type == I915_GGTT_VIEW_NORMAL);
2080 }
2081
2082 struct i915_vma *
2083 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb,
2084                            const struct i915_ggtt_view *view,
2085                            bool uses_fence,
2086                            unsigned long *out_flags)
2087 {
2088         struct drm_device *dev = fb->dev;
2089         struct drm_i915_private *dev_priv = to_i915(dev);
2090         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2091         intel_wakeref_t wakeref;
2092         struct i915_vma *vma;
2093         unsigned int pinctl;
2094         u32 alignment;
2095
2096         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2097
2098         alignment = intel_surf_alignment(fb, 0);
2099
2100         /* Note that the w/a also requires 64 PTE of padding following the
2101          * bo. We currently fill all unused PTE with the shadow page and so
2102          * we should always have valid PTE following the scanout preventing
2103          * the VT-d warning.
2104          */
2105         if (intel_scanout_needs_vtd_wa(dev_priv) && alignment < 256 * 1024)
2106                 alignment = 256 * 1024;
2107
2108         /*
2109          * Global gtt pte registers are special registers which actually forward
2110          * writes to a chunk of system memory. Which means that there is no risk
2111          * that the register values disappear as soon as we call
2112          * intel_runtime_pm_put(), so it is correct to wrap only the
2113          * pin/unpin/fence and not more.
2114          */
2115         wakeref = intel_runtime_pm_get(dev_priv);
2116
2117         atomic_inc(&dev_priv->gpu_error.pending_fb_pin);
2118
2119         pinctl = 0;
2120
2121         /* Valleyview is definitely limited to scanning out the first
2122          * 512MiB. Lets presume this behaviour was inherited from the
2123          * g4x display engine and that all earlier gen are similarly
2124          * limited. Testing suggests that it is a little more
2125          * complicated than this. For example, Cherryview appears quite
2126          * happy to scanout from anywhere within its global aperture.
2127          */
2128         if (HAS_GMCH(dev_priv))
2129                 pinctl |= PIN_MAPPABLE;
2130
2131         vma = i915_gem_object_pin_to_display_plane(obj,
2132                                                    alignment, view, pinctl);
2133         if (IS_ERR(vma))
2134                 goto err;
2135
2136         if (uses_fence && i915_vma_is_map_and_fenceable(vma)) {
2137                 int ret;
2138
2139                 /* Install a fence for tiled scan-out. Pre-i965 always needs a
2140                  * fence, whereas 965+ only requires a fence if using
2141                  * framebuffer compression.  For simplicity, we always, when
2142                  * possible, install a fence as the cost is not that onerous.
2143                  *
2144                  * If we fail to fence the tiled scanout, then either the
2145                  * modeset will reject the change (which is highly unlikely as
2146                  * the affected systems, all but one, do not have unmappable
2147                  * space) or we will not be able to enable full powersaving
2148                  * techniques (also likely not to apply due to various limits
2149                  * FBC and the like impose on the size of the buffer, which
2150                  * presumably we violated anyway with this unmappable buffer).
2151                  * Anyway, it is presumably better to stumble onwards with
2152                  * something and try to run the system in a "less than optimal"
2153                  * mode that matches the user configuration.
2154                  */
2155                 ret = i915_vma_pin_fence(vma);
2156                 if (ret != 0 && INTEL_GEN(dev_priv) < 4) {
2157                         i915_gem_object_unpin_from_display_plane(vma);
2158                         vma = ERR_PTR(ret);
2159                         goto err;
2160                 }
2161
2162                 if (ret == 0 && vma->fence)
2163                         *out_flags |= PLANE_HAS_FENCE;
2164         }
2165
2166         i915_vma_get(vma);
2167 err:
2168         atomic_dec(&dev_priv->gpu_error.pending_fb_pin);
2169
2170         intel_runtime_pm_put(dev_priv, wakeref);
2171         return vma;
2172 }
2173
2174 void intel_unpin_fb_vma(struct i915_vma *vma, unsigned long flags)
2175 {
2176         lockdep_assert_held(&vma->vm->i915->drm.struct_mutex);
2177
2178         if (flags & PLANE_HAS_FENCE)
2179                 i915_vma_unpin_fence(vma);
2180         i915_gem_object_unpin_from_display_plane(vma);
2181         i915_vma_put(vma);
2182 }
2183
2184 static int intel_fb_pitch(const struct drm_framebuffer *fb, int color_plane,
2185                           unsigned int rotation)
2186 {
2187         if (drm_rotation_90_or_270(rotation))
2188                 return to_intel_framebuffer(fb)->rotated[color_plane].pitch;
2189         else
2190                 return fb->pitches[color_plane];
2191 }
2192
2193 /*
2194  * Convert the x/y offsets into a linear offset.
2195  * Only valid with 0/180 degree rotation, which is fine since linear
2196  * offset is only used with linear buffers on pre-hsw and tiled buffers
2197  * with gen2/3, and 90/270 degree rotations isn't supported on any of them.
2198  */
2199 u32 intel_fb_xy_to_linear(int x, int y,
2200                           const struct intel_plane_state *state,
2201                           int color_plane)
2202 {
2203         const struct drm_framebuffer *fb = state->base.fb;
2204         unsigned int cpp = fb->format->cpp[color_plane];
2205         unsigned int pitch = state->color_plane[color_plane].stride;
2206
2207         return y * pitch + x * cpp;
2208 }
2209
2210 /*
2211  * Add the x/y offsets derived from fb->offsets[] to the user
2212  * specified plane src x/y offsets. The resulting x/y offsets
2213  * specify the start of scanout from the beginning of the gtt mapping.
2214  */
2215 void intel_add_fb_offsets(int *x, int *y,
2216                           const struct intel_plane_state *state,
2217                           int color_plane)
2218
2219 {
2220         *x += state->color_plane[color_plane].x;
2221         *y += state->color_plane[color_plane].y;
2222 }
2223
2224 static u32 intel_adjust_tile_offset(int *x, int *y,
2225                                     unsigned int tile_width,
2226                                     unsigned int tile_height,
2227                                     unsigned int tile_size,
2228                                     unsigned int pitch_tiles,
2229                                     u32 old_offset,
2230                                     u32 new_offset)
2231 {
2232         unsigned int pitch_pixels = pitch_tiles * tile_width;
2233         unsigned int tiles;
2234
2235         WARN_ON(old_offset & (tile_size - 1));
2236         WARN_ON(new_offset & (tile_size - 1));
2237         WARN_ON(new_offset > old_offset);
2238
2239         tiles = (old_offset - new_offset) / tile_size;
2240
2241         *y += tiles / pitch_tiles * tile_height;
2242         *x += tiles % pitch_tiles * tile_width;
2243
2244         /* minimize x in case it got needlessly big */
2245         *y += *x / pitch_pixels * tile_height;
2246         *x %= pitch_pixels;
2247
2248         return new_offset;
2249 }
2250
2251 static bool is_surface_linear(u64 modifier, int color_plane)
2252 {
2253         return modifier == DRM_FORMAT_MOD_LINEAR;
2254 }
2255
2256 static u32 intel_adjust_aligned_offset(int *x, int *y,
2257                                        const struct drm_framebuffer *fb,
2258                                        int color_plane,
2259                                        unsigned int rotation,
2260                                        unsigned int pitch,
2261                                        u32 old_offset, u32 new_offset)
2262 {
2263         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2264         unsigned int cpp = fb->format->cpp[color_plane];
2265
2266         WARN_ON(new_offset > old_offset);
2267
2268         if (!is_surface_linear(fb->modifier, color_plane)) {
2269                 unsigned int tile_size, tile_width, tile_height;
2270                 unsigned int pitch_tiles;
2271
2272                 tile_size = intel_tile_size(dev_priv);
2273                 intel_tile_dims(fb, color_plane, &tile_width, &tile_height);
2274
2275                 if (drm_rotation_90_or_270(rotation)) {
2276                         pitch_tiles = pitch / tile_height;
2277                         swap(tile_width, tile_height);
2278                 } else {
2279                         pitch_tiles = pitch / (tile_width * cpp);
2280                 }
2281
2282                 intel_adjust_tile_offset(x, y, tile_width, tile_height,
2283                                          tile_size, pitch_tiles,
2284                                          old_offset, new_offset);
2285         } else {
2286                 old_offset += *y * pitch + *x * cpp;
2287
2288                 *y = (old_offset - new_offset) / pitch;
2289                 *x = ((old_offset - new_offset) - *y * pitch) / cpp;
2290         }
2291
2292         return new_offset;
2293 }
2294
2295 /*
2296  * Adjust the tile offset by moving the difference into
2297  * the x/y offsets.
2298  */
2299 static u32 intel_plane_adjust_aligned_offset(int *x, int *y,
2300                                              const struct intel_plane_state *state,
2301                                              int color_plane,
2302                                              u32 old_offset, u32 new_offset)
2303 {
2304         return intel_adjust_aligned_offset(x, y, state->base.fb, color_plane,
2305                                            state->base.rotation,
2306                                            state->color_plane[color_plane].stride,
2307                                            old_offset, new_offset);
2308 }
2309
2310 /*
2311  * Computes the aligned offset to the base tile and adjusts
2312  * x, y. bytes per pixel is assumed to be a power-of-two.
2313  *
2314  * In the 90/270 rotated case, x and y are assumed
2315  * to be already rotated to match the rotated GTT view, and
2316  * pitch is the tile_height aligned framebuffer height.
2317  *
2318  * This function is used when computing the derived information
2319  * under intel_framebuffer, so using any of that information
2320  * here is not allowed. Anything under drm_framebuffer can be
2321  * used. This is why the user has to pass in the pitch since it
2322  * is specified in the rotated orientation.
2323  */
2324 static u32 intel_compute_aligned_offset(struct drm_i915_private *dev_priv,
2325                                         int *x, int *y,
2326                                         const struct drm_framebuffer *fb,
2327                                         int color_plane,
2328                                         unsigned int pitch,
2329                                         unsigned int rotation,
2330                                         u32 alignment)
2331 {
2332         unsigned int cpp = fb->format->cpp[color_plane];
2333         u32 offset, offset_aligned;
2334
2335         if (alignment)
2336                 alignment--;
2337
2338         if (!is_surface_linear(fb->modifier, color_plane)) {
2339                 unsigned int tile_size, tile_width, tile_height;
2340                 unsigned int tile_rows, tiles, pitch_tiles;
2341
2342                 tile_size = intel_tile_size(dev_priv);
2343                 intel_tile_dims(fb, color_plane, &tile_width, &tile_height);
2344
2345                 if (drm_rotation_90_or_270(rotation)) {
2346                         pitch_tiles = pitch / tile_height;
2347                         swap(tile_width, tile_height);
2348                 } else {
2349                         pitch_tiles = pitch / (tile_width * cpp);
2350                 }
2351
2352                 tile_rows = *y / tile_height;
2353                 *y %= tile_height;
2354
2355                 tiles = *x / tile_width;
2356                 *x %= tile_width;
2357
2358                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2359                 offset_aligned = offset & ~alignment;
2360
2361                 intel_adjust_tile_offset(x, y, tile_width, tile_height,
2362                                          tile_size, pitch_tiles,
2363                                          offset, offset_aligned);
2364         } else {
2365                 offset = *y * pitch + *x * cpp;
2366                 offset_aligned = offset & ~alignment;
2367
2368                 *y = (offset & alignment) / pitch;
2369                 *x = ((offset & alignment) - *y * pitch) / cpp;
2370         }
2371
2372         return offset_aligned;
2373 }
2374
2375 static u32 intel_plane_compute_aligned_offset(int *x, int *y,
2376                                               const struct intel_plane_state *state,
2377                                               int color_plane)
2378 {
2379         struct intel_plane *intel_plane = to_intel_plane(state->base.plane);
2380         struct drm_i915_private *dev_priv = to_i915(intel_plane->base.dev);
2381         const struct drm_framebuffer *fb = state->base.fb;
2382         unsigned int rotation = state->base.rotation;
2383         int pitch = state->color_plane[color_plane].stride;
2384         u32 alignment;
2385
2386         if (intel_plane->id == PLANE_CURSOR)
2387                 alignment = intel_cursor_alignment(dev_priv);
2388         else
2389                 alignment = intel_surf_alignment(fb, color_plane);
2390
2391         return intel_compute_aligned_offset(dev_priv, x, y, fb, color_plane,
2392                                             pitch, rotation, alignment);
2393 }
2394
2395 /* Convert the fb->offset[] into x/y offsets */
2396 static int intel_fb_offset_to_xy(int *x, int *y,
2397                                  const struct drm_framebuffer *fb,
2398                                  int color_plane)
2399 {
2400         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2401         unsigned int height;
2402
2403         if (fb->modifier != DRM_FORMAT_MOD_LINEAR &&
2404             fb->offsets[color_plane] % intel_tile_size(dev_priv)) {
2405                 DRM_DEBUG_KMS("Misaligned offset 0x%08x for color plane %d\n",
2406                               fb->offsets[color_plane], color_plane);
2407                 return -EINVAL;
2408         }
2409
2410         height = drm_framebuffer_plane_height(fb->height, fb, color_plane);
2411         height = ALIGN(height, intel_tile_height(fb, color_plane));
2412
2413         /* Catch potential overflows early */
2414         if (add_overflows_t(u32, mul_u32_u32(height, fb->pitches[color_plane]),
2415                             fb->offsets[color_plane])) {
2416                 DRM_DEBUG_KMS("Bad offset 0x%08x or pitch %d for color plane %d\n",
2417                               fb->offsets[color_plane], fb->pitches[color_plane],
2418                               color_plane);
2419                 return -ERANGE;
2420         }
2421
2422         *x = 0;
2423         *y = 0;
2424
2425         intel_adjust_aligned_offset(x, y,
2426                                     fb, color_plane, DRM_MODE_ROTATE_0,
2427                                     fb->pitches[color_plane],
2428                                     fb->offsets[color_plane], 0);
2429
2430         return 0;
2431 }
2432
2433 static unsigned int intel_fb_modifier_to_tiling(u64 fb_modifier)
2434 {
2435         switch (fb_modifier) {
2436         case I915_FORMAT_MOD_X_TILED:
2437                 return I915_TILING_X;
2438         case I915_FORMAT_MOD_Y_TILED:
2439         case I915_FORMAT_MOD_Y_TILED_CCS:
2440                 return I915_TILING_Y;
2441         default:
2442                 return I915_TILING_NONE;
2443         }
2444 }
2445
2446 /*
2447  * From the Sky Lake PRM:
2448  * "The Color Control Surface (CCS) contains the compression status of
2449  *  the cache-line pairs. The compression state of the cache-line pair
2450  *  is specified by 2 bits in the CCS. Each CCS cache-line represents
2451  *  an area on the main surface of 16 x16 sets of 128 byte Y-tiled
2452  *  cache-line-pairs. CCS is always Y tiled."
2453  *
2454  * Since cache line pairs refers to horizontally adjacent cache lines,
2455  * each cache line in the CCS corresponds to an area of 32x16 cache
2456  * lines on the main surface. Since each pixel is 4 bytes, this gives
2457  * us a ratio of one byte in the CCS for each 8x16 pixels in the
2458  * main surface.
2459  */
2460 static const struct drm_format_info ccs_formats[] = {
2461         { .format = DRM_FORMAT_XRGB8888, .depth = 24, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2462         { .format = DRM_FORMAT_XBGR8888, .depth = 24, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2463         { .format = DRM_FORMAT_ARGB8888, .depth = 32, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2464         { .format = DRM_FORMAT_ABGR8888, .depth = 32, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2465 };
2466
2467 static const struct drm_format_info *
2468 lookup_format_info(const struct drm_format_info formats[],
2469                    int num_formats, u32 format)
2470 {
2471         int i;
2472
2473         for (i = 0; i < num_formats; i++) {
2474                 if (formats[i].format == format)
2475                         return &formats[i];
2476         }
2477
2478         return NULL;
2479 }
2480
2481 static const struct drm_format_info *
2482 intel_get_format_info(const struct drm_mode_fb_cmd2 *cmd)
2483 {
2484         switch (cmd->modifier[0]) {
2485         case I915_FORMAT_MOD_Y_TILED_CCS:
2486         case I915_FORMAT_MOD_Yf_TILED_CCS:
2487                 return lookup_format_info(ccs_formats,
2488                                           ARRAY_SIZE(ccs_formats),
2489                                           cmd->pixel_format);
2490         default:
2491                 return NULL;
2492         }
2493 }
2494
2495 bool is_ccs_modifier(u64 modifier)
2496 {
2497         return modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
2498                modifier == I915_FORMAT_MOD_Yf_TILED_CCS;
2499 }
2500
2501 u32 intel_plane_fb_max_stride(struct drm_i915_private *dev_priv,
2502                               u32 pixel_format, u64 modifier)
2503 {
2504         struct intel_crtc *crtc;
2505         struct intel_plane *plane;
2506
2507         /*
2508          * We assume the primary plane for pipe A has
2509          * the highest stride limits of them all.
2510          */
2511         crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_A);
2512         plane = to_intel_plane(crtc->base.primary);
2513
2514         return plane->max_stride(plane, pixel_format, modifier,
2515                                  DRM_MODE_ROTATE_0);
2516 }
2517
2518 static
2519 u32 intel_fb_max_stride(struct drm_i915_private *dev_priv,
2520                         u32 pixel_format, u64 modifier)
2521 {
2522         /*
2523          * Arbitrary limit for gen4+ chosen to match the
2524          * render engine max stride.
2525          *
2526          * The new CCS hash mode makes remapping impossible
2527          */
2528         if (!is_ccs_modifier(modifier)) {
2529                 if (INTEL_GEN(dev_priv) >= 7)
2530                         return 256*1024;
2531                 else if (INTEL_GEN(dev_priv) >= 4)
2532                         return 128*1024;
2533         }
2534
2535         return intel_plane_fb_max_stride(dev_priv, pixel_format, modifier);
2536 }
2537
2538 static u32
2539 intel_fb_stride_alignment(const struct drm_framebuffer *fb, int color_plane)
2540 {
2541         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2542
2543         if (fb->modifier == DRM_FORMAT_MOD_LINEAR) {
2544                 u32 max_stride = intel_plane_fb_max_stride(dev_priv,
2545                                                            fb->format->format,
2546                                                            fb->modifier);
2547
2548                 /*
2549                  * To make remapping with linear generally feasible
2550                  * we need the stride to be page aligned.
2551                  */
2552                 if (fb->pitches[color_plane] > max_stride)
2553                         return intel_tile_size(dev_priv);
2554                 else
2555                         return 64;
2556         } else {
2557                 return intel_tile_width_bytes(fb, color_plane);
2558         }
2559 }
2560
2561 bool intel_plane_can_remap(const struct intel_plane_state *plane_state)
2562 {
2563         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2564         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
2565         const struct drm_framebuffer *fb = plane_state->base.fb;
2566         int i;
2567
2568         /* We don't want to deal with remapping with cursors */
2569         if (plane->id == PLANE_CURSOR)
2570                 return false;
2571
2572         /*
2573          * The display engine limits already match/exceed the
2574          * render engine limits, so not much point in remapping.
2575          * Would also need to deal with the fence POT alignment
2576          * and gen2 2KiB GTT tile size.
2577          */
2578         if (INTEL_GEN(dev_priv) < 4)
2579                 return false;
2580
2581         /*
2582          * The new CCS hash mode isn't compatible with remapping as
2583          * the virtual address of the pages affects the compressed data.
2584          */
2585         if (is_ccs_modifier(fb->modifier))
2586                 return false;
2587
2588         /* Linear needs a page aligned stride for remapping */
2589         if (fb->modifier == DRM_FORMAT_MOD_LINEAR) {
2590                 unsigned int alignment = intel_tile_size(dev_priv) - 1;
2591
2592                 for (i = 0; i < fb->format->num_planes; i++) {
2593                         if (fb->pitches[i] & alignment)
2594                                 return false;
2595                 }
2596         }
2597
2598         return true;
2599 }
2600
2601 static bool intel_plane_needs_remap(const struct intel_plane_state *plane_state)
2602 {
2603         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2604         const struct drm_framebuffer *fb = plane_state->base.fb;
2605         unsigned int rotation = plane_state->base.rotation;
2606         u32 stride, max_stride;
2607
2608         /*
2609          * No remapping for invisible planes since we don't have
2610          * an actual source viewport to remap.
2611          */
2612         if (!plane_state->base.visible)
2613                 return false;
2614
2615         if (!intel_plane_can_remap(plane_state))
2616                 return false;
2617
2618         /*
2619          * FIXME: aux plane limits on gen9+ are
2620          * unclear in Bspec, for now no checking.
2621          */
2622         stride = intel_fb_pitch(fb, 0, rotation);
2623         max_stride = plane->max_stride(plane, fb->format->format,
2624                                        fb->modifier, rotation);
2625
2626         return stride > max_stride;
2627 }
2628
2629 static int
2630 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2631                    struct drm_framebuffer *fb)
2632 {
2633         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
2634         struct intel_rotation_info *rot_info = &intel_fb->rot_info;
2635         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2636         u32 gtt_offset_rotated = 0;
2637         unsigned int max_size = 0;
2638         int i, num_planes = fb->format->num_planes;
2639         unsigned int tile_size = intel_tile_size(dev_priv);
2640
2641         for (i = 0; i < num_planes; i++) {
2642                 unsigned int width, height;
2643                 unsigned int cpp, size;
2644                 u32 offset;
2645                 int x, y;
2646                 int ret;
2647
2648                 cpp = fb->format->cpp[i];
2649                 width = drm_framebuffer_plane_width(fb->width, fb, i);
2650                 height = drm_framebuffer_plane_height(fb->height, fb, i);
2651
2652                 ret = intel_fb_offset_to_xy(&x, &y, fb, i);
2653                 if (ret) {
2654                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2655                                       i, fb->offsets[i]);
2656                         return ret;
2657                 }
2658
2659                 if (is_ccs_modifier(fb->modifier) && i == 1) {
2660                         int hsub = fb->format->hsub;
2661                         int vsub = fb->format->vsub;
2662                         int tile_width, tile_height;
2663                         int main_x, main_y;
2664                         int ccs_x, ccs_y;
2665
2666                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2667                         tile_width *= hsub;
2668                         tile_height *= vsub;
2669
2670                         ccs_x = (x * hsub) % tile_width;
2671                         ccs_y = (y * vsub) % tile_height;
2672                         main_x = intel_fb->normal[0].x % tile_width;
2673                         main_y = intel_fb->normal[0].y % tile_height;
2674
2675                         /*
2676                          * CCS doesn't have its own x/y offset register, so the intra CCS tile
2677                          * x/y offsets must match between CCS and the main surface.
2678                          */
2679                         if (main_x != ccs_x || main_y != ccs_y) {
2680                                 DRM_DEBUG_KMS("Bad CCS x/y (main %d,%d ccs %d,%d) full (main %d,%d ccs %d,%d)\n",
2681                                               main_x, main_y,
2682                                               ccs_x, ccs_y,
2683                                               intel_fb->normal[0].x,
2684                                               intel_fb->normal[0].y,
2685                                               x, y);
2686                                 return -EINVAL;
2687                         }
2688                 }
2689
2690                 /*
2691                  * The fence (if used) is aligned to the start of the object
2692                  * so having the framebuffer wrap around across the edge of the
2693                  * fenced region doesn't really work. We have no API to configure
2694                  * the fence start offset within the object (nor could we probably
2695                  * on gen2/3). So it's just easier if we just require that the
2696                  * fb layout agrees with the fence layout. We already check that the
2697                  * fb stride matches the fence stride elsewhere.
2698                  */
2699                 if (i == 0 && i915_gem_object_is_tiled(obj) &&
2700                     (x + width) * cpp > fb->pitches[i]) {
2701                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2702                                       i, fb->offsets[i]);
2703                         return -EINVAL;
2704                 }
2705
2706                 /*
2707                  * First pixel of the framebuffer from
2708                  * the start of the normal gtt mapping.
2709                  */
2710                 intel_fb->normal[i].x = x;
2711                 intel_fb->normal[i].y = y;
2712
2713                 offset = intel_compute_aligned_offset(dev_priv, &x, &y, fb, i,
2714                                                       fb->pitches[i],
2715                                                       DRM_MODE_ROTATE_0,
2716                                                       tile_size);
2717                 offset /= tile_size;
2718
2719                 if (!is_surface_linear(fb->modifier, i)) {
2720                         unsigned int tile_width, tile_height;
2721                         unsigned int pitch_tiles;
2722                         struct drm_rect r;
2723
2724                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2725
2726                         rot_info->plane[i].offset = offset;
2727                         rot_info->plane[i].stride = DIV_ROUND_UP(fb->pitches[i], tile_width * cpp);
2728                         rot_info->plane[i].width = DIV_ROUND_UP(x + width, tile_width);
2729                         rot_info->plane[i].height = DIV_ROUND_UP(y + height, tile_height);
2730
2731                         intel_fb->rotated[i].pitch =
2732                                 rot_info->plane[i].height * tile_height;
2733
2734                         /* how many tiles does this plane need */
2735                         size = rot_info->plane[i].stride * rot_info->plane[i].height;
2736                         /*
2737                          * If the plane isn't horizontally tile aligned,
2738                          * we need one more tile.
2739                          */
2740                         if (x != 0)
2741                                 size++;
2742
2743                         /* rotate the x/y offsets to match the GTT view */
2744                         r.x1 = x;
2745                         r.y1 = y;
2746                         r.x2 = x + width;
2747                         r.y2 = y + height;
2748                         drm_rect_rotate(&r,
2749                                         rot_info->plane[i].width * tile_width,
2750                                         rot_info->plane[i].height * tile_height,
2751                                         DRM_MODE_ROTATE_270);
2752                         x = r.x1;
2753                         y = r.y1;
2754
2755                         /* rotate the tile dimensions to match the GTT view */
2756                         pitch_tiles = intel_fb->rotated[i].pitch / tile_height;
2757                         swap(tile_width, tile_height);
2758
2759                         /*
2760                          * We only keep the x/y offsets, so push all of the
2761                          * gtt offset into the x/y offsets.
2762                          */
2763                         intel_adjust_tile_offset(&x, &y,
2764                                                  tile_width, tile_height,
2765                                                  tile_size, pitch_tiles,
2766                                                  gtt_offset_rotated * tile_size, 0);
2767
2768                         gtt_offset_rotated += rot_info->plane[i].width * rot_info->plane[i].height;
2769
2770                         /*
2771                          * First pixel of the framebuffer from
2772                          * the start of the rotated gtt mapping.
2773                          */
2774                         intel_fb->rotated[i].x = x;
2775                         intel_fb->rotated[i].y = y;
2776                 } else {
2777                         size = DIV_ROUND_UP((y + height) * fb->pitches[i] +
2778                                             x * cpp, tile_size);
2779                 }
2780
2781                 /* how many tiles in total needed in the bo */
2782                 max_size = max(max_size, offset + size);
2783         }
2784
2785         if (mul_u32_u32(max_size, tile_size) > obj->base.size) {
2786                 DRM_DEBUG_KMS("fb too big for bo (need %llu bytes, have %zu bytes)\n",
2787                               mul_u32_u32(max_size, tile_size), obj->base.size);
2788                 return -EINVAL;
2789         }
2790
2791         return 0;
2792 }
2793
2794 static void
2795 intel_plane_remap_gtt(struct intel_plane_state *plane_state)
2796 {
2797         struct drm_i915_private *dev_priv =
2798                 to_i915(plane_state->base.plane->dev);
2799         struct drm_framebuffer *fb = plane_state->base.fb;
2800         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
2801         struct intel_rotation_info *info = &plane_state->view.rotated;
2802         unsigned int rotation = plane_state->base.rotation;
2803         int i, num_planes = fb->format->num_planes;
2804         unsigned int tile_size = intel_tile_size(dev_priv);
2805         unsigned int src_x, src_y;
2806         unsigned int src_w, src_h;
2807         u32 gtt_offset = 0;
2808
2809         memset(&plane_state->view, 0, sizeof(plane_state->view));
2810         plane_state->view.type = drm_rotation_90_or_270(rotation) ?
2811                 I915_GGTT_VIEW_ROTATED : I915_GGTT_VIEW_REMAPPED;
2812
2813         src_x = plane_state->base.src.x1 >> 16;
2814         src_y = plane_state->base.src.y1 >> 16;
2815         src_w = drm_rect_width(&plane_state->base.src) >> 16;
2816         src_h = drm_rect_height(&plane_state->base.src) >> 16;
2817
2818         WARN_ON(is_ccs_modifier(fb->modifier));
2819
2820         /* Make src coordinates relative to the viewport */
2821         drm_rect_translate(&plane_state->base.src,
2822                            -(src_x << 16), -(src_y << 16));
2823
2824         /* Rotate src coordinates to match rotated GTT view */
2825         if (drm_rotation_90_or_270(rotation))
2826                 drm_rect_rotate(&plane_state->base.src,
2827                                 src_w << 16, src_h << 16,
2828                                 DRM_MODE_ROTATE_270);
2829
2830         for (i = 0; i < num_planes; i++) {
2831                 unsigned int hsub = i ? fb->format->hsub : 1;
2832                 unsigned int vsub = i ? fb->format->vsub : 1;
2833                 unsigned int cpp = fb->format->cpp[i];
2834                 unsigned int tile_width, tile_height;
2835                 unsigned int width, height;
2836                 unsigned int pitch_tiles;
2837                 unsigned int x, y;
2838                 u32 offset;
2839
2840                 intel_tile_dims(fb, i, &tile_width, &tile_height);
2841
2842                 x = src_x / hsub;
2843                 y = src_y / vsub;
2844                 width = src_w / hsub;
2845                 height = src_h / vsub;
2846
2847                 /*
2848                  * First pixel of the src viewport from the
2849                  * start of the normal gtt mapping.
2850                  */
2851                 x += intel_fb->normal[i].x;
2852                 y += intel_fb->normal[i].y;
2853
2854                 offset = intel_compute_aligned_offset(dev_priv, &x, &y,
2855                                                       fb, i, fb->pitches[i],
2856                                                       DRM_MODE_ROTATE_0, tile_size);
2857                 offset /= tile_size;
2858
2859                 info->plane[i].offset = offset;
2860                 info->plane[i].stride = DIV_ROUND_UP(fb->pitches[i],
2861                                                      tile_width * cpp);
2862                 info->plane[i].width = DIV_ROUND_UP(x + width, tile_width);
2863                 info->plane[i].height = DIV_ROUND_UP(y + height, tile_height);
2864
2865                 if (drm_rotation_90_or_270(rotation)) {
2866                         struct drm_rect r;
2867
2868                         /* rotate the x/y offsets to match the GTT view */
2869                         r.x1 = x;
2870                         r.y1 = y;
2871                         r.x2 = x + width;
2872                         r.y2 = y + height;
2873                         drm_rect_rotate(&r,
2874                                         info->plane[i].width * tile_width,
2875                                         info->plane[i].height * tile_height,
2876                                         DRM_MODE_ROTATE_270);
2877                         x = r.x1;
2878                         y = r.y1;
2879
2880                         pitch_tiles = info->plane[i].height;
2881                         plane_state->color_plane[i].stride = pitch_tiles * tile_height;
2882
2883                         /* rotate the tile dimensions to match the GTT view */
2884                         swap(tile_width, tile_height);
2885                 } else {
2886                         pitch_tiles = info->plane[i].width;
2887                         plane_state->color_plane[i].stride = pitch_tiles * tile_width * cpp;
2888                 }
2889
2890                 /*
2891                  * We only keep the x/y offsets, so push all of the
2892                  * gtt offset into the x/y offsets.
2893                  */
2894                 intel_adjust_tile_offset(&x, &y,
2895                                          tile_width, tile_height,
2896                                          tile_size, pitch_tiles,
2897                                          gtt_offset * tile_size, 0);
2898
2899                 gtt_offset += info->plane[i].width * info->plane[i].height;
2900
2901                 plane_state->color_plane[i].offset = 0;
2902                 plane_state->color_plane[i].x = x;
2903                 plane_state->color_plane[i].y = y;
2904         }
2905 }
2906
2907 static int
2908 intel_plane_compute_gtt(struct intel_plane_state *plane_state)
2909 {
2910         const struct intel_framebuffer *fb =
2911                 to_intel_framebuffer(plane_state->base.fb);
2912         unsigned int rotation = plane_state->base.rotation;
2913         int i, num_planes;
2914
2915         if (!fb)
2916                 return 0;
2917
2918         num_planes = fb->base.format->num_planes;
2919
2920         if (intel_plane_needs_remap(plane_state)) {
2921                 intel_plane_remap_gtt(plane_state);
2922
2923                 /*
2924                  * Sometimes even remapping can't overcome
2925                  * the stride limitations :( Can happen with
2926                  * big plane sizes and suitably misaligned
2927                  * offsets.
2928                  */
2929                 return intel_plane_check_stride(plane_state);
2930         }
2931
2932         intel_fill_fb_ggtt_view(&plane_state->view, &fb->base, rotation);
2933
2934         for (i = 0; i < num_planes; i++) {
2935                 plane_state->color_plane[i].stride = intel_fb_pitch(&fb->base, i, rotation);
2936                 plane_state->color_plane[i].offset = 0;
2937
2938                 if (drm_rotation_90_or_270(rotation)) {
2939                         plane_state->color_plane[i].x = fb->rotated[i].x;
2940                         plane_state->color_plane[i].y = fb->rotated[i].y;
2941                 } else {
2942                         plane_state->color_plane[i].x = fb->normal[i].x;
2943                         plane_state->color_plane[i].y = fb->normal[i].y;
2944                 }
2945         }
2946
2947         /* Rotate src coordinates to match rotated GTT view */
2948         if (drm_rotation_90_or_270(rotation))
2949                 drm_rect_rotate(&plane_state->base.src,
2950                                 fb->base.width << 16, fb->base.height << 16,
2951                                 DRM_MODE_ROTATE_270);
2952
2953         return intel_plane_check_stride(plane_state);
2954 }
2955
2956 static int i9xx_format_to_fourcc(int format)
2957 {
2958         switch (format) {
2959         case DISPPLANE_8BPP:
2960                 return DRM_FORMAT_C8;
2961         case DISPPLANE_BGRX555:
2962                 return DRM_FORMAT_XRGB1555;
2963         case DISPPLANE_BGRX565:
2964                 return DRM_FORMAT_RGB565;
2965         default:
2966         case DISPPLANE_BGRX888:
2967                 return DRM_FORMAT_XRGB8888;
2968         case DISPPLANE_RGBX888:
2969                 return DRM_FORMAT_XBGR8888;
2970         case DISPPLANE_BGRX101010:
2971                 return DRM_FORMAT_XRGB2101010;
2972         case DISPPLANE_RGBX101010:
2973                 return DRM_FORMAT_XBGR2101010;
2974         }
2975 }
2976
2977 int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2978 {
2979         switch (format) {
2980         case PLANE_CTL_FORMAT_RGB_565:
2981                 return DRM_FORMAT_RGB565;
2982         case PLANE_CTL_FORMAT_NV12:
2983                 return DRM_FORMAT_NV12;
2984         case PLANE_CTL_FORMAT_P010:
2985                 return DRM_FORMAT_P010;
2986         case PLANE_CTL_FORMAT_P012:
2987                 return DRM_FORMAT_P012;
2988         case PLANE_CTL_FORMAT_P016:
2989                 return DRM_FORMAT_P016;
2990         case PLANE_CTL_FORMAT_Y210:
2991                 return DRM_FORMAT_Y210;
2992         case PLANE_CTL_FORMAT_Y212:
2993                 return DRM_FORMAT_Y212;
2994         case PLANE_CTL_FORMAT_Y216:
2995                 return DRM_FORMAT_Y216;
2996         case PLANE_CTL_FORMAT_Y410:
2997                 return DRM_FORMAT_XVYU2101010;
2998         case PLANE_CTL_FORMAT_Y412:
2999                 return DRM_FORMAT_XVYU12_16161616;
3000         case PLANE_CTL_FORMAT_Y416:
3001                 return DRM_FORMAT_XVYU16161616;
3002         default:
3003         case PLANE_CTL_FORMAT_XRGB_8888:
3004                 if (rgb_order) {
3005                         if (alpha)
3006                                 return DRM_FORMAT_ABGR8888;
3007                         else
3008                                 return DRM_FORMAT_XBGR8888;
3009                 } else {
3010                         if (alpha)
3011                                 return DRM_FORMAT_ARGB8888;
3012                         else
3013                                 return DRM_FORMAT_XRGB8888;
3014                 }
3015         case PLANE_CTL_FORMAT_XRGB_2101010:
3016                 if (rgb_order)
3017                         return DRM_FORMAT_XBGR2101010;
3018                 else
3019                         return DRM_FORMAT_XRGB2101010;
3020         case PLANE_CTL_FORMAT_XRGB_16161616F:
3021                 if (rgb_order) {
3022                         if (alpha)
3023                                 return DRM_FORMAT_ABGR16161616F;
3024                         else
3025                                 return DRM_FORMAT_XBGR16161616F;
3026                 } else {
3027                         if (alpha)
3028                                 return DRM_FORMAT_ARGB16161616F;
3029                         else
3030                                 return DRM_FORMAT_XRGB16161616F;
3031                 }
3032         }
3033 }
3034
3035 static bool
3036 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
3037                               struct intel_initial_plane_config *plane_config)
3038 {
3039         struct drm_device *dev = crtc->base.dev;
3040         struct drm_i915_private *dev_priv = to_i915(dev);
3041         struct drm_i915_gem_object *obj = NULL;
3042         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
3043         struct drm_framebuffer *fb = &plane_config->fb->base;
3044         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
3045         u32 size_aligned = round_up(plane_config->base + plane_config->size,
3046                                     PAGE_SIZE);
3047
3048         size_aligned -= base_aligned;
3049
3050         if (plane_config->size == 0)
3051                 return false;
3052
3053         /* If the FB is too big, just don't use it since fbdev is not very
3054          * important and we should probably use that space with FBC or other
3055          * features. */
3056         if (size_aligned * 2 > dev_priv->stolen_usable_size)
3057                 return false;
3058
3059         switch (fb->modifier) {
3060         case DRM_FORMAT_MOD_LINEAR:
3061         case I915_FORMAT_MOD_X_TILED:
3062         case I915_FORMAT_MOD_Y_TILED:
3063                 break;
3064         default:
3065                 DRM_DEBUG_DRIVER("Unsupported modifier for initial FB: 0x%llx\n",
3066                                  fb->modifier);
3067                 return false;
3068         }
3069
3070         mutex_lock(&dev->struct_mutex);
3071         obj = i915_gem_object_create_stolen_for_preallocated(dev_priv,
3072                                                              base_aligned,
3073                                                              base_aligned,
3074                                                              size_aligned);
3075         mutex_unlock(&dev->struct_mutex);
3076         if (!obj)
3077                 return false;
3078
3079         switch (plane_config->tiling) {
3080         case I915_TILING_NONE:
3081                 break;
3082         case I915_TILING_X:
3083         case I915_TILING_Y:
3084                 obj->tiling_and_stride = fb->pitches[0] | plane_config->tiling;
3085                 break;
3086         default:
3087                 MISSING_CASE(plane_config->tiling);
3088                 return false;
3089         }
3090
3091         mode_cmd.pixel_format = fb->format->format;
3092         mode_cmd.width = fb->width;
3093         mode_cmd.height = fb->height;
3094         mode_cmd.pitches[0] = fb->pitches[0];
3095         mode_cmd.modifier[0] = fb->modifier;
3096         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
3097
3098         if (intel_framebuffer_init(to_intel_framebuffer(fb), obj, &mode_cmd)) {
3099                 DRM_DEBUG_KMS("intel fb init failed\n");
3100                 goto out_unref_obj;
3101         }
3102
3103
3104         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
3105         return true;
3106
3107 out_unref_obj:
3108         i915_gem_object_put(obj);
3109         return false;
3110 }
3111
3112 static void
3113 intel_set_plane_visible(struct intel_crtc_state *crtc_state,
3114                         struct intel_plane_state *plane_state,
3115                         bool visible)
3116 {
3117         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
3118
3119         plane_state->base.visible = visible;
3120
3121         if (visible)
3122                 crtc_state->base.plane_mask |= drm_plane_mask(&plane->base);
3123         else
3124                 crtc_state->base.plane_mask &= ~drm_plane_mask(&plane->base);
3125 }
3126
3127 static void fixup_active_planes(struct intel_crtc_state *crtc_state)
3128 {
3129         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
3130         struct drm_plane *plane;
3131
3132         /*
3133          * Active_planes aliases if multiple "primary" or cursor planes
3134          * have been used on the same (or wrong) pipe. plane_mask uses
3135          * unique ids, hence we can use that to reconstruct active_planes.
3136          */
3137         crtc_state->active_planes = 0;
3138
3139         drm_for_each_plane_mask(plane, &dev_priv->drm,
3140                                 crtc_state->base.plane_mask)
3141                 crtc_state->active_planes |= BIT(to_intel_plane(plane)->id);
3142 }
3143
3144 static void intel_plane_disable_noatomic(struct intel_crtc *crtc,
3145                                          struct intel_plane *plane)
3146 {
3147         struct intel_crtc_state *crtc_state =
3148                 to_intel_crtc_state(crtc->base.state);
3149         struct intel_plane_state *plane_state =
3150                 to_intel_plane_state(plane->base.state);
3151
3152         DRM_DEBUG_KMS("Disabling [PLANE:%d:%s] on [CRTC:%d:%s]\n",
3153                       plane->base.base.id, plane->base.name,
3154                       crtc->base.base.id, crtc->base.name);
3155
3156         intel_set_plane_visible(crtc_state, plane_state, false);
3157         fixup_active_planes(crtc_state);
3158
3159         if (plane->id == PLANE_PRIMARY)
3160                 intel_pre_disable_primary_noatomic(&crtc->base);
3161
3162         intel_disable_plane(plane, crtc_state);
3163 }
3164
3165 static void
3166 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
3167                              struct intel_initial_plane_config *plane_config)
3168 {
3169         struct drm_device *dev = intel_crtc->base.dev;
3170         struct drm_i915_private *dev_priv = to_i915(dev);
3171         struct drm_crtc *c;
3172         struct drm_i915_gem_object *obj;
3173         struct drm_plane *primary = intel_crtc->base.primary;
3174         struct drm_plane_state *plane_state = primary->state;
3175         struct intel_plane *intel_plane = to_intel_plane(primary);
3176         struct intel_plane_state *intel_state =
3177                 to_intel_plane_state(plane_state);
3178         struct drm_framebuffer *fb;
3179
3180         if (!plane_config->fb)
3181                 return;
3182
3183         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
3184                 fb = &plane_config->fb->base;
3185                 goto valid_fb;
3186         }
3187
3188         kfree(plane_config->fb);
3189
3190         /*
3191          * Failed to alloc the obj, check to see if we should share
3192          * an fb with another CRTC instead
3193          */
3194         for_each_crtc(dev, c) {
3195                 struct intel_plane_state *state;
3196
3197                 if (c == &intel_crtc->base)
3198                         continue;
3199
3200                 if (!to_intel_crtc(c)->active)
3201                         continue;
3202
3203                 state = to_intel_plane_state(c->primary->state);
3204                 if (!state->vma)
3205                         continue;
3206
3207                 if (intel_plane_ggtt_offset(state) == plane_config->base) {
3208                         fb = state->base.fb;
3209                         drm_framebuffer_get(fb);
3210                         goto valid_fb;
3211                 }
3212         }
3213
3214         /*
3215          * We've failed to reconstruct the BIOS FB.  Current display state
3216          * indicates that the primary plane is visible, but has a NULL FB,
3217          * which will lead to problems later if we don't fix it up.  The
3218          * simplest solution is to just disable the primary plane now and
3219          * pretend the BIOS never had it enabled.
3220          */
3221         intel_plane_disable_noatomic(intel_crtc, intel_plane);
3222
3223         return;
3224
3225 valid_fb:
3226         intel_state->base.rotation = plane_config->rotation;
3227         intel_fill_fb_ggtt_view(&intel_state->view, fb,
3228                                 intel_state->base.rotation);
3229         intel_state->color_plane[0].stride =
3230                 intel_fb_pitch(fb, 0, intel_state->base.rotation);
3231
3232         mutex_lock(&dev->struct_mutex);
3233         intel_state->vma =
3234                 intel_pin_and_fence_fb_obj(fb,
3235                                            &intel_state->view,
3236                                            intel_plane_uses_fence(intel_state),
3237                                            &intel_state->flags);
3238         mutex_unlock(&dev->struct_mutex);
3239         if (IS_ERR(intel_state->vma)) {
3240                 DRM_ERROR("failed to pin boot fb on pipe %d: %li\n",
3241                           intel_crtc->pipe, PTR_ERR(intel_state->vma));
3242
3243                 intel_state->vma = NULL;
3244                 drm_framebuffer_put(fb);
3245                 return;
3246         }
3247
3248         obj = intel_fb_obj(fb);
3249         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
3250
3251         plane_state->src_x = 0;
3252         plane_state->src_y = 0;
3253         plane_state->src_w = fb->width << 16;
3254         plane_state->src_h = fb->height << 16;
3255
3256         plane_state->crtc_x = 0;
3257         plane_state->crtc_y = 0;
3258         plane_state->crtc_w = fb->width;
3259         plane_state->crtc_h = fb->height;
3260
3261         intel_state->base.src = drm_plane_state_src(plane_state);
3262         intel_state->base.dst = drm_plane_state_dest(plane_state);
3263
3264         if (i915_gem_object_is_tiled(obj))
3265                 dev_priv->preserve_bios_swizzle = true;
3266
3267         plane_state->fb = fb;
3268         plane_state->crtc = &intel_crtc->base;
3269
3270         atomic_or(to_intel_plane(primary)->frontbuffer_bit,
3271                   &obj->frontbuffer_bits);
3272 }
3273
3274 static int skl_max_plane_width(const struct drm_framebuffer *fb,
3275                                int color_plane,
3276                                unsigned int rotation)
3277 {
3278         int cpp = fb->format->cpp[color_plane];
3279
3280         switch (fb->modifier) {
3281         case DRM_FORMAT_MOD_LINEAR:
3282         case I915_FORMAT_MOD_X_TILED:
3283                 return 4096;
3284         case I915_FORMAT_MOD_Y_TILED_CCS:
3285         case I915_FORMAT_MOD_Yf_TILED_CCS:
3286                 /* FIXME AUX plane? */
3287         case I915_FORMAT_MOD_Y_TILED:
3288         case I915_FORMAT_MOD_Yf_TILED:
3289                 if (cpp == 8)
3290                         return 2048;
3291                 else
3292                         return 4096;
3293         default:
3294                 MISSING_CASE(fb->modifier);
3295                 return 2048;
3296         }
3297 }
3298
3299 static int glk_max_plane_width(const struct drm_framebuffer *fb,
3300                                int color_plane,
3301                                unsigned int rotation)
3302 {
3303         int cpp = fb->format->cpp[color_plane];
3304
3305         switch (fb->modifier) {
3306         case DRM_FORMAT_MOD_LINEAR:
3307         case I915_FORMAT_MOD_X_TILED:
3308                 if (cpp == 8)
3309                         return 4096;
3310                 else
3311                         return 5120;
3312         case I915_FORMAT_MOD_Y_TILED_CCS:
3313         case I915_FORMAT_MOD_Yf_TILED_CCS:
3314                 /* FIXME AUX plane? */
3315         case I915_FORMAT_MOD_Y_TILED:
3316         case I915_FORMAT_MOD_Yf_TILED:
3317                 if (cpp == 8)
3318                         return 2048;
3319                 else
3320                         return 5120;
3321         default:
3322                 MISSING_CASE(fb->modifier);
3323                 return 2048;
3324         }
3325 }
3326
3327 static int icl_max_plane_width(const struct drm_framebuffer *fb,
3328                                int color_plane,
3329                                unsigned int rotation)
3330 {
3331         return 5120;
3332 }
3333
3334 static bool skl_check_main_ccs_coordinates(struct intel_plane_state *plane_state,
3335                                            int main_x, int main_y, u32 main_offset)
3336 {
3337         const struct drm_framebuffer *fb = plane_state->base.fb;
3338         int hsub = fb->format->hsub;
3339         int vsub = fb->format->vsub;
3340         int aux_x = plane_state->color_plane[1].x;
3341         int aux_y = plane_state->color_plane[1].y;
3342         u32 aux_offset = plane_state->color_plane[1].offset;
3343         u32 alignment = intel_surf_alignment(fb, 1);
3344
3345         while (aux_offset >= main_offset && aux_y <= main_y) {
3346                 int x, y;
3347
3348                 if (aux_x == main_x && aux_y == main_y)
3349                         break;
3350
3351                 if (aux_offset == 0)
3352                         break;
3353
3354                 x = aux_x / hsub;
3355                 y = aux_y / vsub;
3356                 aux_offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 1,
3357                                                                aux_offset, aux_offset - alignment);
3358                 aux_x = x * hsub + aux_x % hsub;
3359                 aux_y = y * vsub + aux_y % vsub;
3360         }
3361
3362         if (aux_x != main_x || aux_y != main_y)
3363                 return false;
3364
3365         plane_state->color_plane[1].offset = aux_offset;
3366         plane_state->color_plane[1].x = aux_x;
3367         plane_state->color_plane[1].y = aux_y;
3368
3369         return true;
3370 }
3371
3372 static int skl_check_main_surface(struct intel_plane_state *plane_state)
3373 {
3374         struct drm_i915_private *dev_priv = to_i915(plane_state->base.plane->dev);
3375         const struct drm_framebuffer *fb = plane_state->base.fb;
3376         unsigned int rotation = plane_state->base.rotation;
3377         int x = plane_state->base.src.x1 >> 16;
3378         int y = plane_state->base.src.y1 >> 16;
3379         int w = drm_rect_width(&plane_state->base.src) >> 16;
3380         int h = drm_rect_height(&plane_state->base.src) >> 16;
3381         int max_width;
3382         int max_height = 4096;
3383         u32 alignment, offset, aux_offset = plane_state->color_plane[1].offset;
3384
3385         if (INTEL_GEN(dev_priv) >= 11)
3386                 max_width = icl_max_plane_width(fb, 0, rotation);
3387         else if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv))
3388                 max_width = glk_max_plane_width(fb, 0, rotation);
3389         else
3390                 max_width = skl_max_plane_width(fb, 0, rotation);
3391
3392         if (w > max_width || h > max_height) {
3393                 DRM_DEBUG_KMS("requested Y/RGB source size %dx%d too big (limit %dx%d)\n",
3394                               w, h, max_width, max_height);
3395                 return -EINVAL;
3396         }
3397
3398         intel_add_fb_offsets(&x, &y, plane_state, 0);
3399         offset = intel_plane_compute_aligned_offset(&x, &y, plane_state, 0);
3400         alignment = intel_surf_alignment(fb, 0);
3401
3402         /*
3403          * AUX surface offset is specified as the distance from the
3404          * main surface offset, and it must be non-negative. Make
3405          * sure that is what we will get.
3406          */
3407         if (offset > aux_offset)
3408                 offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 0,
3409                                                            offset, aux_offset & ~(alignment - 1));
3410
3411         /*
3412          * When using an X-tiled surface, the plane blows up
3413          * if the x offset + width exceed the stride.
3414          *
3415          * TODO: linear and Y-tiled seem fine, Yf untested,
3416          */
3417         if (fb->modifier == I915_FORMAT_MOD_X_TILED) {
3418                 int cpp = fb->format->cpp[0];
3419
3420                 while ((x + w) * cpp > plane_state->color_plane[0].stride) {
3421                         if (offset == 0) {
3422                                 DRM_DEBUG_KMS("Unable to find suitable display surface offset due to X-tiling\n");
3423                                 return -EINVAL;
3424                         }
3425
3426                         offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 0,
3427                                                                    offset, offset - alignment);
3428                 }
3429         }
3430
3431         /*
3432          * CCS AUX surface doesn't have its own x/y offsets, we must make sure
3433          * they match with the main surface x/y offsets.
3434          */
3435         if (is_ccs_modifier(fb->modifier)) {
3436                 while (!skl_check_main_ccs_coordinates(plane_state, x, y, offset)) {
3437                         if (offset == 0)
3438                                 break;
3439
3440                         offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 0,
3441                                                                    offset, offset - alignment);
3442                 }
3443
3444                 if (x != plane_state->color_plane[1].x || y != plane_state->color_plane[1].y) {
3445                         DRM_DEBUG_KMS("Unable to find suitable display surface offset due to CCS\n");
3446                         return -EINVAL;
3447                 }
3448         }
3449
3450         plane_state->color_plane[0].offset = offset;
3451         plane_state->color_plane[0].x = x;
3452         plane_state->color_plane[0].y = y;
3453
3454         /*
3455          * Put the final coordinates back so that the src
3456          * coordinate checks will see the right values.
3457          */
3458         drm_rect_translate(&plane_state->base.src,
3459                            (x << 16) - plane_state->base.src.x1,
3460                            (y << 16) - plane_state->base.src.y1);
3461
3462         return 0;
3463 }
3464
3465 static int skl_check_nv12_aux_surface(struct intel_plane_state *plane_state)
3466 {
3467         const struct drm_framebuffer *fb = plane_state->base.fb;
3468         unsigned int rotation = plane_state->base.rotation;
3469         int max_width = skl_max_plane_width(fb, 1, rotation);
3470         int max_height = 4096;
3471         int x = plane_state->base.src.x1 >> 17;
3472         int y = plane_state->base.src.y1 >> 17;
3473         int w = drm_rect_width(&plane_state->base.src) >> 17;
3474         int h = drm_rect_height(&plane_state->base.src) >> 17;
3475         u32 offset;
3476
3477         intel_add_fb_offsets(&x, &y, plane_state, 1);
3478         offset = intel_plane_compute_aligned_offset(&x, &y, plane_state, 1);
3479
3480         /* FIXME not quite sure how/if these apply to the chroma plane */
3481         if (w > max_width || h > max_height) {
3482                 DRM_DEBUG_KMS("CbCr source size %dx%d too big (limit %dx%d)\n",
3483                               w, h, max_width, max_height);
3484                 return -EINVAL;
3485         }
3486
3487         plane_state->color_plane[1].offset = offset;
3488         plane_state->color_plane[1].x = x;
3489         plane_state->color_plane[1].y = y;
3490
3491         return 0;
3492 }
3493
3494 static int skl_check_ccs_aux_surface(struct intel_plane_state *plane_state)
3495 {
3496         const struct drm_framebuffer *fb = plane_state->base.fb;
3497         int src_x = plane_state->base.src.x1 >> 16;
3498         int src_y = plane_state->base.src.y1 >> 16;
3499         int hsub = fb->format->hsub;
3500         int vsub = fb->format->vsub;
3501         int x = src_x / hsub;
3502         int y = src_y / vsub;
3503         u32 offset;
3504
3505         intel_add_fb_offsets(&x, &y, plane_state, 1);
3506         offset = intel_plane_compute_aligned_offset(&x, &y, plane_state, 1);
3507
3508         plane_state->color_plane[1].offset = offset;
3509         plane_state->color_plane[1].x = x * hsub + src_x % hsub;
3510         plane_state->color_plane[1].y = y * vsub + src_y % vsub;
3511
3512         return 0;
3513 }
3514
3515 int skl_check_plane_surface(struct intel_plane_state *plane_state)
3516 {
3517         const struct drm_framebuffer *fb = plane_state->base.fb;
3518         int ret;
3519
3520         ret = intel_plane_compute_gtt(plane_state);
3521         if (ret)
3522                 return ret;
3523
3524         if (!plane_state->base.visible)
3525                 return 0;
3526
3527         /*
3528          * Handle the AUX surface first since
3529          * the main surface setup depends on it.
3530          */
3531         if (is_planar_yuv_format(fb->format->format)) {
3532                 ret = skl_check_nv12_aux_surface(plane_state);
3533                 if (ret)
3534                         return ret;
3535         } else if (is_ccs_modifier(fb->modifier)) {
3536                 ret = skl_check_ccs_aux_surface(plane_state);
3537                 if (ret)
3538                         return ret;
3539         } else {
3540                 plane_state->color_plane[1].offset = ~0xfff;
3541                 plane_state->color_plane[1].x = 0;
3542                 plane_state->color_plane[1].y = 0;
3543         }
3544
3545         ret = skl_check_main_surface(plane_state);
3546         if (ret)
3547                 return ret;
3548
3549         return 0;
3550 }
3551
3552 unsigned int
3553 i9xx_plane_max_stride(struct intel_plane *plane,
3554                       u32 pixel_format, u64 modifier,
3555                       unsigned int rotation)
3556 {
3557         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3558
3559         if (!HAS_GMCH(dev_priv)) {
3560                 return 32*1024;
3561         } else if (INTEL_GEN(dev_priv) >= 4) {
3562                 if (modifier == I915_FORMAT_MOD_X_TILED)
3563                         return 16*1024;
3564                 else
3565                         return 32*1024;
3566         } else if (INTEL_GEN(dev_priv) >= 3) {
3567                 if (modifier == I915_FORMAT_MOD_X_TILED)
3568                         return 8*1024;
3569                 else
3570                         return 16*1024;
3571         } else {
3572                 if (plane->i9xx_plane == PLANE_C)
3573                         return 4*1024;
3574                 else
3575                         return 8*1024;
3576         }
3577 }
3578
3579 static u32 i9xx_plane_ctl_crtc(const struct intel_crtc_state *crtc_state)
3580 {
3581         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
3582         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
3583         u32 dspcntr = 0;
3584
3585         if (crtc_state->gamma_enable)
3586                 dspcntr |= DISPPLANE_GAMMA_ENABLE;
3587
3588         if (crtc_state->csc_enable)
3589                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
3590
3591         if (INTEL_GEN(dev_priv) < 5)
3592                 dspcntr |= DISPPLANE_SEL_PIPE(crtc->pipe);
3593
3594         return dspcntr;
3595 }
3596
3597 static u32 i9xx_plane_ctl(const struct intel_crtc_state *crtc_state,
3598                           const struct intel_plane_state *plane_state)
3599 {
3600         struct drm_i915_private *dev_priv =
3601                 to_i915(plane_state->base.plane->dev);
3602         const struct drm_framebuffer *fb = plane_state->base.fb;
3603         unsigned int rotation = plane_state->base.rotation;
3604         u32 dspcntr;
3605
3606         dspcntr = DISPLAY_PLANE_ENABLE;
3607
3608         if (IS_G4X(dev_priv) || IS_GEN(dev_priv, 5) ||
3609             IS_GEN(dev_priv, 6) || IS_IVYBRIDGE(dev_priv))
3610                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
3611
3612         switch (fb->format->format) {
3613         case DRM_FORMAT_C8:
3614                 dspcntr |= DISPPLANE_8BPP;
3615                 break;
3616         case DRM_FORMAT_XRGB1555:
3617                 dspcntr |= DISPPLANE_BGRX555;
3618                 break;
3619         case DRM_FORMAT_RGB565:
3620                 dspcntr |= DISPPLANE_BGRX565;
3621                 break;
3622         case DRM_FORMAT_XRGB8888:
3623                 dspcntr |= DISPPLANE_BGRX888;
3624                 break;
3625         case DRM_FORMAT_XBGR8888:
3626                 dspcntr |= DISPPLANE_RGBX888;
3627                 break;
3628         case DRM_FORMAT_XRGB2101010:
3629                 dspcntr |= DISPPLANE_BGRX101010;
3630                 break;
3631         case DRM_FORMAT_XBGR2101010:
3632                 dspcntr |= DISPPLANE_RGBX101010;
3633                 break;
3634         default:
3635                 MISSING_CASE(fb->format->format);
3636                 return 0;
3637         }
3638
3639         if (INTEL_GEN(dev_priv) >= 4 &&
3640             fb->modifier == I915_FORMAT_MOD_X_TILED)
3641                 dspcntr |= DISPPLANE_TILED;
3642
3643         if (rotation & DRM_MODE_ROTATE_180)
3644                 dspcntr |= DISPPLANE_ROTATE_180;
3645
3646         if (rotation & DRM_MODE_REFLECT_X)
3647                 dspcntr |= DISPPLANE_MIRROR;
3648
3649         return dspcntr;
3650 }
3651
3652 int i9xx_check_plane_surface(struct intel_plane_state *plane_state)
3653 {
3654         struct drm_i915_private *dev_priv =
3655                 to_i915(plane_state->base.plane->dev);
3656         int src_x, src_y;
3657         u32 offset;
3658         int ret;
3659
3660         ret = intel_plane_compute_gtt(plane_state);
3661         if (ret)
3662                 return ret;
3663
3664         if (!plane_state->base.visible)
3665                 return 0;
3666
3667         src_x = plane_state->base.src.x1 >> 16;
3668         src_y = plane_state->base.src.y1 >> 16;
3669
3670         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
3671
3672         if (INTEL_GEN(dev_priv) >= 4)
3673                 offset = intel_plane_compute_aligned_offset(&src_x, &src_y,
3674                                                             plane_state, 0);
3675         else
3676                 offset = 0;
3677
3678         /*
3679          * Put the final coordinates back so that the src
3680          * coordinate checks will see the right values.
3681          */
3682         drm_rect_translate(&plane_state->base.src,
3683                            (src_x << 16) - plane_state->base.src.x1,
3684                            (src_y << 16) - plane_state->base.src.y1);
3685
3686         /* HSW/BDW do this automagically in hardware */
3687         if (!IS_HASWELL(dev_priv) && !IS_BROADWELL(dev_priv)) {
3688                 unsigned int rotation = plane_state->base.rotation;
3689                 int src_w = drm_rect_width(&plane_state->base.src) >> 16;
3690                 int src_h = drm_rect_height(&plane_state->base.src) >> 16;
3691
3692                 if (rotation & DRM_MODE_ROTATE_180) {
3693                         src_x += src_w - 1;
3694                         src_y += src_h - 1;
3695                 } else if (rotation & DRM_MODE_REFLECT_X) {
3696                         src_x += src_w - 1;
3697                 }
3698         }
3699
3700         plane_state->color_plane[0].offset = offset;
3701         plane_state->color_plane[0].x = src_x;
3702         plane_state->color_plane[0].y = src_y;
3703
3704         return 0;
3705 }
3706
3707 static int
3708 i9xx_plane_check(struct intel_crtc_state *crtc_state,
3709                  struct intel_plane_state *plane_state)
3710 {
3711         int ret;
3712
3713         ret = chv_plane_check_rotation(plane_state);
3714         if (ret)
3715                 return ret;
3716
3717         ret = drm_atomic_helper_check_plane_state(&plane_state->base,
3718                                                   &crtc_state->base,
3719                                                   DRM_PLANE_HELPER_NO_SCALING,
3720                                                   DRM_PLANE_HELPER_NO_SCALING,
3721                                                   false, true);
3722         if (ret)
3723                 return ret;
3724
3725         ret = i9xx_check_plane_surface(plane_state);
3726         if (ret)
3727                 return ret;
3728
3729         if (!plane_state->base.visible)
3730                 return 0;
3731
3732         ret = intel_plane_check_src_coordinates(plane_state);
3733         if (ret)
3734                 return ret;
3735
3736         plane_state->ctl = i9xx_plane_ctl(crtc_state, plane_state);
3737
3738         return 0;
3739 }
3740
3741 static void i9xx_update_plane(struct intel_plane *plane,
3742                               const struct intel_crtc_state *crtc_state,
3743                               const struct intel_plane_state *plane_state)
3744 {
3745         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3746         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3747         u32 linear_offset;
3748         int x = plane_state->color_plane[0].x;
3749         int y = plane_state->color_plane[0].y;
3750         unsigned long irqflags;
3751         u32 dspaddr_offset;
3752         u32 dspcntr;
3753
3754         dspcntr = plane_state->ctl | i9xx_plane_ctl_crtc(crtc_state);
3755
3756         linear_offset = intel_fb_xy_to_linear(x, y, plane_state, 0);
3757
3758         if (INTEL_GEN(dev_priv) >= 4)
3759                 dspaddr_offset = plane_state->color_plane[0].offset;
3760         else
3761                 dspaddr_offset = linear_offset;
3762
3763         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3764
3765         I915_WRITE_FW(DSPSTRIDE(i9xx_plane), plane_state->color_plane[0].stride);
3766
3767         if (INTEL_GEN(dev_priv) < 4) {
3768                 /* pipesrc and dspsize control the size that is scaled from,
3769                  * which should always be the user's requested size.
3770                  */
3771                 I915_WRITE_FW(DSPPOS(i9xx_plane), 0);
3772                 I915_WRITE_FW(DSPSIZE(i9xx_plane),
3773                               ((crtc_state->pipe_src_h - 1) << 16) |
3774                               (crtc_state->pipe_src_w - 1));
3775         } else if (IS_CHERRYVIEW(dev_priv) && i9xx_plane == PLANE_B) {
3776                 I915_WRITE_FW(PRIMPOS(i9xx_plane), 0);
3777                 I915_WRITE_FW(PRIMSIZE(i9xx_plane),
3778                               ((crtc_state->pipe_src_h - 1) << 16) |
3779                               (crtc_state->pipe_src_w - 1));
3780                 I915_WRITE_FW(PRIMCNSTALPHA(i9xx_plane), 0);
3781         }
3782
3783         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
3784                 I915_WRITE_FW(DSPOFFSET(i9xx_plane), (y << 16) | x);
3785         } else if (INTEL_GEN(dev_priv) >= 4) {
3786                 I915_WRITE_FW(DSPLINOFF(i9xx_plane), linear_offset);
3787                 I915_WRITE_FW(DSPTILEOFF(i9xx_plane), (y << 16) | x);
3788         }
3789
3790         /*
3791          * The control register self-arms if the plane was previously
3792          * disabled. Try to make the plane enable atomic by writing
3793          * the control register just before the surface register.
3794          */
3795         I915_WRITE_FW(DSPCNTR(i9xx_plane), dspcntr);
3796         if (INTEL_GEN(dev_priv) >= 4)
3797                 I915_WRITE_FW(DSPSURF(i9xx_plane),
3798                               intel_plane_ggtt_offset(plane_state) +
3799                               dspaddr_offset);
3800         else
3801                 I915_WRITE_FW(DSPADDR(i9xx_plane),
3802                               intel_plane_ggtt_offset(plane_state) +
3803                               dspaddr_offset);
3804
3805         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3806 }
3807
3808 static void i9xx_disable_plane(struct intel_plane *plane,
3809                                const struct intel_crtc_state *crtc_state)
3810 {
3811         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3812         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3813         unsigned long irqflags;
3814         u32 dspcntr;
3815
3816         /*
3817          * DSPCNTR pipe gamma enable on g4x+ and pipe csc
3818          * enable on ilk+ affect the pipe bottom color as
3819          * well, so we must configure them even if the plane
3820          * is disabled.
3821          *
3822          * On pre-g4x there is no way to gamma correct the
3823          * pipe bottom color but we'll keep on doing this
3824          * anyway so that the crtc state readout works correctly.
3825          */
3826         dspcntr = i9xx_plane_ctl_crtc(crtc_state);
3827
3828         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3829
3830         I915_WRITE_FW(DSPCNTR(i9xx_plane), dspcntr);
3831         if (INTEL_GEN(dev_priv) >= 4)
3832                 I915_WRITE_FW(DSPSURF(i9xx_plane), 0);
3833         else
3834                 I915_WRITE_FW(DSPADDR(i9xx_plane), 0);
3835
3836         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3837 }
3838
3839 static bool i9xx_plane_get_hw_state(struct intel_plane *plane,
3840                                     enum pipe *pipe)
3841 {
3842         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3843         enum intel_display_power_domain power_domain;
3844         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3845         intel_wakeref_t wakeref;
3846         bool ret;
3847         u32 val;
3848
3849         /*
3850          * Not 100% correct for planes that can move between pipes,
3851          * but that's only the case for gen2-4 which don't have any
3852          * display power wells.
3853          */
3854         power_domain = POWER_DOMAIN_PIPE(plane->pipe);
3855         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
3856         if (!wakeref)
3857                 return false;
3858
3859         val = I915_READ(DSPCNTR(i9xx_plane));
3860
3861         ret = val & DISPLAY_PLANE_ENABLE;
3862
3863         if (INTEL_GEN(dev_priv) >= 5)
3864                 *pipe = plane->pipe;
3865         else
3866                 *pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
3867                         DISPPLANE_SEL_PIPE_SHIFT;
3868
3869         intel_display_power_put(dev_priv, power_domain, wakeref);
3870
3871         return ret;
3872 }
3873
3874 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
3875 {
3876         struct drm_device *dev = intel_crtc->base.dev;
3877         struct drm_i915_private *dev_priv = to_i915(dev);
3878
3879         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
3880         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
3881         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
3882 }
3883
3884 /*
3885  * This function detaches (aka. unbinds) unused scalers in hardware
3886  */
3887 static void skl_detach_scalers(const struct intel_crtc_state *crtc_state)
3888 {
3889         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
3890         const struct intel_crtc_scaler_state *scaler_state =
3891                 &crtc_state->scaler_state;
3892         int i;
3893
3894         /* loop through and disable scalers that aren't in use */
3895         for (i = 0; i < intel_crtc->num_scalers; i++) {
3896                 if (!scaler_state->scalers[i].in_use)
3897                         skl_detach_scaler(intel_crtc, i);
3898         }
3899 }
3900
3901 static unsigned int skl_plane_stride_mult(const struct drm_framebuffer *fb,
3902                                           int color_plane, unsigned int rotation)
3903 {
3904         /*
3905          * The stride is either expressed as a multiple of 64 bytes chunks for
3906          * linear buffers or in number of tiles for tiled buffers.
3907          */
3908         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
3909                 return 64;
3910         else if (drm_rotation_90_or_270(rotation))
3911                 return intel_tile_height(fb, color_plane);
3912         else
3913                 return intel_tile_width_bytes(fb, color_plane);
3914 }
3915
3916 u32 skl_plane_stride(const struct intel_plane_state *plane_state,
3917                      int color_plane)
3918 {
3919         const struct drm_framebuffer *fb = plane_state->base.fb;
3920         unsigned int rotation = plane_state->base.rotation;
3921         u32 stride = plane_state->color_plane[color_plane].stride;
3922
3923         if (color_plane >= fb->format->num_planes)
3924                 return 0;
3925
3926         return stride / skl_plane_stride_mult(fb, color_plane, rotation);
3927 }
3928
3929 static u32 skl_plane_ctl_format(u32 pixel_format)
3930 {
3931         switch (pixel_format) {
3932         case DRM_FORMAT_C8:
3933                 return PLANE_CTL_FORMAT_INDEXED;
3934         case DRM_FORMAT_RGB565:
3935                 return PLANE_CTL_FORMAT_RGB_565;
3936         case DRM_FORMAT_XBGR8888:
3937         case DRM_FORMAT_ABGR8888:
3938                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
3939         case DRM_FORMAT_XRGB8888:
3940         case DRM_FORMAT_ARGB8888:
3941                 return PLANE_CTL_FORMAT_XRGB_8888;
3942         case DRM_FORMAT_XRGB2101010:
3943                 return PLANE_CTL_FORMAT_XRGB_2101010;
3944         case DRM_FORMAT_XBGR2101010:
3945                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
3946         case DRM_FORMAT_XBGR16161616F:
3947         case DRM_FORMAT_ABGR16161616F:
3948                 return PLANE_CTL_FORMAT_XRGB_16161616F | PLANE_CTL_ORDER_RGBX;
3949         case DRM_FORMAT_XRGB16161616F:
3950         case DRM_FORMAT_ARGB16161616F:
3951                 return PLANE_CTL_FORMAT_XRGB_16161616F;
3952         case DRM_FORMAT_YUYV:
3953                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
3954         case DRM_FORMAT_YVYU:
3955                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
3956         case DRM_FORMAT_UYVY:
3957                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
3958         case DRM_FORMAT_VYUY:
3959                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
3960         case DRM_FORMAT_NV12:
3961                 return PLANE_CTL_FORMAT_NV12;
3962         case DRM_FORMAT_P010:
3963                 return PLANE_CTL_FORMAT_P010;
3964         case DRM_FORMAT_P012:
3965                 return PLANE_CTL_FORMAT_P012;
3966         case DRM_FORMAT_P016:
3967                 return PLANE_CTL_FORMAT_P016;
3968         case DRM_FORMAT_Y210:
3969                 return PLANE_CTL_FORMAT_Y210;
3970         case DRM_FORMAT_Y212:
3971                 return PLANE_CTL_FORMAT_Y212;
3972         case DRM_FORMAT_Y216:
3973                 return PLANE_CTL_FORMAT_Y216;
3974         case DRM_FORMAT_XVYU2101010:
3975                 return PLANE_CTL_FORMAT_Y410;
3976         case DRM_FORMAT_XVYU12_16161616:
3977                 return PLANE_CTL_FORMAT_Y412;
3978         case DRM_FORMAT_XVYU16161616:
3979                 return PLANE_CTL_FORMAT_Y416;
3980         default:
3981                 MISSING_CASE(pixel_format);
3982         }
3983
3984         return 0;
3985 }
3986
3987 static u32 skl_plane_ctl_alpha(const struct intel_plane_state *plane_state)
3988 {
3989         if (!plane_state->base.fb->format->has_alpha)
3990                 return PLANE_CTL_ALPHA_DISABLE;
3991
3992         switch (plane_state->base.pixel_blend_mode) {
3993         case DRM_MODE_BLEND_PIXEL_NONE:
3994                 return PLANE_CTL_ALPHA_DISABLE;
3995         case DRM_MODE_BLEND_PREMULTI:
3996                 return PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3997         case DRM_MODE_BLEND_COVERAGE:
3998                 return PLANE_CTL_ALPHA_HW_PREMULTIPLY;
3999         default:
4000                 MISSING_CASE(plane_state->base.pixel_blend_mode);
4001                 return PLANE_CTL_ALPHA_DISABLE;
4002         }
4003 }
4004
4005 static u32 glk_plane_color_ctl_alpha(const struct intel_plane_state *plane_state)
4006 {
4007         if (!plane_state->base.fb->format->has_alpha)
4008                 return PLANE_COLOR_ALPHA_DISABLE;
4009
4010         switch (plane_state->base.pixel_blend_mode) {
4011         case DRM_MODE_BLEND_PIXEL_NONE:
4012                 return PLANE_COLOR_ALPHA_DISABLE;
4013         case DRM_MODE_BLEND_PREMULTI:
4014                 return PLANE_COLOR_ALPHA_SW_PREMULTIPLY;
4015         case DRM_MODE_BLEND_COVERAGE:
4016                 return PLANE_COLOR_ALPHA_HW_PREMULTIPLY;
4017         default:
4018                 MISSING_CASE(plane_state->base.pixel_blend_mode);
4019                 return PLANE_COLOR_ALPHA_DISABLE;
4020         }
4021 }
4022
4023 static u32 skl_plane_ctl_tiling(u64 fb_modifier)
4024 {
4025         switch (fb_modifier) {
4026         case DRM_FORMAT_MOD_LINEAR:
4027                 break;
4028         case I915_FORMAT_MOD_X_TILED:
4029                 return PLANE_CTL_TILED_X;
4030         case I915_FORMAT_MOD_Y_TILED:
4031                 return PLANE_CTL_TILED_Y;
4032         case I915_FORMAT_MOD_Y_TILED_CCS:
4033                 return PLANE_CTL_TILED_Y | PLANE_CTL_RENDER_DECOMPRESSION_ENABLE;
4034         case I915_FORMAT_MOD_Yf_TILED:
4035                 return PLANE_CTL_TILED_YF;
4036         case I915_FORMAT_MOD_Yf_TILED_CCS:
4037                 return PLANE_CTL_TILED_YF | PLANE_CTL_RENDER_DECOMPRESSION_ENABLE;
4038         default:
4039                 MISSING_CASE(fb_modifier);
4040         }
4041
4042         return 0;
4043 }
4044
4045 static u32 skl_plane_ctl_rotate(unsigned int rotate)
4046 {
4047         switch (rotate) {
4048         case DRM_MODE_ROTATE_0:
4049                 break;
4050         /*
4051          * DRM_MODE_ROTATE_ is counter clockwise to stay compatible with Xrandr
4052          * while i915 HW rotation is clockwise, thats why this swapping.
4053          */
4054         case DRM_MODE_ROTATE_90:
4055                 return PLANE_CTL_ROTATE_270;
4056         case DRM_MODE_ROTATE_180:
4057                 return PLANE_CTL_ROTATE_180;
4058         case DRM_MODE_ROTATE_270:
4059                 return PLANE_CTL_ROTATE_90;
4060         default:
4061                 MISSING_CASE(rotate);
4062         }
4063
4064         return 0;
4065 }
4066
4067 static u32 cnl_plane_ctl_flip(unsigned int reflect)
4068 {
4069         switch (reflect) {
4070         case 0:
4071                 break;
4072         case DRM_MODE_REFLECT_X:
4073                 return PLANE_CTL_FLIP_HORIZONTAL;
4074         case DRM_MODE_REFLECT_Y:
4075         default:
4076                 MISSING_CASE(reflect);
4077         }
4078
4079         return 0;
4080 }
4081
4082 u32 skl_plane_ctl_crtc(const struct intel_crtc_state *crtc_state)
4083 {
4084         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
4085         u32 plane_ctl = 0;
4086
4087         if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv))
4088                 return plane_ctl;
4089
4090         if (crtc_state->gamma_enable)
4091                 plane_ctl |= PLANE_CTL_PIPE_GAMMA_ENABLE;
4092
4093         if (crtc_state->csc_enable)
4094                 plane_ctl |= PLANE_CTL_PIPE_CSC_ENABLE;
4095
4096         return plane_ctl;
4097 }
4098
4099 u32 skl_plane_ctl(const struct intel_crtc_state *crtc_state,
4100                   const struct intel_plane_state *plane_state)
4101 {
4102         struct drm_i915_private *dev_priv =
4103                 to_i915(plane_state->base.plane->dev);
4104         const struct drm_framebuffer *fb = plane_state->base.fb;
4105         unsigned int rotation = plane_state->base.rotation;
4106         const struct drm_intel_sprite_colorkey *key = &plane_state->ckey;
4107         u32 plane_ctl;
4108
4109         plane_ctl = PLANE_CTL_ENABLE;
4110
4111         if (INTEL_GEN(dev_priv) < 10 && !IS_GEMINILAKE(dev_priv)) {
4112                 plane_ctl |= skl_plane_ctl_alpha(plane_state);
4113                 plane_ctl |= PLANE_CTL_PLANE_GAMMA_DISABLE;
4114
4115                 if (plane_state->base.color_encoding == DRM_COLOR_YCBCR_BT709)
4116                         plane_ctl |= PLANE_CTL_YUV_TO_RGB_CSC_FORMAT_BT709;
4117
4118                 if (plane_state->base.color_range == DRM_COLOR_YCBCR_FULL_RANGE)
4119                         plane_ctl |= PLANE_CTL_YUV_RANGE_CORRECTION_DISABLE;
4120         }
4121
4122         plane_ctl |= skl_plane_ctl_format(fb->format->format);
4123         plane_ctl |= skl_plane_ctl_tiling(fb->modifier);
4124         plane_ctl |= skl_plane_ctl_rotate(rotation & DRM_MODE_ROTATE_MASK);
4125
4126         if (INTEL_GEN(dev_priv) >= 10)
4127                 plane_ctl |= cnl_plane_ctl_flip(rotation &
4128                                                 DRM_MODE_REFLECT_MASK);
4129
4130         if (key->flags & I915_SET_COLORKEY_DESTINATION)
4131                 plane_ctl |= PLANE_CTL_KEY_ENABLE_DESTINATION;
4132         else if (key->flags & I915_SET_COLORKEY_SOURCE)
4133                 plane_ctl |= PLANE_CTL_KEY_ENABLE_SOURCE;
4134
4135         return plane_ctl;
4136 }
4137
4138 u32 glk_plane_color_ctl_crtc(const struct intel_crtc_state *crtc_state)
4139 {
4140         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
4141         u32 plane_color_ctl = 0;
4142
4143         if (INTEL_GEN(dev_priv) >= 11)
4144                 return plane_color_ctl;
4145
4146         if (crtc_state->gamma_enable)
4147                 plane_color_ctl |= PLANE_COLOR_PIPE_GAMMA_ENABLE;
4148
4149         if (crtc_state->csc_enable)
4150                 plane_color_ctl |= PLANE_COLOR_PIPE_CSC_ENABLE;
4151
4152         return plane_color_ctl;
4153 }
4154
4155 u32 glk_plane_color_ctl(const struct intel_crtc_state *crtc_state,
4156                         const struct intel_plane_state *plane_state)
4157 {
4158         struct drm_i915_private *dev_priv =
4159                 to_i915(plane_state->base.plane->dev);
4160         const struct drm_framebuffer *fb = plane_state->base.fb;
4161         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
4162         u32 plane_color_ctl = 0;
4163
4164         plane_color_ctl |= PLANE_COLOR_PLANE_GAMMA_DISABLE;
4165         plane_color_ctl |= glk_plane_color_ctl_alpha(plane_state);
4166
4167         if (fb->format->is_yuv && !icl_is_hdr_plane(dev_priv, plane->id)) {
4168                 if (plane_state->base.color_encoding == DRM_COLOR_YCBCR_BT709)
4169                         plane_color_ctl |= PLANE_COLOR_CSC_MODE_YUV709_TO_RGB709;
4170                 else
4171                         plane_color_ctl |= PLANE_COLOR_CSC_MODE_YUV601_TO_RGB709;
4172
4173                 if (plane_state->base.color_range == DRM_COLOR_YCBCR_FULL_RANGE)
4174                         plane_color_ctl |= PLANE_COLOR_YUV_RANGE_CORRECTION_DISABLE;
4175         } else if (fb->format->is_yuv) {
4176                 plane_color_ctl |= PLANE_COLOR_INPUT_CSC_ENABLE;
4177         }
4178
4179         return plane_color_ctl;
4180 }
4181
4182 static int
4183 __intel_display_resume(struct drm_device *dev,
4184                        struct drm_atomic_state *state,
4185                        struct drm_modeset_acquire_ctx *ctx)
4186 {
4187         struct drm_crtc_state *crtc_state;
4188         struct drm_crtc *crtc;
4189         int i, ret;
4190
4191         intel_modeset_setup_hw_state(dev, ctx);
4192         i915_redisable_vga(to_i915(dev));
4193
4194         if (!state)
4195                 return 0;
4196
4197         /*
4198          * We've duplicated the state, pointers to the old state are invalid.
4199          *
4200          * Don't attempt to use the old state until we commit the duplicated state.
4201          */
4202         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
4203                 /*
4204                  * Force recalculation even if we restore
4205                  * current state. With fast modeset this may not result
4206                  * in a modeset when the state is compatible.
4207                  */
4208                 crtc_state->mode_changed = true;
4209         }
4210
4211         /* ignore any reset values/BIOS leftovers in the WM registers */
4212         if (!HAS_GMCH(to_i915(dev)))
4213                 to_intel_atomic_state(state)->skip_intermediate_wm = true;
4214
4215         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
4216
4217         WARN_ON(ret == -EDEADLK);
4218         return ret;
4219 }
4220
4221 static bool gpu_reset_clobbers_display(struct drm_i915_private *dev_priv)
4222 {
4223         return (INTEL_INFO(dev_priv)->gpu_reset_clobbers_display &&
4224                 intel_has_gpu_reset(dev_priv));
4225 }
4226
4227 void intel_prepare_reset(struct drm_i915_private *dev_priv)
4228 {
4229         struct drm_device *dev = &dev_priv->drm;
4230         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
4231         struct drm_atomic_state *state;
4232         int ret;
4233
4234         /* reset doesn't touch the display */
4235         if (!i915_modparams.force_reset_modeset_test &&
4236             !gpu_reset_clobbers_display(dev_priv))
4237                 return;
4238
4239         /* We have a modeset vs reset deadlock, defensively unbreak it. */
4240         set_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
4241         wake_up_all(&dev_priv->gpu_error.wait_queue);
4242
4243         if (atomic_read(&dev_priv->gpu_error.pending_fb_pin)) {
4244                 DRM_DEBUG_KMS("Modeset potentially stuck, unbreaking through wedging\n");
4245                 i915_gem_set_wedged(dev_priv);
4246         }
4247
4248         /*
4249          * Need mode_config.mutex so that we don't
4250          * trample ongoing ->detect() and whatnot.
4251          */
4252         mutex_lock(&dev->mode_config.mutex);
4253         drm_modeset_acquire_init(ctx, 0);
4254         while (1) {
4255                 ret = drm_modeset_lock_all_ctx(dev, ctx);
4256                 if (ret != -EDEADLK)
4257                         break;
4258
4259                 drm_modeset_backoff(ctx);
4260         }
4261         /*
4262          * Disabling the crtcs gracefully seems nicer. Also the
4263          * g33 docs say we should at least disable all the planes.
4264          */
4265         state = drm_atomic_helper_duplicate_state(dev, ctx);
4266         if (IS_ERR(state)) {
4267                 ret = PTR_ERR(state);
4268                 DRM_ERROR("Duplicating state failed with %i\n", ret);
4269                 return;
4270         }
4271
4272         ret = drm_atomic_helper_disable_all(dev, ctx);
4273         if (ret) {
4274                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
4275                 drm_atomic_state_put(state);
4276                 return;
4277         }
4278
4279         dev_priv->modeset_restore_state = state;
4280         state->acquire_ctx = ctx;
4281 }
4282
4283 void intel_finish_reset(struct drm_i915_private *dev_priv)
4284 {
4285         struct drm_device *dev = &dev_priv->drm;
4286         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
4287         struct drm_atomic_state *state;
4288         int ret;
4289
4290         /* reset doesn't touch the display */
4291         if (!test_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags))
4292                 return;
4293
4294         state = fetch_and_zero(&dev_priv->modeset_restore_state);
4295         if (!state)
4296                 goto unlock;
4297
4298         /* reset doesn't touch the display */
4299         if (!gpu_reset_clobbers_display(dev_priv)) {
4300                 /* for testing only restore the display */
4301                 ret = __intel_display_resume(dev, state, ctx);
4302                 if (ret)
4303                         DRM_ERROR("Restoring old state failed with %i\n", ret);
4304         } else {
4305                 /*
4306                  * The display has been reset as well,
4307                  * so need a full re-initialization.
4308                  */
4309                 intel_pps_unlock_regs_wa(dev_priv);
4310                 intel_modeset_init_hw(dev);
4311                 intel_init_clock_gating(dev_priv);
4312
4313                 spin_lock_irq(&dev_priv->irq_lock);
4314                 if (dev_priv->display.hpd_irq_setup)
4315                         dev_priv->display.hpd_irq_setup(dev_priv);
4316                 spin_unlock_irq(&dev_priv->irq_lock);
4317
4318                 ret = __intel_display_resume(dev, state, ctx);
4319                 if (ret)
4320                         DRM_ERROR("Restoring old state failed with %i\n", ret);
4321
4322                 intel_hpd_init(dev_priv);
4323         }
4324
4325         drm_atomic_state_put(state);
4326 unlock:
4327         drm_modeset_drop_locks(ctx);
4328         drm_modeset_acquire_fini(ctx);
4329         mutex_unlock(&dev->mode_config.mutex);
4330
4331         clear_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
4332 }
4333
4334 static void icl_set_pipe_chicken(struct intel_crtc *crtc)
4335 {
4336         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4337         enum pipe pipe = crtc->pipe;
4338         u32 tmp;
4339
4340         tmp = I915_READ(PIPE_CHICKEN(pipe));
4341
4342         /*
4343          * Display WA #1153: icl
4344          * enable hardware to bypass the alpha math
4345          * and rounding for per-pixel values 00 and 0xff
4346          */
4347         tmp |= PER_PIXEL_ALPHA_BYPASS_EN;
4348         /*
4349          * Display WA # 1605353570: icl
4350          * Set the pixel rounding bit to 1 for allowing
4351          * passthrough of Frame buffer pixels unmodified
4352          * across pipe
4353          */
4354         tmp |= PIXEL_ROUNDING_TRUNC_FB_PASSTHRU;
4355         I915_WRITE(PIPE_CHICKEN(pipe), tmp);
4356 }
4357
4358 static void intel_update_pipe_config(const struct intel_crtc_state *old_crtc_state,
4359                                      const struct intel_crtc_state *new_crtc_state)
4360 {
4361         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
4362         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4363
4364         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
4365         crtc->base.mode = new_crtc_state->base.mode;
4366
4367         /*
4368          * Update pipe size and adjust fitter if needed: the reason for this is
4369          * that in compute_mode_changes we check the native mode (not the pfit
4370          * mode) to see if we can flip rather than do a full mode set. In the
4371          * fastboot case, we'll flip, but if we don't update the pipesrc and
4372          * pfit state, we'll end up with a big fb scanned out into the wrong
4373          * sized surface.
4374          */
4375
4376         I915_WRITE(PIPESRC(crtc->pipe),
4377                    ((new_crtc_state->pipe_src_w - 1) << 16) |
4378                    (new_crtc_state->pipe_src_h - 1));
4379
4380         /* on skylake this is done by detaching scalers */
4381         if (INTEL_GEN(dev_priv) >= 9) {
4382                 skl_detach_scalers(new_crtc_state);
4383
4384                 if (new_crtc_state->pch_pfit.enabled)
4385                         skylake_pfit_enable(new_crtc_state);
4386         } else if (HAS_PCH_SPLIT(dev_priv)) {
4387                 if (new_crtc_state->pch_pfit.enabled)
4388                         ironlake_pfit_enable(new_crtc_state);
4389                 else if (old_crtc_state->pch_pfit.enabled)
4390                         ironlake_pfit_disable(old_crtc_state);
4391         }
4392
4393         if (INTEL_GEN(dev_priv) >= 11)
4394                 icl_set_pipe_chicken(crtc);
4395 }
4396
4397 static void intel_fdi_normal_train(struct intel_crtc *crtc)
4398 {
4399         struct drm_device *dev = crtc->base.dev;
4400         struct drm_i915_private *dev_priv = to_i915(dev);
4401         int pipe = crtc->pipe;
4402         i915_reg_t reg;
4403         u32 temp;
4404
4405         /* enable normal train */
4406         reg = FDI_TX_CTL(pipe);
4407         temp = I915_READ(reg);
4408         if (IS_IVYBRIDGE(dev_priv)) {
4409                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
4410                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
4411         } else {
4412                 temp &= ~FDI_LINK_TRAIN_NONE;
4413                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
4414         }
4415         I915_WRITE(reg, temp);
4416
4417         reg = FDI_RX_CTL(pipe);
4418         temp = I915_READ(reg);
4419         if (HAS_PCH_CPT(dev_priv)) {
4420                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4421                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
4422         } else {
4423                 temp &= ~FDI_LINK_TRAIN_NONE;
4424                 temp |= FDI_LINK_TRAIN_NONE;
4425         }
4426         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
4427
4428         /* wait one idle pattern time */
4429         POSTING_READ(reg);
4430         udelay(1000);
4431
4432         /* IVB wants error correction enabled */
4433         if (IS_IVYBRIDGE(dev_priv))
4434                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
4435                            FDI_FE_ERRC_ENABLE);
4436 }
4437
4438 /* The FDI link training functions for ILK/Ibexpeak. */
4439 static void ironlake_fdi_link_train(struct intel_crtc *crtc,
4440                                     const struct intel_crtc_state *crtc_state)
4441 {
4442         struct drm_device *dev = crtc->base.dev;
4443         struct drm_i915_private *dev_priv = to_i915(dev);
4444         int pipe = crtc->pipe;
4445         i915_reg_t reg;
4446         u32 temp, tries;
4447
4448         /* FDI needs bits from pipe first */
4449         assert_pipe_enabled(dev_priv, pipe);
4450
4451         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4452            for train result */
4453         reg = FDI_RX_IMR(pipe);
4454         temp = I915_READ(reg);
4455         temp &= ~FDI_RX_SYMBOL_LOCK;
4456         temp &= ~FDI_RX_BIT_LOCK;
4457         I915_WRITE(reg, temp);
4458         I915_READ(reg);
4459         udelay(150);
4460
4461         /* enable CPU FDI TX and PCH FDI RX */
4462         reg = FDI_TX_CTL(pipe);
4463         temp = I915_READ(reg);
4464         temp &= ~FDI_DP_PORT_WIDTH_MASK;
4465         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4466         temp &= ~FDI_LINK_TRAIN_NONE;
4467         temp |= FDI_LINK_TRAIN_PATTERN_1;
4468         I915_WRITE(reg, temp | FDI_TX_ENABLE);
4469
4470         reg = FDI_RX_CTL(pipe);
4471         temp = I915_READ(reg);
4472         temp &= ~FDI_LINK_TRAIN_NONE;
4473         temp |= FDI_LINK_TRAIN_PATTERN_1;
4474         I915_WRITE(reg, temp | FDI_RX_ENABLE);
4475
4476         POSTING_READ(reg);
4477         udelay(150);
4478
4479         /* Ironlake workaround, enable clock pointer after FDI enable*/
4480         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
4481         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
4482                    FDI_RX_PHASE_SYNC_POINTER_EN);
4483
4484         reg = FDI_RX_IIR(pipe);
4485         for (tries = 0; tries < 5; tries++) {
4486                 temp = I915_READ(reg);
4487                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4488
4489                 if ((temp & FDI_RX_BIT_LOCK)) {
4490                         DRM_DEBUG_KMS("FDI train 1 done.\n");
4491                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4492                         break;
4493                 }
4494         }
4495         if (tries == 5)
4496                 DRM_ERROR("FDI train 1 fail!\n");
4497
4498         /* Train 2 */
4499         reg = FDI_TX_CTL(pipe);
4500         temp = I915_READ(reg);
4501         temp &= ~FDI_LINK_TRAIN_NONE;
4502         temp |= FDI_LINK_TRAIN_PATTERN_2;
4503         I915_WRITE(reg, temp);
4504
4505         reg = FDI_RX_CTL(pipe);
4506         temp = I915_READ(reg);
4507         temp &= ~FDI_LINK_TRAIN_NONE;
4508         temp |= FDI_LINK_TRAIN_PATTERN_2;
4509         I915_WRITE(reg, temp);
4510
4511         POSTING_READ(reg);
4512         udelay(150);
4513
4514         reg = FDI_RX_IIR(pipe);
4515         for (tries = 0; tries < 5; tries++) {
4516                 temp = I915_READ(reg);
4517                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4518
4519                 if (temp & FDI_RX_SYMBOL_LOCK) {
4520                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4521                         DRM_DEBUG_KMS("FDI train 2 done.\n");
4522                         break;
4523                 }
4524         }
4525         if (tries == 5)
4526                 DRM_ERROR("FDI train 2 fail!\n");
4527
4528         DRM_DEBUG_KMS("FDI train done\n");
4529
4530 }
4531
4532 static const int snb_b_fdi_train_param[] = {
4533         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
4534         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
4535         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
4536         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
4537 };
4538
4539 /* The FDI link training functions for SNB/Cougarpoint. */
4540 static void gen6_fdi_link_train(struct intel_crtc *crtc,
4541                                 const struct intel_crtc_state *crtc_state)
4542 {
4543         struct drm_device *dev = crtc->base.dev;
4544         struct drm_i915_private *dev_priv = to_i915(dev);
4545         int pipe = crtc->pipe;
4546         i915_reg_t reg;
4547         u32 temp, i, retry;
4548
4549         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4550            for train result */
4551         reg = FDI_RX_IMR(pipe);
4552         temp = I915_READ(reg);
4553         temp &= ~FDI_RX_SYMBOL_LOCK;
4554         temp &= ~FDI_RX_BIT_LOCK;
4555         I915_WRITE(reg, temp);
4556
4557         POSTING_READ(reg);
4558         udelay(150);
4559
4560         /* enable CPU FDI TX and PCH FDI RX */
4561         reg = FDI_TX_CTL(pipe);
4562         temp = I915_READ(reg);
4563         temp &= ~FDI_DP_PORT_WIDTH_MASK;
4564         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4565         temp &= ~FDI_LINK_TRAIN_NONE;
4566         temp |= FDI_LINK_TRAIN_PATTERN_1;
4567         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4568         /* SNB-B */
4569         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
4570         I915_WRITE(reg, temp | FDI_TX_ENABLE);
4571
4572         I915_WRITE(FDI_RX_MISC(pipe),
4573                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4574
4575         reg = FDI_RX_CTL(pipe);
4576         temp = I915_READ(reg);
4577         if (HAS_PCH_CPT(dev_priv)) {
4578                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4579                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4580         } else {
4581                 temp &= ~FDI_LINK_TRAIN_NONE;
4582                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4583         }
4584         I915_WRITE(reg, temp | FDI_RX_ENABLE);
4585
4586         POSTING_READ(reg);
4587         udelay(150);
4588
4589         for (i = 0; i < 4; i++) {
4590                 reg = FDI_TX_CTL(pipe);
4591                 temp = I915_READ(reg);
4592                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4593                 temp |= snb_b_fdi_train_param[i];
4594                 I915_WRITE(reg, temp);
4595
4596                 POSTING_READ(reg);
4597                 udelay(500);
4598
4599                 for (retry = 0; retry < 5; retry++) {
4600                         reg = FDI_RX_IIR(pipe);
4601                         temp = I915_READ(reg);
4602                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4603                         if (temp & FDI_RX_BIT_LOCK) {
4604                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4605                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
4606                                 break;
4607                         }
4608                         udelay(50);
4609                 }
4610                 if (retry < 5)
4611                         break;
4612         }
4613         if (i == 4)
4614                 DRM_ERROR("FDI train 1 fail!\n");
4615
4616         /* Train 2 */
4617         reg = FDI_TX_CTL(pipe);
4618         temp = I915_READ(reg);
4619         temp &= ~FDI_LINK_TRAIN_NONE;
4620         temp |= FDI_LINK_TRAIN_PATTERN_2;
4621         if (IS_GEN(dev_priv, 6)) {
4622                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4623                 /* SNB-B */
4624                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
4625         }
4626         I915_WRITE(reg, temp);
4627
4628         reg = FDI_RX_CTL(pipe);
4629         temp = I915_READ(reg);
4630         if (HAS_PCH_CPT(dev_priv)) {
4631                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4632                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4633         } else {
4634                 temp &= ~FDI_LINK_TRAIN_NONE;
4635                 temp |= FDI_LINK_TRAIN_PATTERN_2;
4636         }
4637         I915_WRITE(reg, temp);
4638
4639         POSTING_READ(reg);
4640         udelay(150);
4641
4642         for (i = 0; i < 4; i++) {
4643                 reg = FDI_TX_CTL(pipe);
4644                 temp = I915_READ(reg);
4645                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4646                 temp |= snb_b_fdi_train_param[i];
4647                 I915_WRITE(reg, temp);
4648
4649                 POSTING_READ(reg);
4650                 udelay(500);
4651
4652                 for (retry = 0; retry < 5; retry++) {
4653                         reg = FDI_RX_IIR(pipe);
4654                         temp = I915_READ(reg);
4655                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4656                         if (temp & FDI_RX_SYMBOL_LOCK) {
4657                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4658                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
4659                                 break;
4660                         }
4661                         udelay(50);
4662                 }
4663                 if (retry < 5)
4664                         break;
4665         }
4666         if (i == 4)
4667                 DRM_ERROR("FDI train 2 fail!\n");
4668
4669         DRM_DEBUG_KMS("FDI train done.\n");
4670 }
4671
4672 /* Manual link training for Ivy Bridge A0 parts */
4673 static void ivb_manual_fdi_link_train(struct intel_crtc *crtc,
4674                                       const struct intel_crtc_state *crtc_state)
4675 {
4676         struct drm_device *dev = crtc->base.dev;
4677         struct drm_i915_private *dev_priv = to_i915(dev);
4678         int pipe = crtc->pipe;
4679         i915_reg_t reg;
4680         u32 temp, i, j;
4681
4682         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4683            for train result */
4684         reg = FDI_RX_IMR(pipe);
4685         temp = I915_READ(reg);
4686         temp &= ~FDI_RX_SYMBOL_LOCK;
4687         temp &= ~FDI_RX_BIT_LOCK;
4688         I915_WRITE(reg, temp);
4689
4690         POSTING_READ(reg);
4691         udelay(150);
4692
4693         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
4694                       I915_READ(FDI_RX_IIR(pipe)));
4695
4696         /* Try each vswing and preemphasis setting twice before moving on */
4697         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
4698                 /* disable first in case we need to retry */
4699                 reg = FDI_TX_CTL(pipe);
4700                 temp = I915_READ(reg);
4701                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
4702                 temp &= ~FDI_TX_ENABLE;
4703                 I915_WRITE(reg, temp);
4704
4705                 reg = FDI_RX_CTL(pipe);
4706                 temp = I915_READ(reg);
4707                 temp &= ~FDI_LINK_TRAIN_AUTO;
4708                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4709                 temp &= ~FDI_RX_ENABLE;
4710                 I915_WRITE(reg, temp);
4711
4712                 /* enable CPU FDI TX and PCH FDI RX */
4713                 reg = FDI_TX_CTL(pipe);
4714                 temp = I915_READ(reg);
4715                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
4716                 temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4717                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
4718                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4719                 temp |= snb_b_fdi_train_param[j/2];
4720                 temp |= FDI_COMPOSITE_SYNC;
4721                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
4722
4723                 I915_WRITE(FDI_RX_MISC(pipe),
4724                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4725
4726                 reg = FDI_RX_CTL(pipe);
4727                 temp = I915_READ(reg);
4728                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4729                 temp |= FDI_COMPOSITE_SYNC;
4730                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
4731
4732                 POSTING_READ(reg);
4733                 udelay(1); /* should be 0.5us */
4734
4735                 for (i = 0; i < 4; i++) {
4736                         reg = FDI_RX_IIR(pipe);
4737                         temp = I915_READ(reg);
4738                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4739
4740                         if (temp & FDI_RX_BIT_LOCK ||
4741                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
4742                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4743                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
4744                                               i);
4745                                 break;
4746                         }
4747                         udelay(1); /* should be 0.5us */
4748                 }
4749                 if (i == 4) {
4750                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
4751                         continue;
4752                 }
4753
4754                 /* Train 2 */
4755                 reg = FDI_TX_CTL(pipe);
4756                 temp = I915_READ(reg);
4757                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
4758                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
4759                 I915_WRITE(reg, temp);
4760
4761                 reg = FDI_RX_CTL(pipe);
4762                 temp = I915_READ(reg);
4763                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4764                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4765                 I915_WRITE(reg, temp);
4766
4767                 POSTING_READ(reg);
4768                 udelay(2); /* should be 1.5us */
4769
4770                 for (i = 0; i < 4; i++) {
4771                         reg = FDI_RX_IIR(pipe);
4772                         temp = I915_READ(reg);
4773                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4774
4775                         if (temp & FDI_RX_SYMBOL_LOCK ||
4776                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
4777                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4778                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
4779                                               i);
4780                                 goto train_done;
4781                         }
4782                         udelay(2); /* should be 1.5us */
4783                 }
4784                 if (i == 4)
4785                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
4786         }
4787
4788 train_done:
4789         DRM_DEBUG_KMS("FDI train done.\n");
4790 }
4791
4792 static void ironlake_fdi_pll_enable(const struct intel_crtc_state *crtc_state)
4793 {
4794         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
4795         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
4796         int pipe = intel_crtc->pipe;
4797         i915_reg_t reg;
4798         u32 temp;
4799
4800         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
4801         reg = FDI_RX_CTL(pipe);
4802         temp = I915_READ(reg);
4803         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
4804         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4805         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4806         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
4807
4808         POSTING_READ(reg);
4809         udelay(200);
4810
4811         /* Switch from Rawclk to PCDclk */
4812         temp = I915_READ(reg);
4813         I915_WRITE(reg, temp | FDI_PCDCLK);
4814
4815         POSTING_READ(reg);
4816         udelay(200);
4817
4818         /* Enable CPU FDI TX PLL, always on for Ironlake */
4819         reg = FDI_TX_CTL(pipe);
4820         temp = I915_READ(reg);
4821         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
4822                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
4823
4824                 POSTING_READ(reg);
4825                 udelay(100);
4826         }
4827 }
4828
4829 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
4830 {
4831         struct drm_device *dev = intel_crtc->base.dev;
4832         struct drm_i915_private *dev_priv = to_i915(dev);
4833         int pipe = intel_crtc->pipe;
4834         i915_reg_t reg;
4835         u32 temp;
4836
4837         /* Switch from PCDclk to Rawclk */
4838         reg = FDI_RX_CTL(pipe);
4839         temp = I915_READ(reg);
4840         I915_WRITE(reg, temp & ~FDI_PCDCLK);
4841
4842         /* Disable CPU FDI TX PLL */
4843         reg = FDI_TX_CTL(pipe);
4844         temp = I915_READ(reg);
4845         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
4846
4847         POSTING_READ(reg);
4848         udelay(100);
4849
4850         reg = FDI_RX_CTL(pipe);
4851         temp = I915_READ(reg);
4852         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
4853
4854         /* Wait for the clocks to turn off. */
4855         POSTING_READ(reg);
4856         udelay(100);
4857 }
4858
4859 static void ironlake_fdi_disable(struct drm_crtc *crtc)
4860 {
4861         struct drm_device *dev = crtc->dev;
4862         struct drm_i915_private *dev_priv = to_i915(dev);
4863         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4864         int pipe = intel_crtc->pipe;
4865         i915_reg_t reg;
4866         u32 temp;
4867
4868         /* disable CPU FDI tx and PCH FDI rx */
4869         reg = FDI_TX_CTL(pipe);
4870         temp = I915_READ(reg);
4871         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
4872         POSTING_READ(reg);
4873
4874         reg = FDI_RX_CTL(pipe);
4875         temp = I915_READ(reg);
4876         temp &= ~(0x7 << 16);
4877         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4878         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
4879
4880         POSTING_READ(reg);
4881         udelay(100);
4882
4883         /* Ironlake workaround, disable clock pointer after downing FDI */
4884         if (HAS_PCH_IBX(dev_priv))
4885                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
4886
4887         /* still set train pattern 1 */
4888         reg = FDI_TX_CTL(pipe);
4889         temp = I915_READ(reg);
4890         temp &= ~FDI_LINK_TRAIN_NONE;
4891         temp |= FDI_LINK_TRAIN_PATTERN_1;
4892         I915_WRITE(reg, temp);
4893
4894         reg = FDI_RX_CTL(pipe);
4895         temp = I915_READ(reg);
4896         if (HAS_PCH_CPT(dev_priv)) {
4897                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4898                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4899         } else {
4900                 temp &= ~FDI_LINK_TRAIN_NONE;
4901                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4902         }
4903         /* BPC in FDI rx is consistent with that in PIPECONF */
4904         temp &= ~(0x07 << 16);
4905         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4906         I915_WRITE(reg, temp);
4907
4908         POSTING_READ(reg);
4909         udelay(100);
4910 }
4911
4912 bool intel_has_pending_fb_unpin(struct drm_i915_private *dev_priv)
4913 {
4914         struct drm_crtc *crtc;
4915         bool cleanup_done;
4916
4917         drm_for_each_crtc(crtc, &dev_priv->drm) {
4918                 struct drm_crtc_commit *commit;
4919                 spin_lock(&crtc->commit_lock);
4920                 commit = list_first_entry_or_null(&crtc->commit_list,
4921                                                   struct drm_crtc_commit, commit_entry);
4922                 cleanup_done = commit ?
4923                         try_wait_for_completion(&commit->cleanup_done) : true;
4924                 spin_unlock(&crtc->commit_lock);
4925
4926                 if (cleanup_done)
4927                         continue;
4928
4929                 drm_crtc_wait_one_vblank(crtc);
4930
4931                 return true;
4932         }
4933
4934         return false;
4935 }
4936
4937 void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
4938 {
4939         u32 temp;
4940
4941         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
4942
4943         mutex_lock(&dev_priv->sb_lock);
4944
4945         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4946         temp |= SBI_SSCCTL_DISABLE;
4947         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4948
4949         mutex_unlock(&dev_priv->sb_lock);
4950 }
4951
4952 /* Program iCLKIP clock to the desired frequency */
4953 static void lpt_program_iclkip(const struct intel_crtc_state *crtc_state)
4954 {
4955         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4956         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4957         int clock = crtc_state->base.adjusted_mode.crtc_clock;
4958         u32 divsel, phaseinc, auxdiv, phasedir = 0;
4959         u32 temp;
4960
4961         lpt_disable_iclkip(dev_priv);
4962
4963         /* The iCLK virtual clock root frequency is in MHz,
4964          * but the adjusted_mode->crtc_clock in in KHz. To get the
4965          * divisors, it is necessary to divide one by another, so we
4966          * convert the virtual clock precision to KHz here for higher
4967          * precision.
4968          */
4969         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
4970                 u32 iclk_virtual_root_freq = 172800 * 1000;
4971                 u32 iclk_pi_range = 64;
4972                 u32 desired_divisor;
4973
4974                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4975                                                     clock << auxdiv);
4976                 divsel = (desired_divisor / iclk_pi_range) - 2;
4977                 phaseinc = desired_divisor % iclk_pi_range;
4978
4979                 /*
4980                  * Near 20MHz is a corner case which is
4981                  * out of range for the 7-bit divisor
4982                  */
4983                 if (divsel <= 0x7f)
4984                         break;
4985         }
4986
4987         /* This should not happen with any sane values */
4988         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
4989                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
4990         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
4991                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
4992
4993         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
4994                         clock,
4995                         auxdiv,
4996                         divsel,
4997                         phasedir,
4998                         phaseinc);
4999
5000         mutex_lock(&dev_priv->sb_lock);
5001
5002         /* Program SSCDIVINTPHASE6 */
5003         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
5004         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
5005         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
5006         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
5007         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
5008         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
5009         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
5010         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
5011
5012         /* Program SSCAUXDIV */
5013         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
5014         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
5015         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
5016         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
5017
5018         /* Enable modulator and associated divider */
5019         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
5020         temp &= ~SBI_SSCCTL_DISABLE;
5021         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
5022
5023         mutex_unlock(&dev_priv->sb_lock);
5024
5025         /* Wait for initialization time */
5026         udelay(24);
5027
5028         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
5029 }
5030
5031 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
5032 {
5033         u32 divsel, phaseinc, auxdiv;
5034         u32 iclk_virtual_root_freq = 172800 * 1000;
5035         u32 iclk_pi_range = 64;
5036         u32 desired_divisor;
5037         u32 temp;
5038
5039         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
5040                 return 0;
5041
5042         mutex_lock(&dev_priv->sb_lock);
5043
5044         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
5045         if (temp & SBI_SSCCTL_DISABLE) {
5046                 mutex_unlock(&dev_priv->sb_lock);
5047                 return 0;
5048         }
5049
5050         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
5051         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
5052                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
5053         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
5054                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
5055
5056         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
5057         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
5058                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
5059
5060         mutex_unlock(&dev_priv->sb_lock);
5061
5062         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
5063
5064         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
5065                                  desired_divisor << auxdiv);
5066 }
5067
5068 static void ironlake_pch_transcoder_set_timings(const struct intel_crtc_state *crtc_state,
5069                                                 enum pipe pch_transcoder)
5070 {
5071         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5072         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5073         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
5074
5075         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
5076                    I915_READ(HTOTAL(cpu_transcoder)));
5077         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
5078                    I915_READ(HBLANK(cpu_transcoder)));
5079         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
5080                    I915_READ(HSYNC(cpu_transcoder)));
5081
5082         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
5083                    I915_READ(VTOTAL(cpu_transcoder)));
5084         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
5085                    I915_READ(VBLANK(cpu_transcoder)));
5086         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
5087                    I915_READ(VSYNC(cpu_transcoder)));
5088         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
5089                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
5090 }
5091
5092 static void cpt_set_fdi_bc_bifurcation(struct drm_i915_private *dev_priv, bool enable)
5093 {
5094         u32 temp;
5095
5096         temp = I915_READ(SOUTH_CHICKEN1);
5097         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
5098                 return;
5099
5100         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
5101         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
5102
5103         temp &= ~FDI_BC_BIFURCATION_SELECT;
5104         if (enable)
5105                 temp |= FDI_BC_BIFURCATION_SELECT;
5106
5107         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
5108         I915_WRITE(SOUTH_CHICKEN1, temp);
5109         POSTING_READ(SOUTH_CHICKEN1);
5110 }
5111
5112 static void ivybridge_update_fdi_bc_bifurcation(const struct intel_crtc_state *crtc_state)
5113 {
5114         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5115         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5116
5117         switch (crtc->pipe) {
5118         case PIPE_A:
5119                 break;
5120         case PIPE_B:
5121                 if (crtc_state->fdi_lanes > 2)
5122                         cpt_set_fdi_bc_bifurcation(dev_priv, false);
5123                 else
5124                         cpt_set_fdi_bc_bifurcation(dev_priv, true);
5125
5126                 break;
5127         case PIPE_C:
5128                 cpt_set_fdi_bc_bifurcation(dev_priv, true);
5129
5130                 break;
5131         default:
5132                 BUG();
5133         }
5134 }
5135
5136 /*
5137  * Finds the encoder associated with the given CRTC. This can only be
5138  * used when we know that the CRTC isn't feeding multiple encoders!
5139  */
5140 static struct intel_encoder *
5141 intel_get_crtc_new_encoder(const struct intel_atomic_state *state,
5142                            const struct intel_crtc_state *crtc_state)
5143 {
5144         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5145         const struct drm_connector_state *connector_state;
5146         const struct drm_connector *connector;
5147         struct intel_encoder *encoder = NULL;
5148         int num_encoders = 0;
5149         int i;
5150
5151         for_each_new_connector_in_state(&state->base, connector, connector_state, i) {
5152                 if (connector_state->crtc != &crtc->base)
5153                         continue;
5154
5155                 encoder = to_intel_encoder(connector_state->best_encoder);
5156                 num_encoders++;
5157         }
5158
5159         WARN(num_encoders != 1, "%d encoders for pipe %c\n",
5160              num_encoders, pipe_name(crtc->pipe));
5161
5162         return encoder;
5163 }
5164
5165 /*
5166  * Enable PCH resources required for PCH ports:
5167  *   - PCH PLLs
5168  *   - FDI training & RX/TX
5169  *   - update transcoder timings
5170  *   - DP transcoding bits
5171  *   - transcoder
5172  */
5173 static void ironlake_pch_enable(const struct intel_atomic_state *state,
5174                                 const struct intel_crtc_state *crtc_state)
5175 {
5176         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5177         struct drm_device *dev = crtc->base.dev;
5178         struct drm_i915_private *dev_priv = to_i915(dev);
5179         int pipe = crtc->pipe;
5180         u32 temp;
5181
5182         assert_pch_transcoder_disabled(dev_priv, pipe);
5183
5184         if (IS_IVYBRIDGE(dev_priv))
5185                 ivybridge_update_fdi_bc_bifurcation(crtc_state);
5186
5187         /* Write the TU size bits before fdi link training, so that error
5188          * detection works. */
5189         I915_WRITE(FDI_RX_TUSIZE1(pipe),
5190                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
5191
5192         /* For PCH output, training FDI link */
5193         dev_priv->display.fdi_link_train(crtc, crtc_state);
5194
5195         /* We need to program the right clock selection before writing the pixel
5196          * mutliplier into the DPLL. */
5197         if (HAS_PCH_CPT(dev_priv)) {
5198                 u32 sel;
5199
5200                 temp = I915_READ(PCH_DPLL_SEL);
5201                 temp |= TRANS_DPLL_ENABLE(pipe);
5202                 sel = TRANS_DPLLB_SEL(pipe);
5203                 if (crtc_state->shared_dpll ==
5204                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
5205                         temp |= sel;
5206                 else
5207                         temp &= ~sel;
5208                 I915_WRITE(PCH_DPLL_SEL, temp);
5209         }
5210
5211         /* XXX: pch pll's can be enabled any time before we enable the PCH
5212          * transcoder, and we actually should do this to not upset any PCH
5213          * transcoder that already use the clock when we share it.
5214          *
5215          * Note that enable_shared_dpll tries to do the right thing, but
5216          * get_shared_dpll unconditionally resets the pll - we need that to have
5217          * the right LVDS enable sequence. */
5218         intel_enable_shared_dpll(crtc_state);
5219
5220         /* set transcoder timing, panel must allow it */
5221         assert_panel_unlocked(dev_priv, pipe);
5222         ironlake_pch_transcoder_set_timings(crtc_state, pipe);
5223
5224         intel_fdi_normal_train(crtc);
5225
5226         /* For PCH DP, enable TRANS_DP_CTL */
5227         if (HAS_PCH_CPT(dev_priv) &&
5228             intel_crtc_has_dp_encoder(crtc_state)) {
5229                 const struct drm_display_mode *adjusted_mode =
5230                         &crtc_state->base.adjusted_mode;
5231                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
5232                 i915_reg_t reg = TRANS_DP_CTL(pipe);
5233                 enum port port;
5234
5235                 temp = I915_READ(reg);
5236                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
5237                           TRANS_DP_SYNC_MASK |
5238                           TRANS_DP_BPC_MASK);
5239                 temp |= TRANS_DP_OUTPUT_ENABLE;
5240                 temp |= bpc << 9; /* same format but at 11:9 */
5241
5242                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
5243                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
5244                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
5245                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
5246
5247                 port = intel_get_crtc_new_encoder(state, crtc_state)->port;
5248                 WARN_ON(port < PORT_B || port > PORT_D);
5249                 temp |= TRANS_DP_PORT_SEL(port);
5250
5251                 I915_WRITE(reg, temp);
5252         }
5253
5254         ironlake_enable_pch_transcoder(crtc_state);
5255 }
5256
5257 static void lpt_pch_enable(const struct intel_atomic_state *state,
5258                            const struct intel_crtc_state *crtc_state)
5259 {
5260         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5261         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5262         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
5263
5264         assert_pch_transcoder_disabled(dev_priv, PIPE_A);
5265
5266         lpt_program_iclkip(crtc_state);
5267
5268         /* Set transcoder timing. */
5269         ironlake_pch_transcoder_set_timings(crtc_state, PIPE_A);
5270
5271         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
5272 }
5273
5274 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
5275 {
5276         struct drm_i915_private *dev_priv = to_i915(dev);
5277         i915_reg_t dslreg = PIPEDSL(pipe);
5278         u32 temp;
5279
5280         temp = I915_READ(dslreg);
5281         udelay(500);
5282         if (wait_for(I915_READ(dslreg) != temp, 5)) {
5283                 if (wait_for(I915_READ(dslreg) != temp, 5))
5284                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
5285         }
5286 }
5287
5288 /*
5289  * The hardware phase 0.0 refers to the center of the pixel.
5290  * We want to start from the top/left edge which is phase
5291  * -0.5. That matches how the hardware calculates the scaling
5292  * factors (from top-left of the first pixel to bottom-right
5293  * of the last pixel, as opposed to the pixel centers).
5294  *
5295  * For 4:2:0 subsampled chroma planes we obviously have to
5296  * adjust that so that the chroma sample position lands in
5297  * the right spot.
5298  *
5299  * Note that for packed YCbCr 4:2:2 formats there is no way to
5300  * control chroma siting. The hardware simply replicates the
5301  * chroma samples for both of the luma samples, and thus we don't
5302  * actually get the expected MPEG2 chroma siting convention :(
5303  * The same behaviour is observed on pre-SKL platforms as well.
5304  *
5305  * Theory behind the formula (note that we ignore sub-pixel
5306  * source coordinates):
5307  * s = source sample position
5308  * d = destination sample position
5309  *
5310  * Downscaling 4:1:
5311  * -0.5
5312  * | 0.0
5313  * | |     1.5 (initial phase)
5314  * | |     |
5315  * v v     v
5316  * | s | s | s | s |
5317  * |       d       |
5318  *
5319  * Upscaling 1:4:
5320  * -0.5
5321  * | -0.375 (initial phase)
5322  * | |     0.0
5323  * | |     |
5324  * v v     v
5325  * |       s       |
5326  * | d | d | d | d |
5327  */
5328 u16 skl_scaler_calc_phase(int sub, int scale, bool chroma_cosited)
5329 {
5330         int phase = -0x8000;
5331         u16 trip = 0;
5332
5333         if (chroma_cosited)
5334                 phase += (sub - 1) * 0x8000 / sub;
5335
5336         phase += scale / (2 * sub);
5337
5338         /*
5339          * Hardware initial phase limited to [-0.5:1.5].
5340          * Since the max hardware scale factor is 3.0, we
5341          * should never actually excdeed 1.0 here.
5342          */
5343         WARN_ON(phase < -0x8000 || phase > 0x18000);
5344
5345         if (phase < 0)
5346                 phase = 0x10000 + phase;
5347         else
5348                 trip = PS_PHASE_TRIP;
5349
5350         return ((phase >> 2) & PS_PHASE_MASK) | trip;
5351 }
5352
5353 #define SKL_MIN_SRC_W 8
5354 #define SKL_MAX_SRC_W 4096
5355 #define SKL_MIN_SRC_H 8
5356 #define SKL_MAX_SRC_H 4096
5357 #define SKL_MIN_DST_W 8
5358 #define SKL_MAX_DST_W 4096
5359 #define SKL_MIN_DST_H 8
5360 #define SKL_MAX_DST_H 4096
5361 #define ICL_MAX_SRC_W 5120
5362 #define ICL_MAX_SRC_H 4096
5363 #define ICL_MAX_DST_W 5120
5364 #define ICL_MAX_DST_H 4096
5365 #define SKL_MIN_YUV_420_SRC_W 16
5366 #define SKL_MIN_YUV_420_SRC_H 16
5367
5368 static int
5369 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
5370                   unsigned int scaler_user, int *scaler_id,
5371                   int src_w, int src_h, int dst_w, int dst_h,
5372                   const struct drm_format_info *format, bool need_scaler)
5373 {
5374         struct intel_crtc_scaler_state *scaler_state =
5375                 &crtc_state->scaler_state;
5376         struct intel_crtc *intel_crtc =
5377                 to_intel_crtc(crtc_state->base.crtc);
5378         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
5379         const struct drm_display_mode *adjusted_mode =
5380                 &crtc_state->base.adjusted_mode;
5381
5382         /*
5383          * Src coordinates are already rotated by 270 degrees for
5384          * the 90/270 degree plane rotation cases (to match the
5385          * GTT mapping), hence no need to account for rotation here.
5386          */
5387         if (src_w != dst_w || src_h != dst_h)
5388                 need_scaler = true;
5389
5390         /*
5391          * Scaling/fitting not supported in IF-ID mode in GEN9+
5392          * TODO: Interlace fetch mode doesn't support YUV420 planar formats.
5393          * Once NV12 is enabled, handle it here while allocating scaler
5394          * for NV12.
5395          */
5396         if (INTEL_GEN(dev_priv) >= 9 && crtc_state->base.enable &&
5397             need_scaler && adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
5398                 DRM_DEBUG_KMS("Pipe/Plane scaling not supported with IF-ID mode\n");
5399                 return -EINVAL;
5400         }
5401
5402         /*
5403          * if plane is being disabled or scaler is no more required or force detach
5404          *  - free scaler binded to this plane/crtc
5405          *  - in order to do this, update crtc->scaler_usage
5406          *
5407          * Here scaler state in crtc_state is set free so that
5408          * scaler can be assigned to other user. Actual register
5409          * update to free the scaler is done in plane/panel-fit programming.
5410          * For this purpose crtc/plane_state->scaler_id isn't reset here.
5411          */
5412         if (force_detach || !need_scaler) {
5413                 if (*scaler_id >= 0) {
5414                         scaler_state->scaler_users &= ~(1 << scaler_user);
5415                         scaler_state->scalers[*scaler_id].in_use = 0;
5416
5417                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
5418                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
5419                                 intel_crtc->pipe, scaler_user, *scaler_id,
5420                                 scaler_state->scaler_users);
5421                         *scaler_id = -1;
5422                 }
5423                 return 0;
5424         }
5425
5426         if (format && is_planar_yuv_format(format->format) &&
5427             (src_h < SKL_MIN_YUV_420_SRC_H || src_w < SKL_MIN_YUV_420_SRC_W)) {
5428                 DRM_DEBUG_KMS("Planar YUV: src dimensions not met\n");
5429                 return -EINVAL;
5430         }
5431
5432         /* range checks */
5433         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
5434             dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
5435             (INTEL_GEN(dev_priv) >= 11 &&
5436              (src_w > ICL_MAX_SRC_W || src_h > ICL_MAX_SRC_H ||
5437               dst_w > ICL_MAX_DST_W || dst_h > ICL_MAX_DST_H)) ||
5438             (INTEL_GEN(dev_priv) < 11 &&
5439              (src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
5440               dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H))) {
5441                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
5442                         "size is out of scaler range\n",
5443                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
5444                 return -EINVAL;
5445         }
5446
5447         /* mark this plane as a scaler user in crtc_state */
5448         scaler_state->scaler_users |= (1 << scaler_user);
5449         DRM_DEBUG_KMS("scaler_user index %u.%u: "
5450                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
5451                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
5452                 scaler_state->scaler_users);
5453
5454         return 0;
5455 }
5456
5457 /**
5458  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
5459  *
5460  * @state: crtc's scaler state
5461  *
5462  * Return
5463  *     0 - scaler_usage updated successfully
5464  *    error - requested scaling cannot be supported or other error condition
5465  */
5466 int skl_update_scaler_crtc(struct intel_crtc_state *state)
5467 {
5468         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
5469         bool need_scaler = false;
5470
5471         if (state->output_format == INTEL_OUTPUT_FORMAT_YCBCR420)
5472                 need_scaler = true;
5473
5474         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
5475                                  &state->scaler_state.scaler_id,
5476                                  state->pipe_src_w, state->pipe_src_h,
5477                                  adjusted_mode->crtc_hdisplay,
5478                                  adjusted_mode->crtc_vdisplay, NULL, need_scaler);
5479 }
5480
5481 /**
5482  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
5483  * @crtc_state: crtc's scaler state
5484  * @plane_state: atomic plane state to update
5485  *
5486  * Return
5487  *     0 - scaler_usage updated successfully
5488  *    error - requested scaling cannot be supported or other error condition
5489  */
5490 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
5491                                    struct intel_plane_state *plane_state)
5492 {
5493         struct intel_plane *intel_plane =
5494                 to_intel_plane(plane_state->base.plane);
5495         struct drm_i915_private *dev_priv = to_i915(intel_plane->base.dev);
5496         struct drm_framebuffer *fb = plane_state->base.fb;
5497         int ret;
5498         bool force_detach = !fb || !plane_state->base.visible;
5499         bool need_scaler = false;
5500
5501         /* Pre-gen11 and SDR planes always need a scaler for planar formats. */
5502         if (!icl_is_hdr_plane(dev_priv, intel_plane->id) &&
5503             fb && is_planar_yuv_format(fb->format->format))
5504                 need_scaler = true;
5505
5506         ret = skl_update_scaler(crtc_state, force_detach,
5507                                 drm_plane_index(&intel_plane->base),
5508                                 &plane_state->scaler_id,
5509                                 drm_rect_width(&plane_state->base.src) >> 16,
5510                                 drm_rect_height(&plane_state->base.src) >> 16,
5511                                 drm_rect_width(&plane_state->base.dst),
5512                                 drm_rect_height(&plane_state->base.dst),
5513                                 fb ? fb->format : NULL, need_scaler);
5514
5515         if (ret || plane_state->scaler_id < 0)
5516                 return ret;
5517
5518         /* check colorkey */
5519         if (plane_state->ckey.flags) {
5520                 DRM_DEBUG_KMS("[PLANE:%d:%s] scaling with color key not allowed",
5521                               intel_plane->base.base.id,
5522                               intel_plane->base.name);
5523                 return -EINVAL;
5524         }
5525
5526         /* Check src format */
5527         switch (fb->format->format) {
5528         case DRM_FORMAT_RGB565:
5529         case DRM_FORMAT_XBGR8888:
5530         case DRM_FORMAT_XRGB8888:
5531         case DRM_FORMAT_ABGR8888:
5532         case DRM_FORMAT_ARGB8888:
5533         case DRM_FORMAT_XRGB2101010:
5534         case DRM_FORMAT_XBGR2101010:
5535         case DRM_FORMAT_XBGR16161616F:
5536         case DRM_FORMAT_ABGR16161616F:
5537         case DRM_FORMAT_XRGB16161616F:
5538         case DRM_FORMAT_ARGB16161616F:
5539         case DRM_FORMAT_YUYV:
5540         case DRM_FORMAT_YVYU:
5541         case DRM_FORMAT_UYVY:
5542         case DRM_FORMAT_VYUY:
5543         case DRM_FORMAT_NV12:
5544         case DRM_FORMAT_P010:
5545         case DRM_FORMAT_P012:
5546         case DRM_FORMAT_P016:
5547         case DRM_FORMAT_Y210:
5548         case DRM_FORMAT_Y212:
5549         case DRM_FORMAT_Y216:
5550         case DRM_FORMAT_XVYU2101010:
5551         case DRM_FORMAT_XVYU12_16161616:
5552         case DRM_FORMAT_XVYU16161616:
5553                 break;
5554         default:
5555                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d unsupported scaling format 0x%x\n",
5556                               intel_plane->base.base.id, intel_plane->base.name,
5557                               fb->base.id, fb->format->format);
5558                 return -EINVAL;
5559         }
5560
5561         return 0;
5562 }
5563
5564 static void skylake_scaler_disable(struct intel_crtc *crtc)
5565 {
5566         int i;
5567
5568         for (i = 0; i < crtc->num_scalers; i++)
5569                 skl_detach_scaler(crtc, i);
5570 }
5571
5572 static void skylake_pfit_enable(const struct intel_crtc_state *crtc_state)
5573 {
5574         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5575         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5576         enum pipe pipe = crtc->pipe;
5577         const struct intel_crtc_scaler_state *scaler_state =
5578                 &crtc_state->scaler_state;
5579
5580         if (crtc_state->pch_pfit.enabled) {
5581                 u16 uv_rgb_hphase, uv_rgb_vphase;
5582                 int pfit_w, pfit_h, hscale, vscale;
5583                 int id;
5584
5585                 if (WARN_ON(crtc_state->scaler_state.scaler_id < 0))
5586                         return;
5587
5588                 pfit_w = (crtc_state->pch_pfit.size >> 16) & 0xFFFF;
5589                 pfit_h = crtc_state->pch_pfit.size & 0xFFFF;
5590
5591                 hscale = (crtc_state->pipe_src_w << 16) / pfit_w;
5592                 vscale = (crtc_state->pipe_src_h << 16) / pfit_h;
5593
5594                 uv_rgb_hphase = skl_scaler_calc_phase(1, hscale, false);
5595                 uv_rgb_vphase = skl_scaler_calc_phase(1, vscale, false);
5596
5597                 id = scaler_state->scaler_id;
5598                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
5599                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
5600                 I915_WRITE_FW(SKL_PS_VPHASE(pipe, id),
5601                               PS_Y_PHASE(0) | PS_UV_RGB_PHASE(uv_rgb_vphase));
5602                 I915_WRITE_FW(SKL_PS_HPHASE(pipe, id),
5603                               PS_Y_PHASE(0) | PS_UV_RGB_PHASE(uv_rgb_hphase));
5604                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc_state->pch_pfit.pos);
5605                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc_state->pch_pfit.size);
5606         }
5607 }
5608
5609 static void ironlake_pfit_enable(const struct intel_crtc_state *crtc_state)
5610 {
5611         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5612         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5613         int pipe = crtc->pipe;
5614
5615         if (crtc_state->pch_pfit.enabled) {
5616                 /* Force use of hard-coded filter coefficients
5617                  * as some pre-programmed values are broken,
5618                  * e.g. x201.
5619                  */
5620                 if (IS_IVYBRIDGE(dev_priv) || IS_HASWELL(dev_priv))
5621                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
5622                                                  PF_PIPE_SEL_IVB(pipe));
5623                 else
5624                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
5625                 I915_WRITE(PF_WIN_POS(pipe), crtc_state->pch_pfit.pos);
5626                 I915_WRITE(PF_WIN_SZ(pipe), crtc_state->pch_pfit.size);
5627         }
5628 }
5629
5630 void hsw_enable_ips(const struct intel_crtc_state *crtc_state)
5631 {
5632         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5633         struct drm_device *dev = crtc->base.dev;
5634         struct drm_i915_private *dev_priv = to_i915(dev);
5635
5636         if (!crtc_state->ips_enabled)
5637                 return;
5638
5639         /*
5640          * We can only enable IPS after we enable a plane and wait for a vblank
5641          * This function is called from post_plane_update, which is run after
5642          * a vblank wait.
5643          */
5644         WARN_ON(!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)));
5645
5646         if (IS_BROADWELL(dev_priv)) {
5647                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL,
5648                                                 IPS_ENABLE | IPS_PCODE_CONTROL));
5649                 /* Quoting Art Runyan: "its not safe to expect any particular
5650                  * value in IPS_CTL bit 31 after enabling IPS through the
5651                  * mailbox." Moreover, the mailbox may return a bogus state,
5652                  * so we need to just enable it and continue on.
5653                  */
5654         } else {
5655                 I915_WRITE(IPS_CTL, IPS_ENABLE);
5656                 /* The bit only becomes 1 in the next vblank, so this wait here
5657                  * is essentially intel_wait_for_vblank. If we don't have this
5658                  * and don't wait for vblanks until the end of crtc_enable, then
5659                  * the HW state readout code will complain that the expected
5660                  * IPS_CTL value is not the one we read. */
5661                 if (intel_wait_for_register(&dev_priv->uncore,
5662                                             IPS_CTL, IPS_ENABLE, IPS_ENABLE,
5663                                             50))
5664                         DRM_ERROR("Timed out waiting for IPS enable\n");
5665         }
5666 }
5667
5668 void hsw_disable_ips(const struct intel_crtc_state *crtc_state)
5669 {
5670         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5671         struct drm_device *dev = crtc->base.dev;
5672         struct drm_i915_private *dev_priv = to_i915(dev);
5673
5674         if (!crtc_state->ips_enabled)
5675                 return;
5676
5677         if (IS_BROADWELL(dev_priv)) {
5678                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
5679                 /*
5680                  * Wait for PCODE to finish disabling IPS. The BSpec specified
5681                  * 42ms timeout value leads to occasional timeouts so use 100ms
5682                  * instead.
5683                  */
5684                 if (intel_wait_for_register(&dev_priv->uncore,
5685                                             IPS_CTL, IPS_ENABLE, 0,
5686                                             100))
5687                         DRM_ERROR("Timed out waiting for IPS disable\n");
5688         } else {
5689                 I915_WRITE(IPS_CTL, 0);
5690                 POSTING_READ(IPS_CTL);
5691         }
5692
5693         /* We need to wait for a vblank before we can disable the plane. */
5694         intel_wait_for_vblank(dev_priv, crtc->pipe);
5695 }
5696
5697 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
5698 {
5699         if (intel_crtc->overlay) {
5700                 struct drm_device *dev = intel_crtc->base.dev;
5701
5702                 mutex_lock(&dev->struct_mutex);
5703                 (void) intel_overlay_switch_off(intel_crtc->overlay);
5704                 mutex_unlock(&dev->struct_mutex);
5705         }
5706
5707         /* Let userspace switch the overlay on again. In most cases userspace
5708          * has to recompute where to put it anyway.
5709          */
5710 }
5711
5712 /**
5713  * intel_post_enable_primary - Perform operations after enabling primary plane
5714  * @crtc: the CRTC whose primary plane was just enabled
5715  * @new_crtc_state: the enabling state
5716  *
5717  * Performs potentially sleeping operations that must be done after the primary
5718  * plane is enabled, such as updating FBC and IPS.  Note that this may be
5719  * called due to an explicit primary plane update, or due to an implicit
5720  * re-enable that is caused when a sprite plane is updated to no longer
5721  * completely hide the primary plane.
5722  */
5723 static void
5724 intel_post_enable_primary(struct drm_crtc *crtc,
5725                           const struct intel_crtc_state *new_crtc_state)
5726 {
5727         struct drm_device *dev = crtc->dev;
5728         struct drm_i915_private *dev_priv = to_i915(dev);
5729         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5730         int pipe = intel_crtc->pipe;
5731
5732         /*
5733          * Gen2 reports pipe underruns whenever all planes are disabled.
5734          * So don't enable underrun reporting before at least some planes
5735          * are enabled.
5736          * FIXME: Need to fix the logic to work when we turn off all planes
5737          * but leave the pipe running.
5738          */
5739         if (IS_GEN(dev_priv, 2))
5740                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5741
5742         /* Underruns don't always raise interrupts, so check manually. */
5743         intel_check_cpu_fifo_underruns(dev_priv);
5744         intel_check_pch_fifo_underruns(dev_priv);
5745 }
5746
5747 /* FIXME get rid of this and use pre_plane_update */
5748 static void
5749 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
5750 {
5751         struct drm_device *dev = crtc->dev;
5752         struct drm_i915_private *dev_priv = to_i915(dev);
5753         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5754         int pipe = intel_crtc->pipe;
5755
5756         /*
5757          * Gen2 reports pipe underruns whenever all planes are disabled.
5758          * So disable underrun reporting before all the planes get disabled.
5759          */
5760         if (IS_GEN(dev_priv, 2))
5761                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5762
5763         hsw_disable_ips(to_intel_crtc_state(crtc->state));
5764
5765         /*
5766          * Vblank time updates from the shadow to live plane control register
5767          * are blocked if the memory self-refresh mode is active at that
5768          * moment. So to make sure the plane gets truly disabled, disable
5769          * first the self-refresh mode. The self-refresh enable bit in turn
5770          * will be checked/applied by the HW only at the next frame start
5771          * event which is after the vblank start event, so we need to have a
5772          * wait-for-vblank between disabling the plane and the pipe.
5773          */
5774         if (HAS_GMCH(dev_priv) &&
5775             intel_set_memory_cxsr(dev_priv, false))
5776                 intel_wait_for_vblank(dev_priv, pipe);
5777 }
5778
5779 static bool hsw_pre_update_disable_ips(const struct intel_crtc_state *old_crtc_state,
5780                                        const struct intel_crtc_state *new_crtc_state)
5781 {
5782         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
5783         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5784
5785         if (!old_crtc_state->ips_enabled)
5786                 return false;
5787
5788         if (needs_modeset(&new_crtc_state->base))
5789                 return true;
5790
5791         /*
5792          * Workaround : Do not read or write the pipe palette/gamma data while
5793          * GAMMA_MODE is configured for split gamma and IPS_CTL has IPS enabled.
5794          *
5795          * Disable IPS before we program the LUT.
5796          */
5797         if (IS_HASWELL(dev_priv) &&
5798             (new_crtc_state->base.color_mgmt_changed ||
5799              new_crtc_state->update_pipe) &&
5800             new_crtc_state->gamma_mode == GAMMA_MODE_MODE_SPLIT)
5801                 return true;
5802
5803         return !new_crtc_state->ips_enabled;
5804 }
5805
5806 static bool hsw_post_update_enable_ips(const struct intel_crtc_state *old_crtc_state,
5807                                        const struct intel_crtc_state *new_crtc_state)
5808 {
5809         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
5810         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5811
5812         if (!new_crtc_state->ips_enabled)
5813                 return false;
5814
5815         if (needs_modeset(&new_crtc_state->base))
5816                 return true;
5817
5818         /*
5819          * Workaround : Do not read or write the pipe palette/gamma data while
5820          * GAMMA_MODE is configured for split gamma and IPS_CTL has IPS enabled.
5821          *
5822          * Re-enable IPS after the LUT has been programmed.
5823          */
5824         if (IS_HASWELL(dev_priv) &&
5825             (new_crtc_state->base.color_mgmt_changed ||
5826              new_crtc_state->update_pipe) &&
5827             new_crtc_state->gamma_mode == GAMMA_MODE_MODE_SPLIT)
5828                 return true;
5829
5830         /*
5831          * We can't read out IPS on broadwell, assume the worst and
5832          * forcibly enable IPS on the first fastset.
5833          */
5834         if (new_crtc_state->update_pipe &&
5835             old_crtc_state->base.adjusted_mode.private_flags & I915_MODE_FLAG_INHERITED)
5836                 return true;
5837
5838         return !old_crtc_state->ips_enabled;
5839 }
5840
5841 static bool needs_nv12_wa(struct drm_i915_private *dev_priv,
5842                           const struct intel_crtc_state *crtc_state)
5843 {
5844         if (!crtc_state->nv12_planes)
5845                 return false;
5846
5847         /* WA Display #0827: Gen9:all */
5848         if (IS_GEN(dev_priv, 9) && !IS_GEMINILAKE(dev_priv))
5849                 return true;
5850
5851         return false;
5852 }
5853
5854 static bool needs_scalerclk_wa(struct drm_i915_private *dev_priv,
5855                                const struct intel_crtc_state *crtc_state)
5856 {
5857         /* Wa_2006604312:icl */
5858         if (crtc_state->scaler_state.scaler_users > 0 && IS_ICELAKE(dev_priv))
5859                 return true;
5860
5861         return false;
5862 }
5863
5864 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
5865 {
5866         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5867         struct drm_device *dev = crtc->base.dev;
5868         struct drm_i915_private *dev_priv = to_i915(dev);
5869         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5870         struct intel_crtc_state *pipe_config =
5871                 intel_atomic_get_new_crtc_state(to_intel_atomic_state(old_state),
5872                                                 crtc);
5873         struct drm_plane *primary = crtc->base.primary;
5874         struct drm_plane_state *old_primary_state =
5875                 drm_atomic_get_old_plane_state(old_state, primary);
5876
5877         intel_frontbuffer_flip(to_i915(crtc->base.dev), pipe_config->fb_bits);
5878
5879         if (pipe_config->update_wm_post && pipe_config->base.active)
5880                 intel_update_watermarks(crtc);
5881
5882         if (hsw_post_update_enable_ips(old_crtc_state, pipe_config))
5883                 hsw_enable_ips(pipe_config);
5884
5885         if (old_primary_state) {
5886                 struct drm_plane_state *new_primary_state =
5887                         drm_atomic_get_new_plane_state(old_state, primary);
5888
5889                 intel_fbc_post_update(crtc);
5890
5891                 if (new_primary_state->visible &&
5892                     (needs_modeset(&pipe_config->base) ||
5893                      !old_primary_state->visible))
5894                         intel_post_enable_primary(&crtc->base, pipe_config);
5895         }
5896
5897         if (needs_nv12_wa(dev_priv, old_crtc_state) &&
5898             !needs_nv12_wa(dev_priv, pipe_config))
5899                 skl_wa_827(dev_priv, crtc->pipe, false);
5900
5901         if (needs_scalerclk_wa(dev_priv, old_crtc_state) &&
5902             !needs_scalerclk_wa(dev_priv, pipe_config))
5903                 icl_wa_scalerclkgating(dev_priv, crtc->pipe, false);
5904 }
5905
5906 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state,
5907                                    struct intel_crtc_state *pipe_config)
5908 {
5909         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5910         struct drm_device *dev = crtc->base.dev;
5911         struct drm_i915_private *dev_priv = to_i915(dev);
5912         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5913         struct drm_plane *primary = crtc->base.primary;
5914         struct drm_plane_state *old_primary_state =
5915                 drm_atomic_get_old_plane_state(old_state, primary);
5916         bool modeset = needs_modeset(&pipe_config->base);
5917         struct intel_atomic_state *old_intel_state =
5918                 to_intel_atomic_state(old_state);
5919
5920         if (hsw_pre_update_disable_ips(old_crtc_state, pipe_config))
5921                 hsw_disable_ips(old_crtc_state);
5922
5923         if (old_primary_state) {
5924                 struct intel_plane_state *new_primary_state =
5925                         intel_atomic_get_new_plane_state(old_intel_state,
5926                                                          to_intel_plane(primary));
5927
5928                 intel_fbc_pre_update(crtc, pipe_config, new_primary_state);
5929                 /*
5930                  * Gen2 reports pipe underruns whenever all planes are disabled.
5931                  * So disable underrun reporting before all the planes get disabled.
5932                  */
5933                 if (IS_GEN(dev_priv, 2) && old_primary_state->visible &&
5934                     (modeset || !new_primary_state->base.visible))
5935                         intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, false);
5936         }
5937
5938         /* Display WA 827 */
5939         if (!needs_nv12_wa(dev_priv, old_crtc_state) &&
5940             needs_nv12_wa(dev_priv, pipe_config))
5941                 skl_wa_827(dev_priv, crtc->pipe, true);
5942
5943         /* Wa_2006604312:icl */
5944         if (!needs_scalerclk_wa(dev_priv, old_crtc_state) &&
5945             needs_scalerclk_wa(dev_priv, pipe_config))
5946                 icl_wa_scalerclkgating(dev_priv, crtc->pipe, true);
5947
5948         /*
5949          * Vblank time updates from the shadow to live plane control register
5950          * are blocked if the memory self-refresh mode is active at that
5951          * moment. So to make sure the plane gets truly disabled, disable
5952          * first the self-refresh mode. The self-refresh enable bit in turn
5953          * will be checked/applied by the HW only at the next frame start
5954          * event which is after the vblank start event, so we need to have a
5955          * wait-for-vblank between disabling the plane and the pipe.
5956          */
5957         if (HAS_GMCH(dev_priv) && old_crtc_state->base.active &&
5958             pipe_config->disable_cxsr && intel_set_memory_cxsr(dev_priv, false))
5959                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5960
5961         /*
5962          * IVB workaround: must disable low power watermarks for at least
5963          * one frame before enabling scaling.  LP watermarks can be re-enabled
5964          * when scaling is disabled.
5965          *
5966          * WaCxSRDisabledForSpriteScaling:ivb
5967          */
5968         if (pipe_config->disable_lp_wm && ilk_disable_lp_wm(dev) &&
5969             old_crtc_state->base.active)
5970                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5971
5972         /*
5973          * If we're doing a modeset, we're done.  No need to do any pre-vblank
5974          * watermark programming here.
5975          */
5976         if (needs_modeset(&pipe_config->base))
5977                 return;
5978
5979         /*
5980          * For platforms that support atomic watermarks, program the
5981          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
5982          * will be the intermediate values that are safe for both pre- and
5983          * post- vblank; when vblank happens, the 'active' values will be set
5984          * to the final 'target' values and we'll do this again to get the
5985          * optimal watermarks.  For gen9+ platforms, the values we program here
5986          * will be the final target values which will get automatically latched
5987          * at vblank time; no further programming will be necessary.
5988          *
5989          * If a platform hasn't been transitioned to atomic watermarks yet,
5990          * we'll continue to update watermarks the old way, if flags tell
5991          * us to.
5992          */
5993         if (dev_priv->display.initial_watermarks != NULL)
5994                 dev_priv->display.initial_watermarks(old_intel_state,
5995                                                      pipe_config);
5996         else if (pipe_config->update_wm_pre)
5997                 intel_update_watermarks(crtc);
5998 }
5999
6000 static void intel_crtc_disable_planes(struct intel_atomic_state *state,
6001                                       struct intel_crtc *crtc)
6002 {
6003         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6004         const struct intel_crtc_state *new_crtc_state =
6005                 intel_atomic_get_new_crtc_state(state, crtc);
6006         unsigned int update_mask = new_crtc_state->update_planes;
6007         const struct intel_plane_state *old_plane_state;
6008         struct intel_plane *plane;
6009         unsigned fb_bits = 0;
6010         int i;
6011
6012         intel_crtc_dpms_overlay_disable(crtc);
6013
6014         for_each_old_intel_plane_in_state(state, plane, old_plane_state, i) {
6015                 if (crtc->pipe != plane->pipe ||
6016                     !(update_mask & BIT(plane->id)))
6017                         continue;
6018
6019                 intel_disable_plane(plane, new_crtc_state);
6020
6021                 if (old_plane_state->base.visible)
6022                         fb_bits |= plane->frontbuffer_bit;
6023         }
6024
6025         intel_frontbuffer_flip(dev_priv, fb_bits);
6026 }
6027
6028 static void intel_encoders_pre_pll_enable(struct drm_crtc *crtc,
6029                                           struct intel_crtc_state *crtc_state,
6030                                           struct drm_atomic_state *old_state)
6031 {
6032         struct drm_connector_state *conn_state;
6033         struct drm_connector *conn;
6034         int i;
6035
6036         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
6037                 struct intel_encoder *encoder =
6038                         to_intel_encoder(conn_state->best_encoder);
6039
6040                 if (conn_state->crtc != crtc)
6041                         continue;
6042
6043                 if (encoder->pre_pll_enable)
6044                         encoder->pre_pll_enable(encoder, crtc_state, conn_state);
6045         }
6046 }
6047
6048 static void intel_encoders_pre_enable(struct drm_crtc *crtc,
6049                                       struct intel_crtc_state *crtc_state,
6050                                       struct drm_atomic_state *old_state)
6051 {
6052         struct drm_connector_state *conn_state;
6053         struct drm_connector *conn;
6054         int i;
6055
6056         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
6057                 struct intel_encoder *encoder =
6058                         to_intel_encoder(conn_state->best_encoder);
6059
6060                 if (conn_state->crtc != crtc)
6061                         continue;
6062
6063                 if (encoder->pre_enable)
6064                         encoder->pre_enable(encoder, crtc_state, conn_state);
6065         }
6066 }
6067
6068 static void intel_encoders_enable(struct drm_crtc *crtc,
6069                                   struct intel_crtc_state *crtc_state,
6070                                   struct drm_atomic_state *old_state)
6071 {
6072         struct drm_connector_state *conn_state;
6073         struct drm_connector *conn;
6074         int i;
6075
6076         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
6077                 struct intel_encoder *encoder =
6078                         to_intel_encoder(conn_state->best_encoder);
6079
6080                 if (conn_state->crtc != crtc)
6081                         continue;
6082
6083                 if (encoder->enable)
6084                         encoder->enable(encoder, crtc_state, conn_state);
6085                 intel_opregion_notify_encoder(encoder, true);
6086         }
6087 }
6088
6089 static void intel_encoders_disable(struct drm_crtc *crtc,
6090                                    struct intel_crtc_state *old_crtc_state,
6091                                    struct drm_atomic_state *old_state)
6092 {
6093         struct drm_connector_state *old_conn_state;
6094         struct drm_connector *conn;
6095         int i;
6096
6097         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
6098                 struct intel_encoder *encoder =
6099                         to_intel_encoder(old_conn_state->best_encoder);
6100
6101                 if (old_conn_state->crtc != crtc)
6102                         continue;
6103
6104                 intel_opregion_notify_encoder(encoder, false);
6105                 if (encoder->disable)
6106                         encoder->disable(encoder, old_crtc_state, old_conn_state);
6107         }
6108 }
6109
6110 static void intel_encoders_post_disable(struct drm_crtc *crtc,
6111                                         struct intel_crtc_state *old_crtc_state,
6112                                         struct drm_atomic_state *old_state)
6113 {
6114         struct drm_connector_state *old_conn_state;
6115         struct drm_connector *conn;
6116         int i;
6117
6118         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
6119                 struct intel_encoder *encoder =
6120                         to_intel_encoder(old_conn_state->best_encoder);
6121
6122                 if (old_conn_state->crtc != crtc)
6123                         continue;
6124
6125                 if (encoder->post_disable)
6126                         encoder->post_disable(encoder, old_crtc_state, old_conn_state);
6127         }
6128 }
6129
6130 static void intel_encoders_post_pll_disable(struct drm_crtc *crtc,
6131                                             struct intel_crtc_state *old_crtc_state,
6132                                             struct drm_atomic_state *old_state)
6133 {
6134         struct drm_connector_state *old_conn_state;
6135         struct drm_connector *conn;
6136         int i;
6137
6138         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
6139                 struct intel_encoder *encoder =
6140                         to_intel_encoder(old_conn_state->best_encoder);
6141
6142                 if (old_conn_state->crtc != crtc)
6143                         continue;
6144
6145                 if (encoder->post_pll_disable)
6146                         encoder->post_pll_disable(encoder, old_crtc_state, old_conn_state);
6147         }
6148 }
6149
6150 static void intel_encoders_update_pipe(struct drm_crtc *crtc,
6151                                        struct intel_crtc_state *crtc_state,
6152                                        struct drm_atomic_state *old_state)
6153 {
6154         struct drm_connector_state *conn_state;
6155         struct drm_connector *conn;
6156         int i;
6157
6158         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
6159                 struct intel_encoder *encoder =
6160                         to_intel_encoder(conn_state->best_encoder);
6161
6162                 if (conn_state->crtc != crtc)
6163                         continue;
6164
6165                 if (encoder->update_pipe)
6166                         encoder->update_pipe(encoder, crtc_state, conn_state);
6167         }
6168 }
6169
6170 static void intel_disable_primary_plane(const struct intel_crtc_state *crtc_state)
6171 {
6172         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6173         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
6174
6175         plane->disable_plane(plane, crtc_state);
6176 }
6177
6178 static void ironlake_crtc_enable(struct intel_crtc_state *pipe_config,
6179                                  struct drm_atomic_state *old_state)
6180 {
6181         struct drm_crtc *crtc = pipe_config->base.crtc;
6182         struct drm_device *dev = crtc->dev;
6183         struct drm_i915_private *dev_priv = to_i915(dev);
6184         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6185         int pipe = intel_crtc->pipe;
6186         struct intel_atomic_state *old_intel_state =
6187                 to_intel_atomic_state(old_state);
6188
6189         if (WARN_ON(intel_crtc->active))
6190                 return;
6191
6192         /*
6193          * Sometimes spurious CPU pipe underruns happen during FDI
6194          * training, at least with VGA+HDMI cloning. Suppress them.
6195          *
6196          * On ILK we get an occasional spurious CPU pipe underruns
6197          * between eDP port A enable and vdd enable. Also PCH port
6198          * enable seems to result in the occasional CPU pipe underrun.
6199          *
6200          * Spurious PCH underruns also occur during PCH enabling.
6201          */
6202         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6203         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
6204
6205         if (pipe_config->has_pch_encoder)
6206                 intel_prepare_shared_dpll(pipe_config);
6207
6208         if (intel_crtc_has_dp_encoder(pipe_config))
6209                 intel_dp_set_m_n(pipe_config, M1_N1);
6210
6211         intel_set_pipe_timings(pipe_config);
6212         intel_set_pipe_src_size(pipe_config);
6213
6214         if (pipe_config->has_pch_encoder) {
6215                 intel_cpu_transcoder_set_m_n(pipe_config,
6216                                              &pipe_config->fdi_m_n, NULL);
6217         }
6218
6219         ironlake_set_pipeconf(pipe_config);
6220
6221         intel_crtc->active = true;
6222
6223         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6224
6225         if (pipe_config->has_pch_encoder) {
6226                 /* Note: FDI PLL enabling _must_ be done before we enable the
6227                  * cpu pipes, hence this is separate from all the other fdi/pch
6228                  * enabling. */
6229                 ironlake_fdi_pll_enable(pipe_config);
6230         } else {
6231                 assert_fdi_tx_disabled(dev_priv, pipe);
6232                 assert_fdi_rx_disabled(dev_priv, pipe);
6233         }
6234
6235         ironlake_pfit_enable(pipe_config);
6236
6237         /*
6238          * On ILK+ LUT must be loaded before the pipe is running but with
6239          * clocks enabled
6240          */
6241         intel_color_load_luts(pipe_config);
6242         intel_color_commit(pipe_config);
6243         /* update DSPCNTR to configure gamma for pipe bottom color */
6244         intel_disable_primary_plane(pipe_config);
6245
6246         if (dev_priv->display.initial_watermarks != NULL)
6247                 dev_priv->display.initial_watermarks(old_intel_state, pipe_config);
6248         intel_enable_pipe(pipe_config);
6249
6250         if (pipe_config->has_pch_encoder)
6251                 ironlake_pch_enable(old_intel_state, pipe_config);
6252
6253         assert_vblank_disabled(crtc);
6254         intel_crtc_vblank_on(pipe_config);
6255
6256         intel_encoders_enable(crtc, pipe_config, old_state);
6257
6258         if (HAS_PCH_CPT(dev_priv))
6259                 cpt_verify_modeset(dev, intel_crtc->pipe);
6260
6261         /*
6262          * Must wait for vblank to avoid spurious PCH FIFO underruns.
6263          * And a second vblank wait is needed at least on ILK with
6264          * some interlaced HDMI modes. Let's do the double wait always
6265          * in case there are more corner cases we don't know about.
6266          */
6267         if (pipe_config->has_pch_encoder) {
6268                 intel_wait_for_vblank(dev_priv, pipe);
6269                 intel_wait_for_vblank(dev_priv, pipe);
6270         }
6271         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6272         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
6273 }
6274
6275 /* IPS only exists on ULT machines and is tied to pipe A. */
6276 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
6277 {
6278         return HAS_IPS(to_i915(crtc->base.dev)) && crtc->pipe == PIPE_A;
6279 }
6280
6281 static void glk_pipe_scaler_clock_gating_wa(struct drm_i915_private *dev_priv,
6282                                             enum pipe pipe, bool apply)
6283 {
6284         u32 val = I915_READ(CLKGATE_DIS_PSL(pipe));
6285         u32 mask = DPF_GATING_DIS | DPF_RAM_GATING_DIS | DPFR_GATING_DIS;
6286
6287         if (apply)
6288                 val |= mask;
6289         else
6290                 val &= ~mask;
6291
6292         I915_WRITE(CLKGATE_DIS_PSL(pipe), val);
6293 }
6294
6295 static void icl_pipe_mbus_enable(struct intel_crtc *crtc)
6296 {
6297         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6298         enum pipe pipe = crtc->pipe;
6299         u32 val;
6300
6301         val = MBUS_DBOX_A_CREDIT(2);
6302         val |= MBUS_DBOX_BW_CREDIT(1);
6303         val |= MBUS_DBOX_B_CREDIT(8);
6304
6305         I915_WRITE(PIPE_MBUS_DBOX_CTL(pipe), val);
6306 }
6307
6308 static void haswell_crtc_enable(struct intel_crtc_state *pipe_config,
6309                                 struct drm_atomic_state *old_state)
6310 {
6311         struct drm_crtc *crtc = pipe_config->base.crtc;
6312         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6313         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6314         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
6315         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
6316         struct intel_atomic_state *old_intel_state =
6317                 to_intel_atomic_state(old_state);
6318         bool psl_clkgate_wa;
6319
6320         if (WARN_ON(intel_crtc->active))
6321                 return;
6322
6323         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
6324
6325         if (pipe_config->shared_dpll)
6326                 intel_enable_shared_dpll(pipe_config);
6327
6328         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6329
6330         if (intel_crtc_has_dp_encoder(pipe_config))
6331                 intel_dp_set_m_n(pipe_config, M1_N1);
6332
6333         if (!transcoder_is_dsi(cpu_transcoder))
6334                 intel_set_pipe_timings(pipe_config);
6335
6336         intel_set_pipe_src_size(pipe_config);
6337
6338         if (cpu_transcoder != TRANSCODER_EDP &&
6339             !transcoder_is_dsi(cpu_transcoder)) {
6340                 I915_WRITE(PIPE_MULT(cpu_transcoder),
6341                            pipe_config->pixel_multiplier - 1);
6342         }
6343
6344         if (pipe_config->has_pch_encoder) {
6345                 intel_cpu_transcoder_set_m_n(pipe_config,
6346                                              &pipe_config->fdi_m_n, NULL);
6347         }
6348
6349         if (!transcoder_is_dsi(cpu_transcoder))
6350                 haswell_set_pipeconf(pipe_config);
6351
6352         if (INTEL_GEN(dev_priv) >= 9 || IS_BROADWELL(dev_priv))
6353                 bdw_set_pipemisc(pipe_config);
6354
6355         intel_crtc->active = true;
6356
6357         /* Display WA #1180: WaDisableScalarClockGating: glk, cnl */
6358         psl_clkgate_wa = (IS_GEMINILAKE(dev_priv) || IS_CANNONLAKE(dev_priv)) &&
6359                          pipe_config->pch_pfit.enabled;
6360         if (psl_clkgate_wa)
6361                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, true);
6362
6363         if (INTEL_GEN(dev_priv) >= 9)
6364                 skylake_pfit_enable(pipe_config);
6365         else
6366                 ironlake_pfit_enable(pipe_config);
6367
6368         /*
6369          * On ILK+ LUT must be loaded before the pipe is running but with
6370          * clocks enabled
6371          */
6372         intel_color_load_luts(pipe_config);
6373         intel_color_commit(pipe_config);
6374         /* update DSPCNTR to configure gamma/csc for pipe bottom color */
6375         if (INTEL_GEN(dev_priv) < 9)
6376                 intel_disable_primary_plane(pipe_config);
6377
6378         if (INTEL_GEN(dev_priv) >= 11)
6379                 icl_set_pipe_chicken(intel_crtc);
6380
6381         intel_ddi_set_pipe_settings(pipe_config);
6382         if (!transcoder_is_dsi(cpu_transcoder))
6383                 intel_ddi_enable_transcoder_func(pipe_config);
6384
6385         if (dev_priv->display.initial_watermarks != NULL)
6386                 dev_priv->display.initial_watermarks(old_intel_state, pipe_config);
6387
6388         if (INTEL_GEN(dev_priv) >= 11)
6389                 icl_pipe_mbus_enable(intel_crtc);
6390
6391         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
6392         if (!transcoder_is_dsi(cpu_transcoder))
6393                 intel_enable_pipe(pipe_config);
6394
6395         if (pipe_config->has_pch_encoder)
6396                 lpt_pch_enable(old_intel_state, pipe_config);
6397
6398         if (intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DP_MST))
6399                 intel_ddi_set_vc_payload_alloc(pipe_config, true);
6400
6401         assert_vblank_disabled(crtc);
6402         intel_crtc_vblank_on(pipe_config);
6403
6404         intel_encoders_enable(crtc, pipe_config, old_state);
6405
6406         if (psl_clkgate_wa) {
6407                 intel_wait_for_vblank(dev_priv, pipe);
6408                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, false);
6409         }
6410
6411         /* If we change the relative order between pipe/planes enabling, we need
6412          * to change the workaround. */
6413         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
6414         if (IS_HASWELL(dev_priv) && hsw_workaround_pipe != INVALID_PIPE) {
6415                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
6416                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
6417         }
6418 }
6419
6420 static void ironlake_pfit_disable(const struct intel_crtc_state *old_crtc_state)
6421 {
6422         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
6423         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6424         enum pipe pipe = crtc->pipe;
6425
6426         /* To avoid upsetting the power well on haswell only disable the pfit if
6427          * it's in use. The hw state code will make sure we get this right. */
6428         if (old_crtc_state->pch_pfit.enabled) {
6429                 I915_WRITE(PF_CTL(pipe), 0);
6430                 I915_WRITE(PF_WIN_POS(pipe), 0);
6431                 I915_WRITE(PF_WIN_SZ(pipe), 0);
6432         }
6433 }
6434
6435 static void ironlake_crtc_disable(struct intel_crtc_state *old_crtc_state,
6436                                   struct drm_atomic_state *old_state)
6437 {
6438         struct drm_crtc *crtc = old_crtc_state->base.crtc;
6439         struct drm_device *dev = crtc->dev;
6440         struct drm_i915_private *dev_priv = to_i915(dev);
6441         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6442         int pipe = intel_crtc->pipe;
6443
6444         /*
6445          * Sometimes spurious CPU pipe underruns happen when the
6446          * pipe is already disabled, but FDI RX/TX is still enabled.
6447          * Happens at least with VGA+HDMI cloning. Suppress them.
6448          */
6449         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6450         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
6451
6452         intel_encoders_disable(crtc, old_crtc_state, old_state);
6453
6454         drm_crtc_vblank_off(crtc);
6455         assert_vblank_disabled(crtc);
6456
6457         intel_disable_pipe(old_crtc_state);
6458
6459         ironlake_pfit_disable(old_crtc_state);
6460
6461         if (old_crtc_state->has_pch_encoder)
6462                 ironlake_fdi_disable(crtc);
6463
6464         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
6465
6466         if (old_crtc_state->has_pch_encoder) {
6467                 ironlake_disable_pch_transcoder(dev_priv, pipe);
6468
6469                 if (HAS_PCH_CPT(dev_priv)) {
6470                         i915_reg_t reg;
6471                         u32 temp;
6472
6473                         /* disable TRANS_DP_CTL */
6474                         reg = TRANS_DP_CTL(pipe);
6475                         temp = I915_READ(reg);
6476                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
6477                                   TRANS_DP_PORT_SEL_MASK);
6478                         temp |= TRANS_DP_PORT_SEL_NONE;
6479                         I915_WRITE(reg, temp);
6480
6481                         /* disable DPLL_SEL */
6482                         temp = I915_READ(PCH_DPLL_SEL);
6483                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
6484                         I915_WRITE(PCH_DPLL_SEL, temp);
6485                 }
6486
6487                 ironlake_fdi_pll_disable(intel_crtc);
6488         }
6489
6490         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6491         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
6492 }
6493
6494 static void haswell_crtc_disable(struct intel_crtc_state *old_crtc_state,
6495                                  struct drm_atomic_state *old_state)
6496 {
6497         struct drm_crtc *crtc = old_crtc_state->base.crtc;
6498         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6499         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6500         enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
6501
6502         intel_encoders_disable(crtc, old_crtc_state, old_state);
6503
6504         drm_crtc_vblank_off(crtc);
6505         assert_vblank_disabled(crtc);
6506
6507         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
6508         if (!transcoder_is_dsi(cpu_transcoder))
6509                 intel_disable_pipe(old_crtc_state);
6510
6511         if (intel_crtc_has_type(old_crtc_state, INTEL_OUTPUT_DP_MST))
6512                 intel_ddi_set_vc_payload_alloc(old_crtc_state, false);
6513
6514         if (!transcoder_is_dsi(cpu_transcoder))
6515                 intel_ddi_disable_transcoder_func(old_crtc_state);
6516
6517         intel_dsc_disable(old_crtc_state);
6518
6519         if (INTEL_GEN(dev_priv) >= 9)
6520                 skylake_scaler_disable(intel_crtc);
6521         else
6522                 ironlake_pfit_disable(old_crtc_state);
6523
6524         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
6525
6526         intel_encoders_post_pll_disable(crtc, old_crtc_state, old_state);
6527 }
6528
6529 static void i9xx_pfit_enable(const struct intel_crtc_state *crtc_state)
6530 {
6531         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6532         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6533
6534         if (!crtc_state->gmch_pfit.control)
6535                 return;
6536
6537         /*
6538          * The panel fitter should only be adjusted whilst the pipe is disabled,
6539          * according to register description and PRM.
6540          */
6541         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
6542         assert_pipe_disabled(dev_priv, crtc->pipe);
6543
6544         I915_WRITE(PFIT_PGM_RATIOS, crtc_state->gmch_pfit.pgm_ratios);
6545         I915_WRITE(PFIT_CONTROL, crtc_state->gmch_pfit.control);
6546
6547         /* Border color in case we don't scale up to the full screen. Black by
6548          * default, change to something else for debugging. */
6549         I915_WRITE(BCLRPAT(crtc->pipe), 0);
6550 }
6551
6552 bool intel_port_is_combophy(struct drm_i915_private *dev_priv, enum port port)
6553 {
6554         if (port == PORT_NONE)
6555                 return false;
6556
6557         if (IS_ELKHARTLAKE(dev_priv))
6558                 return port <= PORT_C;
6559
6560         if (INTEL_GEN(dev_priv) >= 11)
6561                 return port <= PORT_B;
6562
6563         return false;
6564 }
6565
6566 bool intel_port_is_tc(struct drm_i915_private *dev_priv, enum port port)
6567 {
6568         if (INTEL_GEN(dev_priv) >= 11 && !IS_ELKHARTLAKE(dev_priv))
6569                 return port >= PORT_C && port <= PORT_F;
6570
6571         return false;
6572 }
6573
6574 enum tc_port intel_port_to_tc(struct drm_i915_private *dev_priv, enum port port)
6575 {
6576         if (!intel_port_is_tc(dev_priv, port))
6577                 return PORT_TC_NONE;
6578
6579         return port - PORT_C;
6580 }
6581
6582 enum intel_display_power_domain intel_port_to_power_domain(enum port port)
6583 {
6584         switch (port) {
6585         case PORT_A:
6586                 return POWER_DOMAIN_PORT_DDI_A_LANES;
6587         case PORT_B:
6588                 return POWER_DOMAIN_PORT_DDI_B_LANES;
6589         case PORT_C:
6590                 return POWER_DOMAIN_PORT_DDI_C_LANES;
6591         case PORT_D:
6592                 return POWER_DOMAIN_PORT_DDI_D_LANES;
6593         case PORT_E:
6594                 return POWER_DOMAIN_PORT_DDI_E_LANES;
6595         case PORT_F:
6596                 return POWER_DOMAIN_PORT_DDI_F_LANES;
6597         default:
6598                 MISSING_CASE(port);
6599                 return POWER_DOMAIN_PORT_OTHER;
6600         }
6601 }
6602
6603 enum intel_display_power_domain
6604 intel_aux_power_domain(struct intel_digital_port *dig_port)
6605 {
6606         switch (dig_port->aux_ch) {
6607         case AUX_CH_A:
6608                 return POWER_DOMAIN_AUX_A;
6609         case AUX_CH_B:
6610                 return POWER_DOMAIN_AUX_B;
6611         case AUX_CH_C:
6612                 return POWER_DOMAIN_AUX_C;
6613         case AUX_CH_D:
6614                 return POWER_DOMAIN_AUX_D;
6615         case AUX_CH_E:
6616                 return POWER_DOMAIN_AUX_E;
6617         case AUX_CH_F:
6618                 return POWER_DOMAIN_AUX_F;
6619         default:
6620                 MISSING_CASE(dig_port->aux_ch);
6621                 return POWER_DOMAIN_AUX_A;
6622         }
6623 }
6624
6625 static u64 get_crtc_power_domains(struct drm_crtc *crtc,
6626                                   struct intel_crtc_state *crtc_state)
6627 {
6628         struct drm_device *dev = crtc->dev;
6629         struct drm_i915_private *dev_priv = to_i915(dev);
6630         struct drm_encoder *encoder;
6631         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6632         enum pipe pipe = intel_crtc->pipe;
6633         u64 mask;
6634         enum transcoder transcoder = crtc_state->cpu_transcoder;
6635
6636         if (!crtc_state->base.active)
6637                 return 0;
6638
6639         mask = BIT_ULL(POWER_DOMAIN_PIPE(pipe));
6640         mask |= BIT_ULL(POWER_DOMAIN_TRANSCODER(transcoder));
6641         if (crtc_state->pch_pfit.enabled ||
6642             crtc_state->pch_pfit.force_thru)
6643                 mask |= BIT_ULL(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
6644
6645         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
6646                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6647
6648                 mask |= BIT_ULL(intel_encoder->power_domain);
6649         }
6650
6651         if (HAS_DDI(dev_priv) && crtc_state->has_audio)
6652                 mask |= BIT_ULL(POWER_DOMAIN_AUDIO);
6653
6654         if (crtc_state->shared_dpll)
6655                 mask |= BIT_ULL(POWER_DOMAIN_DISPLAY_CORE);
6656
6657         return mask;
6658 }
6659
6660 static u64
6661 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
6662                                struct intel_crtc_state *crtc_state)
6663 {
6664         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6665         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6666         enum intel_display_power_domain domain;
6667         u64 domains, new_domains, old_domains;
6668
6669         old_domains = intel_crtc->enabled_power_domains;
6670         intel_crtc->enabled_power_domains = new_domains =
6671                 get_crtc_power_domains(crtc, crtc_state);
6672
6673         domains = new_domains & ~old_domains;
6674
6675         for_each_power_domain(domain, domains)
6676                 intel_display_power_get(dev_priv, domain);
6677
6678         return old_domains & ~new_domains;
6679 }
6680
6681 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
6682                                       u64 domains)
6683 {
6684         enum intel_display_power_domain domain;
6685
6686         for_each_power_domain(domain, domains)
6687                 intel_display_power_put_unchecked(dev_priv, domain);
6688 }
6689
6690 static void valleyview_crtc_enable(struct intel_crtc_state *pipe_config,
6691                                    struct drm_atomic_state *old_state)
6692 {
6693         struct intel_atomic_state *old_intel_state =
6694                 to_intel_atomic_state(old_state);
6695         struct drm_crtc *crtc = pipe_config->base.crtc;
6696         struct drm_device *dev = crtc->dev;
6697         struct drm_i915_private *dev_priv = to_i915(dev);
6698         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6699         int pipe = intel_crtc->pipe;
6700
6701         if (WARN_ON(intel_crtc->active))
6702                 return;
6703
6704         if (intel_crtc_has_dp_encoder(pipe_config))
6705                 intel_dp_set_m_n(pipe_config, M1_N1);
6706
6707         intel_set_pipe_timings(pipe_config);
6708         intel_set_pipe_src_size(pipe_config);
6709
6710         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
6711                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6712                 I915_WRITE(CHV_CANVAS(pipe), 0);
6713         }
6714
6715         i9xx_set_pipeconf(pipe_config);
6716
6717         intel_crtc->active = true;
6718
6719         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6720
6721         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
6722
6723         if (IS_CHERRYVIEW(dev_priv)) {
6724                 chv_prepare_pll(intel_crtc, pipe_config);
6725                 chv_enable_pll(intel_crtc, pipe_config);
6726         } else {
6727                 vlv_prepare_pll(intel_crtc, pipe_config);
6728                 vlv_enable_pll(intel_crtc, pipe_config);
6729         }
6730
6731         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6732
6733         i9xx_pfit_enable(pipe_config);
6734
6735         intel_color_load_luts(pipe_config);
6736         intel_color_commit(pipe_config);
6737         /* update DSPCNTR to configure gamma for pipe bottom color */
6738         intel_disable_primary_plane(pipe_config);
6739
6740         dev_priv->display.initial_watermarks(old_intel_state,
6741                                              pipe_config);
6742         intel_enable_pipe(pipe_config);
6743
6744         assert_vblank_disabled(crtc);
6745         intel_crtc_vblank_on(pipe_config);
6746
6747         intel_encoders_enable(crtc, pipe_config, old_state);
6748 }
6749
6750 static void i9xx_set_pll_dividers(const struct intel_crtc_state *crtc_state)
6751 {
6752         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6753         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6754
6755         I915_WRITE(FP0(crtc->pipe), crtc_state->dpll_hw_state.fp0);
6756         I915_WRITE(FP1(crtc->pipe), crtc_state->dpll_hw_state.fp1);
6757 }
6758
6759 static void i9xx_crtc_enable(struct intel_crtc_state *pipe_config,
6760                              struct drm_atomic_state *old_state)
6761 {
6762         struct intel_atomic_state *old_intel_state =
6763                 to_intel_atomic_state(old_state);
6764         struct drm_crtc *crtc = pipe_config->base.crtc;
6765         struct drm_device *dev = crtc->dev;
6766         struct drm_i915_private *dev_priv = to_i915(dev);
6767         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6768         enum pipe pipe = intel_crtc->pipe;
6769
6770         if (WARN_ON(intel_crtc->active))
6771                 return;
6772
6773         i9xx_set_pll_dividers(pipe_config);
6774
6775         if (intel_crtc_has_dp_encoder(pipe_config))
6776                 intel_dp_set_m_n(pipe_config, M1_N1);
6777
6778         intel_set_pipe_timings(pipe_config);
6779         intel_set_pipe_src_size(pipe_config);
6780
6781         i9xx_set_pipeconf(pipe_config);
6782
6783         intel_crtc->active = true;
6784
6785         if (!IS_GEN(dev_priv, 2))
6786                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6787
6788         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6789
6790         i9xx_enable_pll(intel_crtc, pipe_config);
6791
6792         i9xx_pfit_enable(pipe_config);
6793
6794         intel_color_load_luts(pipe_config);
6795         intel_color_commit(pipe_config);
6796         /* update DSPCNTR to configure gamma for pipe bottom color */
6797         intel_disable_primary_plane(pipe_config);
6798
6799         if (dev_priv->display.initial_watermarks != NULL)
6800                 dev_priv->display.initial_watermarks(old_intel_state,
6801                                                      pipe_config);
6802         else
6803                 intel_update_watermarks(intel_crtc);
6804         intel_enable_pipe(pipe_config);
6805
6806         assert_vblank_disabled(crtc);
6807         intel_crtc_vblank_on(pipe_config);
6808
6809         intel_encoders_enable(crtc, pipe_config, old_state);
6810 }
6811
6812 static void i9xx_pfit_disable(const struct intel_crtc_state *old_crtc_state)
6813 {
6814         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
6815         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6816
6817         if (!old_crtc_state->gmch_pfit.control)
6818                 return;
6819
6820         assert_pipe_disabled(dev_priv, crtc->pipe);
6821
6822         DRM_DEBUG_KMS("disabling pfit, current: 0x%08x\n",
6823                       I915_READ(PFIT_CONTROL));
6824         I915_WRITE(PFIT_CONTROL, 0);
6825 }
6826
6827 static void i9xx_crtc_disable(struct intel_crtc_state *old_crtc_state,
6828                               struct drm_atomic_state *old_state)
6829 {
6830         struct drm_crtc *crtc = old_crtc_state->base.crtc;
6831         struct drm_device *dev = crtc->dev;
6832         struct drm_i915_private *dev_priv = to_i915(dev);
6833         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6834         int pipe = intel_crtc->pipe;
6835
6836         /*
6837          * On gen2 planes are double buffered but the pipe isn't, so we must
6838          * wait for planes to fully turn off before disabling the pipe.
6839          */
6840         if (IS_GEN(dev_priv, 2))
6841                 intel_wait_for_vblank(dev_priv, pipe);
6842
6843         intel_encoders_disable(crtc, old_crtc_state, old_state);
6844
6845         drm_crtc_vblank_off(crtc);
6846         assert_vblank_disabled(crtc);
6847
6848         intel_disable_pipe(old_crtc_state);
6849
6850         i9xx_pfit_disable(old_crtc_state);
6851
6852         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
6853
6854         if (!intel_crtc_has_type(old_crtc_state, INTEL_OUTPUT_DSI)) {
6855                 if (IS_CHERRYVIEW(dev_priv))
6856                         chv_disable_pll(dev_priv, pipe);
6857                 else if (IS_VALLEYVIEW(dev_priv))
6858                         vlv_disable_pll(dev_priv, pipe);
6859                 else
6860                         i9xx_disable_pll(old_crtc_state);
6861         }
6862
6863         intel_encoders_post_pll_disable(crtc, old_crtc_state, old_state);
6864
6865         if (!IS_GEN(dev_priv, 2))
6866                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6867
6868         if (!dev_priv->display.initial_watermarks)
6869                 intel_update_watermarks(intel_crtc);
6870
6871         /* clock the pipe down to 640x480@60 to potentially save power */
6872         if (IS_I830(dev_priv))
6873                 i830_enable_pipe(dev_priv, pipe);
6874 }
6875
6876 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc,
6877                                         struct drm_modeset_acquire_ctx *ctx)
6878 {
6879         struct intel_encoder *encoder;
6880         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6881         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6882         enum intel_display_power_domain domain;
6883         struct intel_plane *plane;
6884         u64 domains;
6885         struct drm_atomic_state *state;
6886         struct intel_crtc_state *crtc_state;
6887         int ret;
6888
6889         if (!intel_crtc->active)
6890                 return;
6891
6892         for_each_intel_plane_on_crtc(&dev_priv->drm, intel_crtc, plane) {
6893                 const struct intel_plane_state *plane_state =
6894                         to_intel_plane_state(plane->base.state);
6895
6896                 if (plane_state->base.visible)
6897                         intel_plane_disable_noatomic(intel_crtc, plane);
6898         }
6899
6900         state = drm_atomic_state_alloc(crtc->dev);
6901         if (!state) {
6902                 DRM_DEBUG_KMS("failed to disable [CRTC:%d:%s], out of memory",
6903                               crtc->base.id, crtc->name);
6904                 return;
6905         }
6906
6907         state->acquire_ctx = ctx;
6908
6909         /* Everything's already locked, -EDEADLK can't happen. */
6910         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
6911         ret = drm_atomic_add_affected_connectors(state, crtc);
6912
6913         WARN_ON(IS_ERR(crtc_state) || ret);
6914
6915         dev_priv->display.crtc_disable(crtc_state, state);
6916
6917         drm_atomic_state_put(state);
6918
6919         DRM_DEBUG_KMS("[CRTC:%d:%s] hw state adjusted, was enabled, now disabled\n",
6920                       crtc->base.id, crtc->name);
6921
6922         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
6923         crtc->state->active = false;
6924         intel_crtc->active = false;
6925         crtc->enabled = false;
6926         crtc->state->connector_mask = 0;
6927         crtc->state->encoder_mask = 0;
6928
6929         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
6930                 encoder->base.crtc = NULL;
6931
6932         intel_fbc_disable(intel_crtc);
6933         intel_update_watermarks(intel_crtc);
6934         intel_disable_shared_dpll(to_intel_crtc_state(crtc->state));
6935
6936         domains = intel_crtc->enabled_power_domains;
6937         for_each_power_domain(domain, domains)
6938                 intel_display_power_put_unchecked(dev_priv, domain);
6939         intel_crtc->enabled_power_domains = 0;
6940
6941         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6942         dev_priv->min_cdclk[intel_crtc->pipe] = 0;
6943         dev_priv->min_voltage_level[intel_crtc->pipe] = 0;
6944 }
6945
6946 /*
6947  * turn all crtc's off, but do not adjust state
6948  * This has to be paired with a call to intel_modeset_setup_hw_state.
6949  */
6950 int intel_display_suspend(struct drm_device *dev)
6951 {
6952         struct drm_i915_private *dev_priv = to_i915(dev);
6953         struct drm_atomic_state *state;
6954         int ret;
6955
6956         state = drm_atomic_helper_suspend(dev);
6957         ret = PTR_ERR_OR_ZERO(state);
6958         if (ret)
6959                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6960         else
6961                 dev_priv->modeset_restore_state = state;
6962         return ret;
6963 }
6964
6965 void intel_encoder_destroy(struct drm_encoder *encoder)
6966 {
6967         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6968
6969         drm_encoder_cleanup(encoder);
6970         kfree(intel_encoder);
6971 }
6972
6973 /* Cross check the actual hw state with our own modeset state tracking (and it's
6974  * internal consistency). */
6975 static void intel_connector_verify_state(struct drm_crtc_state *crtc_state,
6976                                          struct drm_connector_state *conn_state)
6977 {
6978         struct intel_connector *connector = to_intel_connector(conn_state->connector);
6979
6980         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6981                       connector->base.base.id,
6982                       connector->base.name);
6983
6984         if (connector->get_hw_state(connector)) {
6985                 struct intel_encoder *encoder = connector->encoder;
6986
6987                 I915_STATE_WARN(!crtc_state,
6988                          "connector enabled without attached crtc\n");
6989
6990                 if (!crtc_state)
6991                         return;
6992
6993                 I915_STATE_WARN(!crtc_state->active,
6994                       "connector is active, but attached crtc isn't\n");
6995
6996                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6997                         return;
6998
6999                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
7000                         "atomic encoder doesn't match attached encoder\n");
7001
7002                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
7003                         "attached encoder crtc differs from connector crtc\n");
7004         } else {
7005                 I915_STATE_WARN(crtc_state && crtc_state->active,
7006                         "attached crtc is active, but connector isn't\n");
7007                 I915_STATE_WARN(!crtc_state && conn_state->best_encoder,
7008                         "best encoder set without crtc!\n");
7009         }
7010 }
7011
7012 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
7013 {
7014         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
7015                 return crtc_state->fdi_lanes;
7016
7017         return 0;
7018 }
7019
7020 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
7021                                      struct intel_crtc_state *pipe_config)
7022 {
7023         struct drm_i915_private *dev_priv = to_i915(dev);
7024         struct drm_atomic_state *state = pipe_config->base.state;
7025         struct intel_crtc *other_crtc;
7026         struct intel_crtc_state *other_crtc_state;
7027
7028         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
7029                       pipe_name(pipe), pipe_config->fdi_lanes);
7030         if (pipe_config->fdi_lanes > 4) {
7031                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
7032                               pipe_name(pipe), pipe_config->fdi_lanes);
7033                 return -EINVAL;
7034         }
7035
7036         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
7037                 if (pipe_config->fdi_lanes > 2) {
7038                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
7039                                       pipe_config->fdi_lanes);
7040                         return -EINVAL;
7041                 } else {
7042                         return 0;
7043                 }
7044         }
7045
7046         if (INTEL_INFO(dev_priv)->num_pipes == 2)
7047                 return 0;
7048
7049         /* Ivybridge 3 pipe is really complicated */
7050         switch (pipe) {
7051         case PIPE_A:
7052                 return 0;
7053         case PIPE_B:
7054                 if (pipe_config->fdi_lanes <= 2)
7055                         return 0;
7056
7057                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_C);
7058                 other_crtc_state =
7059                         intel_atomic_get_crtc_state(state, other_crtc);
7060                 if (IS_ERR(other_crtc_state))
7061                         return PTR_ERR(other_crtc_state);
7062
7063                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
7064                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
7065                                       pipe_name(pipe), pipe_config->fdi_lanes);
7066                         return -EINVAL;
7067                 }
7068                 return 0;
7069         case PIPE_C:
7070                 if (pipe_config->fdi_lanes > 2) {
7071                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
7072                                       pipe_name(pipe), pipe_config->fdi_lanes);
7073                         return -EINVAL;
7074                 }
7075
7076                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_B);
7077                 other_crtc_state =
7078                         intel_atomic_get_crtc_state(state, other_crtc);
7079                 if (IS_ERR(other_crtc_state))
7080                         return PTR_ERR(other_crtc_state);
7081
7082                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
7083                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
7084                         return -EINVAL;
7085                 }
7086                 return 0;
7087         default:
7088                 BUG();
7089         }
7090 }
7091
7092 #define RETRY 1
7093 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
7094                                        struct intel_crtc_state *pipe_config)
7095 {
7096         struct drm_device *dev = intel_crtc->base.dev;
7097         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
7098         int lane, link_bw, fdi_dotclock, ret;
7099         bool needs_recompute = false;
7100
7101 retry:
7102         /* FDI is a binary signal running at ~2.7GHz, encoding
7103          * each output octet as 10 bits. The actual frequency
7104          * is stored as a divider into a 100MHz clock, and the
7105          * mode pixel clock is stored in units of 1KHz.
7106          * Hence the bw of each lane in terms of the mode signal
7107          * is:
7108          */
7109         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
7110
7111         fdi_dotclock = adjusted_mode->crtc_clock;
7112
7113         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
7114                                            pipe_config->pipe_bpp);
7115
7116         pipe_config->fdi_lanes = lane;
7117
7118         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
7119                                link_bw, &pipe_config->fdi_m_n, false);
7120
7121         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
7122         if (ret == -EDEADLK)
7123                 return ret;
7124
7125         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
7126                 pipe_config->pipe_bpp -= 2*3;
7127                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
7128                               pipe_config->pipe_bpp);
7129                 needs_recompute = true;
7130                 pipe_config->bw_constrained = true;
7131
7132                 goto retry;
7133         }
7134
7135         if (needs_recompute)
7136                 return RETRY;
7137
7138         return ret;
7139 }
7140
7141 bool hsw_crtc_state_ips_capable(const struct intel_crtc_state *crtc_state)
7142 {
7143         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
7144         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7145
7146         /* IPS only exists on ULT machines and is tied to pipe A. */
7147         if (!hsw_crtc_supports_ips(crtc))
7148                 return false;
7149
7150         if (!i915_modparams.enable_ips)
7151                 return false;
7152
7153         if (crtc_state->pipe_bpp > 24)
7154                 return false;
7155
7156         /*
7157          * We compare against max which means we must take
7158          * the increased cdclk requirement into account when
7159          * calculating the new cdclk.
7160          *
7161          * Should measure whether using a lower cdclk w/o IPS
7162          */
7163         if (IS_BROADWELL(dev_priv) &&
7164             crtc_state->pixel_rate > dev_priv->max_cdclk_freq * 95 / 100)
7165                 return false;
7166
7167         return true;
7168 }
7169
7170 static bool hsw_compute_ips_config(struct intel_crtc_state *crtc_state)
7171 {
7172         struct drm_i915_private *dev_priv =
7173                 to_i915(crtc_state->base.crtc->dev);
7174         struct intel_atomic_state *intel_state =
7175                 to_intel_atomic_state(crtc_state->base.state);
7176
7177         if (!hsw_crtc_state_ips_capable(crtc_state))
7178                 return false;
7179
7180         /*
7181          * When IPS gets enabled, the pipe CRC changes. Since IPS gets
7182          * enabled and disabled dynamically based on package C states,
7183          * user space can't make reliable use of the CRCs, so let's just
7184          * completely disable it.
7185          */
7186         if (crtc_state->crc_enabled)
7187                 return false;
7188
7189         /* IPS should be fine as long as at least one plane is enabled. */
7190         if (!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)))
7191                 return false;
7192
7193         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
7194         if (IS_BROADWELL(dev_priv) &&
7195             crtc_state->pixel_rate > intel_state->cdclk.logical.cdclk * 95 / 100)
7196                 return false;
7197
7198         return true;
7199 }
7200
7201 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
7202 {
7203         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7204
7205         /* GDG double wide on either pipe, otherwise pipe A only */
7206         return INTEL_GEN(dev_priv) < 4 &&
7207                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
7208 }
7209
7210 static u32 ilk_pipe_pixel_rate(const struct intel_crtc_state *pipe_config)
7211 {
7212         u32 pixel_rate;
7213
7214         pixel_rate = pipe_config->base.adjusted_mode.crtc_clock;
7215
7216         /*
7217          * We only use IF-ID interlacing. If we ever use
7218          * PF-ID we'll need to adjust the pixel_rate here.
7219          */
7220
7221         if (pipe_config->pch_pfit.enabled) {
7222                 u64 pipe_w, pipe_h, pfit_w, pfit_h;
7223                 u32 pfit_size = pipe_config->pch_pfit.size;
7224
7225                 pipe_w = pipe_config->pipe_src_w;
7226                 pipe_h = pipe_config->pipe_src_h;
7227
7228                 pfit_w = (pfit_size >> 16) & 0xFFFF;
7229                 pfit_h = pfit_size & 0xFFFF;
7230                 if (pipe_w < pfit_w)
7231                         pipe_w = pfit_w;
7232                 if (pipe_h < pfit_h)
7233                         pipe_h = pfit_h;
7234
7235                 if (WARN_ON(!pfit_w || !pfit_h))
7236                         return pixel_rate;
7237
7238                 pixel_rate = div_u64(mul_u32_u32(pixel_rate, pipe_w * pipe_h),
7239                                      pfit_w * pfit_h);
7240         }
7241
7242         return pixel_rate;
7243 }
7244
7245 static void intel_crtc_compute_pixel_rate(struct intel_crtc_state *crtc_state)
7246 {
7247         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
7248
7249         if (HAS_GMCH(dev_priv))
7250                 /* FIXME calculate proper pipe pixel rate for GMCH pfit */
7251                 crtc_state->pixel_rate =
7252                         crtc_state->base.adjusted_mode.crtc_clock;
7253         else
7254                 crtc_state->pixel_rate =
7255                         ilk_pipe_pixel_rate(crtc_state);
7256 }
7257
7258 static int intel_crtc_compute_config(struct intel_crtc *crtc,
7259                                      struct intel_crtc_state *pipe_config)
7260 {
7261         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7262         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
7263         int clock_limit = dev_priv->max_dotclk_freq;
7264
7265         if (INTEL_GEN(dev_priv) < 4) {
7266                 clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
7267
7268                 /*
7269                  * Enable double wide mode when the dot clock
7270                  * is > 90% of the (display) core speed.
7271                  */
7272                 if (intel_crtc_supports_double_wide(crtc) &&
7273                     adjusted_mode->crtc_clock > clock_limit) {
7274                         clock_limit = dev_priv->max_dotclk_freq;
7275                         pipe_config->double_wide = true;
7276                 }
7277         }
7278
7279         if (adjusted_mode->crtc_clock > clock_limit) {
7280                 DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
7281                               adjusted_mode->crtc_clock, clock_limit,
7282                               yesno(pipe_config->double_wide));
7283                 return -EINVAL;
7284         }
7285
7286         if ((pipe_config->output_format == INTEL_OUTPUT_FORMAT_YCBCR420 ||
7287              pipe_config->output_format == INTEL_OUTPUT_FORMAT_YCBCR444) &&
7288              pipe_config->base.ctm) {
7289                 /*
7290                  * There is only one pipe CSC unit per pipe, and we need that
7291                  * for output conversion from RGB->YCBCR. So if CTM is already
7292                  * applied we can't support YCBCR420 output.
7293                  */
7294                 DRM_DEBUG_KMS("YCBCR420 and CTM together are not possible\n");
7295                 return -EINVAL;
7296         }
7297
7298         /*
7299          * Pipe horizontal size must be even in:
7300          * - DVO ganged mode
7301          * - LVDS dual channel mode
7302          * - Double wide pipe
7303          */
7304         if (pipe_config->pipe_src_w & 1) {
7305                 if (pipe_config->double_wide) {
7306                         DRM_DEBUG_KMS("Odd pipe source width not supported with double wide pipe\n");
7307                         return -EINVAL;
7308                 }
7309
7310                 if (intel_crtc_has_type(pipe_config, INTEL_OUTPUT_LVDS) &&
7311                     intel_is_dual_link_lvds(dev_priv)) {
7312                         DRM_DEBUG_KMS("Odd pipe source width not supported with dual link LVDS\n");
7313                         return -EINVAL;
7314                 }
7315         }
7316
7317         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
7318          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
7319          */
7320         if ((INTEL_GEN(dev_priv) > 4 || IS_G4X(dev_priv)) &&
7321                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
7322                 return -EINVAL;
7323
7324         intel_crtc_compute_pixel_rate(pipe_config);
7325
7326         if (pipe_config->has_pch_encoder)
7327                 return ironlake_fdi_compute_config(crtc, pipe_config);
7328
7329         return 0;
7330 }
7331
7332 static void
7333 intel_reduce_m_n_ratio(u32 *num, u32 *den)
7334 {
7335         while (*num > DATA_LINK_M_N_MASK ||
7336                *den > DATA_LINK_M_N_MASK) {
7337                 *num >>= 1;
7338                 *den >>= 1;
7339         }
7340 }
7341
7342 static void compute_m_n(unsigned int m, unsigned int n,
7343                         u32 *ret_m, u32 *ret_n,
7344                         bool constant_n)
7345 {
7346         /*
7347          * Several DP dongles in particular seem to be fussy about
7348          * too large link M/N values. Give N value as 0x8000 that
7349          * should be acceptable by specific devices. 0x8000 is the
7350          * specified fixed N value for asynchronous clock mode,
7351          * which the devices expect also in synchronous clock mode.
7352          */
7353         if (constant_n)
7354                 *ret_n = 0x8000;
7355         else
7356                 *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
7357
7358         *ret_m = div_u64(mul_u32_u32(m, *ret_n), n);
7359         intel_reduce_m_n_ratio(ret_m, ret_n);
7360 }
7361
7362 void
7363 intel_link_compute_m_n(u16 bits_per_pixel, int nlanes,
7364                        int pixel_clock, int link_clock,
7365                        struct intel_link_m_n *m_n,
7366                        bool constant_n)
7367 {
7368         m_n->tu = 64;
7369
7370         compute_m_n(bits_per_pixel * pixel_clock,
7371                     link_clock * nlanes * 8,
7372                     &m_n->gmch_m, &m_n->gmch_n,
7373                     constant_n);
7374
7375         compute_m_n(pixel_clock, link_clock,
7376                     &m_n->link_m, &m_n->link_n,
7377                     constant_n);
7378 }
7379
7380 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
7381 {
7382         if (i915_modparams.panel_use_ssc >= 0)
7383                 return i915_modparams.panel_use_ssc != 0;
7384         return dev_priv->vbt.lvds_use_ssc
7385                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
7386 }
7387
7388 static u32 pnv_dpll_compute_fp(struct dpll *dpll)
7389 {
7390         return (1 << dpll->n) << 16 | dpll->m2;
7391 }
7392
7393 static u32 i9xx_dpll_compute_fp(struct dpll *dpll)
7394 {
7395         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
7396 }
7397
7398 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
7399                                      struct intel_crtc_state *crtc_state,
7400                                      struct dpll *reduced_clock)
7401 {
7402         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7403         u32 fp, fp2 = 0;
7404
7405         if (IS_PINEVIEW(dev_priv)) {
7406                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
7407                 if (reduced_clock)
7408                         fp2 = pnv_dpll_compute_fp(reduced_clock);
7409         } else {
7410                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
7411                 if (reduced_clock)
7412                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
7413         }
7414
7415         crtc_state->dpll_hw_state.fp0 = fp;
7416
7417         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7418             reduced_clock) {
7419                 crtc_state->dpll_hw_state.fp1 = fp2;
7420         } else {
7421                 crtc_state->dpll_hw_state.fp1 = fp;
7422         }
7423 }
7424
7425 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
7426                 pipe)
7427 {
7428         u32 reg_val;
7429
7430         /*
7431          * PLLB opamp always calibrates to max value of 0x3f, force enable it
7432          * and set it to a reasonable value instead.
7433          */
7434         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7435         reg_val &= 0xffffff00;
7436         reg_val |= 0x00000030;
7437         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7438
7439         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7440         reg_val &= 0x00ffffff;
7441         reg_val |= 0x8c000000;
7442         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7443
7444         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7445         reg_val &= 0xffffff00;
7446         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7447
7448         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7449         reg_val &= 0x00ffffff;
7450         reg_val |= 0xb0000000;
7451         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7452 }
7453
7454 static void intel_pch_transcoder_set_m_n(const struct intel_crtc_state *crtc_state,
7455                                          const struct intel_link_m_n *m_n)
7456 {
7457         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
7458         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7459         enum pipe pipe = crtc->pipe;
7460
7461         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7462         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
7463         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
7464         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
7465 }
7466
7467 static bool transcoder_has_m2_n2(struct drm_i915_private *dev_priv,
7468                                  enum transcoder transcoder)
7469 {
7470         if (IS_HASWELL(dev_priv))
7471                 return transcoder == TRANSCODER_EDP;
7472
7473         /*
7474          * Strictly speaking some registers are available before
7475          * gen7, but we only support DRRS on gen7+
7476          */
7477         return IS_GEN(dev_priv, 7) || IS_CHERRYVIEW(dev_priv);
7478 }
7479
7480 static void intel_cpu_transcoder_set_m_n(const struct intel_crtc_state *crtc_state,
7481                                          const struct intel_link_m_n *m_n,
7482                                          const struct intel_link_m_n *m2_n2)
7483 {
7484         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
7485         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7486         enum pipe pipe = crtc->pipe;
7487         enum transcoder transcoder = crtc_state->cpu_transcoder;
7488
7489         if (INTEL_GEN(dev_priv) >= 5) {
7490                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
7491                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
7492                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
7493                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
7494                 /*
7495                  *  M2_N2 registers are set only if DRRS is supported
7496                  * (to make sure the registers are not unnecessarily accessed).
7497                  */
7498                 if (m2_n2 && crtc_state->has_drrs &&
7499                     transcoder_has_m2_n2(dev_priv, transcoder)) {
7500                         I915_WRITE(PIPE_DATA_M2(transcoder),
7501                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
7502                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
7503                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
7504                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
7505                 }
7506         } else {
7507                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7508                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
7509                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
7510                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
7511         }
7512 }
7513
7514 void intel_dp_set_m_n(const struct intel_crtc_state *crtc_state, enum link_m_n_set m_n)
7515 {
7516         const struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
7517
7518         if (m_n == M1_N1) {
7519                 dp_m_n = &crtc_state->dp_m_n;
7520                 dp_m2_n2 = &crtc_state->dp_m2_n2;
7521         } else if (m_n == M2_N2) {
7522
7523                 /*
7524                  * M2_N2 registers are not supported. Hence m2_n2 divider value
7525                  * needs to be programmed into M1_N1.
7526                  */
7527                 dp_m_n = &crtc_state->dp_m2_n2;
7528         } else {
7529                 DRM_ERROR("Unsupported divider value\n");
7530                 return;
7531         }
7532
7533         if (crtc_state->has_pch_encoder)
7534                 intel_pch_transcoder_set_m_n(crtc_state, &crtc_state->dp_m_n);
7535         else
7536                 intel_cpu_transcoder_set_m_n(crtc_state, dp_m_n, dp_m2_n2);
7537 }
7538
7539 static void vlv_compute_dpll(struct intel_crtc *crtc,
7540                              struct intel_crtc_state *pipe_config)
7541 {
7542         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
7543                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7544         if (crtc->pipe != PIPE_A)
7545                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7546
7547         /* DPLL not used with DSI, but still need the rest set up */
7548         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
7549                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
7550                         DPLL_EXT_BUFFER_ENABLE_VLV;
7551
7552         pipe_config->dpll_hw_state.dpll_md =
7553                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7554 }
7555
7556 static void chv_compute_dpll(struct intel_crtc *crtc,
7557                              struct intel_crtc_state *pipe_config)
7558 {
7559         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
7560                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7561         if (crtc->pipe != PIPE_A)
7562                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7563
7564         /* DPLL not used with DSI, but still need the rest set up */
7565         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
7566                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE;
7567
7568         pipe_config->dpll_hw_state.dpll_md =
7569                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7570 }
7571
7572 static void vlv_prepare_pll(struct intel_crtc *crtc,
7573                             const struct intel_crtc_state *pipe_config)
7574 {
7575         struct drm_device *dev = crtc->base.dev;
7576         struct drm_i915_private *dev_priv = to_i915(dev);
7577         enum pipe pipe = crtc->pipe;
7578         u32 mdiv;
7579         u32 bestn, bestm1, bestm2, bestp1, bestp2;
7580         u32 coreclk, reg_val;
7581
7582         /* Enable Refclk */
7583         I915_WRITE(DPLL(pipe),
7584                    pipe_config->dpll_hw_state.dpll &
7585                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
7586
7587         /* No need to actually set up the DPLL with DSI */
7588         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7589                 return;
7590
7591         vlv_dpio_get(dev_priv);
7592
7593         bestn = pipe_config->dpll.n;
7594         bestm1 = pipe_config->dpll.m1;
7595         bestm2 = pipe_config->dpll.m2;
7596         bestp1 = pipe_config->dpll.p1;
7597         bestp2 = pipe_config->dpll.p2;
7598
7599         /* See eDP HDMI DPIO driver vbios notes doc */
7600
7601         /* PLL B needs special handling */
7602         if (pipe == PIPE_B)
7603                 vlv_pllb_recal_opamp(dev_priv, pipe);
7604
7605         /* Set up Tx target for periodic Rcomp update */
7606         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
7607
7608         /* Disable target IRef on PLL */
7609         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
7610         reg_val &= 0x00ffffff;
7611         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
7612
7613         /* Disable fast lock */
7614         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
7615
7616         /* Set idtafcrecal before PLL is enabled */
7617         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
7618         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
7619         mdiv |= ((bestn << DPIO_N_SHIFT));
7620         mdiv |= (1 << DPIO_K_SHIFT);
7621
7622         /*
7623          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
7624          * but we don't support that).
7625          * Note: don't use the DAC post divider as it seems unstable.
7626          */
7627         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
7628         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7629
7630         mdiv |= DPIO_ENABLE_CALIBRATION;
7631         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7632
7633         /* Set HBR and RBR LPF coefficients */
7634         if (pipe_config->port_clock == 162000 ||
7635             intel_crtc_has_type(pipe_config, INTEL_OUTPUT_ANALOG) ||
7636             intel_crtc_has_type(pipe_config, INTEL_OUTPUT_HDMI))
7637                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7638                                  0x009f0003);
7639         else
7640                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7641                                  0x00d0000f);
7642
7643         if (intel_crtc_has_dp_encoder(pipe_config)) {
7644                 /* Use SSC source */
7645                 if (pipe == PIPE_A)
7646                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7647                                          0x0df40000);
7648                 else
7649                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7650                                          0x0df70000);
7651         } else { /* HDMI or VGA */
7652                 /* Use bend source */
7653                 if (pipe == PIPE_A)
7654                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7655                                          0x0df70000);
7656                 else
7657                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7658                                          0x0df40000);
7659         }
7660
7661         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
7662         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
7663         if (intel_crtc_has_dp_encoder(pipe_config))
7664                 coreclk |= 0x01000000;
7665         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
7666
7667         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
7668
7669         vlv_dpio_put(dev_priv);
7670 }
7671
7672 static void chv_prepare_pll(struct intel_crtc *crtc,
7673                             const struct intel_crtc_state *pipe_config)
7674 {
7675         struct drm_device *dev = crtc->base.dev;
7676         struct drm_i915_private *dev_priv = to_i915(dev);
7677         enum pipe pipe = crtc->pipe;
7678         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7679         u32 loopfilter, tribuf_calcntr;
7680         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
7681         u32 dpio_val;
7682         int vco;
7683
7684         /* Enable Refclk and SSC */
7685         I915_WRITE(DPLL(pipe),
7686                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
7687
7688         /* No need to actually set up the DPLL with DSI */
7689         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7690                 return;
7691
7692         bestn = pipe_config->dpll.n;
7693         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
7694         bestm1 = pipe_config->dpll.m1;
7695         bestm2 = pipe_config->dpll.m2 >> 22;
7696         bestp1 = pipe_config->dpll.p1;
7697         bestp2 = pipe_config->dpll.p2;
7698         vco = pipe_config->dpll.vco;
7699         dpio_val = 0;
7700         loopfilter = 0;
7701
7702         vlv_dpio_get(dev_priv);
7703
7704         /* p1 and p2 divider */
7705         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
7706                         5 << DPIO_CHV_S1_DIV_SHIFT |
7707                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
7708                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
7709                         1 << DPIO_CHV_K_DIV_SHIFT);
7710
7711         /* Feedback post-divider - m2 */
7712         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
7713
7714         /* Feedback refclk divider - n and m1 */
7715         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
7716                         DPIO_CHV_M1_DIV_BY_2 |
7717                         1 << DPIO_CHV_N_DIV_SHIFT);
7718
7719         /* M2 fraction division */
7720         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
7721
7722         /* M2 fraction division enable */
7723         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7724         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
7725         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
7726         if (bestm2_frac)
7727                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
7728         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
7729
7730         /* Program digital lock detect threshold */
7731         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
7732         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
7733                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
7734         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
7735         if (!bestm2_frac)
7736                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
7737         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
7738
7739         /* Loop filter */
7740         if (vco == 5400000) {
7741                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
7742                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
7743                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
7744                 tribuf_calcntr = 0x9;
7745         } else if (vco <= 6200000) {
7746                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
7747                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
7748                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7749                 tribuf_calcntr = 0x9;
7750         } else if (vco <= 6480000) {
7751                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7752                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7753                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7754                 tribuf_calcntr = 0x8;
7755         } else {
7756                 /* Not supported. Apply the same limits as in the max case */
7757                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7758                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7759                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7760                 tribuf_calcntr = 0;
7761         }
7762         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
7763
7764         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
7765         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
7766         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
7767         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
7768
7769         /* AFC Recal */
7770         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
7771                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
7772                         DPIO_AFC_RECAL);
7773
7774         vlv_dpio_put(dev_priv);
7775 }
7776
7777 /**
7778  * vlv_force_pll_on - forcibly enable just the PLL
7779  * @dev_priv: i915 private structure
7780  * @pipe: pipe PLL to enable
7781  * @dpll: PLL configuration
7782  *
7783  * Enable the PLL for @pipe using the supplied @dpll config. To be used
7784  * in cases where we need the PLL enabled even when @pipe is not going to
7785  * be enabled.
7786  */
7787 int vlv_force_pll_on(struct drm_i915_private *dev_priv, enum pipe pipe,
7788                      const struct dpll *dpll)
7789 {
7790         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
7791         struct intel_crtc_state *pipe_config;
7792
7793         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
7794         if (!pipe_config)
7795                 return -ENOMEM;
7796
7797         pipe_config->base.crtc = &crtc->base;
7798         pipe_config->pixel_multiplier = 1;
7799         pipe_config->dpll = *dpll;
7800
7801         if (IS_CHERRYVIEW(dev_priv)) {
7802                 chv_compute_dpll(crtc, pipe_config);
7803                 chv_prepare_pll(crtc, pipe_config);
7804                 chv_enable_pll(crtc, pipe_config);
7805         } else {
7806                 vlv_compute_dpll(crtc, pipe_config);
7807                 vlv_prepare_pll(crtc, pipe_config);
7808                 vlv_enable_pll(crtc, pipe_config);
7809         }
7810
7811         kfree(pipe_config);
7812
7813         return 0;
7814 }
7815
7816 /**
7817  * vlv_force_pll_off - forcibly disable just the PLL
7818  * @dev_priv: i915 private structure
7819  * @pipe: pipe PLL to disable
7820  *
7821  * Disable the PLL for @pipe. To be used in cases where we need
7822  * the PLL enabled even when @pipe is not going to be enabled.
7823  */
7824 void vlv_force_pll_off(struct drm_i915_private *dev_priv, enum pipe pipe)
7825 {
7826         if (IS_CHERRYVIEW(dev_priv))
7827                 chv_disable_pll(dev_priv, pipe);
7828         else
7829                 vlv_disable_pll(dev_priv, pipe);
7830 }
7831
7832 static void i9xx_compute_dpll(struct intel_crtc *crtc,
7833                               struct intel_crtc_state *crtc_state,
7834                               struct dpll *reduced_clock)
7835 {
7836         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7837         u32 dpll;
7838         struct dpll *clock = &crtc_state->dpll;
7839
7840         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7841
7842         dpll = DPLL_VGA_MODE_DIS;
7843
7844         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
7845                 dpll |= DPLLB_MODE_LVDS;
7846         else
7847                 dpll |= DPLLB_MODE_DAC_SERIAL;
7848
7849         if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
7850             IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
7851                 dpll |= (crtc_state->pixel_multiplier - 1)
7852                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7853         }
7854
7855         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7856             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
7857                 dpll |= DPLL_SDVO_HIGH_SPEED;
7858
7859         if (intel_crtc_has_dp_encoder(crtc_state))
7860                 dpll |= DPLL_SDVO_HIGH_SPEED;
7861
7862         /* compute bitmask from p1 value */
7863         if (IS_PINEVIEW(dev_priv))
7864                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7865         else {
7866                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7867                 if (IS_G4X(dev_priv) && reduced_clock)
7868                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7869         }
7870         switch (clock->p2) {
7871         case 5:
7872                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7873                 break;
7874         case 7:
7875                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7876                 break;
7877         case 10:
7878                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7879                 break;
7880         case 14:
7881                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7882                 break;
7883         }
7884         if (INTEL_GEN(dev_priv) >= 4)
7885                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7886
7887         if (crtc_state->sdvo_tv_clock)
7888                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7889         else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7890                  intel_panel_use_ssc(dev_priv))
7891                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7892         else
7893                 dpll |= PLL_REF_INPUT_DREFCLK;
7894
7895         dpll |= DPLL_VCO_ENABLE;
7896         crtc_state->dpll_hw_state.dpll = dpll;
7897
7898         if (INTEL_GEN(dev_priv) >= 4) {
7899                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7900                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7901                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7902         }
7903 }
7904
7905 static void i8xx_compute_dpll(struct intel_crtc *crtc,
7906                               struct intel_crtc_state *crtc_state,
7907                               struct dpll *reduced_clock)
7908 {
7909         struct drm_device *dev = crtc->base.dev;
7910         struct drm_i915_private *dev_priv = to_i915(dev);
7911         u32 dpll;
7912         struct dpll *clock = &crtc_state->dpll;
7913
7914         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7915
7916         dpll = DPLL_VGA_MODE_DIS;
7917
7918         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7919                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7920         } else {
7921                 if (clock->p1 == 2)
7922                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7923                 else
7924                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7925                 if (clock->p2 == 4)
7926                         dpll |= PLL_P2_DIVIDE_BY_4;
7927         }
7928
7929         /*
7930          * Bspec:
7931          * "[Almador Errata}: For the correct operation of the muxed DVO pins
7932          *  (GDEVSELB/I2Cdata, GIRDBY/I2CClk) and (GFRAMEB/DVI_Data,
7933          *  GTRDYB/DVI_Clk): Bit 31 (DPLL VCO Enable) and Bit 30 (2X Clock
7934          *  Enable) must be set to “1” in both the DPLL A Control Register
7935          *  (06014h-06017h) and DPLL B Control Register (06018h-0601Bh)."
7936          *
7937          * For simplicity We simply keep both bits always enabled in
7938          * both DPLLS. The spec says we should disable the DVO 2X clock
7939          * when not needed, but this seems to work fine in practice.
7940          */
7941         if (IS_I830(dev_priv) ||
7942             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO))
7943                 dpll |= DPLL_DVO_2X_MODE;
7944
7945         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7946             intel_panel_use_ssc(dev_priv))
7947                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7948         else
7949                 dpll |= PLL_REF_INPUT_DREFCLK;
7950
7951         dpll |= DPLL_VCO_ENABLE;
7952         crtc_state->dpll_hw_state.dpll = dpll;
7953 }
7954
7955 static void intel_set_pipe_timings(const struct intel_crtc_state *crtc_state)
7956 {
7957         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
7958         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7959         enum pipe pipe = crtc->pipe;
7960         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
7961         const struct drm_display_mode *adjusted_mode = &crtc_state->base.adjusted_mode;
7962         u32 crtc_vtotal, crtc_vblank_end;
7963         int vsyncshift = 0;
7964
7965         /* We need to be careful not to changed the adjusted mode, for otherwise
7966          * the hw state checker will get angry at the mismatch. */
7967         crtc_vtotal = adjusted_mode->crtc_vtotal;
7968         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7969
7970         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7971                 /* the chip adds 2 halflines automatically */
7972                 crtc_vtotal -= 1;
7973                 crtc_vblank_end -= 1;
7974
7975                 if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO))
7976                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7977                 else
7978                         vsyncshift = adjusted_mode->crtc_hsync_start -
7979                                 adjusted_mode->crtc_htotal / 2;
7980                 if (vsyncshift < 0)
7981                         vsyncshift += adjusted_mode->crtc_htotal;
7982         }
7983
7984         if (INTEL_GEN(dev_priv) > 3)
7985                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7986
7987         I915_WRITE(HTOTAL(cpu_transcoder),
7988                    (adjusted_mode->crtc_hdisplay - 1) |
7989                    ((adjusted_mode->crtc_htotal - 1) << 16));
7990         I915_WRITE(HBLANK(cpu_transcoder),
7991                    (adjusted_mode->crtc_hblank_start - 1) |
7992                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7993         I915_WRITE(HSYNC(cpu_transcoder),
7994                    (adjusted_mode->crtc_hsync_start - 1) |
7995                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7996
7997         I915_WRITE(VTOTAL(cpu_transcoder),
7998                    (adjusted_mode->crtc_vdisplay - 1) |
7999                    ((crtc_vtotal - 1) << 16));
8000         I915_WRITE(VBLANK(cpu_transcoder),
8001                    (adjusted_mode->crtc_vblank_start - 1) |
8002                    ((crtc_vblank_end - 1) << 16));
8003         I915_WRITE(VSYNC(cpu_transcoder),
8004                    (adjusted_mode->crtc_vsync_start - 1) |
8005                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
8006
8007         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
8008          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
8009          * documented on the DDI_FUNC_CTL register description, EDP Input Select
8010          * bits. */
8011         if (IS_HASWELL(dev_priv) && cpu_transcoder == TRANSCODER_EDP &&
8012             (pipe == PIPE_B || pipe == PIPE_C))
8013                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
8014
8015 }
8016
8017 static void intel_set_pipe_src_size(const struct intel_crtc_state *crtc_state)
8018 {
8019         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
8020         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8021         enum pipe pipe = crtc->pipe;
8022
8023         /* pipesrc controls the size that is scaled from, which should
8024          * always be the user's requested size.
8025          */
8026         I915_WRITE(PIPESRC(pipe),
8027                    ((crtc_state->pipe_src_w - 1) << 16) |
8028                    (crtc_state->pipe_src_h - 1));
8029 }
8030
8031 static void intel_get_pipe_timings(struct intel_crtc *crtc,
8032                                    struct intel_crtc_state *pipe_config)
8033 {
8034         struct drm_device *dev = crtc->base.dev;
8035         struct drm_i915_private *dev_priv = to_i915(dev);
8036         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
8037         u32 tmp;
8038
8039         tmp = I915_READ(HTOTAL(cpu_transcoder));
8040         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
8041         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
8042
8043         if (!transcoder_is_dsi(cpu_transcoder)) {
8044                 tmp = I915_READ(HBLANK(cpu_transcoder));
8045                 pipe_config->base.adjusted_mode.crtc_hblank_start =
8046                                                         (tmp & 0xffff) + 1;
8047                 pipe_config->base.adjusted_mode.crtc_hblank_end =
8048                                                 ((tmp >> 16) & 0xffff) + 1;
8049         }
8050         tmp = I915_READ(HSYNC(cpu_transcoder));
8051         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
8052         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
8053
8054         tmp = I915_READ(VTOTAL(cpu_transcoder));
8055         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
8056         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
8057
8058         if (!transcoder_is_dsi(cpu_transcoder)) {
8059                 tmp = I915_READ(VBLANK(cpu_transcoder));
8060                 pipe_config->base.adjusted_mode.crtc_vblank_start =
8061                                                         (tmp & 0xffff) + 1;
8062                 pipe_config->base.adjusted_mode.crtc_vblank_end =
8063                                                 ((tmp >> 16) & 0xffff) + 1;
8064         }
8065         tmp = I915_READ(VSYNC(cpu_transcoder));
8066         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
8067         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
8068
8069         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
8070                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
8071                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
8072                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
8073         }
8074 }
8075
8076 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
8077                                     struct intel_crtc_state *pipe_config)
8078 {
8079         struct drm_device *dev = crtc->base.dev;
8080         struct drm_i915_private *dev_priv = to_i915(dev);
8081         u32 tmp;
8082
8083         tmp = I915_READ(PIPESRC(crtc->pipe));
8084         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
8085         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
8086
8087         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
8088         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
8089 }
8090
8091 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
8092                                  struct intel_crtc_state *pipe_config)
8093 {
8094         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
8095         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
8096         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
8097         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
8098
8099         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
8100         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
8101         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
8102         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
8103
8104         mode->flags = pipe_config->base.adjusted_mode.flags;
8105         mode->type = DRM_MODE_TYPE_DRIVER;
8106
8107         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
8108
8109         mode->hsync = drm_mode_hsync(mode);
8110         mode->vrefresh = drm_mode_vrefresh(mode);
8111         drm_mode_set_name(mode);
8112 }
8113
8114 static void i9xx_set_pipeconf(const struct intel_crtc_state *crtc_state)
8115 {
8116         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
8117         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8118         u32 pipeconf;
8119
8120         pipeconf = 0;
8121
8122         /* we keep both pipes enabled on 830 */
8123         if (IS_I830(dev_priv))
8124                 pipeconf |= I915_READ(PIPECONF(crtc->pipe)) & PIPECONF_ENABLE;
8125
8126         if (crtc_state->double_wide)
8127                 pipeconf |= PIPECONF_DOUBLE_WIDE;
8128
8129         /* only g4x and later have fancy bpc/dither controls */
8130         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
8131             IS_CHERRYVIEW(dev_priv)) {
8132                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
8133                 if (crtc_state->dither && crtc_state->pipe_bpp != 30)
8134                         pipeconf |= PIPECONF_DITHER_EN |
8135                                     PIPECONF_DITHER_TYPE_SP;
8136
8137                 switch (crtc_state->pipe_bpp) {
8138                 case 18:
8139                         pipeconf |= PIPECONF_6BPC;
8140                         break;
8141                 case 24:
8142                         pipeconf |= PIPECONF_8BPC;
8143                         break;
8144                 case 30:
8145                         pipeconf |= PIPECONF_10BPC;
8146                         break;
8147                 default:
8148                         /* Case prevented by intel_choose_pipe_bpp_dither. */
8149                         BUG();
8150                 }
8151         }
8152
8153         if (crtc_state->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
8154                 if (INTEL_GEN(dev_priv) < 4 ||
8155                     intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO))
8156                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
8157                 else
8158                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
8159         } else {
8160                 pipeconf |= PIPECONF_PROGRESSIVE;
8161         }
8162
8163         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
8164              crtc_state->limited_color_range)
8165                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
8166
8167         pipeconf |= PIPECONF_GAMMA_MODE(crtc_state->gamma_mode);
8168
8169         I915_WRITE(PIPECONF(crtc->pipe), pipeconf);
8170         POSTING_READ(PIPECONF(crtc->pipe));
8171 }
8172
8173 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
8174                                    struct intel_crtc_state *crtc_state)
8175 {
8176         struct drm_device *dev = crtc->base.dev;
8177         struct drm_i915_private *dev_priv = to_i915(dev);
8178         const struct intel_limit *limit;
8179         int refclk = 48000;
8180
8181         memset(&crtc_state->dpll_hw_state, 0,
8182                sizeof(crtc_state->dpll_hw_state));
8183
8184         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8185                 if (intel_panel_use_ssc(dev_priv)) {
8186                         refclk = dev_priv->vbt.lvds_ssc_freq;
8187                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8188                 }
8189
8190                 limit = &intel_limits_i8xx_lvds;
8191         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO)) {
8192                 limit = &intel_limits_i8xx_dvo;
8193         } else {
8194                 limit = &intel_limits_i8xx_dac;
8195         }
8196
8197         if (!crtc_state->clock_set &&
8198             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8199                                  refclk, NULL, &crtc_state->dpll)) {
8200                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8201                 return -EINVAL;
8202         }
8203
8204         i8xx_compute_dpll(crtc, crtc_state, NULL);
8205
8206         return 0;
8207 }
8208
8209 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
8210                                   struct intel_crtc_state *crtc_state)
8211 {
8212         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8213         const struct intel_limit *limit;
8214         int refclk = 96000;
8215
8216         memset(&crtc_state->dpll_hw_state, 0,
8217                sizeof(crtc_state->dpll_hw_state));
8218
8219         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8220                 if (intel_panel_use_ssc(dev_priv)) {
8221                         refclk = dev_priv->vbt.lvds_ssc_freq;
8222                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8223                 }
8224
8225                 if (intel_is_dual_link_lvds(dev_priv))
8226                         limit = &intel_limits_g4x_dual_channel_lvds;
8227                 else
8228                         limit = &intel_limits_g4x_single_channel_lvds;
8229         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI) ||
8230                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
8231                 limit = &intel_limits_g4x_hdmi;
8232         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO)) {
8233                 limit = &intel_limits_g4x_sdvo;
8234         } else {
8235                 /* The option is for other outputs */
8236                 limit = &intel_limits_i9xx_sdvo;
8237         }
8238
8239         if (!crtc_state->clock_set &&
8240             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8241                                 refclk, NULL, &crtc_state->dpll)) {
8242                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8243                 return -EINVAL;
8244         }
8245
8246         i9xx_compute_dpll(crtc, crtc_state, NULL);
8247
8248         return 0;
8249 }
8250
8251 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
8252                                   struct intel_crtc_state *crtc_state)
8253 {
8254         struct drm_device *dev = crtc->base.dev;
8255         struct drm_i915_private *dev_priv = to_i915(dev);
8256         const struct intel_limit *limit;
8257         int refclk = 96000;
8258
8259         memset(&crtc_state->dpll_hw_state, 0,
8260                sizeof(crtc_state->dpll_hw_state));
8261
8262         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8263                 if (intel_panel_use_ssc(dev_priv)) {
8264                         refclk = dev_priv->vbt.lvds_ssc_freq;
8265                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8266                 }
8267
8268                 limit = &intel_limits_pineview_lvds;
8269         } else {
8270                 limit = &intel_limits_pineview_sdvo;
8271         }
8272
8273         if (!crtc_state->clock_set &&
8274             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8275                                 refclk, NULL, &crtc_state->dpll)) {
8276                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8277                 return -EINVAL;
8278         }
8279
8280         i9xx_compute_dpll(crtc, crtc_state, NULL);
8281
8282         return 0;
8283 }
8284
8285 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
8286                                    struct intel_crtc_state *crtc_state)
8287 {
8288         struct drm_device *dev = crtc->base.dev;
8289         struct drm_i915_private *dev_priv = to_i915(dev);
8290         const struct intel_limit *limit;
8291         int refclk = 96000;
8292
8293         memset(&crtc_state->dpll_hw_state, 0,
8294                sizeof(crtc_state->dpll_hw_state));
8295
8296         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8297                 if (intel_panel_use_ssc(dev_priv)) {
8298                         refclk = dev_priv->vbt.lvds_ssc_freq;
8299                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8300                 }
8301
8302                 limit = &intel_limits_i9xx_lvds;
8303         } else {
8304                 limit = &intel_limits_i9xx_sdvo;
8305         }
8306
8307         if (!crtc_state->clock_set &&
8308             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8309                                  refclk, NULL, &crtc_state->dpll)) {
8310                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8311                 return -EINVAL;
8312         }
8313
8314         i9xx_compute_dpll(crtc, crtc_state, NULL);
8315
8316         return 0;
8317 }
8318
8319 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
8320                                   struct intel_crtc_state *crtc_state)
8321 {
8322         int refclk = 100000;
8323         const struct intel_limit *limit = &intel_limits_chv;
8324
8325         memset(&crtc_state->dpll_hw_state, 0,
8326                sizeof(crtc_state->dpll_hw_state));
8327
8328         if (!crtc_state->clock_set &&
8329             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8330                                 refclk, NULL, &crtc_state->dpll)) {
8331                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8332                 return -EINVAL;
8333         }
8334
8335         chv_compute_dpll(crtc, crtc_state);
8336
8337         return 0;
8338 }
8339
8340 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
8341                                   struct intel_crtc_state *crtc_state)
8342 {
8343         int refclk = 100000;
8344         const struct intel_limit *limit = &intel_limits_vlv;
8345
8346         memset(&crtc_state->dpll_hw_state, 0,
8347                sizeof(crtc_state->dpll_hw_state));
8348
8349         if (!crtc_state->clock_set &&
8350             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8351                                 refclk, NULL, &crtc_state->dpll)) {
8352                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8353                 return -EINVAL;
8354         }
8355
8356         vlv_compute_dpll(crtc, crtc_state);
8357
8358         return 0;
8359 }
8360
8361 static bool i9xx_has_pfit(struct drm_i915_private *dev_priv)
8362 {
8363         if (IS_I830(dev_priv))
8364                 return false;
8365
8366         return INTEL_GEN(dev_priv) >= 4 ||
8367                 IS_PINEVIEW(dev_priv) || IS_MOBILE(dev_priv);
8368 }
8369
8370 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
8371                                  struct intel_crtc_state *pipe_config)
8372 {
8373         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8374         u32 tmp;
8375
8376         if (!i9xx_has_pfit(dev_priv))
8377                 return;
8378
8379         tmp = I915_READ(PFIT_CONTROL);
8380         if (!(tmp & PFIT_ENABLE))
8381                 return;
8382
8383         /* Check whether the pfit is attached to our pipe. */
8384         if (INTEL_GEN(dev_priv) < 4) {
8385                 if (crtc->pipe != PIPE_B)
8386                         return;
8387         } else {
8388                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
8389                         return;
8390         }
8391
8392         pipe_config->gmch_pfit.control = tmp;
8393         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
8394 }
8395
8396 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
8397                                struct intel_crtc_state *pipe_config)
8398 {
8399         struct drm_device *dev = crtc->base.dev;
8400         struct drm_i915_private *dev_priv = to_i915(dev);
8401         int pipe = pipe_config->cpu_transcoder;
8402         struct dpll clock;
8403         u32 mdiv;
8404         int refclk = 100000;
8405
8406         /* In case of DSI, DPLL will not be used */
8407         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
8408                 return;
8409
8410         vlv_dpio_get(dev_priv);
8411         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
8412         vlv_dpio_put(dev_priv);
8413
8414         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
8415         clock.m2 = mdiv & DPIO_M2DIV_MASK;
8416         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
8417         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
8418         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
8419
8420         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
8421 }
8422
8423 static void
8424 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
8425                               struct intel_initial_plane_config *plane_config)
8426 {
8427         struct drm_device *dev = crtc->base.dev;
8428         struct drm_i915_private *dev_priv = to_i915(dev);
8429         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
8430         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
8431         enum pipe pipe;
8432         u32 val, base, offset;
8433         int fourcc, pixel_format;
8434         unsigned int aligned_height;
8435         struct drm_framebuffer *fb;
8436         struct intel_framebuffer *intel_fb;
8437
8438         if (!plane->get_hw_state(plane, &pipe))
8439                 return;
8440
8441         WARN_ON(pipe != crtc->pipe);
8442
8443         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8444         if (!intel_fb) {
8445                 DRM_DEBUG_KMS("failed to alloc fb\n");
8446                 return;
8447         }
8448
8449         fb = &intel_fb->base;
8450
8451         fb->dev = dev;
8452
8453         val = I915_READ(DSPCNTR(i9xx_plane));
8454
8455         if (INTEL_GEN(dev_priv) >= 4) {
8456                 if (val & DISPPLANE_TILED) {
8457                         plane_config->tiling = I915_TILING_X;
8458                         fb->modifier = I915_FORMAT_MOD_X_TILED;
8459                 }
8460
8461                 if (val & DISPPLANE_ROTATE_180)
8462                         plane_config->rotation = DRM_MODE_ROTATE_180;
8463         }
8464
8465         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B &&
8466             val & DISPPLANE_MIRROR)
8467                 plane_config->rotation |= DRM_MODE_REFLECT_X;
8468
8469         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
8470         fourcc = i9xx_format_to_fourcc(pixel_format);
8471         fb->format = drm_format_info(fourcc);
8472
8473         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
8474                 offset = I915_READ(DSPOFFSET(i9xx_plane));
8475                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
8476         } else if (INTEL_GEN(dev_priv) >= 4) {
8477                 if (plane_config->tiling)
8478                         offset = I915_READ(DSPTILEOFF(i9xx_plane));
8479                 else
8480                         offset = I915_READ(DSPLINOFF(i9xx_plane));
8481                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
8482         } else {
8483                 base = I915_READ(DSPADDR(i9xx_plane));
8484         }
8485         plane_config->base = base;
8486
8487         val = I915_READ(PIPESRC(pipe));
8488         fb->width = ((val >> 16) & 0xfff) + 1;
8489         fb->height = ((val >> 0) & 0xfff) + 1;
8490
8491         val = I915_READ(DSPSTRIDE(i9xx_plane));
8492         fb->pitches[0] = val & 0xffffffc0;
8493
8494         aligned_height = intel_fb_align_height(fb, 0, fb->height);
8495
8496         plane_config->size = fb->pitches[0] * aligned_height;
8497
8498         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8499                       crtc->base.name, plane->base.name, fb->width, fb->height,
8500                       fb->format->cpp[0] * 8, base, fb->pitches[0],
8501                       plane_config->size);
8502
8503         plane_config->fb = intel_fb;
8504 }
8505
8506 static void chv_crtc_clock_get(struct intel_crtc *crtc,
8507                                struct intel_crtc_state *pipe_config)
8508 {
8509         struct drm_device *dev = crtc->base.dev;
8510         struct drm_i915_private *dev_priv = to_i915(dev);
8511         int pipe = pipe_config->cpu_transcoder;
8512         enum dpio_channel port = vlv_pipe_to_channel(pipe);
8513         struct dpll clock;
8514         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
8515         int refclk = 100000;
8516
8517         /* In case of DSI, DPLL will not be used */
8518         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
8519                 return;
8520
8521         vlv_dpio_get(dev_priv);
8522         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
8523         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
8524         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
8525         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
8526         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
8527         vlv_dpio_put(dev_priv);
8528
8529         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
8530         clock.m2 = (pll_dw0 & 0xff) << 22;
8531         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
8532                 clock.m2 |= pll_dw2 & 0x3fffff;
8533         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
8534         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
8535         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
8536
8537         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
8538 }
8539
8540 static void intel_get_crtc_ycbcr_config(struct intel_crtc *crtc,
8541                                         struct intel_crtc_state *pipe_config)
8542 {
8543         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8544         enum intel_output_format output = INTEL_OUTPUT_FORMAT_RGB;
8545
8546         pipe_config->lspcon_downsampling = false;
8547
8548         if (IS_BROADWELL(dev_priv) || INTEL_GEN(dev_priv) >= 9) {
8549                 u32 tmp = I915_READ(PIPEMISC(crtc->pipe));
8550
8551                 if (tmp & PIPEMISC_OUTPUT_COLORSPACE_YUV) {
8552                         bool ycbcr420_enabled = tmp & PIPEMISC_YUV420_ENABLE;
8553                         bool blend = tmp & PIPEMISC_YUV420_MODE_FULL_BLEND;
8554
8555                         if (ycbcr420_enabled) {
8556                                 /* We support 4:2:0 in full blend mode only */
8557                                 if (!blend)
8558                                         output = INTEL_OUTPUT_FORMAT_INVALID;
8559                                 else if (!(IS_GEMINILAKE(dev_priv) ||
8560                                            INTEL_GEN(dev_priv) >= 10))
8561                                         output = INTEL_OUTPUT_FORMAT_INVALID;
8562                                 else
8563                                         output = INTEL_OUTPUT_FORMAT_YCBCR420;
8564                         } else {
8565                                 /*
8566                                  * Currently there is no interface defined to
8567                                  * check user preference between RGB/YCBCR444
8568                                  * or YCBCR420. So the only possible case for
8569                                  * YCBCR444 usage is driving YCBCR420 output
8570                                  * with LSPCON, when pipe is configured for
8571                                  * YCBCR444 output and LSPCON takes care of
8572                                  * downsampling it.
8573                                  */
8574                                 pipe_config->lspcon_downsampling = true;
8575                                 output = INTEL_OUTPUT_FORMAT_YCBCR444;
8576                         }
8577                 }
8578         }
8579
8580         pipe_config->output_format = output;
8581 }
8582
8583 static void i9xx_get_pipe_color_config(struct intel_crtc_state *crtc_state)
8584 {
8585         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
8586         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
8587         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8588         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
8589         u32 tmp;
8590
8591         tmp = I915_READ(DSPCNTR(i9xx_plane));
8592
8593         if (tmp & DISPPLANE_GAMMA_ENABLE)
8594                 crtc_state->gamma_enable = true;
8595
8596         if (!HAS_GMCH(dev_priv) &&
8597             tmp & DISPPLANE_PIPE_CSC_ENABLE)
8598                 crtc_state->csc_enable = true;
8599 }
8600
8601 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
8602                                  struct intel_crtc_state *pipe_config)
8603 {
8604         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8605         enum intel_display_power_domain power_domain;
8606         intel_wakeref_t wakeref;
8607         u32 tmp;
8608         bool ret;
8609
8610         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8611         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
8612         if (!wakeref)
8613                 return false;
8614
8615         pipe_config->output_format = INTEL_OUTPUT_FORMAT_RGB;
8616         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8617         pipe_config->shared_dpll = NULL;
8618
8619         ret = false;
8620
8621         tmp = I915_READ(PIPECONF(crtc->pipe));
8622         if (!(tmp & PIPECONF_ENABLE))
8623                 goto out;
8624
8625         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
8626             IS_CHERRYVIEW(dev_priv)) {
8627                 switch (tmp & PIPECONF_BPC_MASK) {
8628                 case PIPECONF_6BPC:
8629                         pipe_config->pipe_bpp = 18;
8630                         break;
8631                 case PIPECONF_8BPC:
8632                         pipe_config->pipe_bpp = 24;
8633                         break;
8634                 case PIPECONF_10BPC:
8635                         pipe_config->pipe_bpp = 30;
8636                         break;
8637                 default:
8638                         break;
8639                 }
8640         }
8641
8642         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
8643             (tmp & PIPECONF_COLOR_RANGE_SELECT))
8644                 pipe_config->limited_color_range = true;
8645
8646         pipe_config->gamma_mode = (tmp & PIPECONF_GAMMA_MODE_MASK_I9XX) >>
8647                 PIPECONF_GAMMA_MODE_SHIFT;
8648
8649         if (IS_CHERRYVIEW(dev_priv))
8650                 pipe_config->cgm_mode = I915_READ(CGM_PIPE_MODE(crtc->pipe));
8651
8652         i9xx_get_pipe_color_config(pipe_config);
8653
8654         if (INTEL_GEN(dev_priv) < 4)
8655                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
8656
8657         intel_get_pipe_timings(crtc, pipe_config);
8658         intel_get_pipe_src_size(crtc, pipe_config);
8659
8660         i9xx_get_pfit_config(crtc, pipe_config);
8661
8662         if (INTEL_GEN(dev_priv) >= 4) {
8663                 /* No way to read it out on pipes B and C */
8664                 if (IS_CHERRYVIEW(dev_priv) && crtc->pipe != PIPE_A)
8665                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
8666                 else
8667                         tmp = I915_READ(DPLL_MD(crtc->pipe));
8668                 pipe_config->pixel_multiplier =
8669                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
8670                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
8671                 pipe_config->dpll_hw_state.dpll_md = tmp;
8672         } else if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
8673                    IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
8674                 tmp = I915_READ(DPLL(crtc->pipe));
8675                 pipe_config->pixel_multiplier =
8676                         ((tmp & SDVO_MULTIPLIER_MASK)
8677                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
8678         } else {
8679                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
8680                  * port and will be fixed up in the encoder->get_config
8681                  * function. */
8682                 pipe_config->pixel_multiplier = 1;
8683         }
8684         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
8685         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
8686                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
8687                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
8688         } else {
8689                 /* Mask out read-only status bits. */
8690                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
8691                                                      DPLL_PORTC_READY_MASK |
8692                                                      DPLL_PORTB_READY_MASK);
8693         }
8694
8695         if (IS_CHERRYVIEW(dev_priv))
8696                 chv_crtc_clock_get(crtc, pipe_config);
8697         else if (IS_VALLEYVIEW(dev_priv))
8698                 vlv_crtc_clock_get(crtc, pipe_config);
8699         else
8700                 i9xx_crtc_clock_get(crtc, pipe_config);
8701
8702         /*
8703          * Normally the dotclock is filled in by the encoder .get_config()
8704          * but in case the pipe is enabled w/o any ports we need a sane
8705          * default.
8706          */
8707         pipe_config->base.adjusted_mode.crtc_clock =
8708                 pipe_config->port_clock / pipe_config->pixel_multiplier;
8709
8710         ret = true;
8711
8712 out:
8713         intel_display_power_put(dev_priv, power_domain, wakeref);
8714
8715         return ret;
8716 }
8717
8718 static void ironlake_init_pch_refclk(struct drm_i915_private *dev_priv)
8719 {
8720         struct intel_encoder *encoder;
8721         int i;
8722         u32 val, final;
8723         bool has_lvds = false;
8724         bool has_cpu_edp = false;
8725         bool has_panel = false;
8726         bool has_ck505 = false;
8727         bool can_ssc = false;
8728         bool using_ssc_source = false;
8729
8730         /* We need to take the global config into account */
8731         for_each_intel_encoder(&dev_priv->drm, encoder) {
8732                 switch (encoder->type) {
8733                 case INTEL_OUTPUT_LVDS:
8734                         has_panel = true;
8735                         has_lvds = true;
8736                         break;
8737                 case INTEL_OUTPUT_EDP:
8738                         has_panel = true;
8739                         if (encoder->port == PORT_A)
8740                                 has_cpu_edp = true;
8741                         break;
8742                 default:
8743                         break;
8744                 }
8745         }
8746
8747         if (HAS_PCH_IBX(dev_priv)) {
8748                 has_ck505 = dev_priv->vbt.display_clock_mode;
8749                 can_ssc = has_ck505;
8750         } else {
8751                 has_ck505 = false;
8752                 can_ssc = true;
8753         }
8754
8755         /* Check if any DPLLs are using the SSC source */
8756         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
8757                 u32 temp = I915_READ(PCH_DPLL(i));
8758
8759                 if (!(temp & DPLL_VCO_ENABLE))
8760                         continue;
8761
8762                 if ((temp & PLL_REF_INPUT_MASK) ==
8763                     PLLB_REF_INPUT_SPREADSPECTRUMIN) {
8764                         using_ssc_source = true;
8765                         break;
8766                 }
8767         }
8768
8769         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d using_ssc_source %d\n",
8770                       has_panel, has_lvds, has_ck505, using_ssc_source);
8771
8772         /* Ironlake: try to setup display ref clock before DPLL
8773          * enabling. This is only under driver's control after
8774          * PCH B stepping, previous chipset stepping should be
8775          * ignoring this setting.
8776          */
8777         val = I915_READ(PCH_DREF_CONTROL);
8778
8779         /* As we must carefully and slowly disable/enable each source in turn,
8780          * compute the final state we want first and check if we need to
8781          * make any changes at all.
8782          */
8783         final = val;
8784         final &= ~DREF_NONSPREAD_SOURCE_MASK;
8785         if (has_ck505)
8786                 final |= DREF_NONSPREAD_CK505_ENABLE;
8787         else
8788                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
8789
8790         final &= ~DREF_SSC_SOURCE_MASK;
8791         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8792         final &= ~DREF_SSC1_ENABLE;
8793
8794         if (has_panel) {
8795                 final |= DREF_SSC_SOURCE_ENABLE;
8796
8797                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
8798                         final |= DREF_SSC1_ENABLE;
8799
8800                 if (has_cpu_edp) {
8801                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
8802                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8803                         else
8804                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8805                 } else
8806                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8807         } else if (using_ssc_source) {
8808                 final |= DREF_SSC_SOURCE_ENABLE;
8809                 final |= DREF_SSC1_ENABLE;
8810         }
8811
8812         if (final == val)
8813                 return;
8814
8815         /* Always enable nonspread source */
8816         val &= ~DREF_NONSPREAD_SOURCE_MASK;
8817
8818         if (has_ck505)
8819                 val |= DREF_NONSPREAD_CK505_ENABLE;
8820         else
8821                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
8822
8823         if (has_panel) {
8824                 val &= ~DREF_SSC_SOURCE_MASK;
8825                 val |= DREF_SSC_SOURCE_ENABLE;
8826
8827                 /* SSC must be turned on before enabling the CPU output  */
8828                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8829                         DRM_DEBUG_KMS("Using SSC on panel\n");
8830                         val |= DREF_SSC1_ENABLE;
8831                 } else
8832                         val &= ~DREF_SSC1_ENABLE;
8833
8834                 /* Get SSC going before enabling the outputs */
8835                 I915_WRITE(PCH_DREF_CONTROL, val);
8836                 POSTING_READ(PCH_DREF_CONTROL);
8837                 udelay(200);
8838
8839                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8840
8841                 /* Enable CPU source on CPU attached eDP */
8842                 if (has_cpu_edp) {
8843                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8844                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
8845                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8846                         } else
8847                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8848                 } else
8849                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8850
8851                 I915_WRITE(PCH_DREF_CONTROL, val);
8852                 POSTING_READ(PCH_DREF_CONTROL);
8853                 udelay(200);
8854         } else {
8855                 DRM_DEBUG_KMS("Disabling CPU source output\n");
8856
8857                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8858
8859                 /* Turn off CPU output */
8860                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8861
8862                 I915_WRITE(PCH_DREF_CONTROL, val);
8863                 POSTING_READ(PCH_DREF_CONTROL);
8864                 udelay(200);
8865
8866                 if (!using_ssc_source) {
8867                         DRM_DEBUG_KMS("Disabling SSC source\n");
8868
8869                         /* Turn off the SSC source */
8870                         val &= ~DREF_SSC_SOURCE_MASK;
8871                         val |= DREF_SSC_SOURCE_DISABLE;
8872
8873                         /* Turn off SSC1 */
8874                         val &= ~DREF_SSC1_ENABLE;
8875
8876                         I915_WRITE(PCH_DREF_CONTROL, val);
8877                         POSTING_READ(PCH_DREF_CONTROL);
8878                         udelay(200);
8879                 }
8880         }
8881
8882         BUG_ON(val != final);
8883 }
8884
8885 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
8886 {
8887         u32 tmp;
8888
8889         tmp = I915_READ(SOUTH_CHICKEN2);
8890         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
8891         I915_WRITE(SOUTH_CHICKEN2, tmp);
8892
8893         if (wait_for_us(I915_READ(SOUTH_CHICKEN2) &
8894                         FDI_MPHY_IOSFSB_RESET_STATUS, 100))
8895                 DRM_ERROR("FDI mPHY reset assert timeout\n");
8896
8897         tmp = I915_READ(SOUTH_CHICKEN2);
8898         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
8899         I915_WRITE(SOUTH_CHICKEN2, tmp);
8900
8901         if (wait_for_us((I915_READ(SOUTH_CHICKEN2) &
8902                          FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
8903                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
8904 }
8905
8906 /* WaMPhyProgramming:hsw */
8907 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
8908 {
8909         u32 tmp;
8910
8911         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
8912         tmp &= ~(0xFF << 24);
8913         tmp |= (0x12 << 24);
8914         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
8915
8916         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
8917         tmp |= (1 << 11);
8918         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
8919
8920         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
8921         tmp |= (1 << 11);
8922         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
8923
8924         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
8925         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8926         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
8927
8928         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
8929         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8930         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
8931
8932         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
8933         tmp &= ~(7 << 13);
8934         tmp |= (5 << 13);
8935         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
8936
8937         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
8938         tmp &= ~(7 << 13);
8939         tmp |= (5 << 13);
8940         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
8941
8942         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
8943         tmp &= ~0xFF;
8944         tmp |= 0x1C;
8945         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
8946
8947         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
8948         tmp &= ~0xFF;
8949         tmp |= 0x1C;
8950         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
8951
8952         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
8953         tmp &= ~(0xFF << 16);
8954         tmp |= (0x1C << 16);
8955         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
8956
8957         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
8958         tmp &= ~(0xFF << 16);
8959         tmp |= (0x1C << 16);
8960         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
8961
8962         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8963         tmp |= (1 << 27);
8964         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8965
8966         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8967         tmp |= (1 << 27);
8968         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8969
8970         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8971         tmp &= ~(0xF << 28);
8972         tmp |= (4 << 28);
8973         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8974
8975         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
8976         tmp &= ~(0xF << 28);
8977         tmp |= (4 << 28);
8978         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
8979 }
8980
8981 /* Implements 3 different sequences from BSpec chapter "Display iCLK
8982  * Programming" based on the parameters passed:
8983  * - Sequence to enable CLKOUT_DP
8984  * - Sequence to enable CLKOUT_DP without spread
8985  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
8986  */
8987 static void lpt_enable_clkout_dp(struct drm_i915_private *dev_priv,
8988                                  bool with_spread, bool with_fdi)
8989 {
8990         u32 reg, tmp;
8991
8992         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
8993                 with_spread = true;
8994         if (WARN(HAS_PCH_LPT_LP(dev_priv) &&
8995             with_fdi, "LP PCH doesn't have FDI\n"))
8996                 with_fdi = false;
8997
8998         mutex_lock(&dev_priv->sb_lock);
8999
9000         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
9001         tmp &= ~SBI_SSCCTL_DISABLE;
9002         tmp |= SBI_SSCCTL_PATHALT;
9003         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
9004
9005         udelay(24);
9006
9007         if (with_spread) {
9008                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
9009                 tmp &= ~SBI_SSCCTL_PATHALT;
9010                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
9011
9012                 if (with_fdi) {
9013                         lpt_reset_fdi_mphy(dev_priv);
9014                         lpt_program_fdi_mphy(dev_priv);
9015                 }
9016         }
9017
9018         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
9019         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
9020         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
9021         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
9022
9023         mutex_unlock(&dev_priv->sb_lock);
9024 }
9025
9026 /* Sequence to disable CLKOUT_DP */
9027 void lpt_disable_clkout_dp(struct drm_i915_private *dev_priv)
9028 {
9029         u32 reg, tmp;
9030
9031         mutex_lock(&dev_priv->sb_lock);
9032
9033         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
9034         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
9035         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
9036         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
9037
9038         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
9039         if (!(tmp & SBI_SSCCTL_DISABLE)) {
9040                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
9041                         tmp |= SBI_SSCCTL_PATHALT;
9042                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
9043                         udelay(32);
9044                 }
9045                 tmp |= SBI_SSCCTL_DISABLE;
9046                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
9047         }
9048
9049         mutex_unlock(&dev_priv->sb_lock);
9050 }
9051
9052 #define BEND_IDX(steps) ((50 + (steps)) / 5)
9053
9054 static const u16 sscdivintphase[] = {
9055         [BEND_IDX( 50)] = 0x3B23,
9056         [BEND_IDX( 45)] = 0x3B23,
9057         [BEND_IDX( 40)] = 0x3C23,
9058         [BEND_IDX( 35)] = 0x3C23,
9059         [BEND_IDX( 30)] = 0x3D23,
9060         [BEND_IDX( 25)] = 0x3D23,
9061         [BEND_IDX( 20)] = 0x3E23,
9062         [BEND_IDX( 15)] = 0x3E23,
9063         [BEND_IDX( 10)] = 0x3F23,
9064         [BEND_IDX(  5)] = 0x3F23,
9065         [BEND_IDX(  0)] = 0x0025,
9066         [BEND_IDX( -5)] = 0x0025,
9067         [BEND_IDX(-10)] = 0x0125,
9068         [BEND_IDX(-15)] = 0x0125,
9069         [BEND_IDX(-20)] = 0x0225,
9070         [BEND_IDX(-25)] = 0x0225,
9071         [BEND_IDX(-30)] = 0x0325,
9072         [BEND_IDX(-35)] = 0x0325,
9073         [BEND_IDX(-40)] = 0x0425,
9074         [BEND_IDX(-45)] = 0x0425,
9075         [BEND_IDX(-50)] = 0x0525,
9076 };
9077
9078 /*
9079  * Bend CLKOUT_DP
9080  * steps -50 to 50 inclusive, in steps of 5
9081  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
9082  * change in clock period = -(steps / 10) * 5.787 ps
9083  */
9084 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
9085 {
9086         u32 tmp;
9087         int idx = BEND_IDX(steps);
9088
9089         if (WARN_ON(steps % 5 != 0))
9090                 return;
9091
9092         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
9093                 return;
9094
9095         mutex_lock(&dev_priv->sb_lock);
9096
9097         if (steps % 10 != 0)
9098                 tmp = 0xAAAAAAAB;
9099         else
9100                 tmp = 0x00000000;
9101         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
9102
9103         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
9104         tmp &= 0xffff0000;
9105         tmp |= sscdivintphase[idx];
9106         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
9107
9108         mutex_unlock(&dev_priv->sb_lock);
9109 }
9110
9111 #undef BEND_IDX
9112
9113 static void lpt_init_pch_refclk(struct drm_i915_private *dev_priv)
9114 {
9115         struct intel_encoder *encoder;
9116         bool has_vga = false;
9117
9118         for_each_intel_encoder(&dev_priv->drm, encoder) {
9119                 switch (encoder->type) {
9120                 case INTEL_OUTPUT_ANALOG:
9121                         has_vga = true;
9122                         break;
9123                 default:
9124                         break;
9125                 }
9126         }
9127
9128         if (has_vga) {
9129                 lpt_bend_clkout_dp(dev_priv, 0);
9130                 lpt_enable_clkout_dp(dev_priv, true, true);
9131         } else {
9132                 lpt_disable_clkout_dp(dev_priv);
9133         }
9134 }
9135
9136 /*
9137  * Initialize reference clocks when the driver loads
9138  */
9139 void intel_init_pch_refclk(struct drm_i915_private *dev_priv)
9140 {
9141         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv))
9142                 ironlake_init_pch_refclk(dev_priv);
9143         else if (HAS_PCH_LPT(dev_priv))
9144                 lpt_init_pch_refclk(dev_priv);
9145 }
9146
9147 static void ironlake_set_pipeconf(const struct intel_crtc_state *crtc_state)
9148 {
9149         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
9150         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9151         enum pipe pipe = crtc->pipe;
9152         u32 val;
9153
9154         val = 0;
9155
9156         switch (crtc_state->pipe_bpp) {
9157         case 18:
9158                 val |= PIPECONF_6BPC;
9159                 break;
9160         case 24:
9161                 val |= PIPECONF_8BPC;
9162                 break;
9163         case 30:
9164                 val |= PIPECONF_10BPC;
9165                 break;
9166         case 36:
9167                 val |= PIPECONF_12BPC;
9168                 break;
9169         default:
9170                 /* Case prevented by intel_choose_pipe_bpp_dither. */
9171                 BUG();
9172         }
9173
9174         if (crtc_state->dither)
9175                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
9176
9177         if (crtc_state->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
9178                 val |= PIPECONF_INTERLACED_ILK;
9179         else
9180                 val |= PIPECONF_PROGRESSIVE;
9181
9182         if (crtc_state->limited_color_range)
9183                 val |= PIPECONF_COLOR_RANGE_SELECT;
9184
9185         val |= PIPECONF_GAMMA_MODE(crtc_state->gamma_mode);
9186
9187         I915_WRITE(PIPECONF(pipe), val);
9188         POSTING_READ(PIPECONF(pipe));
9189 }
9190
9191 static void haswell_set_pipeconf(const struct intel_crtc_state *crtc_state)
9192 {
9193         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
9194         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9195         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
9196         u32 val = 0;
9197
9198         if (IS_HASWELL(dev_priv) && crtc_state->dither)
9199                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
9200
9201         if (crtc_state->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
9202                 val |= PIPECONF_INTERLACED_ILK;
9203         else
9204                 val |= PIPECONF_PROGRESSIVE;
9205
9206         I915_WRITE(PIPECONF(cpu_transcoder), val);
9207         POSTING_READ(PIPECONF(cpu_transcoder));
9208 }
9209
9210 static void bdw_set_pipemisc(const struct intel_crtc_state *crtc_state)
9211 {
9212         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
9213         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9214         u32 val = 0;
9215
9216         switch (crtc_state->pipe_bpp) {
9217         case 18:
9218                 val |= PIPEMISC_DITHER_6_BPC;
9219                 break;
9220         case 24:
9221                 val |= PIPEMISC_DITHER_8_BPC;
9222                 break;
9223         case 30:
9224                 val |= PIPEMISC_DITHER_10_BPC;
9225                 break;
9226         case 36:
9227                 val |= PIPEMISC_DITHER_12_BPC;
9228                 break;
9229         default:
9230                 MISSING_CASE(crtc_state->pipe_bpp);
9231                 break;
9232         }
9233
9234         if (crtc_state->dither)
9235                 val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
9236
9237         if (crtc_state->output_format == INTEL_OUTPUT_FORMAT_YCBCR420 ||
9238             crtc_state->output_format == INTEL_OUTPUT_FORMAT_YCBCR444)
9239                 val |= PIPEMISC_OUTPUT_COLORSPACE_YUV;
9240
9241         if (crtc_state->output_format == INTEL_OUTPUT_FORMAT_YCBCR420)
9242                 val |= PIPEMISC_YUV420_ENABLE |
9243                         PIPEMISC_YUV420_MODE_FULL_BLEND;
9244
9245         if (INTEL_GEN(dev_priv) >= 11 &&
9246             (crtc_state->active_planes & ~(icl_hdr_plane_mask() |
9247                                            BIT(PLANE_CURSOR))) == 0)
9248                 val |= PIPEMISC_HDR_MODE_PRECISION;
9249
9250         I915_WRITE(PIPEMISC(crtc->pipe), val);
9251 }
9252
9253 int bdw_get_pipemisc_bpp(struct intel_crtc *crtc)
9254 {
9255         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9256         u32 tmp;
9257
9258         tmp = I915_READ(PIPEMISC(crtc->pipe));
9259
9260         switch (tmp & PIPEMISC_DITHER_BPC_MASK) {
9261         case PIPEMISC_DITHER_6_BPC:
9262                 return 18;
9263         case PIPEMISC_DITHER_8_BPC:
9264                 return 24;
9265         case PIPEMISC_DITHER_10_BPC:
9266                 return 30;
9267         case PIPEMISC_DITHER_12_BPC:
9268                 return 36;
9269         default:
9270                 MISSING_CASE(tmp);
9271                 return 0;
9272         }
9273 }
9274
9275 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
9276 {
9277         /*
9278          * Account for spread spectrum to avoid
9279          * oversubscribing the link. Max center spread
9280          * is 2.5%; use 5% for safety's sake.
9281          */
9282         u32 bps = target_clock * bpp * 21 / 20;
9283         return DIV_ROUND_UP(bps, link_bw * 8);
9284 }
9285
9286 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
9287 {
9288         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
9289 }
9290
9291 static void ironlake_compute_dpll(struct intel_crtc *crtc,
9292                                   struct intel_crtc_state *crtc_state,
9293                                   struct dpll *reduced_clock)
9294 {
9295         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9296         u32 dpll, fp, fp2;
9297         int factor;
9298
9299         /* Enable autotuning of the PLL clock (if permissible) */
9300         factor = 21;
9301         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
9302                 if ((intel_panel_use_ssc(dev_priv) &&
9303                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
9304                     (HAS_PCH_IBX(dev_priv) &&
9305                      intel_is_dual_link_lvds(dev_priv)))
9306                         factor = 25;
9307         } else if (crtc_state->sdvo_tv_clock) {
9308                 factor = 20;
9309         }
9310
9311         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
9312
9313         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
9314                 fp |= FP_CB_TUNE;
9315
9316         if (reduced_clock) {
9317                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
9318
9319                 if (reduced_clock->m < factor * reduced_clock->n)
9320                         fp2 |= FP_CB_TUNE;
9321         } else {
9322                 fp2 = fp;
9323         }
9324
9325         dpll = 0;
9326
9327         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
9328                 dpll |= DPLLB_MODE_LVDS;
9329         else
9330                 dpll |= DPLLB_MODE_DAC_SERIAL;
9331
9332         dpll |= (crtc_state->pixel_multiplier - 1)
9333                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
9334
9335         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
9336             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
9337                 dpll |= DPLL_SDVO_HIGH_SPEED;
9338
9339         if (intel_crtc_has_dp_encoder(crtc_state))
9340                 dpll |= DPLL_SDVO_HIGH_SPEED;
9341
9342         /*
9343          * The high speed IO clock is only really required for
9344          * SDVO/HDMI/DP, but we also enable it for CRT to make it
9345          * possible to share the DPLL between CRT and HDMI. Enabling
9346          * the clock needlessly does no real harm, except use up a
9347          * bit of power potentially.
9348          *
9349          * We'll limit this to IVB with 3 pipes, since it has only two
9350          * DPLLs and so DPLL sharing is the only way to get three pipes
9351          * driving PCH ports at the same time. On SNB we could do this,
9352          * and potentially avoid enabling the second DPLL, but it's not
9353          * clear if it''s a win or loss power wise. No point in doing
9354          * this on ILK at all since it has a fixed DPLL<->pipe mapping.
9355          */
9356         if (INTEL_INFO(dev_priv)->num_pipes == 3 &&
9357             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG))
9358                 dpll |= DPLL_SDVO_HIGH_SPEED;
9359
9360         /* compute bitmask from p1 value */
9361         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
9362         /* also FPA1 */
9363         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
9364
9365         switch (crtc_state->dpll.p2) {
9366         case 5:
9367                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
9368                 break;
9369         case 7:
9370                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
9371                 break;
9372         case 10:
9373                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
9374                 break;
9375         case 14:
9376                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
9377                 break;
9378         }
9379
9380         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
9381             intel_panel_use_ssc(dev_priv))
9382                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
9383         else
9384                 dpll |= PLL_REF_INPUT_DREFCLK;
9385
9386         dpll |= DPLL_VCO_ENABLE;
9387
9388         crtc_state->dpll_hw_state.dpll = dpll;
9389         crtc_state->dpll_hw_state.fp0 = fp;
9390         crtc_state->dpll_hw_state.fp1 = fp2;
9391 }
9392
9393 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
9394                                        struct intel_crtc_state *crtc_state)
9395 {
9396         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9397         const struct intel_limit *limit;
9398         int refclk = 120000;
9399
9400         memset(&crtc_state->dpll_hw_state, 0,
9401                sizeof(crtc_state->dpll_hw_state));
9402
9403         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
9404         if (!crtc_state->has_pch_encoder)
9405                 return 0;
9406
9407         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
9408                 if (intel_panel_use_ssc(dev_priv)) {
9409                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
9410                                       dev_priv->vbt.lvds_ssc_freq);
9411                         refclk = dev_priv->vbt.lvds_ssc_freq;
9412                 }
9413
9414                 if (intel_is_dual_link_lvds(dev_priv)) {
9415                         if (refclk == 100000)
9416                                 limit = &intel_limits_ironlake_dual_lvds_100m;
9417                         else
9418                                 limit = &intel_limits_ironlake_dual_lvds;
9419                 } else {
9420                         if (refclk == 100000)
9421                                 limit = &intel_limits_ironlake_single_lvds_100m;
9422                         else
9423                                 limit = &intel_limits_ironlake_single_lvds;
9424                 }
9425         } else {
9426                 limit = &intel_limits_ironlake_dac;
9427         }
9428
9429         if (!crtc_state->clock_set &&
9430             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
9431                                 refclk, NULL, &crtc_state->dpll)) {
9432                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
9433                 return -EINVAL;
9434         }
9435
9436         ironlake_compute_dpll(crtc, crtc_state, NULL);
9437
9438         if (!intel_get_shared_dpll(crtc_state, NULL)) {
9439                 DRM_DEBUG_KMS("failed to find PLL for pipe %c\n",
9440                               pipe_name(crtc->pipe));
9441                 return -EINVAL;
9442         }
9443
9444         return 0;
9445 }
9446
9447 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
9448                                          struct intel_link_m_n *m_n)
9449 {
9450         struct drm_device *dev = crtc->base.dev;
9451         struct drm_i915_private *dev_priv = to_i915(dev);
9452         enum pipe pipe = crtc->pipe;
9453
9454         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
9455         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
9456         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
9457                 & ~TU_SIZE_MASK;
9458         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
9459         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
9460                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9461 }
9462
9463 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
9464                                          enum transcoder transcoder,
9465                                          struct intel_link_m_n *m_n,
9466                                          struct intel_link_m_n *m2_n2)
9467 {
9468         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9469         enum pipe pipe = crtc->pipe;
9470
9471         if (INTEL_GEN(dev_priv) >= 5) {
9472                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
9473                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
9474                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
9475                         & ~TU_SIZE_MASK;
9476                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
9477                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
9478                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9479
9480                 if (m2_n2 && transcoder_has_m2_n2(dev_priv, transcoder)) {
9481                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
9482                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
9483                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
9484                                         & ~TU_SIZE_MASK;
9485                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
9486                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
9487                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9488                 }
9489         } else {
9490                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
9491                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
9492                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
9493                         & ~TU_SIZE_MASK;
9494                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
9495                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
9496                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9497         }
9498 }
9499
9500 void intel_dp_get_m_n(struct intel_crtc *crtc,
9501                       struct intel_crtc_state *pipe_config)
9502 {
9503         if (pipe_config->has_pch_encoder)
9504                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
9505         else
9506                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9507                                              &pipe_config->dp_m_n,
9508                                              &pipe_config->dp_m2_n2);
9509 }
9510
9511 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
9512                                         struct intel_crtc_state *pipe_config)
9513 {
9514         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9515                                      &pipe_config->fdi_m_n, NULL);
9516 }
9517
9518 static void skylake_get_pfit_config(struct intel_crtc *crtc,
9519                                     struct intel_crtc_state *pipe_config)
9520 {
9521         struct drm_device *dev = crtc->base.dev;
9522         struct drm_i915_private *dev_priv = to_i915(dev);
9523         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
9524         u32 ps_ctrl = 0;
9525         int id = -1;
9526         int i;
9527
9528         /* find scaler attached to this pipe */
9529         for (i = 0; i < crtc->num_scalers; i++) {
9530                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
9531                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
9532                         id = i;
9533                         pipe_config->pch_pfit.enabled = true;
9534                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
9535                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
9536                         scaler_state->scalers[i].in_use = true;
9537                         break;
9538                 }
9539         }
9540
9541         scaler_state->scaler_id = id;
9542         if (id >= 0) {
9543                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
9544         } else {
9545                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
9546         }
9547 }
9548
9549 static void
9550 skylake_get_initial_plane_config(struct intel_crtc *crtc,
9551                                  struct intel_initial_plane_config *plane_config)
9552 {
9553         struct drm_device *dev = crtc->base.dev;
9554         struct drm_i915_private *dev_priv = to_i915(dev);
9555         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
9556         enum plane_id plane_id = plane->id;
9557         enum pipe pipe;
9558         u32 val, base, offset, stride_mult, tiling, alpha;
9559         int fourcc, pixel_format;
9560         unsigned int aligned_height;
9561         struct drm_framebuffer *fb;
9562         struct intel_framebuffer *intel_fb;
9563
9564         if (!plane->get_hw_state(plane, &pipe))
9565                 return;
9566
9567         WARN_ON(pipe != crtc->pipe);
9568
9569         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9570         if (!intel_fb) {
9571                 DRM_DEBUG_KMS("failed to alloc fb\n");
9572                 return;
9573         }
9574
9575         fb = &intel_fb->base;
9576
9577         fb->dev = dev;
9578
9579         val = I915_READ(PLANE_CTL(pipe, plane_id));
9580
9581         if (INTEL_GEN(dev_priv) >= 11)
9582                 pixel_format = val & ICL_PLANE_CTL_FORMAT_MASK;
9583         else
9584                 pixel_format = val & PLANE_CTL_FORMAT_MASK;
9585
9586         if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv)) {
9587                 alpha = I915_READ(PLANE_COLOR_CTL(pipe, plane_id));
9588                 alpha &= PLANE_COLOR_ALPHA_MASK;
9589         } else {
9590                 alpha = val & PLANE_CTL_ALPHA_MASK;
9591         }
9592
9593         fourcc = skl_format_to_fourcc(pixel_format,
9594                                       val & PLANE_CTL_ORDER_RGBX, alpha);
9595         fb->format = drm_format_info(fourcc);
9596
9597         tiling = val & PLANE_CTL_TILED_MASK;
9598         switch (tiling) {
9599         case PLANE_CTL_TILED_LINEAR:
9600                 fb->modifier = DRM_FORMAT_MOD_LINEAR;
9601                 break;
9602         case PLANE_CTL_TILED_X:
9603                 plane_config->tiling = I915_TILING_X;
9604                 fb->modifier = I915_FORMAT_MOD_X_TILED;
9605                 break;
9606         case PLANE_CTL_TILED_Y:
9607                 plane_config->tiling = I915_TILING_Y;
9608                 if (val & PLANE_CTL_RENDER_DECOMPRESSION_ENABLE)
9609                         fb->modifier = I915_FORMAT_MOD_Y_TILED_CCS;
9610                 else
9611                         fb->modifier = I915_FORMAT_MOD_Y_TILED;
9612                 break;
9613         case PLANE_CTL_TILED_YF:
9614                 if (val & PLANE_CTL_RENDER_DECOMPRESSION_ENABLE)
9615                         fb->modifier = I915_FORMAT_MOD_Yf_TILED_CCS;
9616                 else
9617                         fb->modifier = I915_FORMAT_MOD_Yf_TILED;
9618                 break;
9619         default:
9620                 MISSING_CASE(tiling);
9621                 goto error;
9622         }
9623
9624         /*
9625          * DRM_MODE_ROTATE_ is counter clockwise to stay compatible with Xrandr
9626          * while i915 HW rotation is clockwise, thats why this swapping.
9627          */
9628         switch (val & PLANE_CTL_ROTATE_MASK) {
9629         case PLANE_CTL_ROTATE_0:
9630                 plane_config->rotation = DRM_MODE_ROTATE_0;
9631                 break;
9632         case PLANE_CTL_ROTATE_90:
9633                 plane_config->rotation = DRM_MODE_ROTATE_270;
9634                 break;
9635         case PLANE_CTL_ROTATE_180:
9636                 plane_config->rotation = DRM_MODE_ROTATE_180;
9637                 break;
9638         case PLANE_CTL_ROTATE_270:
9639                 plane_config->rotation = DRM_MODE_ROTATE_90;
9640                 break;
9641         }
9642
9643         if (INTEL_GEN(dev_priv) >= 10 &&
9644             val & PLANE_CTL_FLIP_HORIZONTAL)
9645                 plane_config->rotation |= DRM_MODE_REFLECT_X;
9646
9647         base = I915_READ(PLANE_SURF(pipe, plane_id)) & 0xfffff000;
9648         plane_config->base = base;
9649
9650         offset = I915_READ(PLANE_OFFSET(pipe, plane_id));
9651
9652         val = I915_READ(PLANE_SIZE(pipe, plane_id));
9653         fb->height = ((val >> 16) & 0xfff) + 1;
9654         fb->width = ((val >> 0) & 0x1fff) + 1;
9655
9656         val = I915_READ(PLANE_STRIDE(pipe, plane_id));
9657         stride_mult = skl_plane_stride_mult(fb, 0, DRM_MODE_ROTATE_0);
9658         fb->pitches[0] = (val & 0x3ff) * stride_mult;
9659
9660         aligned_height = intel_fb_align_height(fb, 0, fb->height);
9661
9662         plane_config->size = fb->pitches[0] * aligned_height;
9663
9664         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9665                       crtc->base.name, plane->base.name, fb->width, fb->height,
9666                       fb->format->cpp[0] * 8, base, fb->pitches[0],
9667                       plane_config->size);
9668
9669         plane_config->fb = intel_fb;
9670         return;
9671
9672 error:
9673         kfree(intel_fb);
9674 }
9675
9676 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
9677                                      struct intel_crtc_state *pipe_config)
9678 {
9679         struct drm_device *dev = crtc->base.dev;
9680         struct drm_i915_private *dev_priv = to_i915(dev);
9681         u32 tmp;
9682
9683         tmp = I915_READ(PF_CTL(crtc->pipe));
9684
9685         if (tmp & PF_ENABLE) {
9686                 pipe_config->pch_pfit.enabled = true;
9687                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
9688                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
9689
9690                 /* We currently do not free assignements of panel fitters on
9691                  * ivb/hsw (since we don't use the higher upscaling modes which
9692                  * differentiates them) so just WARN about this case for now. */
9693                 if (IS_GEN(dev_priv, 7)) {
9694                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
9695                                 PF_PIPE_SEL_IVB(crtc->pipe));
9696                 }
9697         }
9698 }
9699
9700 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
9701                                      struct intel_crtc_state *pipe_config)
9702 {
9703         struct drm_device *dev = crtc->base.dev;
9704         struct drm_i915_private *dev_priv = to_i915(dev);
9705         enum intel_display_power_domain power_domain;
9706         intel_wakeref_t wakeref;
9707         u32 tmp;
9708         bool ret;
9709
9710         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9711         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
9712         if (!wakeref)
9713                 return false;
9714
9715         pipe_config->output_format = INTEL_OUTPUT_FORMAT_RGB;
9716         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9717         pipe_config->shared_dpll = NULL;
9718
9719         ret = false;
9720         tmp = I915_READ(PIPECONF(crtc->pipe));
9721         if (!(tmp & PIPECONF_ENABLE))
9722                 goto out;
9723
9724         switch (tmp & PIPECONF_BPC_MASK) {
9725         case PIPECONF_6BPC:
9726                 pipe_config->pipe_bpp = 18;
9727                 break;
9728         case PIPECONF_8BPC:
9729                 pipe_config->pipe_bpp = 24;
9730                 break;
9731         case PIPECONF_10BPC:
9732                 pipe_config->pipe_bpp = 30;
9733                 break;
9734         case PIPECONF_12BPC:
9735                 pipe_config->pipe_bpp = 36;
9736                 break;
9737         default:
9738                 break;
9739         }
9740
9741         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
9742                 pipe_config->limited_color_range = true;
9743
9744         pipe_config->gamma_mode = (tmp & PIPECONF_GAMMA_MODE_MASK_ILK) >>
9745                 PIPECONF_GAMMA_MODE_SHIFT;
9746
9747         pipe_config->csc_mode = I915_READ(PIPE_CSC_MODE(crtc->pipe));
9748
9749         i9xx_get_pipe_color_config(pipe_config);
9750
9751         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
9752                 struct intel_shared_dpll *pll;
9753                 enum intel_dpll_id pll_id;
9754
9755                 pipe_config->has_pch_encoder = true;
9756
9757                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
9758                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9759                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9760
9761                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9762
9763                 if (HAS_PCH_IBX(dev_priv)) {
9764                         /*
9765                          * The pipe->pch transcoder and pch transcoder->pll
9766                          * mapping is fixed.
9767                          */
9768                         pll_id = (enum intel_dpll_id) crtc->pipe;
9769                 } else {
9770                         tmp = I915_READ(PCH_DPLL_SEL);
9771                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
9772                                 pll_id = DPLL_ID_PCH_PLL_B;
9773                         else
9774                                 pll_id= DPLL_ID_PCH_PLL_A;
9775                 }
9776
9777                 pipe_config->shared_dpll =
9778                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
9779                 pll = pipe_config->shared_dpll;
9780
9781                 WARN_ON(!pll->info->funcs->get_hw_state(dev_priv, pll,
9782                                                 &pipe_config->dpll_hw_state));
9783
9784                 tmp = pipe_config->dpll_hw_state.dpll;
9785                 pipe_config->pixel_multiplier =
9786                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
9787                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
9788
9789                 ironlake_pch_clock_get(crtc, pipe_config);
9790         } else {
9791                 pipe_config->pixel_multiplier = 1;
9792         }
9793
9794         intel_get_pipe_timings(crtc, pipe_config);
9795         intel_get_pipe_src_size(crtc, pipe_config);
9796
9797         ironlake_get_pfit_config(crtc, pipe_config);
9798
9799         ret = true;
9800
9801 out:
9802         intel_display_power_put(dev_priv, power_domain, wakeref);
9803
9804         return ret;
9805 }
9806 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9807                                       struct intel_crtc_state *crtc_state)
9808 {
9809         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9810         struct intel_atomic_state *state =
9811                 to_intel_atomic_state(crtc_state->base.state);
9812
9813         if (!intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DSI) ||
9814             INTEL_GEN(dev_priv) >= 11) {
9815                 struct intel_encoder *encoder =
9816                         intel_get_crtc_new_encoder(state, crtc_state);
9817
9818                 if (!intel_get_shared_dpll(crtc_state, encoder)) {
9819                         DRM_DEBUG_KMS("failed to find PLL for pipe %c\n",
9820                                       pipe_name(crtc->pipe));
9821                         return -EINVAL;
9822                 }
9823         }
9824
9825         return 0;
9826 }
9827
9828 static void cannonlake_get_ddi_pll(struct drm_i915_private *dev_priv,
9829                                    enum port port,
9830                                    struct intel_crtc_state *pipe_config)
9831 {
9832         enum intel_dpll_id id;
9833         u32 temp;
9834
9835         temp = I915_READ(DPCLKA_CFGCR0) & DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
9836         id = temp >> DPCLKA_CFGCR0_DDI_CLK_SEL_SHIFT(port);
9837
9838         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL2))
9839                 return;
9840
9841         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9842 }
9843
9844 static void icelake_get_ddi_pll(struct drm_i915_private *dev_priv,
9845                                 enum port port,
9846                                 struct intel_crtc_state *pipe_config)
9847 {
9848         enum intel_dpll_id id;
9849         u32 temp;
9850
9851         /* TODO: TBT pll not implemented. */
9852         if (intel_port_is_combophy(dev_priv, port)) {
9853                 temp = I915_READ(DPCLKA_CFGCR0_ICL) &
9854                        DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
9855                 id = temp >> DPCLKA_CFGCR0_DDI_CLK_SEL_SHIFT(port);
9856         } else if (intel_port_is_tc(dev_priv, port)) {
9857                 id = icl_tc_port_to_pll_id(intel_port_to_tc(dev_priv, port));
9858         } else {
9859                 WARN(1, "Invalid port %x\n", port);
9860                 return;
9861         }
9862
9863         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9864 }
9865
9866 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9867                                 enum port port,
9868                                 struct intel_crtc_state *pipe_config)
9869 {
9870         enum intel_dpll_id id;
9871
9872         switch (port) {
9873         case PORT_A:
9874                 id = DPLL_ID_SKL_DPLL0;
9875                 break;
9876         case PORT_B:
9877                 id = DPLL_ID_SKL_DPLL1;
9878                 break;
9879         case PORT_C:
9880                 id = DPLL_ID_SKL_DPLL2;
9881                 break;
9882         default:
9883                 DRM_ERROR("Incorrect port type\n");
9884                 return;
9885         }
9886
9887         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9888 }
9889
9890 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9891                                 enum port port,
9892                                 struct intel_crtc_state *pipe_config)
9893 {
9894         enum intel_dpll_id id;
9895         u32 temp;
9896
9897         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9898         id = temp >> (port * 3 + 1);
9899
9900         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL3))
9901                 return;
9902
9903         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9904 }
9905
9906 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9907                                 enum port port,
9908                                 struct intel_crtc_state *pipe_config)
9909 {
9910         enum intel_dpll_id id;
9911         u32 ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9912
9913         switch (ddi_pll_sel) {
9914         case PORT_CLK_SEL_WRPLL1:
9915                 id = DPLL_ID_WRPLL1;
9916                 break;
9917         case PORT_CLK_SEL_WRPLL2:
9918                 id = DPLL_ID_WRPLL2;
9919                 break;
9920         case PORT_CLK_SEL_SPLL:
9921                 id = DPLL_ID_SPLL;
9922                 break;
9923         case PORT_CLK_SEL_LCPLL_810:
9924                 id = DPLL_ID_LCPLL_810;
9925                 break;
9926         case PORT_CLK_SEL_LCPLL_1350:
9927                 id = DPLL_ID_LCPLL_1350;
9928                 break;
9929         case PORT_CLK_SEL_LCPLL_2700:
9930                 id = DPLL_ID_LCPLL_2700;
9931                 break;
9932         default:
9933                 MISSING_CASE(ddi_pll_sel);
9934                 /* fall through */
9935         case PORT_CLK_SEL_NONE:
9936                 return;
9937         }
9938
9939         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9940 }
9941
9942 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
9943                                      struct intel_crtc_state *pipe_config,
9944                                      u64 *power_domain_mask,
9945                                      intel_wakeref_t *wakerefs)
9946 {
9947         struct drm_device *dev = crtc->base.dev;
9948         struct drm_i915_private *dev_priv = to_i915(dev);
9949         enum intel_display_power_domain power_domain;
9950         unsigned long panel_transcoder_mask = 0;
9951         unsigned long enabled_panel_transcoders = 0;
9952         enum transcoder panel_transcoder;
9953         intel_wakeref_t wf;
9954         u32 tmp;
9955
9956         if (INTEL_GEN(dev_priv) >= 11)
9957                 panel_transcoder_mask |=
9958                         BIT(TRANSCODER_DSI_0) | BIT(TRANSCODER_DSI_1);
9959
9960         if (HAS_TRANSCODER_EDP(dev_priv))
9961                 panel_transcoder_mask |= BIT(TRANSCODER_EDP);
9962
9963         /*
9964          * The pipe->transcoder mapping is fixed with the exception of the eDP
9965          * and DSI transcoders handled below.
9966          */
9967         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9968
9969         /*
9970          * XXX: Do intel_display_power_get_if_enabled before reading this (for
9971          * consistency and less surprising code; it's in always on power).
9972          */
9973         for_each_set_bit(panel_transcoder,
9974                          &panel_transcoder_mask,
9975                          ARRAY_SIZE(INTEL_INFO(dev_priv)->trans_offsets)) {
9976                 bool force_thru = false;
9977                 enum pipe trans_pipe;
9978
9979                 tmp = I915_READ(TRANS_DDI_FUNC_CTL(panel_transcoder));
9980                 if (!(tmp & TRANS_DDI_FUNC_ENABLE))
9981                         continue;
9982
9983                 /*
9984                  * Log all enabled ones, only use the first one.
9985                  *
9986                  * FIXME: This won't work for two separate DSI displays.
9987                  */
9988                 enabled_panel_transcoders |= BIT(panel_transcoder);
9989                 if (enabled_panel_transcoders != BIT(panel_transcoder))
9990                         continue;
9991
9992                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9993                 default:
9994                         WARN(1, "unknown pipe linked to transcoder %s\n",
9995                              transcoder_name(panel_transcoder));
9996                         /* fall through */
9997                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9998                         force_thru = true;
9999                         /* fall through */
10000                 case TRANS_DDI_EDP_INPUT_A_ON:
10001                         trans_pipe = PIPE_A;
10002                         break;
10003                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
10004                         trans_pipe = PIPE_B;
10005                         break;
10006                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
10007                         trans_pipe = PIPE_C;
10008                         break;
10009                 }
10010
10011                 if (trans_pipe == crtc->pipe) {
10012                         pipe_config->cpu_transcoder = panel_transcoder;
10013                         pipe_config->pch_pfit.force_thru = force_thru;
10014                 }
10015         }
10016
10017         /*
10018          * Valid combos: none, eDP, DSI0, DSI1, DSI0+DSI1
10019          */
10020         WARN_ON((enabled_panel_transcoders & BIT(TRANSCODER_EDP)) &&
10021                 enabled_panel_transcoders != BIT(TRANSCODER_EDP));
10022
10023         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
10024         WARN_ON(*power_domain_mask & BIT_ULL(power_domain));
10025
10026         wf = intel_display_power_get_if_enabled(dev_priv, power_domain);
10027         if (!wf)
10028                 return false;
10029
10030         wakerefs[power_domain] = wf;
10031         *power_domain_mask |= BIT_ULL(power_domain);
10032
10033         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
10034
10035         return tmp & PIPECONF_ENABLE;
10036 }
10037
10038 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
10039                                          struct intel_crtc_state *pipe_config,
10040                                          u64 *power_domain_mask,
10041                                          intel_wakeref_t *wakerefs)
10042 {
10043         struct drm_device *dev = crtc->base.dev;
10044         struct drm_i915_private *dev_priv = to_i915(dev);
10045         enum intel_display_power_domain power_domain;
10046         enum transcoder cpu_transcoder;
10047         intel_wakeref_t wf;
10048         enum port port;
10049         u32 tmp;
10050
10051         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
10052                 if (port == PORT_A)
10053                         cpu_transcoder = TRANSCODER_DSI_A;
10054                 else
10055                         cpu_transcoder = TRANSCODER_DSI_C;
10056
10057                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
10058                 WARN_ON(*power_domain_mask & BIT_ULL(power_domain));
10059
10060                 wf = intel_display_power_get_if_enabled(dev_priv, power_domain);
10061                 if (!wf)
10062                         continue;
10063
10064                 wakerefs[power_domain] = wf;
10065                 *power_domain_mask |= BIT_ULL(power_domain);
10066
10067                 /*
10068                  * The PLL needs to be enabled with a valid divider
10069                  * configuration, otherwise accessing DSI registers will hang
10070                  * the machine. See BSpec North Display Engine
10071                  * registers/MIPI[BXT]. We can break out here early, since we
10072                  * need the same DSI PLL to be enabled for both DSI ports.
10073                  */
10074                 if (!bxt_dsi_pll_is_enabled(dev_priv))
10075                         break;
10076
10077                 /* XXX: this works for video mode only */
10078                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
10079                 if (!(tmp & DPI_ENABLE))
10080                         continue;
10081
10082                 tmp = I915_READ(MIPI_CTRL(port));
10083                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
10084                         continue;
10085
10086                 pipe_config->cpu_transcoder = cpu_transcoder;
10087                 break;
10088         }
10089
10090         return transcoder_is_dsi(pipe_config->cpu_transcoder);
10091 }
10092
10093 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
10094                                        struct intel_crtc_state *pipe_config)
10095 {
10096         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10097         struct intel_shared_dpll *pll;
10098         enum port port;
10099         u32 tmp;
10100
10101         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
10102
10103         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
10104
10105         if (INTEL_GEN(dev_priv) >= 11)
10106                 icelake_get_ddi_pll(dev_priv, port, pipe_config);
10107         else if (IS_CANNONLAKE(dev_priv))
10108                 cannonlake_get_ddi_pll(dev_priv, port, pipe_config);
10109         else if (IS_GEN9_BC(dev_priv))
10110                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
10111         else if (IS_GEN9_LP(dev_priv))
10112                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
10113         else
10114                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
10115
10116         pll = pipe_config->shared_dpll;
10117         if (pll) {
10118                 WARN_ON(!pll->info->funcs->get_hw_state(dev_priv, pll,
10119                                                 &pipe_config->dpll_hw_state));
10120         }
10121
10122         /*
10123          * Haswell has only FDI/PCH transcoder A. It is which is connected to
10124          * DDI E. So just check whether this pipe is wired to DDI E and whether
10125          * the PCH transcoder is on.
10126          */
10127         if (INTEL_GEN(dev_priv) < 9 &&
10128             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
10129                 pipe_config->has_pch_encoder = true;
10130
10131                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
10132                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
10133                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
10134
10135                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
10136         }
10137 }
10138
10139 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
10140                                     struct intel_crtc_state *pipe_config)
10141 {
10142         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10143         intel_wakeref_t wakerefs[POWER_DOMAIN_NUM], wf;
10144         enum intel_display_power_domain power_domain;
10145         u64 power_domain_mask;
10146         bool active;
10147
10148         intel_crtc_init_scalers(crtc, pipe_config);
10149
10150         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
10151         wf = intel_display_power_get_if_enabled(dev_priv, power_domain);
10152         if (!wf)
10153                 return false;
10154
10155         wakerefs[power_domain] = wf;
10156         power_domain_mask = BIT_ULL(power_domain);
10157
10158         pipe_config->shared_dpll = NULL;
10159
10160         active = hsw_get_transcoder_state(crtc, pipe_config,
10161                                           &power_domain_mask, wakerefs);
10162
10163         if (IS_GEN9_LP(dev_priv) &&
10164             bxt_get_dsi_transcoder_state(crtc, pipe_config,
10165                                          &power_domain_mask, wakerefs)) {
10166                 WARN_ON(active);
10167                 active = true;
10168         }
10169
10170         if (!active)
10171                 goto out;
10172
10173         if (!transcoder_is_dsi(pipe_config->cpu_transcoder) ||
10174             INTEL_GEN(dev_priv) >= 11) {
10175                 haswell_get_ddi_port_state(crtc, pipe_config);
10176                 intel_get_pipe_timings(crtc, pipe_config);
10177         }
10178
10179         intel_get_pipe_src_size(crtc, pipe_config);
10180         intel_get_crtc_ycbcr_config(crtc, pipe_config);
10181
10182         pipe_config->gamma_mode = I915_READ(GAMMA_MODE(crtc->pipe));
10183
10184         pipe_config->csc_mode = I915_READ(PIPE_CSC_MODE(crtc->pipe));
10185
10186         if (INTEL_GEN(dev_priv) >= 9) {
10187                 u32 tmp = I915_READ(SKL_BOTTOM_COLOR(crtc->pipe));
10188
10189                 if (tmp & SKL_BOTTOM_COLOR_GAMMA_ENABLE)
10190                         pipe_config->gamma_enable = true;
10191
10192                 if (tmp & SKL_BOTTOM_COLOR_CSC_ENABLE)
10193                         pipe_config->csc_enable = true;
10194         } else {
10195                 i9xx_get_pipe_color_config(pipe_config);
10196         }
10197
10198         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
10199         WARN_ON(power_domain_mask & BIT_ULL(power_domain));
10200
10201         wf = intel_display_power_get_if_enabled(dev_priv, power_domain);
10202         if (wf) {
10203                 wakerefs[power_domain] = wf;
10204                 power_domain_mask |= BIT_ULL(power_domain);
10205
10206                 if (INTEL_GEN(dev_priv) >= 9)
10207                         skylake_get_pfit_config(crtc, pipe_config);
10208                 else
10209                         ironlake_get_pfit_config(crtc, pipe_config);
10210         }
10211
10212         if (hsw_crtc_supports_ips(crtc)) {
10213                 if (IS_HASWELL(dev_priv))
10214                         pipe_config->ips_enabled = I915_READ(IPS_CTL) & IPS_ENABLE;
10215                 else {
10216                         /*
10217                          * We cannot readout IPS state on broadwell, set to
10218                          * true so we can set it to a defined state on first
10219                          * commit.
10220                          */
10221                         pipe_config->ips_enabled = true;
10222                 }
10223         }
10224
10225         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
10226             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
10227                 pipe_config->pixel_multiplier =
10228                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
10229         } else {
10230                 pipe_config->pixel_multiplier = 1;
10231         }
10232
10233 out:
10234         for_each_power_domain(power_domain, power_domain_mask)
10235                 intel_display_power_put(dev_priv,
10236                                         power_domain, wakerefs[power_domain]);
10237
10238         return active;
10239 }
10240
10241 static u32 intel_cursor_base(const struct intel_plane_state *plane_state)
10242 {
10243         struct drm_i915_private *dev_priv =
10244                 to_i915(plane_state->base.plane->dev);
10245         const struct drm_framebuffer *fb = plane_state->base.fb;
10246         const struct drm_i915_gem_object *obj = intel_fb_obj(fb);
10247         u32 base;
10248
10249         if (INTEL_INFO(dev_priv)->display.cursor_needs_physical)
10250                 base = obj->phys_handle->busaddr;
10251         else
10252                 base = intel_plane_ggtt_offset(plane_state);
10253
10254         base += plane_state->color_plane[0].offset;
10255
10256         /* ILK+ do this automagically */
10257         if (HAS_GMCH(dev_priv) &&
10258             plane_state->base.rotation & DRM_MODE_ROTATE_180)
10259                 base += (plane_state->base.crtc_h *
10260                          plane_state->base.crtc_w - 1) * fb->format->cpp[0];
10261
10262         return base;
10263 }
10264
10265 static u32 intel_cursor_position(const struct intel_plane_state *plane_state)
10266 {
10267         int x = plane_state->base.crtc_x;
10268         int y = plane_state->base.crtc_y;
10269         u32 pos = 0;
10270
10271         if (x < 0) {
10272                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
10273                 x = -x;
10274         }
10275         pos |= x << CURSOR_X_SHIFT;
10276
10277         if (y < 0) {
10278                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
10279                 y = -y;
10280         }
10281         pos |= y << CURSOR_Y_SHIFT;
10282
10283         return pos;
10284 }
10285
10286 static bool intel_cursor_size_ok(const struct intel_plane_state *plane_state)
10287 {
10288         const struct drm_mode_config *config =
10289                 &plane_state->base.plane->dev->mode_config;
10290         int width = plane_state->base.crtc_w;
10291         int height = plane_state->base.crtc_h;
10292
10293         return width > 0 && width <= config->cursor_width &&
10294                 height > 0 && height <= config->cursor_height;
10295 }
10296
10297 static int intel_cursor_check_surface(struct intel_plane_state *plane_state)
10298 {
10299         int src_x, src_y;
10300         u32 offset;
10301         int ret;
10302
10303         ret = intel_plane_compute_gtt(plane_state);
10304         if (ret)
10305                 return ret;
10306
10307         if (!plane_state->base.visible)
10308                 return 0;
10309
10310         src_x = plane_state->base.src_x >> 16;
10311         src_y = plane_state->base.src_y >> 16;
10312
10313         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
10314         offset = intel_plane_compute_aligned_offset(&src_x, &src_y,
10315                                                     plane_state, 0);
10316
10317         if (src_x != 0 || src_y != 0) {
10318                 DRM_DEBUG_KMS("Arbitrary cursor panning not supported\n");
10319                 return -EINVAL;
10320         }
10321
10322         plane_state->color_plane[0].offset = offset;
10323
10324         return 0;
10325 }
10326
10327 static int intel_check_cursor(struct intel_crtc_state *crtc_state,
10328                               struct intel_plane_state *plane_state)
10329 {
10330         const struct drm_framebuffer *fb = plane_state->base.fb;
10331         int ret;
10332
10333         if (fb && fb->modifier != DRM_FORMAT_MOD_LINEAR) {
10334                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
10335                 return -EINVAL;
10336         }
10337
10338         ret = drm_atomic_helper_check_plane_state(&plane_state->base,
10339                                                   &crtc_state->base,
10340                                                   DRM_PLANE_HELPER_NO_SCALING,
10341                                                   DRM_PLANE_HELPER_NO_SCALING,
10342                                                   true, true);
10343         if (ret)
10344                 return ret;
10345
10346         ret = intel_cursor_check_surface(plane_state);
10347         if (ret)
10348                 return ret;
10349
10350         if (!plane_state->base.visible)
10351                 return 0;
10352
10353         ret = intel_plane_check_src_coordinates(plane_state);
10354         if (ret)
10355                 return ret;
10356
10357         return 0;
10358 }
10359
10360 static unsigned int
10361 i845_cursor_max_stride(struct intel_plane *plane,
10362                        u32 pixel_format, u64 modifier,
10363                        unsigned int rotation)
10364 {
10365         return 2048;
10366 }
10367
10368 static u32 i845_cursor_ctl_crtc(const struct intel_crtc_state *crtc_state)
10369 {
10370         u32 cntl = 0;
10371
10372         if (crtc_state->gamma_enable)
10373                 cntl |= CURSOR_GAMMA_ENABLE;
10374
10375         return cntl;
10376 }
10377
10378 static u32 i845_cursor_ctl(const struct intel_crtc_state *crtc_state,
10379                            const struct intel_plane_state *plane_state)
10380 {
10381         return CURSOR_ENABLE |
10382                 CURSOR_FORMAT_ARGB |
10383                 CURSOR_STRIDE(plane_state->color_plane[0].stride);
10384 }
10385
10386 static bool i845_cursor_size_ok(const struct intel_plane_state *plane_state)
10387 {
10388         int width = plane_state->base.crtc_w;
10389
10390         /*
10391          * 845g/865g are only limited by the width of their cursors,
10392          * the height is arbitrary up to the precision of the register.
10393          */
10394         return intel_cursor_size_ok(plane_state) && IS_ALIGNED(width, 64);
10395 }
10396
10397 static int i845_check_cursor(struct intel_crtc_state *crtc_state,
10398                              struct intel_plane_state *plane_state)
10399 {
10400         const struct drm_framebuffer *fb = plane_state->base.fb;
10401         int ret;
10402
10403         ret = intel_check_cursor(crtc_state, plane_state);
10404         if (ret)
10405                 return ret;
10406
10407         /* if we want to turn off the cursor ignore width and height */
10408         if (!fb)
10409                 return 0;
10410
10411         /* Check for which cursor types we support */
10412         if (!i845_cursor_size_ok(plane_state)) {
10413                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
10414                           plane_state->base.crtc_w,
10415                           plane_state->base.crtc_h);
10416                 return -EINVAL;
10417         }
10418
10419         WARN_ON(plane_state->base.visible &&
10420                 plane_state->color_plane[0].stride != fb->pitches[0]);
10421
10422         switch (fb->pitches[0]) {
10423         case 256:
10424         case 512:
10425         case 1024:
10426         case 2048:
10427                 break;
10428         default:
10429                 DRM_DEBUG_KMS("Invalid cursor stride (%u)\n",
10430                               fb->pitches[0]);
10431                 return -EINVAL;
10432         }
10433
10434         plane_state->ctl = i845_cursor_ctl(crtc_state, plane_state);
10435
10436         return 0;
10437 }
10438
10439 static void i845_update_cursor(struct intel_plane *plane,
10440                                const struct intel_crtc_state *crtc_state,
10441                                const struct intel_plane_state *plane_state)
10442 {
10443         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10444         u32 cntl = 0, base = 0, pos = 0, size = 0;
10445         unsigned long irqflags;
10446
10447         if (plane_state && plane_state->base.visible) {
10448                 unsigned int width = plane_state->base.crtc_w;
10449                 unsigned int height = plane_state->base.crtc_h;
10450
10451                 cntl = plane_state->ctl |
10452                         i845_cursor_ctl_crtc(crtc_state);
10453
10454                 size = (height << 12) | width;
10455
10456                 base = intel_cursor_base(plane_state);
10457                 pos = intel_cursor_position(plane_state);
10458         }
10459
10460         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
10461
10462         /* On these chipsets we can only modify the base/size/stride
10463          * whilst the cursor is disabled.
10464          */
10465         if (plane->cursor.base != base ||
10466             plane->cursor.size != size ||
10467             plane->cursor.cntl != cntl) {
10468                 I915_WRITE_FW(CURCNTR(PIPE_A), 0);
10469                 I915_WRITE_FW(CURBASE(PIPE_A), base);
10470                 I915_WRITE_FW(CURSIZE, size);
10471                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
10472                 I915_WRITE_FW(CURCNTR(PIPE_A), cntl);
10473
10474                 plane->cursor.base = base;
10475                 plane->cursor.size = size;
10476                 plane->cursor.cntl = cntl;
10477         } else {
10478                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
10479         }
10480
10481         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
10482 }
10483
10484 static void i845_disable_cursor(struct intel_plane *plane,
10485                                 const struct intel_crtc_state *crtc_state)
10486 {
10487         i845_update_cursor(plane, crtc_state, NULL);
10488 }
10489
10490 static bool i845_cursor_get_hw_state(struct intel_plane *plane,
10491                                      enum pipe *pipe)
10492 {
10493         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10494         enum intel_display_power_domain power_domain;
10495         intel_wakeref_t wakeref;
10496         bool ret;
10497
10498         power_domain = POWER_DOMAIN_PIPE(PIPE_A);
10499         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
10500         if (!wakeref)
10501                 return false;
10502
10503         ret = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
10504
10505         *pipe = PIPE_A;
10506
10507         intel_display_power_put(dev_priv, power_domain, wakeref);
10508
10509         return ret;
10510 }
10511
10512 static unsigned int
10513 i9xx_cursor_max_stride(struct intel_plane *plane,
10514                        u32 pixel_format, u64 modifier,
10515                        unsigned int rotation)
10516 {
10517         return plane->base.dev->mode_config.cursor_width * 4;
10518 }
10519
10520 static u32 i9xx_cursor_ctl_crtc(const struct intel_crtc_state *crtc_state)
10521 {
10522         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
10523         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10524         u32 cntl = 0;
10525
10526         if (INTEL_GEN(dev_priv) >= 11)
10527                 return cntl;
10528
10529         if (crtc_state->gamma_enable)
10530                 cntl = MCURSOR_GAMMA_ENABLE;
10531
10532         if (crtc_state->csc_enable)
10533                 cntl |= MCURSOR_PIPE_CSC_ENABLE;
10534
10535         if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10536                 cntl |= MCURSOR_PIPE_SELECT(crtc->pipe);
10537
10538         return cntl;
10539 }
10540
10541 static u32 i9xx_cursor_ctl(const struct intel_crtc_state *crtc_state,
10542                            const struct intel_plane_state *plane_state)
10543 {
10544         struct drm_i915_private *dev_priv =
10545                 to_i915(plane_state->base.plane->dev);
10546         u32 cntl = 0;
10547
10548         if (IS_GEN(dev_priv, 6) || IS_IVYBRIDGE(dev_priv))
10549                 cntl |= MCURSOR_TRICKLE_FEED_DISABLE;
10550
10551         switch (plane_state->base.crtc_w) {
10552         case 64:
10553                 cntl |= MCURSOR_MODE_64_ARGB_AX;
10554                 break;
10555         case 128:
10556                 cntl |= MCURSOR_MODE_128_ARGB_AX;
10557                 break;
10558         case 256:
10559                 cntl |= MCURSOR_MODE_256_ARGB_AX;
10560                 break;
10561         default:
10562                 MISSING_CASE(plane_state->base.crtc_w);
10563                 return 0;
10564         }
10565
10566         if (plane_state->base.rotation & DRM_MODE_ROTATE_180)
10567                 cntl |= MCURSOR_ROTATE_180;
10568
10569         return cntl;
10570 }
10571
10572 static bool i9xx_cursor_size_ok(const struct intel_plane_state *plane_state)
10573 {
10574         struct drm_i915_private *dev_priv =
10575                 to_i915(plane_state->base.plane->dev);
10576         int width = plane_state->base.crtc_w;
10577         int height = plane_state->base.crtc_h;
10578
10579         if (!intel_cursor_size_ok(plane_state))
10580                 return false;
10581
10582         /* Cursor width is limited to a few power-of-two sizes */
10583         switch (width) {
10584         case 256:
10585         case 128:
10586         case 64:
10587                 break;
10588         default:
10589                 return false;
10590         }
10591
10592         /*
10593          * IVB+ have CUR_FBC_CTL which allows an arbitrary cursor
10594          * height from 8 lines up to the cursor width, when the
10595          * cursor is not rotated. Everything else requires square
10596          * cursors.
10597          */
10598         if (HAS_CUR_FBC(dev_priv) &&
10599             plane_state->base.rotation & DRM_MODE_ROTATE_0) {
10600                 if (height < 8 || height > width)
10601                         return false;
10602         } else {
10603                 if (height != width)
10604                         return false;
10605         }
10606
10607         return true;
10608 }
10609
10610 static int i9xx_check_cursor(struct intel_crtc_state *crtc_state,
10611                              struct intel_plane_state *plane_state)
10612 {
10613         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
10614         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10615         const struct drm_framebuffer *fb = plane_state->base.fb;
10616         enum pipe pipe = plane->pipe;
10617         int ret;
10618
10619         ret = intel_check_cursor(crtc_state, plane_state);
10620         if (ret)
10621                 return ret;
10622
10623         /* if we want to turn off the cursor ignore width and height */
10624         if (!fb)
10625                 return 0;
10626
10627         /* Check for which cursor types we support */
10628         if (!i9xx_cursor_size_ok(plane_state)) {
10629                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
10630                           plane_state->base.crtc_w,
10631                           plane_state->base.crtc_h);
10632                 return -EINVAL;
10633         }
10634
10635         WARN_ON(plane_state->base.visible &&
10636                 plane_state->color_plane[0].stride != fb->pitches[0]);
10637
10638         if (fb->pitches[0] != plane_state->base.crtc_w * fb->format->cpp[0]) {
10639                 DRM_DEBUG_KMS("Invalid cursor stride (%u) (cursor width %d)\n",
10640                               fb->pitches[0], plane_state->base.crtc_w);
10641                 return -EINVAL;
10642         }
10643
10644         /*
10645          * There's something wrong with the cursor on CHV pipe C.
10646          * If it straddles the left edge of the screen then
10647          * moving it away from the edge or disabling it often
10648          * results in a pipe underrun, and often that can lead to
10649          * dead pipe (constant underrun reported, and it scans
10650          * out just a solid color). To recover from that, the
10651          * display power well must be turned off and on again.
10652          * Refuse the put the cursor into that compromised position.
10653          */
10654         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_C &&
10655             plane_state->base.visible && plane_state->base.crtc_x < 0) {
10656                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
10657                 return -EINVAL;
10658         }
10659
10660         plane_state->ctl = i9xx_cursor_ctl(crtc_state, plane_state);
10661
10662         return 0;
10663 }
10664
10665 static void i9xx_update_cursor(struct intel_plane *plane,
10666                                const struct intel_crtc_state *crtc_state,
10667                                const struct intel_plane_state *plane_state)
10668 {
10669         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10670         enum pipe pipe = plane->pipe;
10671         u32 cntl = 0, base = 0, pos = 0, fbc_ctl = 0;
10672         unsigned long irqflags;
10673
10674         if (plane_state && plane_state->base.visible) {
10675                 cntl = plane_state->ctl |
10676                         i9xx_cursor_ctl_crtc(crtc_state);
10677
10678                 if (plane_state->base.crtc_h != plane_state->base.crtc_w)
10679                         fbc_ctl = CUR_FBC_CTL_EN | (plane_state->base.crtc_h - 1);
10680
10681                 base = intel_cursor_base(plane_state);
10682                 pos = intel_cursor_position(plane_state);
10683         }
10684
10685         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
10686
10687         /*
10688          * On some platforms writing CURCNTR first will also
10689          * cause CURPOS to be armed by the CURBASE write.
10690          * Without the CURCNTR write the CURPOS write would
10691          * arm itself. Thus we always update CURCNTR before
10692          * CURPOS.
10693          *
10694          * On other platforms CURPOS always requires the
10695          * CURBASE write to arm the update. Additonally
10696          * a write to any of the cursor register will cancel
10697          * an already armed cursor update. Thus leaving out
10698          * the CURBASE write after CURPOS could lead to a
10699          * cursor that doesn't appear to move, or even change
10700          * shape. Thus we always write CURBASE.
10701          *
10702          * The other registers are armed by by the CURBASE write
10703          * except when the plane is getting enabled at which time
10704          * the CURCNTR write arms the update.
10705          */
10706
10707         if (INTEL_GEN(dev_priv) >= 9)
10708                 skl_write_cursor_wm(plane, crtc_state);
10709
10710         if (plane->cursor.base != base ||
10711             plane->cursor.size != fbc_ctl ||
10712             plane->cursor.cntl != cntl) {
10713                 if (HAS_CUR_FBC(dev_priv))
10714                         I915_WRITE_FW(CUR_FBC_CTL(pipe), fbc_ctl);
10715                 I915_WRITE_FW(CURCNTR(pipe), cntl);
10716                 I915_WRITE_FW(CURPOS(pipe), pos);
10717                 I915_WRITE_FW(CURBASE(pipe), base);
10718
10719                 plane->cursor.base = base;
10720                 plane->cursor.size = fbc_ctl;
10721                 plane->cursor.cntl = cntl;
10722         } else {
10723                 I915_WRITE_FW(CURPOS(pipe), pos);
10724                 I915_WRITE_FW(CURBASE(pipe), base);
10725         }
10726
10727         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
10728 }
10729
10730 static void i9xx_disable_cursor(struct intel_plane *plane,
10731                                 const struct intel_crtc_state *crtc_state)
10732 {
10733         i9xx_update_cursor(plane, crtc_state, NULL);
10734 }
10735
10736 static bool i9xx_cursor_get_hw_state(struct intel_plane *plane,
10737                                      enum pipe *pipe)
10738 {
10739         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10740         enum intel_display_power_domain power_domain;
10741         intel_wakeref_t wakeref;
10742         bool ret;
10743         u32 val;
10744
10745         /*
10746          * Not 100% correct for planes that can move between pipes,
10747          * but that's only the case for gen2-3 which don't have any
10748          * display power wells.
10749          */
10750         power_domain = POWER_DOMAIN_PIPE(plane->pipe);
10751         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
10752         if (!wakeref)
10753                 return false;
10754
10755         val = I915_READ(CURCNTR(plane->pipe));
10756
10757         ret = val & MCURSOR_MODE;
10758
10759         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
10760                 *pipe = plane->pipe;
10761         else
10762                 *pipe = (val & MCURSOR_PIPE_SELECT_MASK) >>
10763                         MCURSOR_PIPE_SELECT_SHIFT;
10764
10765         intel_display_power_put(dev_priv, power_domain, wakeref);
10766
10767         return ret;
10768 }
10769
10770 /* VESA 640x480x72Hz mode to set on the pipe */
10771 static const struct drm_display_mode load_detect_mode = {
10772         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10773                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10774 };
10775
10776 struct drm_framebuffer *
10777 intel_framebuffer_create(struct drm_i915_gem_object *obj,
10778                          struct drm_mode_fb_cmd2 *mode_cmd)
10779 {
10780         struct intel_framebuffer *intel_fb;
10781         int ret;
10782
10783         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10784         if (!intel_fb)
10785                 return ERR_PTR(-ENOMEM);
10786
10787         ret = intel_framebuffer_init(intel_fb, obj, mode_cmd);
10788         if (ret)
10789                 goto err;
10790
10791         return &intel_fb->base;
10792
10793 err:
10794         kfree(intel_fb);
10795         return ERR_PTR(ret);
10796 }
10797
10798 static int intel_modeset_disable_planes(struct drm_atomic_state *state,
10799                                         struct drm_crtc *crtc)
10800 {
10801         struct drm_plane *plane;
10802         struct drm_plane_state *plane_state;
10803         int ret, i;
10804
10805         ret = drm_atomic_add_affected_planes(state, crtc);
10806         if (ret)
10807                 return ret;
10808
10809         for_each_new_plane_in_state(state, plane, plane_state, i) {
10810                 if (plane_state->crtc != crtc)
10811                         continue;
10812
10813                 ret = drm_atomic_set_crtc_for_plane(plane_state, NULL);
10814                 if (ret)
10815                         return ret;
10816
10817                 drm_atomic_set_fb_for_plane(plane_state, NULL);
10818         }
10819
10820         return 0;
10821 }
10822
10823 int intel_get_load_detect_pipe(struct drm_connector *connector,
10824                                const struct drm_display_mode *mode,
10825                                struct intel_load_detect_pipe *old,
10826                                struct drm_modeset_acquire_ctx *ctx)
10827 {
10828         struct intel_crtc *intel_crtc;
10829         struct intel_encoder *intel_encoder =
10830                 intel_attached_encoder(connector);
10831         struct drm_crtc *possible_crtc;
10832         struct drm_encoder *encoder = &intel_encoder->base;
10833         struct drm_crtc *crtc = NULL;
10834         struct drm_device *dev = encoder->dev;
10835         struct drm_i915_private *dev_priv = to_i915(dev);
10836         struct drm_mode_config *config = &dev->mode_config;
10837         struct drm_atomic_state *state = NULL, *restore_state = NULL;
10838         struct drm_connector_state *connector_state;
10839         struct intel_crtc_state *crtc_state;
10840         int ret, i = -1;
10841
10842         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10843                       connector->base.id, connector->name,
10844                       encoder->base.id, encoder->name);
10845
10846         old->restore_state = NULL;
10847
10848         WARN_ON(!drm_modeset_is_locked(&config->connection_mutex));
10849
10850         /*
10851          * Algorithm gets a little messy:
10852          *
10853          *   - if the connector already has an assigned crtc, use it (but make
10854          *     sure it's on first)
10855          *
10856          *   - try to find the first unused crtc that can drive this connector,
10857          *     and use that if we find one
10858          */
10859
10860         /* See if we already have a CRTC for this connector */
10861         if (connector->state->crtc) {
10862                 crtc = connector->state->crtc;
10863
10864                 ret = drm_modeset_lock(&crtc->mutex, ctx);
10865                 if (ret)
10866                         goto fail;
10867
10868                 /* Make sure the crtc and connector are running */
10869                 goto found;
10870         }
10871
10872         /* Find an unused one (if possible) */
10873         for_each_crtc(dev, possible_crtc) {
10874                 i++;
10875                 if (!(encoder->possible_crtcs & (1 << i)))
10876                         continue;
10877
10878                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
10879                 if (ret)
10880                         goto fail;
10881
10882                 if (possible_crtc->state->enable) {
10883                         drm_modeset_unlock(&possible_crtc->mutex);
10884                         continue;
10885                 }
10886
10887                 crtc = possible_crtc;
10888                 break;
10889         }
10890
10891         /*
10892          * If we didn't find an unused CRTC, don't use any.
10893          */
10894         if (!crtc) {
10895                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
10896                 ret = -ENODEV;
10897                 goto fail;
10898         }
10899
10900 found:
10901         intel_crtc = to_intel_crtc(crtc);
10902
10903         state = drm_atomic_state_alloc(dev);
10904         restore_state = drm_atomic_state_alloc(dev);
10905         if (!state || !restore_state) {
10906                 ret = -ENOMEM;
10907                 goto fail;
10908         }
10909
10910         state->acquire_ctx = ctx;
10911         restore_state->acquire_ctx = ctx;
10912
10913         connector_state = drm_atomic_get_connector_state(state, connector);
10914         if (IS_ERR(connector_state)) {
10915                 ret = PTR_ERR(connector_state);
10916                 goto fail;
10917         }
10918
10919         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
10920         if (ret)
10921                 goto fail;
10922
10923         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10924         if (IS_ERR(crtc_state)) {
10925                 ret = PTR_ERR(crtc_state);
10926                 goto fail;
10927         }
10928
10929         crtc_state->base.active = crtc_state->base.enable = true;
10930
10931         if (!mode)
10932                 mode = &load_detect_mode;
10933
10934         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
10935         if (ret)
10936                 goto fail;
10937
10938         ret = intel_modeset_disable_planes(state, crtc);
10939         if (ret)
10940                 goto fail;
10941
10942         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
10943         if (!ret)
10944                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
10945         if (!ret)
10946                 ret = drm_atomic_add_affected_planes(restore_state, crtc);
10947         if (ret) {
10948                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
10949                 goto fail;
10950         }
10951
10952         ret = drm_atomic_commit(state);
10953         if (ret) {
10954                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
10955                 goto fail;
10956         }
10957
10958         old->restore_state = restore_state;
10959         drm_atomic_state_put(state);
10960
10961         /* let the connector get through one full cycle before testing */
10962         intel_wait_for_vblank(dev_priv, intel_crtc->pipe);
10963         return true;
10964
10965 fail:
10966         if (state) {
10967                 drm_atomic_state_put(state);
10968                 state = NULL;
10969         }
10970         if (restore_state) {
10971                 drm_atomic_state_put(restore_state);
10972                 restore_state = NULL;
10973         }
10974
10975         if (ret == -EDEADLK)
10976                 return ret;
10977
10978         return false;
10979 }
10980
10981 void intel_release_load_detect_pipe(struct drm_connector *connector,
10982                                     struct intel_load_detect_pipe *old,
10983                                     struct drm_modeset_acquire_ctx *ctx)
10984 {
10985         struct intel_encoder *intel_encoder =
10986                 intel_attached_encoder(connector);
10987         struct drm_encoder *encoder = &intel_encoder->base;
10988         struct drm_atomic_state *state = old->restore_state;
10989         int ret;
10990
10991         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10992                       connector->base.id, connector->name,
10993                       encoder->base.id, encoder->name);
10994
10995         if (!state)
10996                 return;
10997
10998         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
10999         if (ret)
11000                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
11001         drm_atomic_state_put(state);
11002 }
11003
11004 static int i9xx_pll_refclk(struct drm_device *dev,
11005                            const struct intel_crtc_state *pipe_config)
11006 {
11007         struct drm_i915_private *dev_priv = to_i915(dev);
11008         u32 dpll = pipe_config->dpll_hw_state.dpll;
11009
11010         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
11011                 return dev_priv->vbt.lvds_ssc_freq;
11012         else if (HAS_PCH_SPLIT(dev_priv))
11013                 return 120000;
11014         else if (!IS_GEN(dev_priv, 2))
11015                 return 96000;
11016         else
11017                 return 48000;
11018 }
11019
11020 /* Returns the clock of the currently programmed mode of the given pipe. */
11021 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
11022                                 struct intel_crtc_state *pipe_config)
11023 {
11024         struct drm_device *dev = crtc->base.dev;
11025         struct drm_i915_private *dev_priv = to_i915(dev);
11026         int pipe = pipe_config->cpu_transcoder;
11027         u32 dpll = pipe_config->dpll_hw_state.dpll;
11028         u32 fp;
11029         struct dpll clock;
11030         int port_clock;
11031         int refclk = i9xx_pll_refclk(dev, pipe_config);
11032
11033         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
11034                 fp = pipe_config->dpll_hw_state.fp0;
11035         else
11036                 fp = pipe_config->dpll_hw_state.fp1;
11037
11038         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
11039         if (IS_PINEVIEW(dev_priv)) {
11040                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
11041                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
11042         } else {
11043                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
11044                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
11045         }
11046
11047         if (!IS_GEN(dev_priv, 2)) {
11048                 if (IS_PINEVIEW(dev_priv))
11049                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
11050                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
11051                 else
11052                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
11053                                DPLL_FPA01_P1_POST_DIV_SHIFT);
11054
11055                 switch (dpll & DPLL_MODE_MASK) {
11056                 case DPLLB_MODE_DAC_SERIAL:
11057                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
11058                                 5 : 10;
11059                         break;
11060                 case DPLLB_MODE_LVDS:
11061                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
11062                                 7 : 14;
11063                         break;
11064                 default:
11065                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
11066                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
11067                         return;
11068                 }
11069
11070                 if (IS_PINEVIEW(dev_priv))
11071                         port_clock = pnv_calc_dpll_params(refclk, &clock);
11072                 else
11073                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
11074         } else {
11075                 u32 lvds = IS_I830(dev_priv) ? 0 : I915_READ(LVDS);
11076                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
11077
11078                 if (is_lvds) {
11079                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
11080                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
11081
11082                         if (lvds & LVDS_CLKB_POWER_UP)
11083                                 clock.p2 = 7;
11084                         else
11085                                 clock.p2 = 14;
11086                 } else {
11087                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
11088                                 clock.p1 = 2;
11089                         else {
11090                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
11091                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
11092                         }
11093                         if (dpll & PLL_P2_DIVIDE_BY_4)
11094                                 clock.p2 = 4;
11095                         else
11096                                 clock.p2 = 2;
11097                 }
11098
11099                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
11100         }
11101
11102         /*
11103          * This value includes pixel_multiplier. We will use
11104          * port_clock to compute adjusted_mode.crtc_clock in the
11105          * encoder's get_config() function.
11106          */
11107         pipe_config->port_clock = port_clock;
11108 }
11109
11110 int intel_dotclock_calculate(int link_freq,
11111                              const struct intel_link_m_n *m_n)
11112 {
11113         /*
11114          * The calculation for the data clock is:
11115          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
11116          * But we want to avoid losing precison if possible, so:
11117          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
11118          *
11119          * and the link clock is simpler:
11120          * link_clock = (m * link_clock) / n
11121          */
11122
11123         if (!m_n->link_n)
11124                 return 0;
11125
11126         return div_u64(mul_u32_u32(m_n->link_m, link_freq), m_n->link_n);
11127 }
11128
11129 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
11130                                    struct intel_crtc_state *pipe_config)
11131 {
11132         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11133
11134         /* read out port_clock from the DPLL */
11135         i9xx_crtc_clock_get(crtc, pipe_config);
11136
11137         /*
11138          * In case there is an active pipe without active ports,
11139          * we may need some idea for the dotclock anyway.
11140          * Calculate one based on the FDI configuration.
11141          */
11142         pipe_config->base.adjusted_mode.crtc_clock =
11143                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
11144                                          &pipe_config->fdi_m_n);
11145 }
11146
11147 /* Returns the currently programmed mode of the given encoder. */
11148 struct drm_display_mode *
11149 intel_encoder_current_mode(struct intel_encoder *encoder)
11150 {
11151         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
11152         struct intel_crtc_state *crtc_state;
11153         struct drm_display_mode *mode;
11154         struct intel_crtc *crtc;
11155         enum pipe pipe;
11156
11157         if (!encoder->get_hw_state(encoder, &pipe))
11158                 return NULL;
11159
11160         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
11161
11162         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
11163         if (!mode)
11164                 return NULL;
11165
11166         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
11167         if (!crtc_state) {
11168                 kfree(mode);
11169                 return NULL;
11170         }
11171
11172         crtc_state->base.crtc = &crtc->base;
11173
11174         if (!dev_priv->display.get_pipe_config(crtc, crtc_state)) {
11175                 kfree(crtc_state);
11176                 kfree(mode);
11177                 return NULL;
11178         }
11179
11180         encoder->get_config(encoder, crtc_state);
11181
11182         intel_mode_from_pipe_config(mode, crtc_state);
11183
11184         kfree(crtc_state);
11185
11186         return mode;
11187 }
11188
11189 static void intel_crtc_destroy(struct drm_crtc *crtc)
11190 {
11191         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11192
11193         drm_crtc_cleanup(crtc);
11194         kfree(intel_crtc);
11195 }
11196
11197 /**
11198  * intel_wm_need_update - Check whether watermarks need updating
11199  * @cur: current plane state
11200  * @new: new plane state
11201  *
11202  * Check current plane state versus the new one to determine whether
11203  * watermarks need to be recalculated.
11204  *
11205  * Returns true or false.
11206  */
11207 static bool intel_wm_need_update(struct intel_plane_state *cur,
11208                                  struct intel_plane_state *new)
11209 {
11210         /* Update watermarks on tiling or size changes. */
11211         if (new->base.visible != cur->base.visible)
11212                 return true;
11213
11214         if (!cur->base.fb || !new->base.fb)
11215                 return false;
11216
11217         if (cur->base.fb->modifier != new->base.fb->modifier ||
11218             cur->base.rotation != new->base.rotation ||
11219             drm_rect_width(&new->base.src) != drm_rect_width(&cur->base.src) ||
11220             drm_rect_height(&new->base.src) != drm_rect_height(&cur->base.src) ||
11221             drm_rect_width(&new->base.dst) != drm_rect_width(&cur->base.dst) ||
11222             drm_rect_height(&new->base.dst) != drm_rect_height(&cur->base.dst))
11223                 return true;
11224
11225         return false;
11226 }
11227
11228 static bool needs_scaling(const struct intel_plane_state *state)
11229 {
11230         int src_w = drm_rect_width(&state->base.src) >> 16;
11231         int src_h = drm_rect_height(&state->base.src) >> 16;
11232         int dst_w = drm_rect_width(&state->base.dst);
11233         int dst_h = drm_rect_height(&state->base.dst);
11234
11235         return (src_w != dst_w || src_h != dst_h);
11236 }
11237
11238 int intel_plane_atomic_calc_changes(const struct intel_crtc_state *old_crtc_state,
11239                                     struct drm_crtc_state *crtc_state,
11240                                     const struct intel_plane_state *old_plane_state,
11241                                     struct drm_plane_state *plane_state)
11242 {
11243         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
11244         struct drm_crtc *crtc = crtc_state->crtc;
11245         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11246         struct intel_plane *plane = to_intel_plane(plane_state->plane);
11247         struct drm_device *dev = crtc->dev;
11248         struct drm_i915_private *dev_priv = to_i915(dev);
11249         bool mode_changed = needs_modeset(crtc_state);
11250         bool was_crtc_enabled = old_crtc_state->base.active;
11251         bool is_crtc_enabled = crtc_state->active;
11252         bool turn_off, turn_on, visible, was_visible;
11253         struct drm_framebuffer *fb = plane_state->fb;
11254         int ret;
11255
11256         if (INTEL_GEN(dev_priv) >= 9 && plane->id != PLANE_CURSOR) {
11257                 ret = skl_update_scaler_plane(
11258                         to_intel_crtc_state(crtc_state),
11259                         to_intel_plane_state(plane_state));
11260                 if (ret)
11261                         return ret;
11262         }
11263
11264         was_visible = old_plane_state->base.visible;
11265         visible = plane_state->visible;
11266
11267         if (!was_crtc_enabled && WARN_ON(was_visible))
11268                 was_visible = false;
11269
11270         /*
11271          * Visibility is calculated as if the crtc was on, but
11272          * after scaler setup everything depends on it being off
11273          * when the crtc isn't active.
11274          *
11275          * FIXME this is wrong for watermarks. Watermarks should also
11276          * be computed as if the pipe would be active. Perhaps move
11277          * per-plane wm computation to the .check_plane() hook, and
11278          * only combine the results from all planes in the current place?
11279          */
11280         if (!is_crtc_enabled) {
11281                 plane_state->visible = visible = false;
11282                 to_intel_crtc_state(crtc_state)->active_planes &= ~BIT(plane->id);
11283         }
11284
11285         if (!was_visible && !visible)
11286                 return 0;
11287
11288         if (fb != old_plane_state->base.fb)
11289                 pipe_config->fb_changed = true;
11290
11291         turn_off = was_visible && (!visible || mode_changed);
11292         turn_on = visible && (!was_visible || mode_changed);
11293
11294         DRM_DEBUG_ATOMIC("[CRTC:%d:%s] has [PLANE:%d:%s] with fb %i\n",
11295                          intel_crtc->base.base.id, intel_crtc->base.name,
11296                          plane->base.base.id, plane->base.name,
11297                          fb ? fb->base.id : -1);
11298
11299         DRM_DEBUG_ATOMIC("[PLANE:%d:%s] visible %i -> %i, off %i, on %i, ms %i\n",
11300                          plane->base.base.id, plane->base.name,
11301                          was_visible, visible,
11302                          turn_off, turn_on, mode_changed);
11303
11304         if (turn_on) {
11305                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
11306                         pipe_config->update_wm_pre = true;
11307
11308                 /* must disable cxsr around plane enable/disable */
11309                 if (plane->id != PLANE_CURSOR)
11310                         pipe_config->disable_cxsr = true;
11311         } else if (turn_off) {
11312                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
11313                         pipe_config->update_wm_post = true;
11314
11315                 /* must disable cxsr around plane enable/disable */
11316                 if (plane->id != PLANE_CURSOR)
11317                         pipe_config->disable_cxsr = true;
11318         } else if (intel_wm_need_update(to_intel_plane_state(plane->base.state),
11319                                         to_intel_plane_state(plane_state))) {
11320                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
11321                         /* FIXME bollocks */
11322                         pipe_config->update_wm_pre = true;
11323                         pipe_config->update_wm_post = true;
11324                 }
11325         }
11326
11327         if (visible || was_visible)
11328                 pipe_config->fb_bits |= plane->frontbuffer_bit;
11329
11330         /*
11331          * ILK/SNB DVSACNTR/Sprite Enable
11332          * IVB SPR_CTL/Sprite Enable
11333          * "When in Self Refresh Big FIFO mode, a write to enable the
11334          *  plane will be internally buffered and delayed while Big FIFO
11335          *  mode is exiting."
11336          *
11337          * Which means that enabling the sprite can take an extra frame
11338          * when we start in big FIFO mode (LP1+). Thus we need to drop
11339          * down to LP0 and wait for vblank in order to make sure the
11340          * sprite gets enabled on the next vblank after the register write.
11341          * Doing otherwise would risk enabling the sprite one frame after
11342          * we've already signalled flip completion. We can resume LP1+
11343          * once the sprite has been enabled.
11344          *
11345          *
11346          * WaCxSRDisabledForSpriteScaling:ivb
11347          * IVB SPR_SCALE/Scaling Enable
11348          * "Low Power watermarks must be disabled for at least one
11349          *  frame before enabling sprite scaling, and kept disabled
11350          *  until sprite scaling is disabled."
11351          *
11352          * ILK/SNB DVSASCALE/Scaling Enable
11353          * "When in Self Refresh Big FIFO mode, scaling enable will be
11354          *  masked off while Big FIFO mode is exiting."
11355          *
11356          * Despite the w/a only being listed for IVB we assume that
11357          * the ILK/SNB note has similar ramifications, hence we apply
11358          * the w/a on all three platforms.
11359          *
11360          * With experimental results seems this is needed also for primary
11361          * plane, not only sprite plane.
11362          */
11363         if (plane->id != PLANE_CURSOR &&
11364             (IS_GEN_RANGE(dev_priv, 5, 6) ||
11365              IS_IVYBRIDGE(dev_priv)) &&
11366             (turn_on || (!needs_scaling(old_plane_state) &&
11367                          needs_scaling(to_intel_plane_state(plane_state)))))
11368                 pipe_config->disable_lp_wm = true;
11369
11370         return 0;
11371 }
11372
11373 static bool encoders_cloneable(const struct intel_encoder *a,
11374                                const struct intel_encoder *b)
11375 {
11376         /* masks could be asymmetric, so check both ways */
11377         return a == b || (a->cloneable & (1 << b->type) &&
11378                           b->cloneable & (1 << a->type));
11379 }
11380
11381 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
11382                                          struct intel_crtc *crtc,
11383                                          struct intel_encoder *encoder)
11384 {
11385         struct intel_encoder *source_encoder;
11386         struct drm_connector *connector;
11387         struct drm_connector_state *connector_state;
11388         int i;
11389
11390         for_each_new_connector_in_state(state, connector, connector_state, i) {
11391                 if (connector_state->crtc != &crtc->base)
11392                         continue;
11393
11394                 source_encoder =
11395                         to_intel_encoder(connector_state->best_encoder);
11396                 if (!encoders_cloneable(encoder, source_encoder))
11397                         return false;
11398         }
11399
11400         return true;
11401 }
11402
11403 static int icl_add_linked_planes(struct intel_atomic_state *state)
11404 {
11405         struct intel_plane *plane, *linked;
11406         struct intel_plane_state *plane_state, *linked_plane_state;
11407         int i;
11408
11409         for_each_new_intel_plane_in_state(state, plane, plane_state, i) {
11410                 linked = plane_state->linked_plane;
11411
11412                 if (!linked)
11413                         continue;
11414
11415                 linked_plane_state = intel_atomic_get_plane_state(state, linked);
11416                 if (IS_ERR(linked_plane_state))
11417                         return PTR_ERR(linked_plane_state);
11418
11419                 WARN_ON(linked_plane_state->linked_plane != plane);
11420                 WARN_ON(linked_plane_state->slave == plane_state->slave);
11421         }
11422
11423         return 0;
11424 }
11425
11426 static int icl_check_nv12_planes(struct intel_crtc_state *crtc_state)
11427 {
11428         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
11429         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11430         struct intel_atomic_state *state = to_intel_atomic_state(crtc_state->base.state);
11431         struct intel_plane *plane, *linked;
11432         struct intel_plane_state *plane_state;
11433         int i;
11434
11435         if (INTEL_GEN(dev_priv) < 11)
11436                 return 0;
11437
11438         /*
11439          * Destroy all old plane links and make the slave plane invisible
11440          * in the crtc_state->active_planes mask.
11441          */
11442         for_each_new_intel_plane_in_state(state, plane, plane_state, i) {
11443                 if (plane->pipe != crtc->pipe || !plane_state->linked_plane)
11444                         continue;
11445
11446                 plane_state->linked_plane = NULL;
11447                 if (plane_state->slave && !plane_state->base.visible) {
11448                         crtc_state->active_planes &= ~BIT(plane->id);
11449                         crtc_state->update_planes |= BIT(plane->id);
11450                 }
11451
11452                 plane_state->slave = false;
11453         }
11454
11455         if (!crtc_state->nv12_planes)
11456                 return 0;
11457
11458         for_each_new_intel_plane_in_state(state, plane, plane_state, i) {
11459                 struct intel_plane_state *linked_state = NULL;
11460
11461                 if (plane->pipe != crtc->pipe ||
11462                     !(crtc_state->nv12_planes & BIT(plane->id)))
11463                         continue;
11464
11465                 for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, linked) {
11466                         if (!icl_is_nv12_y_plane(linked->id))
11467                                 continue;
11468
11469                         if (crtc_state->active_planes & BIT(linked->id))
11470                                 continue;
11471
11472                         linked_state = intel_atomic_get_plane_state(state, linked);
11473                         if (IS_ERR(linked_state))
11474                                 return PTR_ERR(linked_state);
11475
11476                         break;
11477                 }
11478
11479                 if (!linked_state) {
11480                         DRM_DEBUG_KMS("Need %d free Y planes for planar YUV\n",
11481                                       hweight8(crtc_state->nv12_planes));
11482
11483                         return -EINVAL;
11484                 }
11485
11486                 plane_state->linked_plane = linked;
11487
11488                 linked_state->slave = true;
11489                 linked_state->linked_plane = plane;
11490                 crtc_state->active_planes |= BIT(linked->id);
11491                 crtc_state->update_planes |= BIT(linked->id);
11492                 DRM_DEBUG_KMS("Using %s as Y plane for %s\n", linked->base.name, plane->base.name);
11493         }
11494
11495         return 0;
11496 }
11497
11498 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
11499                                    struct drm_crtc_state *crtc_state)
11500 {
11501         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
11502         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11503         struct intel_crtc_state *pipe_config =
11504                 to_intel_crtc_state(crtc_state);
11505         int ret;
11506         bool mode_changed = needs_modeset(crtc_state);
11507
11508         if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv) &&
11509             mode_changed && !crtc_state->active)
11510                 pipe_config->update_wm_post = true;
11511
11512         if (mode_changed && crtc_state->enable &&
11513             dev_priv->display.crtc_compute_clock &&
11514             !WARN_ON(pipe_config->shared_dpll)) {
11515                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
11516                                                            pipe_config);
11517                 if (ret)
11518                         return ret;
11519         }
11520
11521         if (mode_changed || pipe_config->update_pipe ||
11522             crtc_state->color_mgmt_changed) {
11523                 ret = intel_color_check(pipe_config);
11524                 if (ret)
11525                         return ret;
11526         }
11527
11528         ret = 0;
11529         if (dev_priv->display.compute_pipe_wm) {
11530                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
11531                 if (ret) {
11532                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
11533                         return ret;
11534                 }
11535         }
11536
11537         if (dev_priv->display.compute_intermediate_wm) {
11538                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
11539                         return 0;
11540
11541                 /*
11542                  * Calculate 'intermediate' watermarks that satisfy both the
11543                  * old state and the new state.  We can program these
11544                  * immediately.
11545                  */
11546                 ret = dev_priv->display.compute_intermediate_wm(pipe_config);
11547                 if (ret) {
11548                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
11549                         return ret;
11550                 }
11551         }
11552
11553         if (INTEL_GEN(dev_priv) >= 9) {
11554                 if (mode_changed || pipe_config->update_pipe)
11555                         ret = skl_update_scaler_crtc(pipe_config);
11556
11557                 if (!ret)
11558                         ret = icl_check_nv12_planes(pipe_config);
11559                 if (!ret)
11560                         ret = skl_check_pipe_max_pixel_rate(intel_crtc,
11561                                                             pipe_config);
11562                 if (!ret)
11563                         ret = intel_atomic_setup_scalers(dev_priv, intel_crtc,
11564                                                          pipe_config);
11565         }
11566
11567         if (HAS_IPS(dev_priv))
11568                 pipe_config->ips_enabled = hsw_compute_ips_config(pipe_config);
11569
11570         return ret;
11571 }
11572
11573 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
11574         .atomic_check = intel_crtc_atomic_check,
11575 };
11576
11577 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
11578 {
11579         struct intel_connector *connector;
11580         struct drm_connector_list_iter conn_iter;
11581
11582         drm_connector_list_iter_begin(dev, &conn_iter);
11583         for_each_intel_connector_iter(connector, &conn_iter) {
11584                 if (connector->base.state->crtc)
11585                         drm_connector_put(&connector->base);
11586
11587                 if (connector->base.encoder) {
11588                         connector->base.state->best_encoder =
11589                                 connector->base.encoder;
11590                         connector->base.state->crtc =
11591                                 connector->base.encoder->crtc;
11592
11593                         drm_connector_get(&connector->base);
11594                 } else {
11595                         connector->base.state->best_encoder = NULL;
11596                         connector->base.state->crtc = NULL;
11597                 }
11598         }
11599         drm_connector_list_iter_end(&conn_iter);
11600 }
11601
11602 static int
11603 compute_sink_pipe_bpp(const struct drm_connector_state *conn_state,
11604                       struct intel_crtc_state *pipe_config)
11605 {
11606         struct drm_connector *connector = conn_state->connector;
11607         const struct drm_display_info *info = &connector->display_info;
11608         int bpp;
11609
11610         switch (conn_state->max_bpc) {
11611         case 6 ... 7:
11612                 bpp = 6 * 3;
11613                 break;
11614         case 8 ... 9:
11615                 bpp = 8 * 3;
11616                 break;
11617         case 10 ... 11:
11618                 bpp = 10 * 3;
11619                 break;
11620         case 12:
11621                 bpp = 12 * 3;
11622                 break;
11623         default:
11624                 return -EINVAL;
11625         }
11626
11627         if (bpp < pipe_config->pipe_bpp) {
11628                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] Limiting display bpp to %d instead of "
11629                               "EDID bpp %d, requested bpp %d, max platform bpp %d\n",
11630                               connector->base.id, connector->name,
11631                               bpp, 3 * info->bpc, 3 * conn_state->max_requested_bpc,
11632                               pipe_config->pipe_bpp);
11633
11634                 pipe_config->pipe_bpp = bpp;
11635         }
11636
11637         return 0;
11638 }
11639
11640 static int
11641 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
11642                           struct intel_crtc_state *pipe_config)
11643 {
11644         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11645         struct drm_atomic_state *state = pipe_config->base.state;
11646         struct drm_connector *connector;
11647         struct drm_connector_state *connector_state;
11648         int bpp, i;
11649
11650         if ((IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
11651             IS_CHERRYVIEW(dev_priv)))
11652                 bpp = 10*3;
11653         else if (INTEL_GEN(dev_priv) >= 5)
11654                 bpp = 12*3;
11655         else
11656                 bpp = 8*3;
11657
11658         pipe_config->pipe_bpp = bpp;
11659
11660         /* Clamp display bpp to connector max bpp */
11661         for_each_new_connector_in_state(state, connector, connector_state, i) {
11662                 int ret;
11663
11664                 if (connector_state->crtc != &crtc->base)
11665                         continue;
11666
11667                 ret = compute_sink_pipe_bpp(connector_state, pipe_config);
11668                 if (ret)
11669                         return ret;
11670         }
11671
11672         return 0;
11673 }
11674
11675 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
11676 {
11677         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
11678                         "type: 0x%x flags: 0x%x\n",
11679                 mode->crtc_clock,
11680                 mode->crtc_hdisplay, mode->crtc_hsync_start,
11681                 mode->crtc_hsync_end, mode->crtc_htotal,
11682                 mode->crtc_vdisplay, mode->crtc_vsync_start,
11683                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
11684 }
11685
11686 static inline void
11687 intel_dump_m_n_config(struct intel_crtc_state *pipe_config, char *id,
11688                       unsigned int lane_count, struct intel_link_m_n *m_n)
11689 {
11690         DRM_DEBUG_KMS("%s: lanes: %i; gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
11691                       id, lane_count,
11692                       m_n->gmch_m, m_n->gmch_n,
11693                       m_n->link_m, m_n->link_n, m_n->tu);
11694 }
11695
11696 static void
11697 intel_dump_infoframe(struct drm_i915_private *dev_priv,
11698                      const union hdmi_infoframe *frame)
11699 {
11700         if ((drm_debug & DRM_UT_KMS) == 0)
11701                 return;
11702
11703         hdmi_infoframe_log(KERN_DEBUG, dev_priv->drm.dev, frame);
11704 }
11705
11706 #define OUTPUT_TYPE(x) [INTEL_OUTPUT_ ## x] = #x
11707
11708 static const char * const output_type_str[] = {
11709         OUTPUT_TYPE(UNUSED),
11710         OUTPUT_TYPE(ANALOG),
11711         OUTPUT_TYPE(DVO),
11712         OUTPUT_TYPE(SDVO),
11713         OUTPUT_TYPE(LVDS),
11714         OUTPUT_TYPE(TVOUT),
11715         OUTPUT_TYPE(HDMI),
11716         OUTPUT_TYPE(DP),
11717         OUTPUT_TYPE(EDP),
11718         OUTPUT_TYPE(DSI),
11719         OUTPUT_TYPE(DDI),
11720         OUTPUT_TYPE(DP_MST),
11721 };
11722
11723 #undef OUTPUT_TYPE
11724
11725 static void snprintf_output_types(char *buf, size_t len,
11726                                   unsigned int output_types)
11727 {
11728         char *str = buf;
11729         int i;
11730
11731         str[0] = '\0';
11732
11733         for (i = 0; i < ARRAY_SIZE(output_type_str); i++) {
11734                 int r;
11735
11736                 if ((output_types & BIT(i)) == 0)
11737                         continue;
11738
11739                 r = snprintf(str, len, "%s%s",
11740                              str != buf ? "," : "", output_type_str[i]);
11741                 if (r >= len)
11742                         break;
11743                 str += r;
11744                 len -= r;
11745
11746                 output_types &= ~BIT(i);
11747         }
11748
11749         WARN_ON_ONCE(output_types != 0);
11750 }
11751
11752 static const char * const output_format_str[] = {
11753         [INTEL_OUTPUT_FORMAT_INVALID] = "Invalid",
11754         [INTEL_OUTPUT_FORMAT_RGB] = "RGB",
11755         [INTEL_OUTPUT_FORMAT_YCBCR420] = "YCBCR4:2:0",
11756         [INTEL_OUTPUT_FORMAT_YCBCR444] = "YCBCR4:4:4",
11757 };
11758
11759 static const char *output_formats(enum intel_output_format format)
11760 {
11761         if (format >= ARRAY_SIZE(output_format_str))
11762                 format = INTEL_OUTPUT_FORMAT_INVALID;
11763         return output_format_str[format];
11764 }
11765
11766 static void intel_dump_pipe_config(struct intel_crtc *crtc,
11767                                    struct intel_crtc_state *pipe_config,
11768                                    const char *context)
11769 {
11770         struct drm_device *dev = crtc->base.dev;
11771         struct drm_i915_private *dev_priv = to_i915(dev);
11772         struct drm_plane *plane;
11773         struct intel_plane *intel_plane;
11774         struct intel_plane_state *state;
11775         struct drm_framebuffer *fb;
11776         char buf[64];
11777
11778         DRM_DEBUG_KMS("[CRTC:%d:%s]%s\n",
11779                       crtc->base.base.id, crtc->base.name, context);
11780
11781         snprintf_output_types(buf, sizeof(buf), pipe_config->output_types);
11782         DRM_DEBUG_KMS("output_types: %s (0x%x)\n",
11783                       buf, pipe_config->output_types);
11784
11785         DRM_DEBUG_KMS("output format: %s\n",
11786                       output_formats(pipe_config->output_format));
11787
11788         DRM_DEBUG_KMS("cpu_transcoder: %s, pipe bpp: %i, dithering: %i\n",
11789                       transcoder_name(pipe_config->cpu_transcoder),
11790                       pipe_config->pipe_bpp, pipe_config->dither);
11791
11792         if (pipe_config->has_pch_encoder)
11793                 intel_dump_m_n_config(pipe_config, "fdi",
11794                                       pipe_config->fdi_lanes,
11795                                       &pipe_config->fdi_m_n);
11796
11797         if (intel_crtc_has_dp_encoder(pipe_config)) {
11798                 intel_dump_m_n_config(pipe_config, "dp m_n",
11799                                 pipe_config->lane_count, &pipe_config->dp_m_n);
11800                 if (pipe_config->has_drrs)
11801                         intel_dump_m_n_config(pipe_config, "dp m2_n2",
11802                                               pipe_config->lane_count,
11803                                               &pipe_config->dp_m2_n2);
11804         }
11805
11806         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
11807                       pipe_config->has_audio, pipe_config->has_infoframe);
11808
11809         DRM_DEBUG_KMS("infoframes enabled: 0x%x\n",
11810                       pipe_config->infoframes.enable);
11811
11812         if (pipe_config->infoframes.enable &
11813             intel_hdmi_infoframe_enable(HDMI_PACKET_TYPE_GENERAL_CONTROL))
11814                 DRM_DEBUG_KMS("GCP: 0x%x\n", pipe_config->infoframes.gcp);
11815         if (pipe_config->infoframes.enable &
11816             intel_hdmi_infoframe_enable(HDMI_INFOFRAME_TYPE_AVI))
11817                 intel_dump_infoframe(dev_priv, &pipe_config->infoframes.avi);
11818         if (pipe_config->infoframes.enable &
11819             intel_hdmi_infoframe_enable(HDMI_INFOFRAME_TYPE_SPD))
11820                 intel_dump_infoframe(dev_priv, &pipe_config->infoframes.spd);
11821         if (pipe_config->infoframes.enable &
11822             intel_hdmi_infoframe_enable(HDMI_INFOFRAME_TYPE_VENDOR))
11823                 intel_dump_infoframe(dev_priv, &pipe_config->infoframes.hdmi);
11824
11825         DRM_DEBUG_KMS("requested mode:\n");
11826         drm_mode_debug_printmodeline(&pipe_config->base.mode);
11827         DRM_DEBUG_KMS("adjusted mode:\n");
11828         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
11829         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
11830         DRM_DEBUG_KMS("port clock: %d, pipe src size: %dx%d, pixel rate %d\n",
11831                       pipe_config->port_clock,
11832                       pipe_config->pipe_src_w, pipe_config->pipe_src_h,
11833                       pipe_config->pixel_rate);
11834
11835         if (INTEL_GEN(dev_priv) >= 9)
11836                 DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
11837                               crtc->num_scalers,
11838                               pipe_config->scaler_state.scaler_users,
11839                               pipe_config->scaler_state.scaler_id);
11840
11841         if (HAS_GMCH(dev_priv))
11842                 DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
11843                               pipe_config->gmch_pfit.control,
11844                               pipe_config->gmch_pfit.pgm_ratios,
11845                               pipe_config->gmch_pfit.lvds_border_bits);
11846         else
11847                 DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s, force thru: %s\n",
11848                               pipe_config->pch_pfit.pos,
11849                               pipe_config->pch_pfit.size,
11850                               enableddisabled(pipe_config->pch_pfit.enabled),
11851                               yesno(pipe_config->pch_pfit.force_thru));
11852
11853         DRM_DEBUG_KMS("ips: %i, double wide: %i\n",
11854                       pipe_config->ips_enabled, pipe_config->double_wide);
11855
11856         intel_dpll_dump_hw_state(dev_priv, &pipe_config->dpll_hw_state);
11857
11858         DRM_DEBUG_KMS("planes on this crtc\n");
11859         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
11860                 struct drm_format_name_buf format_name;
11861                 intel_plane = to_intel_plane(plane);
11862                 if (intel_plane->pipe != crtc->pipe)
11863                         continue;
11864
11865                 state = to_intel_plane_state(plane->state);
11866                 fb = state->base.fb;
11867                 if (!fb) {
11868                         DRM_DEBUG_KMS("[PLANE:%d:%s] disabled, scaler_id = %d\n",
11869                                       plane->base.id, plane->name, state->scaler_id);
11870                         continue;
11871                 }
11872
11873                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d, fb = %ux%u format = %s\n",
11874                               plane->base.id, plane->name,
11875                               fb->base.id, fb->width, fb->height,
11876                               drm_get_format_name(fb->format->format, &format_name));
11877                 if (INTEL_GEN(dev_priv) >= 9)
11878                         DRM_DEBUG_KMS("\tscaler:%d src %dx%d+%d+%d dst %dx%d+%d+%d\n",
11879                                       state->scaler_id,
11880                                       state->base.src.x1 >> 16,
11881                                       state->base.src.y1 >> 16,
11882                                       drm_rect_width(&state->base.src) >> 16,
11883                                       drm_rect_height(&state->base.src) >> 16,
11884                                       state->base.dst.x1, state->base.dst.y1,
11885                                       drm_rect_width(&state->base.dst),
11886                                       drm_rect_height(&state->base.dst));
11887         }
11888 }
11889
11890 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
11891 {
11892         struct drm_device *dev = state->dev;
11893         struct drm_connector *connector;
11894         struct drm_connector_list_iter conn_iter;
11895         unsigned int used_ports = 0;
11896         unsigned int used_mst_ports = 0;
11897         bool ret = true;
11898
11899         /*
11900          * Walk the connector list instead of the encoder
11901          * list to detect the problem on ddi platforms
11902          * where there's just one encoder per digital port.
11903          */
11904         drm_connector_list_iter_begin(dev, &conn_iter);
11905         drm_for_each_connector_iter(connector, &conn_iter) {
11906                 struct drm_connector_state *connector_state;
11907                 struct intel_encoder *encoder;
11908
11909                 connector_state = drm_atomic_get_new_connector_state(state, connector);
11910                 if (!connector_state)
11911                         connector_state = connector->state;
11912
11913                 if (!connector_state->best_encoder)
11914                         continue;
11915
11916                 encoder = to_intel_encoder(connector_state->best_encoder);
11917
11918                 WARN_ON(!connector_state->crtc);
11919
11920                 switch (encoder->type) {
11921                         unsigned int port_mask;
11922                 case INTEL_OUTPUT_DDI:
11923                         if (WARN_ON(!HAS_DDI(to_i915(dev))))
11924                                 break;
11925                         /* else: fall through */
11926                 case INTEL_OUTPUT_DP:
11927                 case INTEL_OUTPUT_HDMI:
11928                 case INTEL_OUTPUT_EDP:
11929                         port_mask = 1 << encoder->port;
11930
11931                         /* the same port mustn't appear more than once */
11932                         if (used_ports & port_mask)
11933                                 ret = false;
11934
11935                         used_ports |= port_mask;
11936                         break;
11937                 case INTEL_OUTPUT_DP_MST:
11938                         used_mst_ports |=
11939                                 1 << encoder->port;
11940                         break;
11941                 default:
11942                         break;
11943                 }
11944         }
11945         drm_connector_list_iter_end(&conn_iter);
11946
11947         /* can't mix MST and SST/HDMI on the same port */
11948         if (used_ports & used_mst_ports)
11949                 return false;
11950
11951         return ret;
11952 }
11953
11954 static int
11955 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
11956 {
11957         struct drm_i915_private *dev_priv =
11958                 to_i915(crtc_state->base.crtc->dev);
11959         struct intel_crtc_state *saved_state;
11960
11961         saved_state = kzalloc(sizeof(*saved_state), GFP_KERNEL);
11962         if (!saved_state)
11963                 return -ENOMEM;
11964
11965         /* FIXME: before the switch to atomic started, a new pipe_config was
11966          * kzalloc'd. Code that depends on any field being zero should be
11967          * fixed, so that the crtc_state can be safely duplicated. For now,
11968          * only fields that are know to not cause problems are preserved. */
11969
11970         saved_state->scaler_state = crtc_state->scaler_state;
11971         saved_state->shared_dpll = crtc_state->shared_dpll;
11972         saved_state->dpll_hw_state = crtc_state->dpll_hw_state;
11973         saved_state->crc_enabled = crtc_state->crc_enabled;
11974         if (IS_G4X(dev_priv) ||
11975             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11976                 saved_state->wm = crtc_state->wm;
11977
11978         /* Keep base drm_crtc_state intact, only clear our extended struct */
11979         BUILD_BUG_ON(offsetof(struct intel_crtc_state, base));
11980         memcpy(&crtc_state->base + 1, &saved_state->base + 1,
11981                sizeof(*crtc_state) - sizeof(crtc_state->base));
11982
11983         kfree(saved_state);
11984         return 0;
11985 }
11986
11987 static int
11988 intel_modeset_pipe_config(struct drm_crtc *crtc,
11989                           struct intel_crtc_state *pipe_config)
11990 {
11991         struct drm_atomic_state *state = pipe_config->base.state;
11992         struct intel_encoder *encoder;
11993         struct drm_connector *connector;
11994         struct drm_connector_state *connector_state;
11995         int base_bpp, ret;
11996         int i;
11997         bool retry = true;
11998
11999         ret = clear_intel_crtc_state(pipe_config);
12000         if (ret)
12001                 return ret;
12002
12003         pipe_config->cpu_transcoder =
12004                 (enum transcoder) to_intel_crtc(crtc)->pipe;
12005
12006         /*
12007          * Sanitize sync polarity flags based on requested ones. If neither
12008          * positive or negative polarity is requested, treat this as meaning
12009          * negative polarity.
12010          */
12011         if (!(pipe_config->base.adjusted_mode.flags &
12012               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
12013                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
12014
12015         if (!(pipe_config->base.adjusted_mode.flags &
12016               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
12017                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
12018
12019         ret = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
12020                                         pipe_config);
12021         if (ret)
12022                 return ret;
12023
12024         base_bpp = pipe_config->pipe_bpp;
12025
12026         /*
12027          * Determine the real pipe dimensions. Note that stereo modes can
12028          * increase the actual pipe size due to the frame doubling and
12029          * insertion of additional space for blanks between the frame. This
12030          * is stored in the crtc timings. We use the requested mode to do this
12031          * computation to clearly distinguish it from the adjusted mode, which
12032          * can be changed by the connectors in the below retry loop.
12033          */
12034         drm_mode_get_hv_timing(&pipe_config->base.mode,
12035                                &pipe_config->pipe_src_w,
12036                                &pipe_config->pipe_src_h);
12037
12038         for_each_new_connector_in_state(state, connector, connector_state, i) {
12039                 if (connector_state->crtc != crtc)
12040                         continue;
12041
12042                 encoder = to_intel_encoder(connector_state->best_encoder);
12043
12044                 if (!check_single_encoder_cloning(state, to_intel_crtc(crtc), encoder)) {
12045                         DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
12046                         return -EINVAL;
12047                 }
12048
12049                 /*
12050                  * Determine output_types before calling the .compute_config()
12051                  * hooks so that the hooks can use this information safely.
12052                  */
12053                 if (encoder->compute_output_type)
12054                         pipe_config->output_types |=
12055                                 BIT(encoder->compute_output_type(encoder, pipe_config,
12056                                                                  connector_state));
12057                 else
12058                         pipe_config->output_types |= BIT(encoder->type);
12059         }
12060
12061 encoder_retry:
12062         /* Ensure the port clock defaults are reset when retrying. */
12063         pipe_config->port_clock = 0;
12064         pipe_config->pixel_multiplier = 1;
12065
12066         /* Fill in default crtc timings, allow encoders to overwrite them. */
12067         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
12068                               CRTC_STEREO_DOUBLE);
12069
12070         /* Pass our mode to the connectors and the CRTC to give them a chance to
12071          * adjust it according to limitations or connector properties, and also
12072          * a chance to reject the mode entirely.
12073          */
12074         for_each_new_connector_in_state(state, connector, connector_state, i) {
12075                 if (connector_state->crtc != crtc)
12076                         continue;
12077
12078                 encoder = to_intel_encoder(connector_state->best_encoder);
12079                 ret = encoder->compute_config(encoder, pipe_config,
12080                                               connector_state);
12081                 if (ret < 0) {
12082                         if (ret != -EDEADLK)
12083                                 DRM_DEBUG_KMS("Encoder config failure: %d\n",
12084                                               ret);
12085                         return ret;
12086                 }
12087         }
12088
12089         /* Set default port clock if not overwritten by the encoder. Needs to be
12090          * done afterwards in case the encoder adjusts the mode. */
12091         if (!pipe_config->port_clock)
12092                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
12093                         * pipe_config->pixel_multiplier;
12094
12095         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
12096         if (ret == -EDEADLK)
12097                 return ret;
12098         if (ret < 0) {
12099                 DRM_DEBUG_KMS("CRTC fixup failed\n");
12100                 return ret;
12101         }
12102
12103         if (ret == RETRY) {
12104                 if (WARN(!retry, "loop in pipe configuration computation\n"))
12105                         return -EINVAL;
12106
12107                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
12108                 retry = false;
12109                 goto encoder_retry;
12110         }
12111
12112         /* Dithering seems to not pass-through bits correctly when it should, so
12113          * only enable it on 6bpc panels and when its not a compliance
12114          * test requesting 6bpc video pattern.
12115          */
12116         pipe_config->dither = (pipe_config->pipe_bpp == 6*3) &&
12117                 !pipe_config->dither_force_disable;
12118         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
12119                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
12120
12121         return 0;
12122 }
12123
12124 static bool intel_fuzzy_clock_check(int clock1, int clock2)
12125 {
12126         int diff;
12127
12128         if (clock1 == clock2)
12129                 return true;
12130
12131         if (!clock1 || !clock2)
12132                 return false;
12133
12134         diff = abs(clock1 - clock2);
12135
12136         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
12137                 return true;
12138
12139         return false;
12140 }
12141
12142 static bool
12143 intel_compare_m_n(unsigned int m, unsigned int n,
12144                   unsigned int m2, unsigned int n2,
12145                   bool exact)
12146 {
12147         if (m == m2 && n == n2)
12148                 return true;
12149
12150         if (exact || !m || !n || !m2 || !n2)
12151                 return false;
12152
12153         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
12154
12155         if (n > n2) {
12156                 while (n > n2) {
12157                         m2 <<= 1;
12158                         n2 <<= 1;
12159                 }
12160         } else if (n < n2) {
12161                 while (n < n2) {
12162                         m <<= 1;
12163                         n <<= 1;
12164                 }
12165         }
12166
12167         if (n != n2)
12168                 return false;
12169
12170         return intel_fuzzy_clock_check(m, m2);
12171 }
12172
12173 static bool
12174 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
12175                        struct intel_link_m_n *m2_n2,
12176                        bool adjust)
12177 {
12178         if (m_n->tu == m2_n2->tu &&
12179             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
12180                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
12181             intel_compare_m_n(m_n->link_m, m_n->link_n,
12182                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
12183                 if (adjust)
12184                         *m2_n2 = *m_n;
12185
12186                 return true;
12187         }
12188
12189         return false;
12190 }
12191
12192 static bool
12193 intel_compare_infoframe(const union hdmi_infoframe *a,
12194                         const union hdmi_infoframe *b)
12195 {
12196         return memcmp(a, b, sizeof(*a)) == 0;
12197 }
12198
12199 static void
12200 pipe_config_infoframe_err(struct drm_i915_private *dev_priv,
12201                           bool adjust, const char *name,
12202                           const union hdmi_infoframe *a,
12203                           const union hdmi_infoframe *b)
12204 {
12205         if (adjust) {
12206                 if ((drm_debug & DRM_UT_KMS) == 0)
12207                         return;
12208
12209                 drm_dbg(DRM_UT_KMS, "mismatch in %s infoframe", name);
12210                 drm_dbg(DRM_UT_KMS, "expected:");
12211                 hdmi_infoframe_log(KERN_DEBUG, dev_priv->drm.dev, a);
12212                 drm_dbg(DRM_UT_KMS, "found");
12213                 hdmi_infoframe_log(KERN_DEBUG, dev_priv->drm.dev, b);
12214         } else {
12215                 drm_err("mismatch in %s infoframe", name);
12216                 drm_err("expected:");
12217                 hdmi_infoframe_log(KERN_ERR, dev_priv->drm.dev, a);
12218                 drm_err("found");
12219                 hdmi_infoframe_log(KERN_ERR, dev_priv->drm.dev, b);
12220         }
12221 }
12222
12223 static void __printf(3, 4)
12224 pipe_config_err(bool adjust, const char *name, const char *format, ...)
12225 {
12226         struct va_format vaf;
12227         va_list args;
12228
12229         va_start(args, format);
12230         vaf.fmt = format;
12231         vaf.va = &args;
12232
12233         if (adjust)
12234                 drm_dbg(DRM_UT_KMS, "mismatch in %s %pV", name, &vaf);
12235         else
12236                 drm_err("mismatch in %s %pV", name, &vaf);
12237
12238         va_end(args);
12239 }
12240
12241 static bool fastboot_enabled(struct drm_i915_private *dev_priv)
12242 {
12243         if (i915_modparams.fastboot != -1)
12244                 return i915_modparams.fastboot;
12245
12246         /* Enable fastboot by default on Skylake and newer */
12247         if (INTEL_GEN(dev_priv) >= 9)
12248                 return true;
12249
12250         /* Enable fastboot by default on VLV and CHV */
12251         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
12252                 return true;
12253
12254         /* Disabled by default on all others */
12255         return false;
12256 }
12257
12258 static bool
12259 intel_pipe_config_compare(struct drm_i915_private *dev_priv,
12260                           struct intel_crtc_state *current_config,
12261                           struct intel_crtc_state *pipe_config,
12262                           bool adjust)
12263 {
12264         bool ret = true;
12265         bool fixup_inherited = adjust &&
12266                 (current_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED) &&
12267                 !(pipe_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED);
12268
12269         if (fixup_inherited && !fastboot_enabled(dev_priv)) {
12270                 DRM_DEBUG_KMS("initial modeset and fastboot not set\n");
12271                 ret = false;
12272         }
12273
12274 #define PIPE_CONF_CHECK_X(name) do { \
12275         if (current_config->name != pipe_config->name) { \
12276                 pipe_config_err(adjust, __stringify(name), \
12277                           "(expected 0x%08x, found 0x%08x)\n", \
12278                           current_config->name, \
12279                           pipe_config->name); \
12280                 ret = false; \
12281         } \
12282 } while (0)
12283
12284 #define PIPE_CONF_CHECK_I(name) do { \
12285         if (current_config->name != pipe_config->name) { \
12286                 pipe_config_err(adjust, __stringify(name), \
12287                           "(expected %i, found %i)\n", \
12288                           current_config->name, \
12289                           pipe_config->name); \
12290                 ret = false; \
12291         } \
12292 } while (0)
12293
12294 #define PIPE_CONF_CHECK_BOOL(name) do { \
12295         if (current_config->name != pipe_config->name) { \
12296                 pipe_config_err(adjust, __stringify(name), \
12297                           "(expected %s, found %s)\n", \
12298                           yesno(current_config->name), \
12299                           yesno(pipe_config->name)); \
12300                 ret = false; \
12301         } \
12302 } while (0)
12303
12304 /*
12305  * Checks state where we only read out the enabling, but not the entire
12306  * state itself (like full infoframes or ELD for audio). These states
12307  * require a full modeset on bootup to fix up.
12308  */
12309 #define PIPE_CONF_CHECK_BOOL_INCOMPLETE(name) do { \
12310         if (!fixup_inherited || (!current_config->name && !pipe_config->name)) { \
12311                 PIPE_CONF_CHECK_BOOL(name); \
12312         } else { \
12313                 pipe_config_err(adjust, __stringify(name), \
12314                           "unable to verify whether state matches exactly, forcing modeset (expected %s, found %s)\n", \
12315                           yesno(current_config->name), \
12316                           yesno(pipe_config->name)); \
12317                 ret = false; \
12318         } \
12319 } while (0)
12320
12321 #define PIPE_CONF_CHECK_P(name) do { \
12322         if (current_config->name != pipe_config->name) { \
12323                 pipe_config_err(adjust, __stringify(name), \
12324                           "(expected %p, found %p)\n", \
12325                           current_config->name, \
12326                           pipe_config->name); \
12327                 ret = false; \
12328         } \
12329 } while (0)
12330
12331 #define PIPE_CONF_CHECK_M_N(name) do { \
12332         if (!intel_compare_link_m_n(&current_config->name, \
12333                                     &pipe_config->name,\
12334                                     adjust)) { \
12335                 pipe_config_err(adjust, __stringify(name), \
12336                           "(expected tu %i gmch %i/%i link %i/%i, " \
12337                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12338                           current_config->name.tu, \
12339                           current_config->name.gmch_m, \
12340                           current_config->name.gmch_n, \
12341                           current_config->name.link_m, \
12342                           current_config->name.link_n, \
12343                           pipe_config->name.tu, \
12344                           pipe_config->name.gmch_m, \
12345                           pipe_config->name.gmch_n, \
12346                           pipe_config->name.link_m, \
12347                           pipe_config->name.link_n); \
12348                 ret = false; \
12349         } \
12350 } while (0)
12351
12352 /* This is required for BDW+ where there is only one set of registers for
12353  * switching between high and low RR.
12354  * This macro can be used whenever a comparison has to be made between one
12355  * hw state and multiple sw state variables.
12356  */
12357 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) do { \
12358         if (!intel_compare_link_m_n(&current_config->name, \
12359                                     &pipe_config->name, adjust) && \
12360             !intel_compare_link_m_n(&current_config->alt_name, \
12361                                     &pipe_config->name, adjust)) { \
12362                 pipe_config_err(adjust, __stringify(name), \
12363                           "(expected tu %i gmch %i/%i link %i/%i, " \
12364                           "or tu %i gmch %i/%i link %i/%i, " \
12365                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12366                           current_config->name.tu, \
12367                           current_config->name.gmch_m, \
12368                           current_config->name.gmch_n, \
12369                           current_config->name.link_m, \
12370                           current_config->name.link_n, \
12371                           current_config->alt_name.tu, \
12372                           current_config->alt_name.gmch_m, \
12373                           current_config->alt_name.gmch_n, \
12374                           current_config->alt_name.link_m, \
12375                           current_config->alt_name.link_n, \
12376                           pipe_config->name.tu, \
12377                           pipe_config->name.gmch_m, \
12378                           pipe_config->name.gmch_n, \
12379                           pipe_config->name.link_m, \
12380                           pipe_config->name.link_n); \
12381                 ret = false; \
12382         } \
12383 } while (0)
12384
12385 #define PIPE_CONF_CHECK_FLAGS(name, mask) do { \
12386         if ((current_config->name ^ pipe_config->name) & (mask)) { \
12387                 pipe_config_err(adjust, __stringify(name), \
12388                           "(%x) (expected %i, found %i)\n", \
12389                           (mask), \
12390                           current_config->name & (mask), \
12391                           pipe_config->name & (mask)); \
12392                 ret = false; \
12393         } \
12394 } while (0)
12395
12396 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) do { \
12397         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
12398                 pipe_config_err(adjust, __stringify(name), \
12399                           "(expected %i, found %i)\n", \
12400                           current_config->name, \
12401                           pipe_config->name); \
12402                 ret = false; \
12403         } \
12404 } while (0)
12405
12406 #define PIPE_CONF_CHECK_INFOFRAME(name) do { \
12407         if (!intel_compare_infoframe(&current_config->infoframes.name, \
12408                                      &pipe_config->infoframes.name)) { \
12409                 pipe_config_infoframe_err(dev_priv, adjust, __stringify(name), \
12410                                           &current_config->infoframes.name, \
12411                                           &pipe_config->infoframes.name); \
12412                 ret = false; \
12413         } \
12414 } while (0)
12415
12416 #define PIPE_CONF_QUIRK(quirk) \
12417         ((current_config->quirks | pipe_config->quirks) & (quirk))
12418
12419         PIPE_CONF_CHECK_I(cpu_transcoder);
12420
12421         PIPE_CONF_CHECK_BOOL(has_pch_encoder);
12422         PIPE_CONF_CHECK_I(fdi_lanes);
12423         PIPE_CONF_CHECK_M_N(fdi_m_n);
12424
12425         PIPE_CONF_CHECK_I(lane_count);
12426         PIPE_CONF_CHECK_X(lane_lat_optim_mask);
12427
12428         if (INTEL_GEN(dev_priv) < 8) {
12429                 PIPE_CONF_CHECK_M_N(dp_m_n);
12430
12431                 if (current_config->has_drrs)
12432                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
12433         } else
12434                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
12435
12436         PIPE_CONF_CHECK_X(output_types);
12437
12438         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
12439         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
12440         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
12441         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
12442         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
12443         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
12444
12445         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
12446         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
12447         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
12448         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
12449         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
12450         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
12451
12452         PIPE_CONF_CHECK_I(pixel_multiplier);
12453         PIPE_CONF_CHECK_I(output_format);
12454         PIPE_CONF_CHECK_BOOL(has_hdmi_sink);
12455         if ((INTEL_GEN(dev_priv) < 8 && !IS_HASWELL(dev_priv)) ||
12456             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
12457                 PIPE_CONF_CHECK_BOOL(limited_color_range);
12458
12459         PIPE_CONF_CHECK_BOOL(hdmi_scrambling);
12460         PIPE_CONF_CHECK_BOOL(hdmi_high_tmds_clock_ratio);
12461         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_infoframe);
12462
12463         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_audio);
12464
12465         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12466                               DRM_MODE_FLAG_INTERLACE);
12467
12468         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
12469                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12470                                       DRM_MODE_FLAG_PHSYNC);
12471                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12472                                       DRM_MODE_FLAG_NHSYNC);
12473                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12474                                       DRM_MODE_FLAG_PVSYNC);
12475                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12476                                       DRM_MODE_FLAG_NVSYNC);
12477         }
12478
12479         PIPE_CONF_CHECK_X(gmch_pfit.control);
12480         /* pfit ratios are autocomputed by the hw on gen4+ */
12481         if (INTEL_GEN(dev_priv) < 4)
12482                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
12483         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
12484
12485         /*
12486          * Changing the EDP transcoder input mux
12487          * (A_ONOFF vs. A_ON) requires a full modeset.
12488          */
12489         PIPE_CONF_CHECK_BOOL(pch_pfit.force_thru);
12490
12491         if (!adjust) {
12492                 PIPE_CONF_CHECK_I(pipe_src_w);
12493                 PIPE_CONF_CHECK_I(pipe_src_h);
12494
12495                 PIPE_CONF_CHECK_BOOL(pch_pfit.enabled);
12496                 if (current_config->pch_pfit.enabled) {
12497                         PIPE_CONF_CHECK_X(pch_pfit.pos);
12498                         PIPE_CONF_CHECK_X(pch_pfit.size);
12499                 }
12500
12501                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
12502                 PIPE_CONF_CHECK_CLOCK_FUZZY(pixel_rate);
12503
12504                 PIPE_CONF_CHECK_X(gamma_mode);
12505                 if (IS_CHERRYVIEW(dev_priv))
12506                         PIPE_CONF_CHECK_X(cgm_mode);
12507                 else
12508                         PIPE_CONF_CHECK_X(csc_mode);
12509                 PIPE_CONF_CHECK_BOOL(gamma_enable);
12510                 PIPE_CONF_CHECK_BOOL(csc_enable);
12511         }
12512
12513         PIPE_CONF_CHECK_BOOL(double_wide);
12514
12515         PIPE_CONF_CHECK_P(shared_dpll);
12516         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
12517         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
12518         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
12519         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
12520         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
12521         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
12522         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
12523         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
12524         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
12525         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr0);
12526         PIPE_CONF_CHECK_X(dpll_hw_state.ebb0);
12527         PIPE_CONF_CHECK_X(dpll_hw_state.ebb4);
12528         PIPE_CONF_CHECK_X(dpll_hw_state.pll0);
12529         PIPE_CONF_CHECK_X(dpll_hw_state.pll1);
12530         PIPE_CONF_CHECK_X(dpll_hw_state.pll2);
12531         PIPE_CONF_CHECK_X(dpll_hw_state.pll3);
12532         PIPE_CONF_CHECK_X(dpll_hw_state.pll6);
12533         PIPE_CONF_CHECK_X(dpll_hw_state.pll8);
12534         PIPE_CONF_CHECK_X(dpll_hw_state.pll9);
12535         PIPE_CONF_CHECK_X(dpll_hw_state.pll10);
12536         PIPE_CONF_CHECK_X(dpll_hw_state.pcsdw12);
12537         PIPE_CONF_CHECK_X(dpll_hw_state.mg_refclkin_ctl);
12538         PIPE_CONF_CHECK_X(dpll_hw_state.mg_clktop2_coreclkctl1);
12539         PIPE_CONF_CHECK_X(dpll_hw_state.mg_clktop2_hsclkctl);
12540         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_div0);
12541         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_div1);
12542         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_lf);
12543         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_frac_lock);
12544         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_ssc);
12545         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_bias);
12546         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_tdc_coldst_bias);
12547
12548         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
12549         PIPE_CONF_CHECK_X(dsi_pll.div);
12550
12551         if (IS_G4X(dev_priv) || INTEL_GEN(dev_priv) >= 5)
12552                 PIPE_CONF_CHECK_I(pipe_bpp);
12553
12554         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
12555         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
12556
12557         PIPE_CONF_CHECK_I(min_voltage_level);
12558
12559         PIPE_CONF_CHECK_X(infoframes.enable);
12560         PIPE_CONF_CHECK_X(infoframes.gcp);
12561         PIPE_CONF_CHECK_INFOFRAME(avi);
12562         PIPE_CONF_CHECK_INFOFRAME(spd);
12563         PIPE_CONF_CHECK_INFOFRAME(hdmi);
12564
12565 #undef PIPE_CONF_CHECK_X
12566 #undef PIPE_CONF_CHECK_I
12567 #undef PIPE_CONF_CHECK_BOOL
12568 #undef PIPE_CONF_CHECK_BOOL_INCOMPLETE
12569 #undef PIPE_CONF_CHECK_P
12570 #undef PIPE_CONF_CHECK_FLAGS
12571 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
12572 #undef PIPE_CONF_QUIRK
12573
12574         return ret;
12575 }
12576
12577 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
12578                                            const struct intel_crtc_state *pipe_config)
12579 {
12580         if (pipe_config->has_pch_encoder) {
12581                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
12582                                                             &pipe_config->fdi_m_n);
12583                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
12584
12585                 /*
12586                  * FDI already provided one idea for the dotclock.
12587                  * Yell if the encoder disagrees.
12588                  */
12589                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
12590                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
12591                      fdi_dotclock, dotclock);
12592         }
12593 }
12594
12595 static void verify_wm_state(struct drm_crtc *crtc,
12596                             struct drm_crtc_state *new_state)
12597 {
12598         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
12599         struct skl_hw_state {
12600                 struct skl_ddb_entry ddb_y[I915_MAX_PLANES];
12601                 struct skl_ddb_entry ddb_uv[I915_MAX_PLANES];
12602                 struct skl_ddb_allocation ddb;
12603                 struct skl_pipe_wm wm;
12604         } *hw;
12605         struct skl_ddb_allocation *sw_ddb;
12606         struct skl_pipe_wm *sw_wm;
12607         struct skl_ddb_entry *hw_ddb_entry, *sw_ddb_entry;
12608         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12609         const enum pipe pipe = intel_crtc->pipe;
12610         int plane, level, max_level = ilk_wm_max_level(dev_priv);
12611
12612         if (INTEL_GEN(dev_priv) < 9 || !new_state->active)
12613                 return;
12614
12615         hw = kzalloc(sizeof(*hw), GFP_KERNEL);
12616         if (!hw)
12617                 return;
12618
12619         skl_pipe_wm_get_hw_state(intel_crtc, &hw->wm);
12620         sw_wm = &to_intel_crtc_state(new_state)->wm.skl.optimal;
12621
12622         skl_pipe_ddb_get_hw_state(intel_crtc, hw->ddb_y, hw->ddb_uv);
12623
12624         skl_ddb_get_hw_state(dev_priv, &hw->ddb);
12625         sw_ddb = &dev_priv->wm.skl_hw.ddb;
12626
12627         if (INTEL_GEN(dev_priv) >= 11 &&
12628             hw->ddb.enabled_slices != sw_ddb->enabled_slices)
12629                 DRM_ERROR("mismatch in DBUF Slices (expected %u, got %u)\n",
12630                           sw_ddb->enabled_slices,
12631                           hw->ddb.enabled_slices);
12632
12633         /* planes */
12634         for_each_universal_plane(dev_priv, pipe, plane) {
12635                 struct skl_plane_wm *hw_plane_wm, *sw_plane_wm;
12636
12637                 hw_plane_wm = &hw->wm.planes[plane];
12638                 sw_plane_wm = &sw_wm->planes[plane];
12639
12640                 /* Watermarks */
12641                 for (level = 0; level <= max_level; level++) {
12642                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
12643                                                 &sw_plane_wm->wm[level]))
12644                                 continue;
12645
12646                         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",
12647                                   pipe_name(pipe), plane + 1, level,
12648                                   sw_plane_wm->wm[level].plane_en,
12649                                   sw_plane_wm->wm[level].plane_res_b,
12650                                   sw_plane_wm->wm[level].plane_res_l,
12651                                   hw_plane_wm->wm[level].plane_en,
12652                                   hw_plane_wm->wm[level].plane_res_b,
12653                                   hw_plane_wm->wm[level].plane_res_l);
12654                 }
12655
12656                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
12657                                          &sw_plane_wm->trans_wm)) {
12658                         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",
12659                                   pipe_name(pipe), plane + 1,
12660                                   sw_plane_wm->trans_wm.plane_en,
12661                                   sw_plane_wm->trans_wm.plane_res_b,
12662                                   sw_plane_wm->trans_wm.plane_res_l,
12663                                   hw_plane_wm->trans_wm.plane_en,
12664                                   hw_plane_wm->trans_wm.plane_res_b,
12665                                   hw_plane_wm->trans_wm.plane_res_l);
12666                 }
12667
12668                 /* DDB */
12669                 hw_ddb_entry = &hw->ddb_y[plane];
12670                 sw_ddb_entry = &to_intel_crtc_state(new_state)->wm.skl.plane_ddb_y[plane];
12671
12672                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
12673                         DRM_ERROR("mismatch in DDB state pipe %c plane %d (expected (%u,%u), found (%u,%u))\n",
12674                                   pipe_name(pipe), plane + 1,
12675                                   sw_ddb_entry->start, sw_ddb_entry->end,
12676                                   hw_ddb_entry->start, hw_ddb_entry->end);
12677                 }
12678         }
12679
12680         /*
12681          * cursor
12682          * If the cursor plane isn't active, we may not have updated it's ddb
12683          * allocation. In that case since the ddb allocation will be updated
12684          * once the plane becomes visible, we can skip this check
12685          */
12686         if (1) {
12687                 struct skl_plane_wm *hw_plane_wm, *sw_plane_wm;
12688
12689                 hw_plane_wm = &hw->wm.planes[PLANE_CURSOR];
12690                 sw_plane_wm = &sw_wm->planes[PLANE_CURSOR];
12691
12692                 /* Watermarks */
12693                 for (level = 0; level <= max_level; level++) {
12694                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
12695                                                 &sw_plane_wm->wm[level]))
12696                                 continue;
12697
12698                         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",
12699                                   pipe_name(pipe), level,
12700                                   sw_plane_wm->wm[level].plane_en,
12701                                   sw_plane_wm->wm[level].plane_res_b,
12702                                   sw_plane_wm->wm[level].plane_res_l,
12703                                   hw_plane_wm->wm[level].plane_en,
12704                                   hw_plane_wm->wm[level].plane_res_b,
12705                                   hw_plane_wm->wm[level].plane_res_l);
12706                 }
12707
12708                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
12709                                          &sw_plane_wm->trans_wm)) {
12710                         DRM_ERROR("mismatch in trans WM pipe %c cursor (expected e=%d b=%u l=%u, got e=%d b=%u l=%u)\n",
12711                                   pipe_name(pipe),
12712                                   sw_plane_wm->trans_wm.plane_en,
12713                                   sw_plane_wm->trans_wm.plane_res_b,
12714                                   sw_plane_wm->trans_wm.plane_res_l,
12715                                   hw_plane_wm->trans_wm.plane_en,
12716                                   hw_plane_wm->trans_wm.plane_res_b,
12717                                   hw_plane_wm->trans_wm.plane_res_l);
12718                 }
12719
12720                 /* DDB */
12721                 hw_ddb_entry = &hw->ddb_y[PLANE_CURSOR];
12722                 sw_ddb_entry = &to_intel_crtc_state(new_state)->wm.skl.plane_ddb_y[PLANE_CURSOR];
12723
12724                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
12725                         DRM_ERROR("mismatch in DDB state pipe %c cursor (expected (%u,%u), found (%u,%u))\n",
12726                                   pipe_name(pipe),
12727                                   sw_ddb_entry->start, sw_ddb_entry->end,
12728                                   hw_ddb_entry->start, hw_ddb_entry->end);
12729                 }
12730         }
12731
12732         kfree(hw);
12733 }
12734
12735 static void
12736 verify_connector_state(struct drm_device *dev,
12737                        struct drm_atomic_state *state,
12738                        struct drm_crtc *crtc)
12739 {
12740         struct drm_connector *connector;
12741         struct drm_connector_state *new_conn_state;
12742         int i;
12743
12744         for_each_new_connector_in_state(state, connector, new_conn_state, i) {
12745                 struct drm_encoder *encoder = connector->encoder;
12746                 struct drm_crtc_state *crtc_state = NULL;
12747
12748                 if (new_conn_state->crtc != crtc)
12749                         continue;
12750
12751                 if (crtc)
12752                         crtc_state = drm_atomic_get_new_crtc_state(state, new_conn_state->crtc);
12753
12754                 intel_connector_verify_state(crtc_state, new_conn_state);
12755
12756                 I915_STATE_WARN(new_conn_state->best_encoder != encoder,
12757                      "connector's atomic encoder doesn't match legacy encoder\n");
12758         }
12759 }
12760
12761 static void
12762 verify_encoder_state(struct drm_device *dev, struct drm_atomic_state *state)
12763 {
12764         struct intel_encoder *encoder;
12765         struct drm_connector *connector;
12766         struct drm_connector_state *old_conn_state, *new_conn_state;
12767         int i;
12768
12769         for_each_intel_encoder(dev, encoder) {
12770                 bool enabled = false, found = false;
12771                 enum pipe pipe;
12772
12773                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
12774                               encoder->base.base.id,
12775                               encoder->base.name);
12776
12777                 for_each_oldnew_connector_in_state(state, connector, old_conn_state,
12778                                                    new_conn_state, i) {
12779                         if (old_conn_state->best_encoder == &encoder->base)
12780                                 found = true;
12781
12782                         if (new_conn_state->best_encoder != &encoder->base)
12783                                 continue;
12784                         found = enabled = true;
12785
12786                         I915_STATE_WARN(new_conn_state->crtc !=
12787                                         encoder->base.crtc,
12788                              "connector's crtc doesn't match encoder crtc\n");
12789                 }
12790
12791                 if (!found)
12792                         continue;
12793
12794                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
12795                      "encoder's enabled state mismatch "
12796                      "(expected %i, found %i)\n",
12797                      !!encoder->base.crtc, enabled);
12798
12799                 if (!encoder->base.crtc) {
12800                         bool active;
12801
12802                         active = encoder->get_hw_state(encoder, &pipe);
12803                         I915_STATE_WARN(active,
12804                              "encoder detached but still enabled on pipe %c.\n",
12805                              pipe_name(pipe));
12806                 }
12807         }
12808 }
12809
12810 static void
12811 verify_crtc_state(struct drm_crtc *crtc,
12812                   struct drm_crtc_state *old_crtc_state,
12813                   struct drm_crtc_state *new_crtc_state)
12814 {
12815         struct drm_device *dev = crtc->dev;
12816         struct drm_i915_private *dev_priv = to_i915(dev);
12817         struct intel_encoder *encoder;
12818         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12819         struct intel_crtc_state *pipe_config, *sw_config;
12820         struct drm_atomic_state *old_state;
12821         bool active;
12822
12823         old_state = old_crtc_state->state;
12824         __drm_atomic_helper_crtc_destroy_state(old_crtc_state);
12825         pipe_config = to_intel_crtc_state(old_crtc_state);
12826         memset(pipe_config, 0, sizeof(*pipe_config));
12827         pipe_config->base.crtc = crtc;
12828         pipe_config->base.state = old_state;
12829
12830         DRM_DEBUG_KMS("[CRTC:%d:%s]\n", crtc->base.id, crtc->name);
12831
12832         active = dev_priv->display.get_pipe_config(intel_crtc, pipe_config);
12833
12834         /* we keep both pipes enabled on 830 */
12835         if (IS_I830(dev_priv))
12836                 active = new_crtc_state->active;
12837
12838         I915_STATE_WARN(new_crtc_state->active != active,
12839              "crtc active state doesn't match with hw state "
12840              "(expected %i, found %i)\n", new_crtc_state->active, active);
12841
12842         I915_STATE_WARN(intel_crtc->active != new_crtc_state->active,
12843              "transitional active state does not match atomic hw state "
12844              "(expected %i, found %i)\n", new_crtc_state->active, intel_crtc->active);
12845
12846         for_each_encoder_on_crtc(dev, crtc, encoder) {
12847                 enum pipe pipe;
12848
12849                 active = encoder->get_hw_state(encoder, &pipe);
12850                 I915_STATE_WARN(active != new_crtc_state->active,
12851                         "[ENCODER:%i] active %i with crtc active %i\n",
12852                         encoder->base.base.id, active, new_crtc_state->active);
12853
12854                 I915_STATE_WARN(active && intel_crtc->pipe != pipe,
12855                                 "Encoder connected to wrong pipe %c\n",
12856                                 pipe_name(pipe));
12857
12858                 if (active)
12859                         encoder->get_config(encoder, pipe_config);
12860         }
12861
12862         intel_crtc_compute_pixel_rate(pipe_config);
12863
12864         if (!new_crtc_state->active)
12865                 return;
12866
12867         intel_pipe_config_sanity_check(dev_priv, pipe_config);
12868
12869         sw_config = to_intel_crtc_state(new_crtc_state);
12870         if (!intel_pipe_config_compare(dev_priv, sw_config,
12871                                        pipe_config, false)) {
12872                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
12873                 intel_dump_pipe_config(intel_crtc, pipe_config,
12874                                        "[hw state]");
12875                 intel_dump_pipe_config(intel_crtc, sw_config,
12876                                        "[sw state]");
12877         }
12878 }
12879
12880 static void
12881 intel_verify_planes(struct intel_atomic_state *state)
12882 {
12883         struct intel_plane *plane;
12884         const struct intel_plane_state *plane_state;
12885         int i;
12886
12887         for_each_new_intel_plane_in_state(state, plane,
12888                                           plane_state, i)
12889                 assert_plane(plane, plane_state->slave ||
12890                              plane_state->base.visible);
12891 }
12892
12893 static void
12894 verify_single_dpll_state(struct drm_i915_private *dev_priv,
12895                          struct intel_shared_dpll *pll,
12896                          struct drm_crtc *crtc,
12897                          struct drm_crtc_state *new_state)
12898 {
12899         struct intel_dpll_hw_state dpll_hw_state;
12900         unsigned int crtc_mask;
12901         bool active;
12902
12903         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
12904
12905         DRM_DEBUG_KMS("%s\n", pll->info->name);
12906
12907         active = pll->info->funcs->get_hw_state(dev_priv, pll, &dpll_hw_state);
12908
12909         if (!(pll->info->flags & INTEL_DPLL_ALWAYS_ON)) {
12910                 I915_STATE_WARN(!pll->on && pll->active_mask,
12911                      "pll in active use but not on in sw tracking\n");
12912                 I915_STATE_WARN(pll->on && !pll->active_mask,
12913                      "pll is on but not used by any active crtc\n");
12914                 I915_STATE_WARN(pll->on != active,
12915                      "pll on state mismatch (expected %i, found %i)\n",
12916                      pll->on, active);
12917         }
12918
12919         if (!crtc) {
12920                 I915_STATE_WARN(pll->active_mask & ~pll->state.crtc_mask,
12921                                 "more active pll users than references: %x vs %x\n",
12922                                 pll->active_mask, pll->state.crtc_mask);
12923
12924                 return;
12925         }
12926
12927         crtc_mask = drm_crtc_mask(crtc);
12928
12929         if (new_state->active)
12930                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
12931                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
12932                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
12933         else
12934                 I915_STATE_WARN(pll->active_mask & crtc_mask,
12935                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
12936                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
12937
12938         I915_STATE_WARN(!(pll->state.crtc_mask & crtc_mask),
12939                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
12940                         crtc_mask, pll->state.crtc_mask);
12941
12942         I915_STATE_WARN(pll->on && memcmp(&pll->state.hw_state,
12943                                           &dpll_hw_state,
12944                                           sizeof(dpll_hw_state)),
12945                         "pll hw state mismatch\n");
12946 }
12947
12948 static void
12949 verify_shared_dpll_state(struct drm_device *dev, struct drm_crtc *crtc,
12950                          struct drm_crtc_state *old_crtc_state,
12951                          struct drm_crtc_state *new_crtc_state)
12952 {
12953         struct drm_i915_private *dev_priv = to_i915(dev);
12954         struct intel_crtc_state *old_state = to_intel_crtc_state(old_crtc_state);
12955         struct intel_crtc_state *new_state = to_intel_crtc_state(new_crtc_state);
12956
12957         if (new_state->shared_dpll)
12958                 verify_single_dpll_state(dev_priv, new_state->shared_dpll, crtc, new_crtc_state);
12959
12960         if (old_state->shared_dpll &&
12961             old_state->shared_dpll != new_state->shared_dpll) {
12962                 unsigned int crtc_mask = drm_crtc_mask(crtc);
12963                 struct intel_shared_dpll *pll = old_state->shared_dpll;
12964
12965                 I915_STATE_WARN(pll->active_mask & crtc_mask,
12966                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
12967                                 pipe_name(drm_crtc_index(crtc)));
12968                 I915_STATE_WARN(pll->state.crtc_mask & crtc_mask,
12969                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
12970                                 pipe_name(drm_crtc_index(crtc)));
12971         }
12972 }
12973
12974 static void
12975 intel_modeset_verify_crtc(struct drm_crtc *crtc,
12976                           struct drm_atomic_state *state,
12977                           struct drm_crtc_state *old_state,
12978                           struct drm_crtc_state *new_state)
12979 {
12980         if (!needs_modeset(new_state) &&
12981             !to_intel_crtc_state(new_state)->update_pipe)
12982                 return;
12983
12984         verify_wm_state(crtc, new_state);
12985         verify_connector_state(crtc->dev, state, crtc);
12986         verify_crtc_state(crtc, old_state, new_state);
12987         verify_shared_dpll_state(crtc->dev, crtc, old_state, new_state);
12988 }
12989
12990 static void
12991 verify_disabled_dpll_state(struct drm_device *dev)
12992 {
12993         struct drm_i915_private *dev_priv = to_i915(dev);
12994         int i;
12995
12996         for (i = 0; i < dev_priv->num_shared_dpll; i++)
12997                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
12998 }
12999
13000 static void
13001 intel_modeset_verify_disabled(struct drm_device *dev,
13002                               struct drm_atomic_state *state)
13003 {
13004         verify_encoder_state(dev, state);
13005         verify_connector_state(dev, state, NULL);
13006         verify_disabled_dpll_state(dev);
13007 }
13008
13009 static void update_scanline_offset(const struct intel_crtc_state *crtc_state)
13010 {
13011         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
13012         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13013
13014         /*
13015          * The scanline counter increments at the leading edge of hsync.
13016          *
13017          * On most platforms it starts counting from vtotal-1 on the
13018          * first active line. That means the scanline counter value is
13019          * always one less than what we would expect. Ie. just after
13020          * start of vblank, which also occurs at start of hsync (on the
13021          * last active line), the scanline counter will read vblank_start-1.
13022          *
13023          * On gen2 the scanline counter starts counting from 1 instead
13024          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
13025          * to keep the value positive), instead of adding one.
13026          *
13027          * On HSW+ the behaviour of the scanline counter depends on the output
13028          * type. For DP ports it behaves like most other platforms, but on HDMI
13029          * there's an extra 1 line difference. So we need to add two instead of
13030          * one to the value.
13031          *
13032          * On VLV/CHV DSI the scanline counter would appear to increment
13033          * approx. 1/3 of a scanline before start of vblank. Unfortunately
13034          * that means we can't tell whether we're in vblank or not while
13035          * we're on that particular line. We must still set scanline_offset
13036          * to 1 so that the vblank timestamps come out correct when we query
13037          * the scanline counter from within the vblank interrupt handler.
13038          * However if queried just before the start of vblank we'll get an
13039          * answer that's slightly in the future.
13040          */
13041         if (IS_GEN(dev_priv, 2)) {
13042                 const struct drm_display_mode *adjusted_mode = &crtc_state->base.adjusted_mode;
13043                 int vtotal;
13044
13045                 vtotal = adjusted_mode->crtc_vtotal;
13046                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
13047                         vtotal /= 2;
13048
13049                 crtc->scanline_offset = vtotal - 1;
13050         } else if (HAS_DDI(dev_priv) &&
13051                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI)) {
13052                 crtc->scanline_offset = 2;
13053         } else
13054                 crtc->scanline_offset = 1;
13055 }
13056
13057 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
13058 {
13059         struct drm_device *dev = state->dev;
13060         struct drm_i915_private *dev_priv = to_i915(dev);
13061         struct drm_crtc *crtc;
13062         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
13063         int i;
13064
13065         if (!dev_priv->display.crtc_compute_clock)
13066                 return;
13067
13068         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13069                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13070                 struct intel_shared_dpll *old_dpll =
13071                         to_intel_crtc_state(old_crtc_state)->shared_dpll;
13072
13073                 if (!needs_modeset(new_crtc_state))
13074                         continue;
13075
13076                 to_intel_crtc_state(new_crtc_state)->shared_dpll = NULL;
13077
13078                 if (!old_dpll)
13079                         continue;
13080
13081                 intel_release_shared_dpll(old_dpll, intel_crtc, state);
13082         }
13083 }
13084
13085 /*
13086  * This implements the workaround described in the "notes" section of the mode
13087  * set sequence documentation. When going from no pipes or single pipe to
13088  * multiple pipes, and planes are enabled after the pipe, we need to wait at
13089  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
13090  */
13091 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
13092 {
13093         struct drm_crtc_state *crtc_state;
13094         struct intel_crtc *intel_crtc;
13095         struct drm_crtc *crtc;
13096         struct intel_crtc_state *first_crtc_state = NULL;
13097         struct intel_crtc_state *other_crtc_state = NULL;
13098         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
13099         int i;
13100
13101         /* look at all crtc's that are going to be enabled in during modeset */
13102         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
13103                 intel_crtc = to_intel_crtc(crtc);
13104
13105                 if (!crtc_state->active || !needs_modeset(crtc_state))
13106                         continue;
13107
13108                 if (first_crtc_state) {
13109                         other_crtc_state = to_intel_crtc_state(crtc_state);
13110                         break;
13111                 } else {
13112                         first_crtc_state = to_intel_crtc_state(crtc_state);
13113                         first_pipe = intel_crtc->pipe;
13114                 }
13115         }
13116
13117         /* No workaround needed? */
13118         if (!first_crtc_state)
13119                 return 0;
13120
13121         /* w/a possibly needed, check how many crtc's are already enabled. */
13122         for_each_intel_crtc(state->dev, intel_crtc) {
13123                 struct intel_crtc_state *pipe_config;
13124
13125                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
13126                 if (IS_ERR(pipe_config))
13127                         return PTR_ERR(pipe_config);
13128
13129                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
13130
13131                 if (!pipe_config->base.active ||
13132                     needs_modeset(&pipe_config->base))
13133                         continue;
13134
13135                 /* 2 or more enabled crtcs means no need for w/a */
13136                 if (enabled_pipe != INVALID_PIPE)
13137                         return 0;
13138
13139                 enabled_pipe = intel_crtc->pipe;
13140         }
13141
13142         if (enabled_pipe != INVALID_PIPE)
13143                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
13144         else if (other_crtc_state)
13145                 other_crtc_state->hsw_workaround_pipe = first_pipe;
13146
13147         return 0;
13148 }
13149
13150 static int intel_lock_all_pipes(struct drm_atomic_state *state)
13151 {
13152         struct drm_crtc *crtc;
13153
13154         /* Add all pipes to the state */
13155         for_each_crtc(state->dev, crtc) {
13156                 struct drm_crtc_state *crtc_state;
13157
13158                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
13159                 if (IS_ERR(crtc_state))
13160                         return PTR_ERR(crtc_state);
13161         }
13162
13163         return 0;
13164 }
13165
13166 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
13167 {
13168         struct drm_crtc *crtc;
13169
13170         /*
13171          * Add all pipes to the state, and force
13172          * a modeset on all the active ones.
13173          */
13174         for_each_crtc(state->dev, crtc) {
13175                 struct drm_crtc_state *crtc_state;
13176                 int ret;
13177
13178                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
13179                 if (IS_ERR(crtc_state))
13180                         return PTR_ERR(crtc_state);
13181
13182                 if (!crtc_state->active || needs_modeset(crtc_state))
13183                         continue;
13184
13185                 crtc_state->mode_changed = true;
13186
13187                 ret = drm_atomic_add_affected_connectors(state, crtc);
13188                 if (ret)
13189                         return ret;
13190
13191                 ret = drm_atomic_add_affected_planes(state, crtc);
13192                 if (ret)
13193                         return ret;
13194         }
13195
13196         return 0;
13197 }
13198
13199 static int intel_modeset_checks(struct drm_atomic_state *state)
13200 {
13201         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13202         struct drm_i915_private *dev_priv = to_i915(state->dev);
13203         struct drm_crtc *crtc;
13204         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
13205         int ret = 0, i;
13206
13207         if (!check_digital_port_conflicts(state)) {
13208                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
13209                 return -EINVAL;
13210         }
13211
13212         /* keep the current setting */
13213         if (!intel_state->cdclk.force_min_cdclk_changed)
13214                 intel_state->cdclk.force_min_cdclk =
13215                         dev_priv->cdclk.force_min_cdclk;
13216
13217         intel_state->modeset = true;
13218         intel_state->active_crtcs = dev_priv->active_crtcs;
13219         intel_state->cdclk.logical = dev_priv->cdclk.logical;
13220         intel_state->cdclk.actual = dev_priv->cdclk.actual;
13221         intel_state->cdclk.pipe = INVALID_PIPE;
13222
13223         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13224                 if (new_crtc_state->active)
13225                         intel_state->active_crtcs |= 1 << i;
13226                 else
13227                         intel_state->active_crtcs &= ~(1 << i);
13228
13229                 if (old_crtc_state->active != new_crtc_state->active)
13230                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
13231         }
13232
13233         /*
13234          * See if the config requires any additional preparation, e.g.
13235          * to adjust global state with pipes off.  We need to do this
13236          * here so we can get the modeset_pipe updated config for the new
13237          * mode set on this crtc.  For other crtcs we need to use the
13238          * adjusted_mode bits in the crtc directly.
13239          */
13240         if (dev_priv->display.modeset_calc_cdclk) {
13241                 enum pipe pipe;
13242
13243                 ret = dev_priv->display.modeset_calc_cdclk(state);
13244                 if (ret < 0)
13245                         return ret;
13246
13247                 /*
13248                  * Writes to dev_priv->cdclk.logical must protected by
13249                  * holding all the crtc locks, even if we don't end up
13250                  * touching the hardware
13251                  */
13252                 if (intel_cdclk_changed(&dev_priv->cdclk.logical,
13253                                         &intel_state->cdclk.logical)) {
13254                         ret = intel_lock_all_pipes(state);
13255                         if (ret < 0)
13256                                 return ret;
13257                 }
13258
13259                 if (is_power_of_2(intel_state->active_crtcs)) {
13260                         struct drm_crtc *crtc;
13261                         struct drm_crtc_state *crtc_state;
13262
13263                         pipe = ilog2(intel_state->active_crtcs);
13264                         crtc = &intel_get_crtc_for_pipe(dev_priv, pipe)->base;
13265                         crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
13266                         if (crtc_state && needs_modeset(crtc_state))
13267                                 pipe = INVALID_PIPE;
13268                 } else {
13269                         pipe = INVALID_PIPE;
13270                 }
13271
13272                 /* All pipes must be switched off while we change the cdclk. */
13273                 if (pipe != INVALID_PIPE &&
13274                     intel_cdclk_needs_cd2x_update(dev_priv,
13275                                                   &dev_priv->cdclk.actual,
13276                                                   &intel_state->cdclk.actual)) {
13277                         ret = intel_lock_all_pipes(state);
13278                         if (ret < 0)
13279                                 return ret;
13280
13281                         intel_state->cdclk.pipe = pipe;
13282                 } else if (intel_cdclk_needs_modeset(&dev_priv->cdclk.actual,
13283                                                      &intel_state->cdclk.actual)) {
13284                         ret = intel_modeset_all_pipes(state);
13285                         if (ret < 0)
13286                                 return ret;
13287
13288                         intel_state->cdclk.pipe = INVALID_PIPE;
13289                 }
13290
13291                 DRM_DEBUG_KMS("New cdclk calculated to be logical %u kHz, actual %u kHz\n",
13292                               intel_state->cdclk.logical.cdclk,
13293                               intel_state->cdclk.actual.cdclk);
13294                 DRM_DEBUG_KMS("New voltage level calculated to be logical %u, actual %u\n",
13295                               intel_state->cdclk.logical.voltage_level,
13296                               intel_state->cdclk.actual.voltage_level);
13297         }
13298
13299         intel_modeset_clear_plls(state);
13300
13301         if (IS_HASWELL(dev_priv))
13302                 return haswell_mode_set_planes_workaround(state);
13303
13304         return 0;
13305 }
13306
13307 /*
13308  * Handle calculation of various watermark data at the end of the atomic check
13309  * phase.  The code here should be run after the per-crtc and per-plane 'check'
13310  * handlers to ensure that all derived state has been updated.
13311  */
13312 static int calc_watermark_data(struct intel_atomic_state *state)
13313 {
13314         struct drm_device *dev = state->base.dev;
13315         struct drm_i915_private *dev_priv = to_i915(dev);
13316
13317         /* Is there platform-specific watermark information to calculate? */
13318         if (dev_priv->display.compute_global_watermarks)
13319                 return dev_priv->display.compute_global_watermarks(state);
13320
13321         return 0;
13322 }
13323
13324 /**
13325  * intel_atomic_check - validate state object
13326  * @dev: drm device
13327  * @state: state to validate
13328  */
13329 static int intel_atomic_check(struct drm_device *dev,
13330                               struct drm_atomic_state *state)
13331 {
13332         struct drm_i915_private *dev_priv = to_i915(dev);
13333         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13334         struct drm_crtc *crtc;
13335         struct drm_crtc_state *old_crtc_state, *crtc_state;
13336         int ret, i;
13337         bool any_ms = intel_state->cdclk.force_min_cdclk_changed;
13338
13339         /* Catch I915_MODE_FLAG_INHERITED */
13340         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
13341                                       crtc_state, i) {
13342                 if (crtc_state->mode.private_flags !=
13343                     old_crtc_state->mode.private_flags)
13344                         crtc_state->mode_changed = true;
13345         }
13346
13347         ret = drm_atomic_helper_check_modeset(dev, state);
13348         if (ret)
13349                 return ret;
13350
13351         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, crtc_state, i) {
13352                 struct intel_crtc_state *pipe_config =
13353                         to_intel_crtc_state(crtc_state);
13354
13355                 if (!needs_modeset(crtc_state))
13356                         continue;
13357
13358                 if (!crtc_state->enable) {
13359                         any_ms = true;
13360                         continue;
13361                 }
13362
13363                 ret = intel_modeset_pipe_config(crtc, pipe_config);
13364                 if (ret == -EDEADLK)
13365                         return ret;
13366                 if (ret) {
13367                         intel_dump_pipe_config(to_intel_crtc(crtc),
13368                                                pipe_config, "[failed]");
13369                         return ret;
13370                 }
13371
13372                 if (intel_pipe_config_compare(dev_priv,
13373                                         to_intel_crtc_state(old_crtc_state),
13374                                         pipe_config, true)) {
13375                         crtc_state->mode_changed = false;
13376                         pipe_config->update_pipe = true;
13377                 }
13378
13379                 if (needs_modeset(crtc_state))
13380                         any_ms = true;
13381
13382                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
13383                                        needs_modeset(crtc_state) ?
13384                                        "[modeset]" : "[fastset]");
13385         }
13386
13387         ret = drm_dp_mst_atomic_check(state);
13388         if (ret)
13389                 return ret;
13390
13391         if (any_ms) {
13392                 ret = intel_modeset_checks(state);
13393
13394                 if (ret)
13395                         return ret;
13396         } else {
13397                 intel_state->cdclk.logical = dev_priv->cdclk.logical;
13398         }
13399
13400         ret = icl_add_linked_planes(intel_state);
13401         if (ret)
13402                 return ret;
13403
13404         ret = drm_atomic_helper_check_planes(dev, state);
13405         if (ret)
13406                 return ret;
13407
13408         intel_fbc_choose_crtc(dev_priv, intel_state);
13409         return calc_watermark_data(intel_state);
13410 }
13411
13412 static int intel_atomic_prepare_commit(struct drm_device *dev,
13413                                        struct drm_atomic_state *state)
13414 {
13415         return drm_atomic_helper_prepare_planes(dev, state);
13416 }
13417
13418 u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc)
13419 {
13420         struct drm_device *dev = crtc->base.dev;
13421         struct drm_vblank_crtc *vblank = &dev->vblank[drm_crtc_index(&crtc->base)];
13422
13423         if (!vblank->max_vblank_count)
13424                 return (u32)drm_crtc_accurate_vblank_count(&crtc->base);
13425
13426         return dev->driver->get_vblank_counter(dev, crtc->pipe);
13427 }
13428
13429 static void intel_update_crtc(struct drm_crtc *crtc,
13430                               struct drm_atomic_state *state,
13431                               struct drm_crtc_state *old_crtc_state,
13432                               struct drm_crtc_state *new_crtc_state)
13433 {
13434         struct drm_device *dev = crtc->dev;
13435         struct drm_i915_private *dev_priv = to_i915(dev);
13436         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13437         struct intel_crtc_state *pipe_config = to_intel_crtc_state(new_crtc_state);
13438         bool modeset = needs_modeset(new_crtc_state);
13439         struct intel_plane_state *new_plane_state =
13440                 intel_atomic_get_new_plane_state(to_intel_atomic_state(state),
13441                                                  to_intel_plane(crtc->primary));
13442
13443         if (modeset) {
13444                 update_scanline_offset(pipe_config);
13445                 dev_priv->display.crtc_enable(pipe_config, state);
13446
13447                 /* vblanks work again, re-enable pipe CRC. */
13448                 intel_crtc_enable_pipe_crc(intel_crtc);
13449         } else {
13450                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
13451                                        pipe_config);
13452
13453                 if (pipe_config->update_pipe)
13454                         intel_encoders_update_pipe(crtc, pipe_config, state);
13455         }
13456
13457         if (pipe_config->update_pipe && !pipe_config->enable_fbc)
13458                 intel_fbc_disable(intel_crtc);
13459         else if (new_plane_state)
13460                 intel_fbc_enable(intel_crtc, pipe_config, new_plane_state);
13461
13462         intel_begin_crtc_commit(to_intel_atomic_state(state), intel_crtc);
13463
13464         if (INTEL_GEN(dev_priv) >= 9)
13465                 skl_update_planes_on_crtc(to_intel_atomic_state(state), intel_crtc);
13466         else
13467                 i9xx_update_planes_on_crtc(to_intel_atomic_state(state), intel_crtc);
13468
13469         intel_finish_crtc_commit(to_intel_atomic_state(state), intel_crtc);
13470 }
13471
13472 static void intel_update_crtcs(struct drm_atomic_state *state)
13473 {
13474         struct drm_crtc *crtc;
13475         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
13476         int i;
13477
13478         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13479                 if (!new_crtc_state->active)
13480                         continue;
13481
13482                 intel_update_crtc(crtc, state, old_crtc_state,
13483                                   new_crtc_state);
13484         }
13485 }
13486
13487 static void skl_update_crtcs(struct drm_atomic_state *state)
13488 {
13489         struct drm_i915_private *dev_priv = to_i915(state->dev);
13490         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13491         struct drm_crtc *crtc;
13492         struct intel_crtc *intel_crtc;
13493         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
13494         struct intel_crtc_state *cstate;
13495         unsigned int updated = 0;
13496         bool progress;
13497         enum pipe pipe;
13498         int i;
13499         u8 hw_enabled_slices = dev_priv->wm.skl_hw.ddb.enabled_slices;
13500         u8 required_slices = intel_state->wm_results.ddb.enabled_slices;
13501         struct skl_ddb_entry entries[I915_MAX_PIPES] = {};
13502
13503         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i)
13504                 /* ignore allocations for crtc's that have been turned off. */
13505                 if (new_crtc_state->active)
13506                         entries[i] = to_intel_crtc_state(old_crtc_state)->wm.skl.ddb;
13507
13508         /* If 2nd DBuf slice required, enable it here */
13509         if (INTEL_GEN(dev_priv) >= 11 && required_slices > hw_enabled_slices)
13510                 icl_dbuf_slices_update(dev_priv, required_slices);
13511
13512         /*
13513          * Whenever the number of active pipes changes, we need to make sure we
13514          * update the pipes in the right order so that their ddb allocations
13515          * never overlap with eachother inbetween CRTC updates. Otherwise we'll
13516          * cause pipe underruns and other bad stuff.
13517          */
13518         do {
13519                 progress = false;
13520
13521                 for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13522                         bool vbl_wait = false;
13523                         unsigned int cmask = drm_crtc_mask(crtc);
13524
13525                         intel_crtc = to_intel_crtc(crtc);
13526                         cstate = to_intel_crtc_state(new_crtc_state);
13527                         pipe = intel_crtc->pipe;
13528
13529                         if (updated & cmask || !cstate->base.active)
13530                                 continue;
13531
13532                         if (skl_ddb_allocation_overlaps(&cstate->wm.skl.ddb,
13533                                                         entries,
13534                                                         INTEL_INFO(dev_priv)->num_pipes, i))
13535                                 continue;
13536
13537                         updated |= cmask;
13538                         entries[i] = cstate->wm.skl.ddb;
13539
13540                         /*
13541                          * If this is an already active pipe, it's DDB changed,
13542                          * and this isn't the last pipe that needs updating
13543                          * then we need to wait for a vblank to pass for the
13544                          * new ddb allocation to take effect.
13545                          */
13546                         if (!skl_ddb_entry_equal(&cstate->wm.skl.ddb,
13547                                                  &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb) &&
13548                             !new_crtc_state->active_changed &&
13549                             intel_state->wm_results.dirty_pipes != updated)
13550                                 vbl_wait = true;
13551
13552                         intel_update_crtc(crtc, state, old_crtc_state,
13553                                           new_crtc_state);
13554
13555                         if (vbl_wait)
13556                                 intel_wait_for_vblank(dev_priv, pipe);
13557
13558                         progress = true;
13559                 }
13560         } while (progress);
13561
13562         /* If 2nd DBuf slice is no more required disable it */
13563         if (INTEL_GEN(dev_priv) >= 11 && required_slices < hw_enabled_slices)
13564                 icl_dbuf_slices_update(dev_priv, required_slices);
13565 }
13566
13567 static void intel_atomic_helper_free_state(struct drm_i915_private *dev_priv)
13568 {
13569         struct intel_atomic_state *state, *next;
13570         struct llist_node *freed;
13571
13572         freed = llist_del_all(&dev_priv->atomic_helper.free_list);
13573         llist_for_each_entry_safe(state, next, freed, freed)
13574                 drm_atomic_state_put(&state->base);
13575 }
13576
13577 static void intel_atomic_helper_free_state_worker(struct work_struct *work)
13578 {
13579         struct drm_i915_private *dev_priv =
13580                 container_of(work, typeof(*dev_priv), atomic_helper.free_work);
13581
13582         intel_atomic_helper_free_state(dev_priv);
13583 }
13584
13585 static void intel_atomic_commit_fence_wait(struct intel_atomic_state *intel_state)
13586 {
13587         struct wait_queue_entry wait_fence, wait_reset;
13588         struct drm_i915_private *dev_priv = to_i915(intel_state->base.dev);
13589
13590         init_wait_entry(&wait_fence, 0);
13591         init_wait_entry(&wait_reset, 0);
13592         for (;;) {
13593                 prepare_to_wait(&intel_state->commit_ready.wait,
13594                                 &wait_fence, TASK_UNINTERRUPTIBLE);
13595                 prepare_to_wait(&dev_priv->gpu_error.wait_queue,
13596                                 &wait_reset, TASK_UNINTERRUPTIBLE);
13597
13598
13599                 if (i915_sw_fence_done(&intel_state->commit_ready)
13600                     || test_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags))
13601                         break;
13602
13603                 schedule();
13604         }
13605         finish_wait(&intel_state->commit_ready.wait, &wait_fence);
13606         finish_wait(&dev_priv->gpu_error.wait_queue, &wait_reset);
13607 }
13608
13609 static void intel_atomic_cleanup_work(struct work_struct *work)
13610 {
13611         struct drm_atomic_state *state =
13612                 container_of(work, struct drm_atomic_state, commit_work);
13613         struct drm_i915_private *i915 = to_i915(state->dev);
13614
13615         drm_atomic_helper_cleanup_planes(&i915->drm, state);
13616         drm_atomic_helper_commit_cleanup_done(state);
13617         drm_atomic_state_put(state);
13618
13619         intel_atomic_helper_free_state(i915);
13620 }
13621
13622 static void intel_atomic_commit_tail(struct drm_atomic_state *state)
13623 {
13624         struct drm_device *dev = state->dev;
13625         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13626         struct drm_i915_private *dev_priv = to_i915(dev);
13627         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
13628         struct intel_crtc_state *new_intel_crtc_state, *old_intel_crtc_state;
13629         struct drm_crtc *crtc;
13630         struct intel_crtc *intel_crtc;
13631         u64 put_domains[I915_MAX_PIPES] = {};
13632         intel_wakeref_t wakeref = 0;
13633         int i;
13634
13635         intel_atomic_commit_fence_wait(intel_state);
13636
13637         drm_atomic_helper_wait_for_dependencies(state);
13638
13639         if (intel_state->modeset)
13640                 wakeref = intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
13641
13642         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13643                 old_intel_crtc_state = to_intel_crtc_state(old_crtc_state);
13644                 new_intel_crtc_state = to_intel_crtc_state(new_crtc_state);
13645                 intel_crtc = to_intel_crtc(crtc);
13646
13647                 if (needs_modeset(new_crtc_state) ||
13648                     to_intel_crtc_state(new_crtc_state)->update_pipe) {
13649
13650                         put_domains[intel_crtc->pipe] =
13651                                 modeset_get_crtc_power_domains(crtc,
13652                                         new_intel_crtc_state);
13653                 }
13654
13655                 if (!needs_modeset(new_crtc_state))
13656                         continue;
13657
13658                 intel_pre_plane_update(old_intel_crtc_state, new_intel_crtc_state);
13659
13660                 if (old_crtc_state->active) {
13661                         intel_crtc_disable_planes(intel_state, intel_crtc);
13662
13663                         /*
13664                          * We need to disable pipe CRC before disabling the pipe,
13665                          * or we race against vblank off.
13666                          */
13667                         intel_crtc_disable_pipe_crc(intel_crtc);
13668
13669                         dev_priv->display.crtc_disable(old_intel_crtc_state, state);
13670                         intel_crtc->active = false;
13671                         intel_fbc_disable(intel_crtc);
13672                         intel_disable_shared_dpll(old_intel_crtc_state);
13673
13674                         /*
13675                          * Underruns don't always raise
13676                          * interrupts, so check manually.
13677                          */
13678                         intel_check_cpu_fifo_underruns(dev_priv);
13679                         intel_check_pch_fifo_underruns(dev_priv);
13680
13681                         /* FIXME unify this for all platforms */
13682                         if (!new_crtc_state->active &&
13683                             !HAS_GMCH(dev_priv) &&
13684                             dev_priv->display.initial_watermarks)
13685                                 dev_priv->display.initial_watermarks(intel_state,
13686                                                                      new_intel_crtc_state);
13687                 }
13688         }
13689
13690         /* FIXME: Eventually get rid of our intel_crtc->config pointer */
13691         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i)
13692                 to_intel_crtc(crtc)->config = to_intel_crtc_state(new_crtc_state);
13693
13694         if (intel_state->modeset) {
13695                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
13696
13697                 intel_set_cdclk_pre_plane_update(dev_priv,
13698                                                  &intel_state->cdclk.actual,
13699                                                  &dev_priv->cdclk.actual,
13700                                                  intel_state->cdclk.pipe);
13701
13702                 /*
13703                  * SKL workaround: bspec recommends we disable the SAGV when we
13704                  * have more then one pipe enabled
13705                  */
13706                 if (!intel_can_enable_sagv(state))
13707                         intel_disable_sagv(dev_priv);
13708
13709                 intel_modeset_verify_disabled(dev, state);
13710         }
13711
13712         /* Complete the events for pipes that have now been disabled */
13713         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13714                 bool modeset = needs_modeset(new_crtc_state);
13715
13716                 /* Complete events for now disable pipes here. */
13717                 if (modeset && !new_crtc_state->active && new_crtc_state->event) {
13718                         spin_lock_irq(&dev->event_lock);
13719                         drm_crtc_send_vblank_event(crtc, new_crtc_state->event);
13720                         spin_unlock_irq(&dev->event_lock);
13721
13722                         new_crtc_state->event = NULL;
13723                 }
13724         }
13725
13726         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
13727         dev_priv->display.update_crtcs(state);
13728
13729         if (intel_state->modeset)
13730                 intel_set_cdclk_post_plane_update(dev_priv,
13731                                                   &intel_state->cdclk.actual,
13732                                                   &dev_priv->cdclk.actual,
13733                                                   intel_state->cdclk.pipe);
13734
13735         /* FIXME: We should call drm_atomic_helper_commit_hw_done() here
13736          * already, but still need the state for the delayed optimization. To
13737          * fix this:
13738          * - wrap the optimization/post_plane_update stuff into a per-crtc work.
13739          * - schedule that vblank worker _before_ calling hw_done
13740          * - at the start of commit_tail, cancel it _synchrously
13741          * - switch over to the vblank wait helper in the core after that since
13742          *   we don't need out special handling any more.
13743          */
13744         drm_atomic_helper_wait_for_flip_done(dev, state);
13745
13746         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13747                 new_intel_crtc_state = to_intel_crtc_state(new_crtc_state);
13748
13749                 if (new_crtc_state->active &&
13750                     !needs_modeset(new_crtc_state) &&
13751                     (new_intel_crtc_state->base.color_mgmt_changed ||
13752                      new_intel_crtc_state->update_pipe))
13753                         intel_color_load_luts(new_intel_crtc_state);
13754         }
13755
13756         /*
13757          * Now that the vblank has passed, we can go ahead and program the
13758          * optimal watermarks on platforms that need two-step watermark
13759          * programming.
13760          *
13761          * TODO: Move this (and other cleanup) to an async worker eventually.
13762          */
13763         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13764                 new_intel_crtc_state = to_intel_crtc_state(new_crtc_state);
13765
13766                 if (dev_priv->display.optimize_watermarks)
13767                         dev_priv->display.optimize_watermarks(intel_state,
13768                                                               new_intel_crtc_state);
13769         }
13770
13771         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13772                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
13773
13774                 if (put_domains[i])
13775                         modeset_put_power_domains(dev_priv, put_domains[i]);
13776
13777                 intel_modeset_verify_crtc(crtc, state, old_crtc_state, new_crtc_state);
13778         }
13779
13780         if (intel_state->modeset)
13781                 intel_verify_planes(intel_state);
13782
13783         if (intel_state->modeset && intel_can_enable_sagv(state))
13784                 intel_enable_sagv(dev_priv);
13785
13786         drm_atomic_helper_commit_hw_done(state);
13787
13788         if (intel_state->modeset) {
13789                 /* As one of the primary mmio accessors, KMS has a high
13790                  * likelihood of triggering bugs in unclaimed access. After we
13791                  * finish modesetting, see if an error has been flagged, and if
13792                  * so enable debugging for the next modeset - and hope we catch
13793                  * the culprit.
13794                  */
13795                 intel_uncore_arm_unclaimed_mmio_detection(&dev_priv->uncore);
13796                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET, wakeref);
13797         }
13798
13799         /*
13800          * Defer the cleanup of the old state to a separate worker to not
13801          * impede the current task (userspace for blocking modesets) that
13802          * are executed inline. For out-of-line asynchronous modesets/flips,
13803          * deferring to a new worker seems overkill, but we would place a
13804          * schedule point (cond_resched()) here anyway to keep latencies
13805          * down.
13806          */
13807         INIT_WORK(&state->commit_work, intel_atomic_cleanup_work);
13808         queue_work(system_highpri_wq, &state->commit_work);
13809 }
13810
13811 static void intel_atomic_commit_work(struct work_struct *work)
13812 {
13813         struct drm_atomic_state *state =
13814                 container_of(work, struct drm_atomic_state, commit_work);
13815
13816         intel_atomic_commit_tail(state);
13817 }
13818
13819 static int __i915_sw_fence_call
13820 intel_atomic_commit_ready(struct i915_sw_fence *fence,
13821                           enum i915_sw_fence_notify notify)
13822 {
13823         struct intel_atomic_state *state =
13824                 container_of(fence, struct intel_atomic_state, commit_ready);
13825
13826         switch (notify) {
13827         case FENCE_COMPLETE:
13828                 /* we do blocking waits in the worker, nothing to do here */
13829                 break;
13830         case FENCE_FREE:
13831                 {
13832                         struct intel_atomic_helper *helper =
13833                                 &to_i915(state->base.dev)->atomic_helper;
13834
13835                         if (llist_add(&state->freed, &helper->free_list))
13836                                 schedule_work(&helper->free_work);
13837                         break;
13838                 }
13839         }
13840
13841         return NOTIFY_DONE;
13842 }
13843
13844 static void intel_atomic_track_fbs(struct drm_atomic_state *state)
13845 {
13846         struct drm_plane_state *old_plane_state, *new_plane_state;
13847         struct drm_plane *plane;
13848         int i;
13849
13850         for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i)
13851                 i915_gem_track_fb(intel_fb_obj(old_plane_state->fb),
13852                                   intel_fb_obj(new_plane_state->fb),
13853                                   to_intel_plane(plane)->frontbuffer_bit);
13854 }
13855
13856 /**
13857  * intel_atomic_commit - commit validated state object
13858  * @dev: DRM device
13859  * @state: the top-level driver state object
13860  * @nonblock: nonblocking commit
13861  *
13862  * This function commits a top-level state object that has been validated
13863  * with drm_atomic_helper_check().
13864  *
13865  * RETURNS
13866  * Zero for success or -errno.
13867  */
13868 static int intel_atomic_commit(struct drm_device *dev,
13869                                struct drm_atomic_state *state,
13870                                bool nonblock)
13871 {
13872         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13873         struct drm_i915_private *dev_priv = to_i915(dev);
13874         int ret = 0;
13875
13876         drm_atomic_state_get(state);
13877         i915_sw_fence_init(&intel_state->commit_ready,
13878                            intel_atomic_commit_ready);
13879
13880         /*
13881          * The intel_legacy_cursor_update() fast path takes care
13882          * of avoiding the vblank waits for simple cursor
13883          * movement and flips. For cursor on/off and size changes,
13884          * we want to perform the vblank waits so that watermark
13885          * updates happen during the correct frames. Gen9+ have
13886          * double buffered watermarks and so shouldn't need this.
13887          *
13888          * Unset state->legacy_cursor_update before the call to
13889          * drm_atomic_helper_setup_commit() because otherwise
13890          * drm_atomic_helper_wait_for_flip_done() is a noop and
13891          * we get FIFO underruns because we didn't wait
13892          * for vblank.
13893          *
13894          * FIXME doing watermarks and fb cleanup from a vblank worker
13895          * (assuming we had any) would solve these problems.
13896          */
13897         if (INTEL_GEN(dev_priv) < 9 && state->legacy_cursor_update) {
13898                 struct intel_crtc_state *new_crtc_state;
13899                 struct intel_crtc *crtc;
13900                 int i;
13901
13902                 for_each_new_intel_crtc_in_state(intel_state, crtc, new_crtc_state, i)
13903                         if (new_crtc_state->wm.need_postvbl_update ||
13904                             new_crtc_state->update_wm_post)
13905                                 state->legacy_cursor_update = false;
13906         }
13907
13908         ret = intel_atomic_prepare_commit(dev, state);
13909         if (ret) {
13910                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
13911                 i915_sw_fence_commit(&intel_state->commit_ready);
13912                 return ret;
13913         }
13914
13915         ret = drm_atomic_helper_setup_commit(state, nonblock);
13916         if (!ret)
13917                 ret = drm_atomic_helper_swap_state(state, true);
13918
13919         if (ret) {
13920                 i915_sw_fence_commit(&intel_state->commit_ready);
13921
13922                 drm_atomic_helper_cleanup_planes(dev, state);
13923                 return ret;
13924         }
13925         dev_priv->wm.distrust_bios_wm = false;
13926         intel_shared_dpll_swap_state(state);
13927         intel_atomic_track_fbs(state);
13928
13929         if (intel_state->modeset) {
13930                 memcpy(dev_priv->min_cdclk, intel_state->min_cdclk,
13931                        sizeof(intel_state->min_cdclk));
13932                 memcpy(dev_priv->min_voltage_level,
13933                        intel_state->min_voltage_level,
13934                        sizeof(intel_state->min_voltage_level));
13935                 dev_priv->active_crtcs = intel_state->active_crtcs;
13936                 dev_priv->cdclk.force_min_cdclk =
13937                         intel_state->cdclk.force_min_cdclk;
13938
13939                 intel_cdclk_swap_state(intel_state);
13940         }
13941
13942         drm_atomic_state_get(state);
13943         INIT_WORK(&state->commit_work, intel_atomic_commit_work);
13944
13945         i915_sw_fence_commit(&intel_state->commit_ready);
13946         if (nonblock && intel_state->modeset) {
13947                 queue_work(dev_priv->modeset_wq, &state->commit_work);
13948         } else if (nonblock) {
13949                 queue_work(system_unbound_wq, &state->commit_work);
13950         } else {
13951                 if (intel_state->modeset)
13952                         flush_workqueue(dev_priv->modeset_wq);
13953                 intel_atomic_commit_tail(state);
13954         }
13955
13956         return 0;
13957 }
13958
13959 static const struct drm_crtc_funcs intel_crtc_funcs = {
13960         .gamma_set = drm_atomic_helper_legacy_gamma_set,
13961         .set_config = drm_atomic_helper_set_config,
13962         .destroy = intel_crtc_destroy,
13963         .page_flip = drm_atomic_helper_page_flip,
13964         .atomic_duplicate_state = intel_crtc_duplicate_state,
13965         .atomic_destroy_state = intel_crtc_destroy_state,
13966         .set_crc_source = intel_crtc_set_crc_source,
13967         .verify_crc_source = intel_crtc_verify_crc_source,
13968         .get_crc_sources = intel_crtc_get_crc_sources,
13969 };
13970
13971 struct wait_rps_boost {
13972         struct wait_queue_entry wait;
13973
13974         struct drm_crtc *crtc;
13975         struct i915_request *request;
13976 };
13977
13978 static int do_rps_boost(struct wait_queue_entry *_wait,
13979                         unsigned mode, int sync, void *key)
13980 {
13981         struct wait_rps_boost *wait = container_of(_wait, typeof(*wait), wait);
13982         struct i915_request *rq = wait->request;
13983
13984         /*
13985          * If we missed the vblank, but the request is already running it
13986          * is reasonable to assume that it will complete before the next
13987          * vblank without our intervention, so leave RPS alone.
13988          */
13989         if (!i915_request_started(rq))
13990                 gen6_rps_boost(rq);
13991         i915_request_put(rq);
13992
13993         drm_crtc_vblank_put(wait->crtc);
13994
13995         list_del(&wait->wait.entry);
13996         kfree(wait);
13997         return 1;
13998 }
13999
14000 static void add_rps_boost_after_vblank(struct drm_crtc *crtc,
14001                                        struct dma_fence *fence)
14002 {
14003         struct wait_rps_boost *wait;
14004
14005         if (!dma_fence_is_i915(fence))
14006                 return;
14007
14008         if (INTEL_GEN(to_i915(crtc->dev)) < 6)
14009                 return;
14010
14011         if (drm_crtc_vblank_get(crtc))
14012                 return;
14013
14014         wait = kmalloc(sizeof(*wait), GFP_KERNEL);
14015         if (!wait) {
14016                 drm_crtc_vblank_put(crtc);
14017                 return;
14018         }
14019
14020         wait->request = to_request(dma_fence_get(fence));
14021         wait->crtc = crtc;
14022
14023         wait->wait.func = do_rps_boost;
14024         wait->wait.flags = 0;
14025
14026         add_wait_queue(drm_crtc_vblank_waitqueue(crtc), &wait->wait);
14027 }
14028
14029 static int intel_plane_pin_fb(struct intel_plane_state *plane_state)
14030 {
14031         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
14032         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
14033         struct drm_framebuffer *fb = plane_state->base.fb;
14034         struct i915_vma *vma;
14035
14036         if (plane->id == PLANE_CURSOR &&
14037             INTEL_INFO(dev_priv)->display.cursor_needs_physical) {
14038                 struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14039                 const int align = intel_cursor_alignment(dev_priv);
14040                 int err;
14041
14042                 err = i915_gem_object_attach_phys(obj, align);
14043                 if (err)
14044                         return err;
14045         }
14046
14047         vma = intel_pin_and_fence_fb_obj(fb,
14048                                          &plane_state->view,
14049                                          intel_plane_uses_fence(plane_state),
14050                                          &plane_state->flags);
14051         if (IS_ERR(vma))
14052                 return PTR_ERR(vma);
14053
14054         plane_state->vma = vma;
14055
14056         return 0;
14057 }
14058
14059 static void intel_plane_unpin_fb(struct intel_plane_state *old_plane_state)
14060 {
14061         struct i915_vma *vma;
14062
14063         vma = fetch_and_zero(&old_plane_state->vma);
14064         if (vma)
14065                 intel_unpin_fb_vma(vma, old_plane_state->flags);
14066 }
14067
14068 static void fb_obj_bump_render_priority(struct drm_i915_gem_object *obj)
14069 {
14070         struct i915_sched_attr attr = {
14071                 .priority = I915_PRIORITY_DISPLAY,
14072         };
14073
14074         i915_gem_object_wait_priority(obj, 0, &attr);
14075 }
14076
14077 /**
14078  * intel_prepare_plane_fb - Prepare fb for usage on plane
14079  * @plane: drm plane to prepare for
14080  * @new_state: the plane state being prepared
14081  *
14082  * Prepares a framebuffer for usage on a display plane.  Generally this
14083  * involves pinning the underlying object and updating the frontbuffer tracking
14084  * bits.  Some older platforms need special physical address handling for
14085  * cursor planes.
14086  *
14087  * Must be called with struct_mutex held.
14088  *
14089  * Returns 0 on success, negative error code on failure.
14090  */
14091 int
14092 intel_prepare_plane_fb(struct drm_plane *plane,
14093                        struct drm_plane_state *new_state)
14094 {
14095         struct intel_atomic_state *intel_state =
14096                 to_intel_atomic_state(new_state->state);
14097         struct drm_i915_private *dev_priv = to_i915(plane->dev);
14098         struct drm_framebuffer *fb = new_state->fb;
14099         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14100         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
14101         int ret;
14102
14103         if (old_obj) {
14104                 struct drm_crtc_state *crtc_state =
14105                         drm_atomic_get_new_crtc_state(new_state->state,
14106                                                       plane->state->crtc);
14107
14108                 /* Big Hammer, we also need to ensure that any pending
14109                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
14110                  * current scanout is retired before unpinning the old
14111                  * framebuffer. Note that we rely on userspace rendering
14112                  * into the buffer attached to the pipe they are waiting
14113                  * on. If not, userspace generates a GPU hang with IPEHR
14114                  * point to the MI_WAIT_FOR_EVENT.
14115                  *
14116                  * This should only fail upon a hung GPU, in which case we
14117                  * can safely continue.
14118                  */
14119                 if (needs_modeset(crtc_state)) {
14120                         ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
14121                                                               old_obj->resv, NULL,
14122                                                               false, 0,
14123                                                               GFP_KERNEL);
14124                         if (ret < 0)
14125                                 return ret;
14126                 }
14127         }
14128
14129         if (new_state->fence) { /* explicit fencing */
14130                 ret = i915_sw_fence_await_dma_fence(&intel_state->commit_ready,
14131                                                     new_state->fence,
14132                                                     I915_FENCE_TIMEOUT,
14133                                                     GFP_KERNEL);
14134                 if (ret < 0)
14135                         return ret;
14136         }
14137
14138         if (!obj)
14139                 return 0;
14140
14141         ret = i915_gem_object_pin_pages(obj);
14142         if (ret)
14143                 return ret;
14144
14145         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
14146         if (ret) {
14147                 i915_gem_object_unpin_pages(obj);
14148                 return ret;
14149         }
14150
14151         ret = intel_plane_pin_fb(to_intel_plane_state(new_state));
14152
14153         mutex_unlock(&dev_priv->drm.struct_mutex);
14154         i915_gem_object_unpin_pages(obj);
14155         if (ret)
14156                 return ret;
14157
14158         fb_obj_bump_render_priority(obj);
14159         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
14160
14161         if (!new_state->fence) { /* implicit fencing */
14162                 struct dma_fence *fence;
14163
14164                 ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
14165                                                       obj->resv, NULL,
14166                                                       false, I915_FENCE_TIMEOUT,
14167                                                       GFP_KERNEL);
14168                 if (ret < 0)
14169                         return ret;
14170
14171                 fence = reservation_object_get_excl_rcu(obj->resv);
14172                 if (fence) {
14173                         add_rps_boost_after_vblank(new_state->crtc, fence);
14174                         dma_fence_put(fence);
14175                 }
14176         } else {
14177                 add_rps_boost_after_vblank(new_state->crtc, new_state->fence);
14178         }
14179
14180         /*
14181          * We declare pageflips to be interactive and so merit a small bias
14182          * towards upclocking to deliver the frame on time. By only changing
14183          * the RPS thresholds to sample more regularly and aim for higher
14184          * clocks we can hopefully deliver low power workloads (like kodi)
14185          * that are not quite steady state without resorting to forcing
14186          * maximum clocks following a vblank miss (see do_rps_boost()).
14187          */
14188         if (!intel_state->rps_interactive) {
14189                 intel_rps_mark_interactive(dev_priv, true);
14190                 intel_state->rps_interactive = true;
14191         }
14192
14193         return 0;
14194 }
14195
14196 /**
14197  * intel_cleanup_plane_fb - Cleans up an fb after plane use
14198  * @plane: drm plane to clean up for
14199  * @old_state: the state from the previous modeset
14200  *
14201  * Cleans up a framebuffer that has just been removed from a plane.
14202  *
14203  * Must be called with struct_mutex held.
14204  */
14205 void
14206 intel_cleanup_plane_fb(struct drm_plane *plane,
14207                        struct drm_plane_state *old_state)
14208 {
14209         struct intel_atomic_state *intel_state =
14210                 to_intel_atomic_state(old_state->state);
14211         struct drm_i915_private *dev_priv = to_i915(plane->dev);
14212
14213         if (intel_state->rps_interactive) {
14214                 intel_rps_mark_interactive(dev_priv, false);
14215                 intel_state->rps_interactive = false;
14216         }
14217
14218         /* Should only be called after a successful intel_prepare_plane_fb()! */
14219         mutex_lock(&dev_priv->drm.struct_mutex);
14220         intel_plane_unpin_fb(to_intel_plane_state(old_state));
14221         mutex_unlock(&dev_priv->drm.struct_mutex);
14222 }
14223
14224 int
14225 skl_max_scale(const struct intel_crtc_state *crtc_state,
14226               u32 pixel_format)
14227 {
14228         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
14229         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
14230         int max_scale, mult;
14231         int crtc_clock, max_dotclk, tmpclk1, tmpclk2;
14232
14233         if (!crtc_state->base.enable)
14234                 return DRM_PLANE_HELPER_NO_SCALING;
14235
14236         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
14237         max_dotclk = to_intel_atomic_state(crtc_state->base.state)->cdclk.logical.cdclk;
14238
14239         if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) >= 10)
14240                 max_dotclk *= 2;
14241
14242         if (WARN_ON_ONCE(!crtc_clock || max_dotclk < crtc_clock))
14243                 return DRM_PLANE_HELPER_NO_SCALING;
14244
14245         /*
14246          * skl max scale is lower of:
14247          *    close to 3 but not 3, -1 is for that purpose
14248          *            or
14249          *    cdclk/crtc_clock
14250          */
14251         mult = is_planar_yuv_format(pixel_format) ? 2 : 3;
14252         tmpclk1 = (1 << 16) * mult - 1;
14253         tmpclk2 = (1 << 8) * ((max_dotclk << 8) / crtc_clock);
14254         max_scale = min(tmpclk1, tmpclk2);
14255
14256         return max_scale;
14257 }
14258
14259 static void intel_begin_crtc_commit(struct intel_atomic_state *state,
14260                                     struct intel_crtc *crtc)
14261 {
14262         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
14263         struct intel_crtc_state *old_crtc_state =
14264                 intel_atomic_get_old_crtc_state(state, crtc);
14265         struct intel_crtc_state *new_crtc_state =
14266                 intel_atomic_get_new_crtc_state(state, crtc);
14267         bool modeset = needs_modeset(&new_crtc_state->base);
14268
14269         /* Perform vblank evasion around commit operation */
14270         intel_pipe_update_start(new_crtc_state);
14271
14272         if (modeset)
14273                 goto out;
14274
14275         if (new_crtc_state->base.color_mgmt_changed ||
14276             new_crtc_state->update_pipe)
14277                 intel_color_commit(new_crtc_state);
14278
14279         if (new_crtc_state->update_pipe)
14280                 intel_update_pipe_config(old_crtc_state, new_crtc_state);
14281         else if (INTEL_GEN(dev_priv) >= 9)
14282                 skl_detach_scalers(new_crtc_state);
14283
14284         if (INTEL_GEN(dev_priv) >= 9 || IS_BROADWELL(dev_priv))
14285                 bdw_set_pipemisc(new_crtc_state);
14286
14287 out:
14288         if (dev_priv->display.atomic_update_watermarks)
14289                 dev_priv->display.atomic_update_watermarks(state,
14290                                                            new_crtc_state);
14291 }
14292
14293 void intel_crtc_arm_fifo_underrun(struct intel_crtc *crtc,
14294                                   struct intel_crtc_state *crtc_state)
14295 {
14296         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
14297
14298         if (!IS_GEN(dev_priv, 2))
14299                 intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, true);
14300
14301         if (crtc_state->has_pch_encoder) {
14302                 enum pipe pch_transcoder =
14303                         intel_crtc_pch_transcoder(crtc);
14304
14305                 intel_set_pch_fifo_underrun_reporting(dev_priv, pch_transcoder, true);
14306         }
14307 }
14308
14309 static void intel_finish_crtc_commit(struct intel_atomic_state *state,
14310                                      struct intel_crtc *crtc)
14311 {
14312         struct intel_crtc_state *old_crtc_state =
14313                 intel_atomic_get_old_crtc_state(state, crtc);
14314         struct intel_crtc_state *new_crtc_state =
14315                 intel_atomic_get_new_crtc_state(state, crtc);
14316
14317         intel_pipe_update_end(new_crtc_state);
14318
14319         if (new_crtc_state->update_pipe &&
14320             !needs_modeset(&new_crtc_state->base) &&
14321             old_crtc_state->base.mode.private_flags & I915_MODE_FLAG_INHERITED)
14322                 intel_crtc_arm_fifo_underrun(crtc, new_crtc_state);
14323 }
14324
14325 /**
14326  * intel_plane_destroy - destroy a plane
14327  * @plane: plane to destroy
14328  *
14329  * Common destruction function for all types of planes (primary, cursor,
14330  * sprite).
14331  */
14332 void intel_plane_destroy(struct drm_plane *plane)
14333 {
14334         drm_plane_cleanup(plane);
14335         kfree(to_intel_plane(plane));
14336 }
14337
14338 static bool i8xx_plane_format_mod_supported(struct drm_plane *_plane,
14339                                             u32 format, u64 modifier)
14340 {
14341         switch (modifier) {
14342         case DRM_FORMAT_MOD_LINEAR:
14343         case I915_FORMAT_MOD_X_TILED:
14344                 break;
14345         default:
14346                 return false;
14347         }
14348
14349         switch (format) {
14350         case DRM_FORMAT_C8:
14351         case DRM_FORMAT_RGB565:
14352         case DRM_FORMAT_XRGB1555:
14353         case DRM_FORMAT_XRGB8888:
14354                 return modifier == DRM_FORMAT_MOD_LINEAR ||
14355                         modifier == I915_FORMAT_MOD_X_TILED;
14356         default:
14357                 return false;
14358         }
14359 }
14360
14361 static bool i965_plane_format_mod_supported(struct drm_plane *_plane,
14362                                             u32 format, u64 modifier)
14363 {
14364         switch (modifier) {
14365         case DRM_FORMAT_MOD_LINEAR:
14366         case I915_FORMAT_MOD_X_TILED:
14367                 break;
14368         default:
14369                 return false;
14370         }
14371
14372         switch (format) {
14373         case DRM_FORMAT_C8:
14374         case DRM_FORMAT_RGB565:
14375         case DRM_FORMAT_XRGB8888:
14376         case DRM_FORMAT_XBGR8888:
14377         case DRM_FORMAT_XRGB2101010:
14378         case DRM_FORMAT_XBGR2101010:
14379                 return modifier == DRM_FORMAT_MOD_LINEAR ||
14380                         modifier == I915_FORMAT_MOD_X_TILED;
14381         default:
14382                 return false;
14383         }
14384 }
14385
14386 static bool intel_cursor_format_mod_supported(struct drm_plane *_plane,
14387                                               u32 format, u64 modifier)
14388 {
14389         return modifier == DRM_FORMAT_MOD_LINEAR &&
14390                 format == DRM_FORMAT_ARGB8888;
14391 }
14392
14393 static const struct drm_plane_funcs i965_plane_funcs = {
14394         .update_plane = drm_atomic_helper_update_plane,
14395         .disable_plane = drm_atomic_helper_disable_plane,
14396         .destroy = intel_plane_destroy,
14397         .atomic_get_property = intel_plane_atomic_get_property,
14398         .atomic_set_property = intel_plane_atomic_set_property,
14399         .atomic_duplicate_state = intel_plane_duplicate_state,
14400         .atomic_destroy_state = intel_plane_destroy_state,
14401         .format_mod_supported = i965_plane_format_mod_supported,
14402 };
14403
14404 static const struct drm_plane_funcs i8xx_plane_funcs = {
14405         .update_plane = drm_atomic_helper_update_plane,
14406         .disable_plane = drm_atomic_helper_disable_plane,
14407         .destroy = intel_plane_destroy,
14408         .atomic_get_property = intel_plane_atomic_get_property,
14409         .atomic_set_property = intel_plane_atomic_set_property,
14410         .atomic_duplicate_state = intel_plane_duplicate_state,
14411         .atomic_destroy_state = intel_plane_destroy_state,
14412         .format_mod_supported = i8xx_plane_format_mod_supported,
14413 };
14414
14415 static int
14416 intel_legacy_cursor_update(struct drm_plane *plane,
14417                            struct drm_crtc *crtc,
14418                            struct drm_framebuffer *fb,
14419                            int crtc_x, int crtc_y,
14420                            unsigned int crtc_w, unsigned int crtc_h,
14421                            u32 src_x, u32 src_y,
14422                            u32 src_w, u32 src_h,
14423                            struct drm_modeset_acquire_ctx *ctx)
14424 {
14425         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
14426         int ret;
14427         struct drm_plane_state *old_plane_state, *new_plane_state;
14428         struct intel_plane *intel_plane = to_intel_plane(plane);
14429         struct drm_framebuffer *old_fb;
14430         struct intel_crtc_state *crtc_state =
14431                 to_intel_crtc_state(crtc->state);
14432         struct intel_crtc_state *new_crtc_state;
14433
14434         /*
14435          * When crtc is inactive or there is a modeset pending,
14436          * wait for it to complete in the slowpath
14437          */
14438         if (!crtc_state->base.active || needs_modeset(&crtc_state->base) ||
14439             crtc_state->update_pipe)
14440                 goto slow;
14441
14442         old_plane_state = plane->state;
14443         /*
14444          * Don't do an async update if there is an outstanding commit modifying
14445          * the plane.  This prevents our async update's changes from getting
14446          * overridden by a previous synchronous update's state.
14447          */
14448         if (old_plane_state->commit &&
14449             !try_wait_for_completion(&old_plane_state->commit->hw_done))
14450                 goto slow;
14451
14452         /*
14453          * If any parameters change that may affect watermarks,
14454          * take the slowpath. Only changing fb or position should be
14455          * in the fastpath.
14456          */
14457         if (old_plane_state->crtc != crtc ||
14458             old_plane_state->src_w != src_w ||
14459             old_plane_state->src_h != src_h ||
14460             old_plane_state->crtc_w != crtc_w ||
14461             old_plane_state->crtc_h != crtc_h ||
14462             !old_plane_state->fb != !fb)
14463                 goto slow;
14464
14465         new_plane_state = intel_plane_duplicate_state(plane);
14466         if (!new_plane_state)
14467                 return -ENOMEM;
14468
14469         new_crtc_state = to_intel_crtc_state(intel_crtc_duplicate_state(crtc));
14470         if (!new_crtc_state) {
14471                 ret = -ENOMEM;
14472                 goto out_free;
14473         }
14474
14475         drm_atomic_set_fb_for_plane(new_plane_state, fb);
14476
14477         new_plane_state->src_x = src_x;
14478         new_plane_state->src_y = src_y;
14479         new_plane_state->src_w = src_w;
14480         new_plane_state->src_h = src_h;
14481         new_plane_state->crtc_x = crtc_x;
14482         new_plane_state->crtc_y = crtc_y;
14483         new_plane_state->crtc_w = crtc_w;
14484         new_plane_state->crtc_h = crtc_h;
14485
14486         ret = intel_plane_atomic_check_with_state(crtc_state, new_crtc_state,
14487                                                   to_intel_plane_state(old_plane_state),
14488                                                   to_intel_plane_state(new_plane_state));
14489         if (ret)
14490                 goto out_free;
14491
14492         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
14493         if (ret)
14494                 goto out_free;
14495
14496         ret = intel_plane_pin_fb(to_intel_plane_state(new_plane_state));
14497         if (ret)
14498                 goto out_unlock;
14499
14500         intel_fb_obj_flush(intel_fb_obj(fb), ORIGIN_FLIP);
14501
14502         old_fb = old_plane_state->fb;
14503         i915_gem_track_fb(intel_fb_obj(old_fb), intel_fb_obj(fb),
14504                           intel_plane->frontbuffer_bit);
14505
14506         /* Swap plane state */
14507         plane->state = new_plane_state;
14508
14509         /*
14510          * We cannot swap crtc_state as it may be in use by an atomic commit or
14511          * page flip that's running simultaneously. If we swap crtc_state and
14512          * destroy the old state, we will cause a use-after-free there.
14513          *
14514          * Only update active_planes, which is needed for our internal
14515          * bookkeeping. Either value will do the right thing when updating
14516          * planes atomically. If the cursor was part of the atomic update then
14517          * we would have taken the slowpath.
14518          */
14519         crtc_state->active_planes = new_crtc_state->active_planes;
14520
14521         if (plane->state->visible)
14522                 intel_update_plane(intel_plane, crtc_state,
14523                                    to_intel_plane_state(plane->state));
14524         else
14525                 intel_disable_plane(intel_plane, crtc_state);
14526
14527         intel_plane_unpin_fb(to_intel_plane_state(old_plane_state));
14528
14529 out_unlock:
14530         mutex_unlock(&dev_priv->drm.struct_mutex);
14531 out_free:
14532         if (new_crtc_state)
14533                 intel_crtc_destroy_state(crtc, &new_crtc_state->base);
14534         if (ret)
14535                 intel_plane_destroy_state(plane, new_plane_state);
14536         else
14537                 intel_plane_destroy_state(plane, old_plane_state);
14538         return ret;
14539
14540 slow:
14541         return drm_atomic_helper_update_plane(plane, crtc, fb,
14542                                               crtc_x, crtc_y, crtc_w, crtc_h,
14543                                               src_x, src_y, src_w, src_h, ctx);
14544 }
14545
14546 static const struct drm_plane_funcs intel_cursor_plane_funcs = {
14547         .update_plane = intel_legacy_cursor_update,
14548         .disable_plane = drm_atomic_helper_disable_plane,
14549         .destroy = intel_plane_destroy,
14550         .atomic_get_property = intel_plane_atomic_get_property,
14551         .atomic_set_property = intel_plane_atomic_set_property,
14552         .atomic_duplicate_state = intel_plane_duplicate_state,
14553         .atomic_destroy_state = intel_plane_destroy_state,
14554         .format_mod_supported = intel_cursor_format_mod_supported,
14555 };
14556
14557 static bool i9xx_plane_has_fbc(struct drm_i915_private *dev_priv,
14558                                enum i9xx_plane_id i9xx_plane)
14559 {
14560         if (!HAS_FBC(dev_priv))
14561                 return false;
14562
14563         if (IS_BROADWELL(dev_priv) || IS_HASWELL(dev_priv))
14564                 return i9xx_plane == PLANE_A; /* tied to pipe A */
14565         else if (IS_IVYBRIDGE(dev_priv))
14566                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B ||
14567                         i9xx_plane == PLANE_C;
14568         else if (INTEL_GEN(dev_priv) >= 4)
14569                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B;
14570         else
14571                 return i9xx_plane == PLANE_A;
14572 }
14573
14574 static struct intel_plane *
14575 intel_primary_plane_create(struct drm_i915_private *dev_priv, enum pipe pipe)
14576 {
14577         struct intel_plane *plane;
14578         const struct drm_plane_funcs *plane_funcs;
14579         unsigned int supported_rotations;
14580         unsigned int possible_crtcs;
14581         const u64 *modifiers;
14582         const u32 *formats;
14583         int num_formats;
14584         int ret;
14585
14586         if (INTEL_GEN(dev_priv) >= 9)
14587                 return skl_universal_plane_create(dev_priv, pipe,
14588                                                   PLANE_PRIMARY);
14589
14590         plane = intel_plane_alloc();
14591         if (IS_ERR(plane))
14592                 return plane;
14593
14594         plane->pipe = pipe;
14595         /*
14596          * On gen2/3 only plane A can do FBC, but the panel fitter and LVDS
14597          * port is hooked to pipe B. Hence we want plane A feeding pipe B.
14598          */
14599         if (HAS_FBC(dev_priv) && INTEL_GEN(dev_priv) < 4)
14600                 plane->i9xx_plane = (enum i9xx_plane_id) !pipe;
14601         else
14602                 plane->i9xx_plane = (enum i9xx_plane_id) pipe;
14603         plane->id = PLANE_PRIMARY;
14604         plane->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, plane->id);
14605
14606         plane->has_fbc = i9xx_plane_has_fbc(dev_priv, plane->i9xx_plane);
14607         if (plane->has_fbc) {
14608                 struct intel_fbc *fbc = &dev_priv->fbc;
14609
14610                 fbc->possible_framebuffer_bits |= plane->frontbuffer_bit;
14611         }
14612
14613         if (INTEL_GEN(dev_priv) >= 4) {
14614                 formats = i965_primary_formats;
14615                 num_formats = ARRAY_SIZE(i965_primary_formats);
14616                 modifiers = i9xx_format_modifiers;
14617
14618                 plane->max_stride = i9xx_plane_max_stride;
14619                 plane->update_plane = i9xx_update_plane;
14620                 plane->disable_plane = i9xx_disable_plane;
14621                 plane->get_hw_state = i9xx_plane_get_hw_state;
14622                 plane->check_plane = i9xx_plane_check;
14623
14624                 plane_funcs = &i965_plane_funcs;
14625         } else {
14626                 formats = i8xx_primary_formats;
14627                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
14628                 modifiers = i9xx_format_modifiers;
14629
14630                 plane->max_stride = i9xx_plane_max_stride;
14631                 plane->update_plane = i9xx_update_plane;
14632                 plane->disable_plane = i9xx_disable_plane;
14633                 plane->get_hw_state = i9xx_plane_get_hw_state;
14634                 plane->check_plane = i9xx_plane_check;
14635
14636                 plane_funcs = &i8xx_plane_funcs;
14637         }
14638
14639         possible_crtcs = BIT(pipe);
14640
14641         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
14642                 ret = drm_universal_plane_init(&dev_priv->drm, &plane->base,
14643                                                possible_crtcs, plane_funcs,
14644                                                formats, num_formats, modifiers,
14645                                                DRM_PLANE_TYPE_PRIMARY,
14646                                                "primary %c", pipe_name(pipe));
14647         else
14648                 ret = drm_universal_plane_init(&dev_priv->drm, &plane->base,
14649                                                possible_crtcs, plane_funcs,
14650                                                formats, num_formats, modifiers,
14651                                                DRM_PLANE_TYPE_PRIMARY,
14652                                                "plane %c",
14653                                                plane_name(plane->i9xx_plane));
14654         if (ret)
14655                 goto fail;
14656
14657         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
14658                 supported_rotations =
14659                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180 |
14660                         DRM_MODE_REFLECT_X;
14661         } else if (INTEL_GEN(dev_priv) >= 4) {
14662                 supported_rotations =
14663                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180;
14664         } else {
14665                 supported_rotations = DRM_MODE_ROTATE_0;
14666         }
14667
14668         if (INTEL_GEN(dev_priv) >= 4)
14669                 drm_plane_create_rotation_property(&plane->base,
14670                                                    DRM_MODE_ROTATE_0,
14671                                                    supported_rotations);
14672
14673         drm_plane_helper_add(&plane->base, &intel_plane_helper_funcs);
14674
14675         return plane;
14676
14677 fail:
14678         intel_plane_free(plane);
14679
14680         return ERR_PTR(ret);
14681 }
14682
14683 static struct intel_plane *
14684 intel_cursor_plane_create(struct drm_i915_private *dev_priv,
14685                           enum pipe pipe)
14686 {
14687         unsigned int possible_crtcs;
14688         struct intel_plane *cursor;
14689         int ret;
14690
14691         cursor = intel_plane_alloc();
14692         if (IS_ERR(cursor))
14693                 return cursor;
14694
14695         cursor->pipe = pipe;
14696         cursor->i9xx_plane = (enum i9xx_plane_id) pipe;
14697         cursor->id = PLANE_CURSOR;
14698         cursor->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, cursor->id);
14699
14700         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
14701                 cursor->max_stride = i845_cursor_max_stride;
14702                 cursor->update_plane = i845_update_cursor;
14703                 cursor->disable_plane = i845_disable_cursor;
14704                 cursor->get_hw_state = i845_cursor_get_hw_state;
14705                 cursor->check_plane = i845_check_cursor;
14706         } else {
14707                 cursor->max_stride = i9xx_cursor_max_stride;
14708                 cursor->update_plane = i9xx_update_cursor;
14709                 cursor->disable_plane = i9xx_disable_cursor;
14710                 cursor->get_hw_state = i9xx_cursor_get_hw_state;
14711                 cursor->check_plane = i9xx_check_cursor;
14712         }
14713
14714         cursor->cursor.base = ~0;
14715         cursor->cursor.cntl = ~0;
14716
14717         if (IS_I845G(dev_priv) || IS_I865G(dev_priv) || HAS_CUR_FBC(dev_priv))
14718                 cursor->cursor.size = ~0;
14719
14720         possible_crtcs = BIT(pipe);
14721
14722         ret = drm_universal_plane_init(&dev_priv->drm, &cursor->base,
14723                                        possible_crtcs, &intel_cursor_plane_funcs,
14724                                        intel_cursor_formats,
14725                                        ARRAY_SIZE(intel_cursor_formats),
14726                                        cursor_format_modifiers,
14727                                        DRM_PLANE_TYPE_CURSOR,
14728                                        "cursor %c", pipe_name(pipe));
14729         if (ret)
14730                 goto fail;
14731
14732         if (INTEL_GEN(dev_priv) >= 4)
14733                 drm_plane_create_rotation_property(&cursor->base,
14734                                                    DRM_MODE_ROTATE_0,
14735                                                    DRM_MODE_ROTATE_0 |
14736                                                    DRM_MODE_ROTATE_180);
14737
14738         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
14739
14740         return cursor;
14741
14742 fail:
14743         intel_plane_free(cursor);
14744
14745         return ERR_PTR(ret);
14746 }
14747
14748 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
14749                                     struct intel_crtc_state *crtc_state)
14750 {
14751         struct intel_crtc_scaler_state *scaler_state =
14752                 &crtc_state->scaler_state;
14753         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
14754         int i;
14755
14756         crtc->num_scalers = RUNTIME_INFO(dev_priv)->num_scalers[crtc->pipe];
14757         if (!crtc->num_scalers)
14758                 return;
14759
14760         for (i = 0; i < crtc->num_scalers; i++) {
14761                 struct intel_scaler *scaler = &scaler_state->scalers[i];
14762
14763                 scaler->in_use = 0;
14764                 scaler->mode = 0;
14765         }
14766
14767         scaler_state->scaler_id = -1;
14768 }
14769
14770 static int intel_crtc_init(struct drm_i915_private *dev_priv, enum pipe pipe)
14771 {
14772         struct intel_crtc *intel_crtc;
14773         struct intel_crtc_state *crtc_state = NULL;
14774         struct intel_plane *primary = NULL;
14775         struct intel_plane *cursor = NULL;
14776         int sprite, ret;
14777
14778         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
14779         if (!intel_crtc)
14780                 return -ENOMEM;
14781
14782         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
14783         if (!crtc_state) {
14784                 ret = -ENOMEM;
14785                 goto fail;
14786         }
14787         __drm_atomic_helper_crtc_reset(&intel_crtc->base, &crtc_state->base);
14788         intel_crtc->config = crtc_state;
14789
14790         primary = intel_primary_plane_create(dev_priv, pipe);
14791         if (IS_ERR(primary)) {
14792                 ret = PTR_ERR(primary);
14793                 goto fail;
14794         }
14795         intel_crtc->plane_ids_mask |= BIT(primary->id);
14796
14797         for_each_sprite(dev_priv, pipe, sprite) {
14798                 struct intel_plane *plane;
14799
14800                 plane = intel_sprite_plane_create(dev_priv, pipe, sprite);
14801                 if (IS_ERR(plane)) {
14802                         ret = PTR_ERR(plane);
14803                         goto fail;
14804                 }
14805                 intel_crtc->plane_ids_mask |= BIT(plane->id);
14806         }
14807
14808         cursor = intel_cursor_plane_create(dev_priv, pipe);
14809         if (IS_ERR(cursor)) {
14810                 ret = PTR_ERR(cursor);
14811                 goto fail;
14812         }
14813         intel_crtc->plane_ids_mask |= BIT(cursor->id);
14814
14815         ret = drm_crtc_init_with_planes(&dev_priv->drm, &intel_crtc->base,
14816                                         &primary->base, &cursor->base,
14817                                         &intel_crtc_funcs,
14818                                         "pipe %c", pipe_name(pipe));
14819         if (ret)
14820                 goto fail;
14821
14822         intel_crtc->pipe = pipe;
14823
14824         /* initialize shared scalers */
14825         intel_crtc_init_scalers(intel_crtc, crtc_state);
14826
14827         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->pipe_to_crtc_mapping) ||
14828                dev_priv->pipe_to_crtc_mapping[pipe] != NULL);
14829         dev_priv->pipe_to_crtc_mapping[pipe] = intel_crtc;
14830
14831         if (INTEL_GEN(dev_priv) < 9) {
14832                 enum i9xx_plane_id i9xx_plane = primary->i9xx_plane;
14833
14834                 BUG_ON(i9xx_plane >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
14835                        dev_priv->plane_to_crtc_mapping[i9xx_plane] != NULL);
14836                 dev_priv->plane_to_crtc_mapping[i9xx_plane] = intel_crtc;
14837         }
14838
14839         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
14840
14841         intel_color_init(intel_crtc);
14842
14843         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
14844
14845         return 0;
14846
14847 fail:
14848         /*
14849          * drm_mode_config_cleanup() will free up any
14850          * crtcs/planes already initialized.
14851          */
14852         kfree(crtc_state);
14853         kfree(intel_crtc);
14854
14855         return ret;
14856 }
14857
14858 int intel_get_pipe_from_crtc_id_ioctl(struct drm_device *dev, void *data,
14859                                       struct drm_file *file)
14860 {
14861         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
14862         struct drm_crtc *drmmode_crtc;
14863         struct intel_crtc *crtc;
14864
14865         drmmode_crtc = drm_crtc_find(dev, file, pipe_from_crtc_id->crtc_id);
14866         if (!drmmode_crtc)
14867                 return -ENOENT;
14868
14869         crtc = to_intel_crtc(drmmode_crtc);
14870         pipe_from_crtc_id->pipe = crtc->pipe;
14871
14872         return 0;
14873 }
14874
14875 static int intel_encoder_clones(struct intel_encoder *encoder)
14876 {
14877         struct drm_device *dev = encoder->base.dev;
14878         struct intel_encoder *source_encoder;
14879         int index_mask = 0;
14880         int entry = 0;
14881
14882         for_each_intel_encoder(dev, source_encoder) {
14883                 if (encoders_cloneable(encoder, source_encoder))
14884                         index_mask |= (1 << entry);
14885
14886                 entry++;
14887         }
14888
14889         return index_mask;
14890 }
14891
14892 static bool ilk_has_edp_a(struct drm_i915_private *dev_priv)
14893 {
14894         if (!IS_MOBILE(dev_priv))
14895                 return false;
14896
14897         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
14898                 return false;
14899
14900         if (IS_GEN(dev_priv, 5) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
14901                 return false;
14902
14903         return true;
14904 }
14905
14906 static bool intel_ddi_crt_present(struct drm_i915_private *dev_priv)
14907 {
14908         if (INTEL_GEN(dev_priv) >= 9)
14909                 return false;
14910
14911         if (IS_HSW_ULT(dev_priv) || IS_BDW_ULT(dev_priv))
14912                 return false;
14913
14914         if (HAS_PCH_LPT_H(dev_priv) &&
14915             I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
14916                 return false;
14917
14918         /* DDI E can't be used if DDI A requires 4 lanes */
14919         if (I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
14920                 return false;
14921
14922         if (!dev_priv->vbt.int_crt_support)
14923                 return false;
14924
14925         return true;
14926 }
14927
14928 void intel_pps_unlock_regs_wa(struct drm_i915_private *dev_priv)
14929 {
14930         int pps_num;
14931         int pps_idx;
14932
14933         if (HAS_DDI(dev_priv))
14934                 return;
14935         /*
14936          * This w/a is needed at least on CPT/PPT, but to be sure apply it
14937          * everywhere where registers can be write protected.
14938          */
14939         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
14940                 pps_num = 2;
14941         else
14942                 pps_num = 1;
14943
14944         for (pps_idx = 0; pps_idx < pps_num; pps_idx++) {
14945                 u32 val = I915_READ(PP_CONTROL(pps_idx));
14946
14947                 val = (val & ~PANEL_UNLOCK_MASK) | PANEL_UNLOCK_REGS;
14948                 I915_WRITE(PP_CONTROL(pps_idx), val);
14949         }
14950 }
14951
14952 static void intel_pps_init(struct drm_i915_private *dev_priv)
14953 {
14954         if (HAS_PCH_SPLIT(dev_priv) || IS_GEN9_LP(dev_priv))
14955                 dev_priv->pps_mmio_base = PCH_PPS_BASE;
14956         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
14957                 dev_priv->pps_mmio_base = VLV_PPS_BASE;
14958         else
14959                 dev_priv->pps_mmio_base = PPS_BASE;
14960
14961         intel_pps_unlock_regs_wa(dev_priv);
14962 }
14963
14964 static void intel_setup_outputs(struct drm_i915_private *dev_priv)
14965 {
14966         struct intel_encoder *encoder;
14967         bool dpd_is_edp = false;
14968
14969         intel_pps_init(dev_priv);
14970
14971         if (!HAS_DISPLAY(dev_priv))
14972                 return;
14973
14974         if (IS_ELKHARTLAKE(dev_priv)) {
14975                 intel_ddi_init(dev_priv, PORT_A);
14976                 intel_ddi_init(dev_priv, PORT_B);
14977                 intel_ddi_init(dev_priv, PORT_C);
14978                 icl_dsi_init(dev_priv);
14979         } else if (INTEL_GEN(dev_priv) >= 11) {
14980                 intel_ddi_init(dev_priv, PORT_A);
14981                 intel_ddi_init(dev_priv, PORT_B);
14982                 intel_ddi_init(dev_priv, PORT_C);
14983                 intel_ddi_init(dev_priv, PORT_D);
14984                 intel_ddi_init(dev_priv, PORT_E);
14985                 /*
14986                  * On some ICL SKUs port F is not present. No strap bits for
14987                  * this, so rely on VBT.
14988                  * Work around broken VBTs on SKUs known to have no port F.
14989                  */
14990                 if (IS_ICL_WITH_PORT_F(dev_priv) &&
14991                     intel_bios_is_port_present(dev_priv, PORT_F))
14992                         intel_ddi_init(dev_priv, PORT_F);
14993
14994                 icl_dsi_init(dev_priv);
14995         } else if (IS_GEN9_LP(dev_priv)) {
14996                 /*
14997                  * FIXME: Broxton doesn't support port detection via the
14998                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
14999                  * detect the ports.
15000                  */
15001                 intel_ddi_init(dev_priv, PORT_A);
15002                 intel_ddi_init(dev_priv, PORT_B);
15003                 intel_ddi_init(dev_priv, PORT_C);
15004
15005                 vlv_dsi_init(dev_priv);
15006         } else if (HAS_DDI(dev_priv)) {
15007                 int found;
15008
15009                 if (intel_ddi_crt_present(dev_priv))
15010                         intel_crt_init(dev_priv);
15011
15012                 /*
15013                  * Haswell uses DDI functions to detect digital outputs.
15014                  * On SKL pre-D0 the strap isn't connected, so we assume
15015                  * it's there.
15016                  */
15017                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
15018                 /* WaIgnoreDDIAStrap: skl */
15019                 if (found || IS_GEN9_BC(dev_priv))
15020                         intel_ddi_init(dev_priv, PORT_A);
15021
15022                 /* DDI B, C, D, and F detection is indicated by the SFUSE_STRAP
15023                  * register */
15024                 found = I915_READ(SFUSE_STRAP);
15025
15026                 if (found & SFUSE_STRAP_DDIB_DETECTED)
15027                         intel_ddi_init(dev_priv, PORT_B);
15028                 if (found & SFUSE_STRAP_DDIC_DETECTED)
15029                         intel_ddi_init(dev_priv, PORT_C);
15030                 if (found & SFUSE_STRAP_DDID_DETECTED)
15031                         intel_ddi_init(dev_priv, PORT_D);
15032                 if (found & SFUSE_STRAP_DDIF_DETECTED)
15033                         intel_ddi_init(dev_priv, PORT_F);
15034                 /*
15035                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
15036                  */
15037                 if (IS_GEN9_BC(dev_priv) &&
15038                     intel_bios_is_port_present(dev_priv, PORT_E))
15039                         intel_ddi_init(dev_priv, PORT_E);
15040
15041         } else if (HAS_PCH_SPLIT(dev_priv)) {
15042                 int found;
15043
15044                 /*
15045                  * intel_edp_init_connector() depends on this completing first,
15046                  * to prevent the registration of both eDP and LVDS and the
15047                  * incorrect sharing of the PPS.
15048                  */
15049                 intel_lvds_init(dev_priv);
15050                 intel_crt_init(dev_priv);
15051
15052                 dpd_is_edp = intel_dp_is_port_edp(dev_priv, PORT_D);
15053
15054                 if (ilk_has_edp_a(dev_priv))
15055                         intel_dp_init(dev_priv, DP_A, PORT_A);
15056
15057                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
15058                         /* PCH SDVOB multiplex with HDMIB */
15059                         found = intel_sdvo_init(dev_priv, PCH_SDVOB, PORT_B);
15060                         if (!found)
15061                                 intel_hdmi_init(dev_priv, PCH_HDMIB, PORT_B);
15062                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
15063                                 intel_dp_init(dev_priv, PCH_DP_B, PORT_B);
15064                 }
15065
15066                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
15067                         intel_hdmi_init(dev_priv, PCH_HDMIC, PORT_C);
15068
15069                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
15070                         intel_hdmi_init(dev_priv, PCH_HDMID, PORT_D);
15071
15072                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
15073                         intel_dp_init(dev_priv, PCH_DP_C, PORT_C);
15074
15075                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
15076                         intel_dp_init(dev_priv, PCH_DP_D, PORT_D);
15077         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
15078                 bool has_edp, has_port;
15079
15080                 if (IS_VALLEYVIEW(dev_priv) && dev_priv->vbt.int_crt_support)
15081                         intel_crt_init(dev_priv);
15082
15083                 /*
15084                  * The DP_DETECTED bit is the latched state of the DDC
15085                  * SDA pin at boot. However since eDP doesn't require DDC
15086                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
15087                  * eDP ports may have been muxed to an alternate function.
15088                  * Thus we can't rely on the DP_DETECTED bit alone to detect
15089                  * eDP ports. Consult the VBT as well as DP_DETECTED to
15090                  * detect eDP ports.
15091                  *
15092                  * Sadly the straps seem to be missing sometimes even for HDMI
15093                  * ports (eg. on Voyo V3 - CHT x7-Z8700), so check both strap
15094                  * and VBT for the presence of the port. Additionally we can't
15095                  * trust the port type the VBT declares as we've seen at least
15096                  * HDMI ports that the VBT claim are DP or eDP.
15097                  */
15098                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_B);
15099                 has_port = intel_bios_is_port_present(dev_priv, PORT_B);
15100                 if (I915_READ(VLV_DP_B) & DP_DETECTED || has_port)
15101                         has_edp &= intel_dp_init(dev_priv, VLV_DP_B, PORT_B);
15102                 if ((I915_READ(VLV_HDMIB) & SDVO_DETECTED || has_port) && !has_edp)
15103                         intel_hdmi_init(dev_priv, VLV_HDMIB, PORT_B);
15104
15105                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_C);
15106                 has_port = intel_bios_is_port_present(dev_priv, PORT_C);
15107                 if (I915_READ(VLV_DP_C) & DP_DETECTED || has_port)
15108                         has_edp &= intel_dp_init(dev_priv, VLV_DP_C, PORT_C);
15109                 if ((I915_READ(VLV_HDMIC) & SDVO_DETECTED || has_port) && !has_edp)
15110                         intel_hdmi_init(dev_priv, VLV_HDMIC, PORT_C);
15111
15112                 if (IS_CHERRYVIEW(dev_priv)) {
15113                         /*
15114                          * eDP not supported on port D,
15115                          * so no need to worry about it
15116                          */
15117                         has_port = intel_bios_is_port_present(dev_priv, PORT_D);
15118                         if (I915_READ(CHV_DP_D) & DP_DETECTED || has_port)
15119                                 intel_dp_init(dev_priv, CHV_DP_D, PORT_D);
15120                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED || has_port)
15121                                 intel_hdmi_init(dev_priv, CHV_HDMID, PORT_D);
15122                 }
15123
15124                 vlv_dsi_init(dev_priv);
15125         } else if (IS_PINEVIEW(dev_priv)) {
15126                 intel_lvds_init(dev_priv);
15127                 intel_crt_init(dev_priv);
15128         } else if (IS_GEN_RANGE(dev_priv, 3, 4)) {
15129                 bool found = false;
15130
15131                 if (IS_MOBILE(dev_priv))
15132                         intel_lvds_init(dev_priv);
15133
15134                 intel_crt_init(dev_priv);
15135
15136                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
15137                         DRM_DEBUG_KMS("probing SDVOB\n");
15138                         found = intel_sdvo_init(dev_priv, GEN3_SDVOB, PORT_B);
15139                         if (!found && IS_G4X(dev_priv)) {
15140                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
15141                                 intel_hdmi_init(dev_priv, GEN4_HDMIB, PORT_B);
15142                         }
15143
15144                         if (!found && IS_G4X(dev_priv))
15145                                 intel_dp_init(dev_priv, DP_B, PORT_B);
15146                 }
15147
15148                 /* Before G4X SDVOC doesn't have its own detect register */
15149
15150                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
15151                         DRM_DEBUG_KMS("probing SDVOC\n");
15152                         found = intel_sdvo_init(dev_priv, GEN3_SDVOC, PORT_C);
15153                 }
15154
15155                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
15156
15157                         if (IS_G4X(dev_priv)) {
15158                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
15159                                 intel_hdmi_init(dev_priv, GEN4_HDMIC, PORT_C);
15160                         }
15161                         if (IS_G4X(dev_priv))
15162                                 intel_dp_init(dev_priv, DP_C, PORT_C);
15163                 }
15164
15165                 if (IS_G4X(dev_priv) && (I915_READ(DP_D) & DP_DETECTED))
15166                         intel_dp_init(dev_priv, DP_D, PORT_D);
15167
15168                 if (SUPPORTS_TV(dev_priv))
15169                         intel_tv_init(dev_priv);
15170         } else if (IS_GEN(dev_priv, 2)) {
15171                 if (IS_I85X(dev_priv))
15172                         intel_lvds_init(dev_priv);
15173
15174                 intel_crt_init(dev_priv);
15175                 intel_dvo_init(dev_priv);
15176         }
15177
15178         intel_psr_init(dev_priv);
15179
15180         for_each_intel_encoder(&dev_priv->drm, encoder) {
15181                 encoder->base.possible_crtcs = encoder->crtc_mask;
15182                 encoder->base.possible_clones =
15183                         intel_encoder_clones(encoder);
15184         }
15185
15186         intel_init_pch_refclk(dev_priv);
15187
15188         drm_helper_move_panel_connectors_to_head(&dev_priv->drm);
15189 }
15190
15191 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
15192 {
15193         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
15194         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
15195
15196         drm_framebuffer_cleanup(fb);
15197
15198         i915_gem_object_lock(obj);
15199         WARN_ON(!obj->framebuffer_references--);
15200         i915_gem_object_unlock(obj);
15201
15202         i915_gem_object_put(obj);
15203
15204         kfree(intel_fb);
15205 }
15206
15207 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
15208                                                 struct drm_file *file,
15209                                                 unsigned int *handle)
15210 {
15211         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
15212
15213         if (obj->userptr.mm) {
15214                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
15215                 return -EINVAL;
15216         }
15217
15218         return drm_gem_handle_create(file, &obj->base, handle);
15219 }
15220
15221 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
15222                                         struct drm_file *file,
15223                                         unsigned flags, unsigned color,
15224                                         struct drm_clip_rect *clips,
15225                                         unsigned num_clips)
15226 {
15227         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
15228
15229         i915_gem_object_flush_if_display(obj);
15230         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
15231
15232         return 0;
15233 }
15234
15235 static const struct drm_framebuffer_funcs intel_fb_funcs = {
15236         .destroy = intel_user_framebuffer_destroy,
15237         .create_handle = intel_user_framebuffer_create_handle,
15238         .dirty = intel_user_framebuffer_dirty,
15239 };
15240
15241 static int intel_framebuffer_init(struct intel_framebuffer *intel_fb,
15242                                   struct drm_i915_gem_object *obj,
15243                                   struct drm_mode_fb_cmd2 *mode_cmd)
15244 {
15245         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
15246         struct drm_framebuffer *fb = &intel_fb->base;
15247         u32 max_stride;
15248         unsigned int tiling, stride;
15249         int ret = -EINVAL;
15250         int i;
15251
15252         i915_gem_object_lock(obj);
15253         obj->framebuffer_references++;
15254         tiling = i915_gem_object_get_tiling(obj);
15255         stride = i915_gem_object_get_stride(obj);
15256         i915_gem_object_unlock(obj);
15257
15258         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
15259                 /*
15260                  * If there's a fence, enforce that
15261                  * the fb modifier and tiling mode match.
15262                  */
15263                 if (tiling != I915_TILING_NONE &&
15264                     tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
15265                         DRM_DEBUG_KMS("tiling_mode doesn't match fb modifier\n");
15266                         goto err;
15267                 }
15268         } else {
15269                 if (tiling == I915_TILING_X) {
15270                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
15271                 } else if (tiling == I915_TILING_Y) {
15272                         DRM_DEBUG_KMS("No Y tiling for legacy addfb\n");
15273                         goto err;
15274                 }
15275         }
15276
15277         if (!drm_any_plane_has_format(&dev_priv->drm,
15278                                       mode_cmd->pixel_format,
15279                                       mode_cmd->modifier[0])) {
15280                 struct drm_format_name_buf format_name;
15281
15282                 DRM_DEBUG_KMS("unsupported pixel format %s / modifier 0x%llx\n",
15283                               drm_get_format_name(mode_cmd->pixel_format,
15284                                                   &format_name),
15285                               mode_cmd->modifier[0]);
15286                 goto err;
15287         }
15288
15289         /*
15290          * gen2/3 display engine uses the fence if present,
15291          * so the tiling mode must match the fb modifier exactly.
15292          */
15293         if (INTEL_GEN(dev_priv) < 4 &&
15294             tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
15295                 DRM_DEBUG_KMS("tiling_mode must match fb modifier exactly on gen2/3\n");
15296                 goto err;
15297         }
15298
15299         max_stride = intel_fb_max_stride(dev_priv, mode_cmd->pixel_format,
15300                                          mode_cmd->modifier[0]);
15301         if (mode_cmd->pitches[0] > max_stride) {
15302                 DRM_DEBUG_KMS("%s pitch (%u) must be at most %d\n",
15303                               mode_cmd->modifier[0] != DRM_FORMAT_MOD_LINEAR ?
15304                               "tiled" : "linear",
15305                               mode_cmd->pitches[0], max_stride);
15306                 goto err;
15307         }
15308
15309         /*
15310          * If there's a fence, enforce that
15311          * the fb pitch and fence stride match.
15312          */
15313         if (tiling != I915_TILING_NONE && mode_cmd->pitches[0] != stride) {
15314                 DRM_DEBUG_KMS("pitch (%d) must match tiling stride (%d)\n",
15315                               mode_cmd->pitches[0], stride);
15316                 goto err;
15317         }
15318
15319         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
15320         if (mode_cmd->offsets[0] != 0)
15321                 goto err;
15322
15323         drm_helper_mode_fill_fb_struct(&dev_priv->drm, fb, mode_cmd);
15324
15325         for (i = 0; i < fb->format->num_planes; i++) {
15326                 u32 stride_alignment;
15327
15328                 if (mode_cmd->handles[i] != mode_cmd->handles[0]) {
15329                         DRM_DEBUG_KMS("bad plane %d handle\n", i);
15330                         goto err;
15331                 }
15332
15333                 stride_alignment = intel_fb_stride_alignment(fb, i);
15334
15335                 /*
15336                  * Display WA #0531: skl,bxt,kbl,glk
15337                  *
15338                  * Render decompression and plane width > 3840
15339                  * combined with horizontal panning requires the
15340                  * plane stride to be a multiple of 4. We'll just
15341                  * require the entire fb to accommodate that to avoid
15342                  * potential runtime errors at plane configuration time.
15343                  */
15344                 if (IS_GEN(dev_priv, 9) && i == 0 && fb->width > 3840 &&
15345                     is_ccs_modifier(fb->modifier))
15346                         stride_alignment *= 4;
15347
15348                 if (fb->pitches[i] & (stride_alignment - 1)) {
15349                         DRM_DEBUG_KMS("plane %d pitch (%d) must be at least %u byte aligned\n",
15350                                       i, fb->pitches[i], stride_alignment);
15351                         goto err;
15352                 }
15353
15354                 fb->obj[i] = &obj->base;
15355         }
15356
15357         ret = intel_fill_fb_info(dev_priv, fb);
15358         if (ret)
15359                 goto err;
15360
15361         ret = drm_framebuffer_init(&dev_priv->drm, fb, &intel_fb_funcs);
15362         if (ret) {
15363                 DRM_ERROR("framebuffer init failed %d\n", ret);
15364                 goto err;
15365         }
15366
15367         return 0;
15368
15369 err:
15370         i915_gem_object_lock(obj);
15371         obj->framebuffer_references--;
15372         i915_gem_object_unlock(obj);
15373         return ret;
15374 }
15375
15376 static struct drm_framebuffer *
15377 intel_user_framebuffer_create(struct drm_device *dev,
15378                               struct drm_file *filp,
15379                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
15380 {
15381         struct drm_framebuffer *fb;
15382         struct drm_i915_gem_object *obj;
15383         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
15384
15385         obj = i915_gem_object_lookup(filp, mode_cmd.handles[0]);
15386         if (!obj)
15387                 return ERR_PTR(-ENOENT);
15388
15389         fb = intel_framebuffer_create(obj, &mode_cmd);
15390         if (IS_ERR(fb))
15391                 i915_gem_object_put(obj);
15392
15393         return fb;
15394 }
15395
15396 static void intel_atomic_state_free(struct drm_atomic_state *state)
15397 {
15398         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
15399
15400         drm_atomic_state_default_release(state);
15401
15402         i915_sw_fence_fini(&intel_state->commit_ready);
15403
15404         kfree(state);
15405 }
15406
15407 static enum drm_mode_status
15408 intel_mode_valid(struct drm_device *dev,
15409                  const struct drm_display_mode *mode)
15410 {
15411         struct drm_i915_private *dev_priv = to_i915(dev);
15412         int hdisplay_max, htotal_max;
15413         int vdisplay_max, vtotal_max;
15414
15415         /*
15416          * Can't reject DBLSCAN here because Xorg ddxen can add piles
15417          * of DBLSCAN modes to the output's mode list when they detect
15418          * the scaling mode property on the connector. And they don't
15419          * ask the kernel to validate those modes in any way until
15420          * modeset time at which point the client gets a protocol error.
15421          * So in order to not upset those clients we silently ignore the
15422          * DBLSCAN flag on such connectors. For other connectors we will
15423          * reject modes with the DBLSCAN flag in encoder->compute_config().
15424          * And we always reject DBLSCAN modes in connector->mode_valid()
15425          * as we never want such modes on the connector's mode list.
15426          */
15427
15428         if (mode->vscan > 1)
15429                 return MODE_NO_VSCAN;
15430
15431         if (mode->flags & DRM_MODE_FLAG_HSKEW)
15432                 return MODE_H_ILLEGAL;
15433
15434         if (mode->flags & (DRM_MODE_FLAG_CSYNC |
15435                            DRM_MODE_FLAG_NCSYNC |
15436                            DRM_MODE_FLAG_PCSYNC))
15437                 return MODE_HSYNC;
15438
15439         if (mode->flags & (DRM_MODE_FLAG_BCAST |
15440                            DRM_MODE_FLAG_PIXMUX |
15441                            DRM_MODE_FLAG_CLKDIV2))
15442                 return MODE_BAD;
15443
15444         if (INTEL_GEN(dev_priv) >= 9 ||
15445             IS_BROADWELL(dev_priv) || IS_HASWELL(dev_priv)) {
15446                 hdisplay_max = 8192; /* FDI max 4096 handled elsewhere */
15447                 vdisplay_max = 4096;
15448                 htotal_max = 8192;
15449                 vtotal_max = 8192;
15450         } else if (INTEL_GEN(dev_priv) >= 3) {
15451                 hdisplay_max = 4096;
15452                 vdisplay_max = 4096;
15453                 htotal_max = 8192;
15454                 vtotal_max = 8192;
15455         } else {
15456                 hdisplay_max = 2048;
15457                 vdisplay_max = 2048;
15458                 htotal_max = 4096;
15459                 vtotal_max = 4096;
15460         }
15461
15462         if (mode->hdisplay > hdisplay_max ||
15463             mode->hsync_start > htotal_max ||
15464             mode->hsync_end > htotal_max ||
15465             mode->htotal > htotal_max)
15466                 return MODE_H_ILLEGAL;
15467
15468         if (mode->vdisplay > vdisplay_max ||
15469             mode->vsync_start > vtotal_max ||
15470             mode->vsync_end > vtotal_max ||
15471             mode->vtotal > vtotal_max)
15472                 return MODE_V_ILLEGAL;
15473
15474         return MODE_OK;
15475 }
15476
15477 static const struct drm_mode_config_funcs intel_mode_funcs = {
15478         .fb_create = intel_user_framebuffer_create,
15479         .get_format_info = intel_get_format_info,
15480         .output_poll_changed = intel_fbdev_output_poll_changed,
15481         .mode_valid = intel_mode_valid,
15482         .atomic_check = intel_atomic_check,
15483         .atomic_commit = intel_atomic_commit,
15484         .atomic_state_alloc = intel_atomic_state_alloc,
15485         .atomic_state_clear = intel_atomic_state_clear,
15486         .atomic_state_free = intel_atomic_state_free,
15487 };
15488
15489 /**
15490  * intel_init_display_hooks - initialize the display modesetting hooks
15491  * @dev_priv: device private
15492  */
15493 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
15494 {
15495         intel_init_cdclk_hooks(dev_priv);
15496
15497         if (INTEL_GEN(dev_priv) >= 9) {
15498                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
15499                 dev_priv->display.get_initial_plane_config =
15500                         skylake_get_initial_plane_config;
15501                 dev_priv->display.crtc_compute_clock =
15502                         haswell_crtc_compute_clock;
15503                 dev_priv->display.crtc_enable = haswell_crtc_enable;
15504                 dev_priv->display.crtc_disable = haswell_crtc_disable;
15505         } else if (HAS_DDI(dev_priv)) {
15506                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
15507                 dev_priv->display.get_initial_plane_config =
15508                         i9xx_get_initial_plane_config;
15509                 dev_priv->display.crtc_compute_clock =
15510                         haswell_crtc_compute_clock;
15511                 dev_priv->display.crtc_enable = haswell_crtc_enable;
15512                 dev_priv->display.crtc_disable = haswell_crtc_disable;
15513         } else if (HAS_PCH_SPLIT(dev_priv)) {
15514                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
15515                 dev_priv->display.get_initial_plane_config =
15516                         i9xx_get_initial_plane_config;
15517                 dev_priv->display.crtc_compute_clock =
15518                         ironlake_crtc_compute_clock;
15519                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
15520                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
15521         } else if (IS_CHERRYVIEW(dev_priv)) {
15522                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15523                 dev_priv->display.get_initial_plane_config =
15524                         i9xx_get_initial_plane_config;
15525                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
15526                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
15527                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15528         } else if (IS_VALLEYVIEW(dev_priv)) {
15529                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15530                 dev_priv->display.get_initial_plane_config =
15531                         i9xx_get_initial_plane_config;
15532                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
15533                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
15534                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15535         } else if (IS_G4X(dev_priv)) {
15536                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15537                 dev_priv->display.get_initial_plane_config =
15538                         i9xx_get_initial_plane_config;
15539                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
15540                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15541                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15542         } else if (IS_PINEVIEW(dev_priv)) {
15543                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15544                 dev_priv->display.get_initial_plane_config =
15545                         i9xx_get_initial_plane_config;
15546                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
15547                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15548                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15549         } else if (!IS_GEN(dev_priv, 2)) {
15550                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15551                 dev_priv->display.get_initial_plane_config =
15552                         i9xx_get_initial_plane_config;
15553                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
15554                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15555                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15556         } else {
15557                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15558                 dev_priv->display.get_initial_plane_config =
15559                         i9xx_get_initial_plane_config;
15560                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
15561                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15562                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15563         }
15564
15565         if (IS_GEN(dev_priv, 5)) {
15566                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
15567         } else if (IS_GEN(dev_priv, 6)) {
15568                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
15569         } else if (IS_IVYBRIDGE(dev_priv)) {
15570                 /* FIXME: detect B0+ stepping and use auto training */
15571                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
15572         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
15573                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
15574         }
15575
15576         if (INTEL_GEN(dev_priv) >= 9)
15577                 dev_priv->display.update_crtcs = skl_update_crtcs;
15578         else
15579                 dev_priv->display.update_crtcs = intel_update_crtcs;
15580 }
15581
15582 static i915_reg_t i915_vgacntrl_reg(struct drm_i915_private *dev_priv)
15583 {
15584         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
15585                 return VLV_VGACNTRL;
15586         else if (INTEL_GEN(dev_priv) >= 5)
15587                 return CPU_VGACNTRL;
15588         else
15589                 return VGACNTRL;
15590 }
15591
15592 /* Disable the VGA plane that we never use */
15593 static void i915_disable_vga(struct drm_i915_private *dev_priv)
15594 {
15595         struct pci_dev *pdev = dev_priv->drm.pdev;
15596         u8 sr1;
15597         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
15598
15599         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
15600         vga_get_uninterruptible(pdev, VGA_RSRC_LEGACY_IO);
15601         outb(SR01, VGA_SR_INDEX);
15602         sr1 = inb(VGA_SR_DATA);
15603         outb(sr1 | 1<<5, VGA_SR_DATA);
15604         vga_put(pdev, VGA_RSRC_LEGACY_IO);
15605         udelay(300);
15606
15607         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
15608         POSTING_READ(vga_reg);
15609 }
15610
15611 void intel_modeset_init_hw(struct drm_device *dev)
15612 {
15613         struct drm_i915_private *dev_priv = to_i915(dev);
15614
15615         intel_update_cdclk(dev_priv);
15616         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
15617         dev_priv->cdclk.logical = dev_priv->cdclk.actual = dev_priv->cdclk.hw;
15618 }
15619
15620 /*
15621  * Calculate what we think the watermarks should be for the state we've read
15622  * out of the hardware and then immediately program those watermarks so that
15623  * we ensure the hardware settings match our internal state.
15624  *
15625  * We can calculate what we think WM's should be by creating a duplicate of the
15626  * current state (which was constructed during hardware readout) and running it
15627  * through the atomic check code to calculate new watermark values in the
15628  * state object.
15629  */
15630 static void sanitize_watermarks(struct drm_device *dev)
15631 {
15632         struct drm_i915_private *dev_priv = to_i915(dev);
15633         struct drm_atomic_state *state;
15634         struct intel_atomic_state *intel_state;
15635         struct drm_crtc *crtc;
15636         struct drm_crtc_state *cstate;
15637         struct drm_modeset_acquire_ctx ctx;
15638         int ret;
15639         int i;
15640
15641         /* Only supported on platforms that use atomic watermark design */
15642         if (!dev_priv->display.optimize_watermarks)
15643                 return;
15644
15645         /*
15646          * We need to hold connection_mutex before calling duplicate_state so
15647          * that the connector loop is protected.
15648          */
15649         drm_modeset_acquire_init(&ctx, 0);
15650 retry:
15651         ret = drm_modeset_lock_all_ctx(dev, &ctx);
15652         if (ret == -EDEADLK) {
15653                 drm_modeset_backoff(&ctx);
15654                 goto retry;
15655         } else if (WARN_ON(ret)) {
15656                 goto fail;
15657         }
15658
15659         state = drm_atomic_helper_duplicate_state(dev, &ctx);
15660         if (WARN_ON(IS_ERR(state)))
15661                 goto fail;
15662
15663         intel_state = to_intel_atomic_state(state);
15664
15665         /*
15666          * Hardware readout is the only time we don't want to calculate
15667          * intermediate watermarks (since we don't trust the current
15668          * watermarks).
15669          */
15670         if (!HAS_GMCH(dev_priv))
15671                 intel_state->skip_intermediate_wm = true;
15672
15673         ret = intel_atomic_check(dev, state);
15674         if (ret) {
15675                 /*
15676                  * If we fail here, it means that the hardware appears to be
15677                  * programmed in a way that shouldn't be possible, given our
15678                  * understanding of watermark requirements.  This might mean a
15679                  * mistake in the hardware readout code or a mistake in the
15680                  * watermark calculations for a given platform.  Raise a WARN
15681                  * so that this is noticeable.
15682                  *
15683                  * If this actually happens, we'll have to just leave the
15684                  * BIOS-programmed watermarks untouched and hope for the best.
15685                  */
15686                 WARN(true, "Could not determine valid watermarks for inherited state\n");
15687                 goto put_state;
15688         }
15689
15690         /* Write calculated watermark values back */
15691         for_each_new_crtc_in_state(state, crtc, cstate, i) {
15692                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
15693
15694                 cs->wm.need_postvbl_update = true;
15695                 dev_priv->display.optimize_watermarks(intel_state, cs);
15696
15697                 to_intel_crtc_state(crtc->state)->wm = cs->wm;
15698         }
15699
15700 put_state:
15701         drm_atomic_state_put(state);
15702 fail:
15703         drm_modeset_drop_locks(&ctx);
15704         drm_modeset_acquire_fini(&ctx);
15705 }
15706
15707 static void intel_update_fdi_pll_freq(struct drm_i915_private *dev_priv)
15708 {
15709         if (IS_GEN(dev_priv, 5)) {
15710                 u32 fdi_pll_clk =
15711                         I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK;
15712
15713                 dev_priv->fdi_pll_freq = (fdi_pll_clk + 2) * 10000;
15714         } else if (IS_GEN(dev_priv, 6) || IS_IVYBRIDGE(dev_priv)) {
15715                 dev_priv->fdi_pll_freq = 270000;
15716         } else {
15717                 return;
15718         }
15719
15720         DRM_DEBUG_DRIVER("FDI PLL freq=%d\n", dev_priv->fdi_pll_freq);
15721 }
15722
15723 static int intel_initial_commit(struct drm_device *dev)
15724 {
15725         struct drm_atomic_state *state = NULL;
15726         struct drm_modeset_acquire_ctx ctx;
15727         struct drm_crtc *crtc;
15728         struct drm_crtc_state *crtc_state;
15729         int ret = 0;
15730
15731         state = drm_atomic_state_alloc(dev);
15732         if (!state)
15733                 return -ENOMEM;
15734
15735         drm_modeset_acquire_init(&ctx, 0);
15736
15737 retry:
15738         state->acquire_ctx = &ctx;
15739
15740         drm_for_each_crtc(crtc, dev) {
15741                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
15742                 if (IS_ERR(crtc_state)) {
15743                         ret = PTR_ERR(crtc_state);
15744                         goto out;
15745                 }
15746
15747                 if (crtc_state->active) {
15748                         ret = drm_atomic_add_affected_planes(state, crtc);
15749                         if (ret)
15750                                 goto out;
15751
15752                         /*
15753                          * FIXME hack to force a LUT update to avoid the
15754                          * plane update forcing the pipe gamma on without
15755                          * having a proper LUT loaded. Remove once we
15756                          * have readout for pipe gamma enable.
15757                          */
15758                         crtc_state->color_mgmt_changed = true;
15759                 }
15760         }
15761
15762         ret = drm_atomic_commit(state);
15763
15764 out:
15765         if (ret == -EDEADLK) {
15766                 drm_atomic_state_clear(state);
15767                 drm_modeset_backoff(&ctx);
15768                 goto retry;
15769         }
15770
15771         drm_atomic_state_put(state);
15772
15773         drm_modeset_drop_locks(&ctx);
15774         drm_modeset_acquire_fini(&ctx);
15775
15776         return ret;
15777 }
15778
15779 int intel_modeset_init(struct drm_device *dev)
15780 {
15781         struct drm_i915_private *dev_priv = to_i915(dev);
15782         struct i915_ggtt *ggtt = &dev_priv->ggtt;
15783         enum pipe pipe;
15784         struct intel_crtc *crtc;
15785         int ret;
15786
15787         dev_priv->modeset_wq = alloc_ordered_workqueue("i915_modeset", 0);
15788
15789         drm_mode_config_init(dev);
15790
15791         dev->mode_config.min_width = 0;
15792         dev->mode_config.min_height = 0;
15793
15794         dev->mode_config.preferred_depth = 24;
15795         dev->mode_config.prefer_shadow = 1;
15796
15797         dev->mode_config.allow_fb_modifiers = true;
15798
15799         dev->mode_config.funcs = &intel_mode_funcs;
15800
15801         init_llist_head(&dev_priv->atomic_helper.free_list);
15802         INIT_WORK(&dev_priv->atomic_helper.free_work,
15803                   intel_atomic_helper_free_state_worker);
15804
15805         intel_init_quirks(dev_priv);
15806
15807         intel_fbc_init(dev_priv);
15808
15809         intel_init_pm(dev_priv);
15810
15811         /*
15812          * There may be no VBT; and if the BIOS enabled SSC we can
15813          * just keep using it to avoid unnecessary flicker.  Whereas if the
15814          * BIOS isn't using it, don't assume it will work even if the VBT
15815          * indicates as much.
15816          */
15817         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv)) {
15818                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
15819                                             DREF_SSC1_ENABLE);
15820
15821                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
15822                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
15823                                      bios_lvds_use_ssc ? "en" : "dis",
15824                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
15825                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
15826                 }
15827         }
15828
15829         /*
15830          * Maximum framebuffer dimensions, chosen to match
15831          * the maximum render engine surface size on gen4+.
15832          */
15833         if (INTEL_GEN(dev_priv) >= 7) {
15834                 dev->mode_config.max_width = 16384;
15835                 dev->mode_config.max_height = 16384;
15836         } else if (INTEL_GEN(dev_priv) >= 4) {
15837                 dev->mode_config.max_width = 8192;
15838                 dev->mode_config.max_height = 8192;
15839         } else if (IS_GEN(dev_priv, 3)) {
15840                 dev->mode_config.max_width = 4096;
15841                 dev->mode_config.max_height = 4096;
15842         } else {
15843                 dev->mode_config.max_width = 2048;
15844                 dev->mode_config.max_height = 2048;
15845         }
15846
15847         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
15848                 dev->mode_config.cursor_width = IS_I845G(dev_priv) ? 64 : 512;
15849                 dev->mode_config.cursor_height = 1023;
15850         } else if (IS_GEN(dev_priv, 2)) {
15851                 dev->mode_config.cursor_width = 64;
15852                 dev->mode_config.cursor_height = 64;
15853         } else {
15854                 dev->mode_config.cursor_width = 256;
15855                 dev->mode_config.cursor_height = 256;
15856         }
15857
15858         dev->mode_config.fb_base = ggtt->gmadr.start;
15859
15860         DRM_DEBUG_KMS("%d display pipe%s available.\n",
15861                       INTEL_INFO(dev_priv)->num_pipes,
15862                       INTEL_INFO(dev_priv)->num_pipes > 1 ? "s" : "");
15863
15864         for_each_pipe(dev_priv, pipe) {
15865                 ret = intel_crtc_init(dev_priv, pipe);
15866                 if (ret) {
15867                         drm_mode_config_cleanup(dev);
15868                         return ret;
15869                 }
15870         }
15871
15872         intel_shared_dpll_init(dev);
15873         intel_update_fdi_pll_freq(dev_priv);
15874
15875         intel_update_czclk(dev_priv);
15876         intel_modeset_init_hw(dev);
15877
15878         intel_hdcp_component_init(dev_priv);
15879
15880         if (dev_priv->max_cdclk_freq == 0)
15881                 intel_update_max_cdclk(dev_priv);
15882
15883         /* Just disable it once at startup */
15884         i915_disable_vga(dev_priv);
15885         intel_setup_outputs(dev_priv);
15886
15887         drm_modeset_lock_all(dev);
15888         intel_modeset_setup_hw_state(dev, dev->mode_config.acquire_ctx);
15889         drm_modeset_unlock_all(dev);
15890
15891         for_each_intel_crtc(dev, crtc) {
15892                 struct intel_initial_plane_config plane_config = {};
15893
15894                 if (!crtc->active)
15895                         continue;
15896
15897                 /*
15898                  * Note that reserving the BIOS fb up front prevents us
15899                  * from stuffing other stolen allocations like the ring
15900                  * on top.  This prevents some ugliness at boot time, and
15901                  * can even allow for smooth boot transitions if the BIOS
15902                  * fb is large enough for the active pipe configuration.
15903                  */
15904                 dev_priv->display.get_initial_plane_config(crtc,
15905                                                            &plane_config);
15906
15907                 /*
15908                  * If the fb is shared between multiple heads, we'll
15909                  * just get the first one.
15910                  */
15911                 intel_find_initial_plane_obj(crtc, &plane_config);
15912         }
15913
15914         /*
15915          * Make sure hardware watermarks really match the state we read out.
15916          * Note that we need to do this after reconstructing the BIOS fb's
15917          * since the watermark calculation done here will use pstate->fb.
15918          */
15919         if (!HAS_GMCH(dev_priv))
15920                 sanitize_watermarks(dev);
15921
15922         /*
15923          * Force all active planes to recompute their states. So that on
15924          * mode_setcrtc after probe, all the intel_plane_state variables
15925          * are already calculated and there is no assert_plane warnings
15926          * during bootup.
15927          */
15928         ret = intel_initial_commit(dev);
15929         if (ret)
15930                 DRM_DEBUG_KMS("Initial commit in probe failed.\n");
15931
15932         return 0;
15933 }
15934
15935 void i830_enable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
15936 {
15937         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15938         /* 640x480@60Hz, ~25175 kHz */
15939         struct dpll clock = {
15940                 .m1 = 18,
15941                 .m2 = 7,
15942                 .p1 = 13,
15943                 .p2 = 4,
15944                 .n = 2,
15945         };
15946         u32 dpll, fp;
15947         int i;
15948
15949         WARN_ON(i9xx_calc_dpll_params(48000, &clock) != 25154);
15950
15951         DRM_DEBUG_KMS("enabling pipe %c due to force quirk (vco=%d dot=%d)\n",
15952                       pipe_name(pipe), clock.vco, clock.dot);
15953
15954         fp = i9xx_dpll_compute_fp(&clock);
15955         dpll = DPLL_DVO_2X_MODE |
15956                 DPLL_VGA_MODE_DIS |
15957                 ((clock.p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT) |
15958                 PLL_P2_DIVIDE_BY_4 |
15959                 PLL_REF_INPUT_DREFCLK |
15960                 DPLL_VCO_ENABLE;
15961
15962         I915_WRITE(FP0(pipe), fp);
15963         I915_WRITE(FP1(pipe), fp);
15964
15965         I915_WRITE(HTOTAL(pipe), (640 - 1) | ((800 - 1) << 16));
15966         I915_WRITE(HBLANK(pipe), (640 - 1) | ((800 - 1) << 16));
15967         I915_WRITE(HSYNC(pipe), (656 - 1) | ((752 - 1) << 16));
15968         I915_WRITE(VTOTAL(pipe), (480 - 1) | ((525 - 1) << 16));
15969         I915_WRITE(VBLANK(pipe), (480 - 1) | ((525 - 1) << 16));
15970         I915_WRITE(VSYNC(pipe), (490 - 1) | ((492 - 1) << 16));
15971         I915_WRITE(PIPESRC(pipe), ((640 - 1) << 16) | (480 - 1));
15972
15973         /*
15974          * Apparently we need to have VGA mode enabled prior to changing
15975          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
15976          * dividers, even though the register value does change.
15977          */
15978         I915_WRITE(DPLL(pipe), dpll & ~DPLL_VGA_MODE_DIS);
15979         I915_WRITE(DPLL(pipe), dpll);
15980
15981         /* Wait for the clocks to stabilize. */
15982         POSTING_READ(DPLL(pipe));
15983         udelay(150);
15984
15985         /* The pixel multiplier can only be updated once the
15986          * DPLL is enabled and the clocks are stable.
15987          *
15988          * So write it again.
15989          */
15990         I915_WRITE(DPLL(pipe), dpll);
15991
15992         /* We do this three times for luck */
15993         for (i = 0; i < 3 ; i++) {
15994                 I915_WRITE(DPLL(pipe), dpll);
15995                 POSTING_READ(DPLL(pipe));
15996                 udelay(150); /* wait for warmup */
15997         }
15998
15999         I915_WRITE(PIPECONF(pipe), PIPECONF_ENABLE | PIPECONF_PROGRESSIVE);
16000         POSTING_READ(PIPECONF(pipe));
16001
16002         intel_wait_for_pipe_scanline_moving(crtc);
16003 }
16004
16005 void i830_disable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
16006 {
16007         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
16008
16009         DRM_DEBUG_KMS("disabling pipe %c due to force quirk\n",
16010                       pipe_name(pipe));
16011
16012         WARN_ON(I915_READ(DSPCNTR(PLANE_A)) & DISPLAY_PLANE_ENABLE);
16013         WARN_ON(I915_READ(DSPCNTR(PLANE_B)) & DISPLAY_PLANE_ENABLE);
16014         WARN_ON(I915_READ(DSPCNTR(PLANE_C)) & DISPLAY_PLANE_ENABLE);
16015         WARN_ON(I915_READ(CURCNTR(PIPE_A)) & MCURSOR_MODE);
16016         WARN_ON(I915_READ(CURCNTR(PIPE_B)) & MCURSOR_MODE);
16017
16018         I915_WRITE(PIPECONF(pipe), 0);
16019         POSTING_READ(PIPECONF(pipe));
16020
16021         intel_wait_for_pipe_scanline_stopped(crtc);
16022
16023         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
16024         POSTING_READ(DPLL(pipe));
16025 }
16026
16027 static void
16028 intel_sanitize_plane_mapping(struct drm_i915_private *dev_priv)
16029 {
16030         struct intel_crtc *crtc;
16031
16032         if (INTEL_GEN(dev_priv) >= 4)
16033                 return;
16034
16035         for_each_intel_crtc(&dev_priv->drm, crtc) {
16036                 struct intel_plane *plane =
16037                         to_intel_plane(crtc->base.primary);
16038                 struct intel_crtc *plane_crtc;
16039                 enum pipe pipe;
16040
16041                 if (!plane->get_hw_state(plane, &pipe))
16042                         continue;
16043
16044                 if (pipe == crtc->pipe)
16045                         continue;
16046
16047                 DRM_DEBUG_KMS("[PLANE:%d:%s] attached to the wrong pipe, disabling plane\n",
16048                               plane->base.base.id, plane->base.name);
16049
16050                 plane_crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
16051                 intel_plane_disable_noatomic(plane_crtc, plane);
16052         }
16053 }
16054
16055 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
16056 {
16057         struct drm_device *dev = crtc->base.dev;
16058         struct intel_encoder *encoder;
16059
16060         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
16061                 return true;
16062
16063         return false;
16064 }
16065
16066 static struct intel_connector *intel_encoder_find_connector(struct intel_encoder *encoder)
16067 {
16068         struct drm_device *dev = encoder->base.dev;
16069         struct intel_connector *connector;
16070
16071         for_each_connector_on_encoder(dev, &encoder->base, connector)
16072                 return connector;
16073
16074         return NULL;
16075 }
16076
16077 static bool has_pch_trancoder(struct drm_i915_private *dev_priv,
16078                               enum pipe pch_transcoder)
16079 {
16080         return HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv) ||
16081                 (HAS_PCH_LPT_H(dev_priv) && pch_transcoder == PIPE_A);
16082 }
16083
16084 static void intel_sanitize_crtc(struct intel_crtc *crtc,
16085                                 struct drm_modeset_acquire_ctx *ctx)
16086 {
16087         struct drm_device *dev = crtc->base.dev;
16088         struct drm_i915_private *dev_priv = to_i915(dev);
16089         struct intel_crtc_state *crtc_state = to_intel_crtc_state(crtc->base.state);
16090         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
16091
16092         /* Clear any frame start delays used for debugging left by the BIOS */
16093         if (crtc->active && !transcoder_is_dsi(cpu_transcoder)) {
16094                 i915_reg_t reg = PIPECONF(cpu_transcoder);
16095
16096                 I915_WRITE(reg,
16097                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
16098         }
16099
16100         if (crtc_state->base.active) {
16101                 struct intel_plane *plane;
16102
16103                 /* Disable everything but the primary plane */
16104                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
16105                         const struct intel_plane_state *plane_state =
16106                                 to_intel_plane_state(plane->base.state);
16107
16108                         if (plane_state->base.visible &&
16109                             plane->base.type != DRM_PLANE_TYPE_PRIMARY)
16110                                 intel_plane_disable_noatomic(crtc, plane);
16111                 }
16112
16113                 /*
16114                  * Disable any background color set by the BIOS, but enable the
16115                  * gamma and CSC to match how we program our planes.
16116                  */
16117                 if (INTEL_GEN(dev_priv) >= 9)
16118                         I915_WRITE(SKL_BOTTOM_COLOR(crtc->pipe),
16119                                    SKL_BOTTOM_COLOR_GAMMA_ENABLE |
16120                                    SKL_BOTTOM_COLOR_CSC_ENABLE);
16121         }
16122
16123         /* Adjust the state of the output pipe according to whether we
16124          * have active connectors/encoders. */
16125         if (crtc_state->base.active && !intel_crtc_has_encoders(crtc))
16126                 intel_crtc_disable_noatomic(&crtc->base, ctx);
16127
16128         if (crtc_state->base.active || HAS_GMCH(dev_priv)) {
16129                 /*
16130                  * We start out with underrun reporting disabled to avoid races.
16131                  * For correct bookkeeping mark this on active crtcs.
16132                  *
16133                  * Also on gmch platforms we dont have any hardware bits to
16134                  * disable the underrun reporting. Which means we need to start
16135                  * out with underrun reporting disabled also on inactive pipes,
16136                  * since otherwise we'll complain about the garbage we read when
16137                  * e.g. coming up after runtime pm.
16138                  *
16139                  * No protection against concurrent access is required - at
16140                  * worst a fifo underrun happens which also sets this to false.
16141                  */
16142                 crtc->cpu_fifo_underrun_disabled = true;
16143                 /*
16144                  * We track the PCH trancoder underrun reporting state
16145                  * within the crtc. With crtc for pipe A housing the underrun
16146                  * reporting state for PCH transcoder A, crtc for pipe B housing
16147                  * it for PCH transcoder B, etc. LPT-H has only PCH transcoder A,
16148                  * and marking underrun reporting as disabled for the non-existing
16149                  * PCH transcoders B and C would prevent enabling the south
16150                  * error interrupt (see cpt_can_enable_serr_int()).
16151                  */
16152                 if (has_pch_trancoder(dev_priv, crtc->pipe))
16153                         crtc->pch_fifo_underrun_disabled = true;
16154         }
16155 }
16156
16157 static bool has_bogus_dpll_config(const struct intel_crtc_state *crtc_state)
16158 {
16159         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
16160
16161         /*
16162          * Some SNB BIOSen (eg. ASUS K53SV) are known to misprogram
16163          * the hardware when a high res displays plugged in. DPLL P
16164          * divider is zero, and the pipe timings are bonkers. We'll
16165          * try to disable everything in that case.
16166          *
16167          * FIXME would be nice to be able to sanitize this state
16168          * without several WARNs, but for now let's take the easy
16169          * road.
16170          */
16171         return IS_GEN(dev_priv, 6) &&
16172                 crtc_state->base.active &&
16173                 crtc_state->shared_dpll &&
16174                 crtc_state->port_clock == 0;
16175 }
16176
16177 static void intel_sanitize_encoder(struct intel_encoder *encoder)
16178 {
16179         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
16180         struct intel_connector *connector;
16181         struct intel_crtc *crtc = to_intel_crtc(encoder->base.crtc);
16182         struct intel_crtc_state *crtc_state = crtc ?
16183                 to_intel_crtc_state(crtc->base.state) : NULL;
16184
16185         /* We need to check both for a crtc link (meaning that the
16186          * encoder is active and trying to read from a pipe) and the
16187          * pipe itself being active. */
16188         bool has_active_crtc = crtc_state &&
16189                 crtc_state->base.active;
16190
16191         if (crtc_state && has_bogus_dpll_config(crtc_state)) {
16192                 DRM_DEBUG_KMS("BIOS has misprogrammed the hardware. Disabling pipe %c\n",
16193                               pipe_name(crtc->pipe));
16194                 has_active_crtc = false;
16195         }
16196
16197         connector = intel_encoder_find_connector(encoder);
16198         if (connector && !has_active_crtc) {
16199                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
16200                               encoder->base.base.id,
16201                               encoder->base.name);
16202
16203                 /* Connector is active, but has no active pipe. This is
16204                  * fallout from our resume register restoring. Disable
16205                  * the encoder manually again. */
16206                 if (crtc_state) {
16207                         struct drm_encoder *best_encoder;
16208
16209                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
16210                                       encoder->base.base.id,
16211                                       encoder->base.name);
16212
16213                         /* avoid oopsing in case the hooks consult best_encoder */
16214                         best_encoder = connector->base.state->best_encoder;
16215                         connector->base.state->best_encoder = &encoder->base;
16216
16217                         if (encoder->disable)
16218                                 encoder->disable(encoder, crtc_state,
16219                                                  connector->base.state);
16220                         if (encoder->post_disable)
16221                                 encoder->post_disable(encoder, crtc_state,
16222                                                       connector->base.state);
16223
16224                         connector->base.state->best_encoder = best_encoder;
16225                 }
16226                 encoder->base.crtc = NULL;
16227
16228                 /* Inconsistent output/port/pipe state happens presumably due to
16229                  * a bug in one of the get_hw_state functions. Or someplace else
16230                  * in our code, like the register restore mess on resume. Clamp
16231                  * things to off as a safer default. */
16232
16233                 connector->base.dpms = DRM_MODE_DPMS_OFF;
16234                 connector->base.encoder = NULL;
16235         }
16236
16237         /* notify opregion of the sanitized encoder state */
16238         intel_opregion_notify_encoder(encoder, connector && has_active_crtc);
16239
16240         if (INTEL_GEN(dev_priv) >= 11)
16241                 icl_sanitize_encoder_pll_mapping(encoder);
16242 }
16243
16244 void i915_redisable_vga_power_on(struct drm_i915_private *dev_priv)
16245 {
16246         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
16247
16248         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
16249                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
16250                 i915_disable_vga(dev_priv);
16251         }
16252 }
16253
16254 void i915_redisable_vga(struct drm_i915_private *dev_priv)
16255 {
16256         intel_wakeref_t wakeref;
16257
16258         /*
16259          * This function can be called both from intel_modeset_setup_hw_state or
16260          * at a very early point in our resume sequence, where the power well
16261          * structures are not yet restored. Since this function is at a very
16262          * paranoid "someone might have enabled VGA while we were not looking"
16263          * level, just check if the power well is enabled instead of trying to
16264          * follow the "don't touch the power well if we don't need it" policy
16265          * the rest of the driver uses.
16266          */
16267         wakeref = intel_display_power_get_if_enabled(dev_priv,
16268                                                      POWER_DOMAIN_VGA);
16269         if (!wakeref)
16270                 return;
16271
16272         i915_redisable_vga_power_on(dev_priv);
16273
16274         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA, wakeref);
16275 }
16276
16277 /* FIXME read out full plane state for all planes */
16278 static void readout_plane_state(struct drm_i915_private *dev_priv)
16279 {
16280         struct intel_plane *plane;
16281         struct intel_crtc *crtc;
16282
16283         for_each_intel_plane(&dev_priv->drm, plane) {
16284                 struct intel_plane_state *plane_state =
16285                         to_intel_plane_state(plane->base.state);
16286                 struct intel_crtc_state *crtc_state;
16287                 enum pipe pipe = PIPE_A;
16288                 bool visible;
16289
16290                 visible = plane->get_hw_state(plane, &pipe);
16291
16292                 crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
16293                 crtc_state = to_intel_crtc_state(crtc->base.state);
16294
16295                 intel_set_plane_visible(crtc_state, plane_state, visible);
16296
16297                 DRM_DEBUG_KMS("[PLANE:%d:%s] hw state readout: %s, pipe %c\n",
16298                               plane->base.base.id, plane->base.name,
16299                               enableddisabled(visible), pipe_name(pipe));
16300         }
16301
16302         for_each_intel_crtc(&dev_priv->drm, crtc) {
16303                 struct intel_crtc_state *crtc_state =
16304                         to_intel_crtc_state(crtc->base.state);
16305
16306                 fixup_active_planes(crtc_state);
16307         }
16308 }
16309
16310 static void intel_modeset_readout_hw_state(struct drm_device *dev)
16311 {
16312         struct drm_i915_private *dev_priv = to_i915(dev);
16313         enum pipe pipe;
16314         struct intel_crtc *crtc;
16315         struct intel_encoder *encoder;
16316         struct intel_connector *connector;
16317         struct drm_connector_list_iter conn_iter;
16318         int i;
16319
16320         dev_priv->active_crtcs = 0;
16321
16322         for_each_intel_crtc(dev, crtc) {
16323                 struct intel_crtc_state *crtc_state =
16324                         to_intel_crtc_state(crtc->base.state);
16325
16326                 __drm_atomic_helper_crtc_destroy_state(&crtc_state->base);
16327                 memset(crtc_state, 0, sizeof(*crtc_state));
16328                 __drm_atomic_helper_crtc_reset(&crtc->base, &crtc_state->base);
16329
16330                 crtc_state->base.active = crtc_state->base.enable =
16331                         dev_priv->display.get_pipe_config(crtc, crtc_state);
16332
16333                 crtc->base.enabled = crtc_state->base.enable;
16334                 crtc->active = crtc_state->base.active;
16335
16336                 if (crtc_state->base.active)
16337                         dev_priv->active_crtcs |= 1 << crtc->pipe;
16338
16339                 DRM_DEBUG_KMS("[CRTC:%d:%s] hw state readout: %s\n",
16340                               crtc->base.base.id, crtc->base.name,
16341                               enableddisabled(crtc_state->base.active));
16342         }
16343
16344         readout_plane_state(dev_priv);
16345
16346         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
16347                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
16348
16349                 pll->on = pll->info->funcs->get_hw_state(dev_priv, pll,
16350                                                         &pll->state.hw_state);
16351                 pll->state.crtc_mask = 0;
16352                 for_each_intel_crtc(dev, crtc) {
16353                         struct intel_crtc_state *crtc_state =
16354                                 to_intel_crtc_state(crtc->base.state);
16355
16356                         if (crtc_state->base.active &&
16357                             crtc_state->shared_dpll == pll)
16358                                 pll->state.crtc_mask |= 1 << crtc->pipe;
16359                 }
16360                 pll->active_mask = pll->state.crtc_mask;
16361
16362                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
16363                               pll->info->name, pll->state.crtc_mask, pll->on);
16364         }
16365
16366         for_each_intel_encoder(dev, encoder) {
16367                 pipe = 0;
16368
16369                 if (encoder->get_hw_state(encoder, &pipe)) {
16370                         struct intel_crtc_state *crtc_state;
16371
16372                         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
16373                         crtc_state = to_intel_crtc_state(crtc->base.state);
16374
16375                         encoder->base.crtc = &crtc->base;
16376                         encoder->get_config(encoder, crtc_state);
16377                 } else {
16378                         encoder->base.crtc = NULL;
16379                 }
16380
16381                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
16382                               encoder->base.base.id, encoder->base.name,
16383                               enableddisabled(encoder->base.crtc),
16384                               pipe_name(pipe));
16385         }
16386
16387         drm_connector_list_iter_begin(dev, &conn_iter);
16388         for_each_intel_connector_iter(connector, &conn_iter) {
16389                 if (connector->get_hw_state(connector)) {
16390                         connector->base.dpms = DRM_MODE_DPMS_ON;
16391
16392                         encoder = connector->encoder;
16393                         connector->base.encoder = &encoder->base;
16394
16395                         if (encoder->base.crtc &&
16396                             encoder->base.crtc->state->active) {
16397                                 /*
16398                                  * This has to be done during hardware readout
16399                                  * because anything calling .crtc_disable may
16400                                  * rely on the connector_mask being accurate.
16401                                  */
16402                                 encoder->base.crtc->state->connector_mask |=
16403                                         drm_connector_mask(&connector->base);
16404                                 encoder->base.crtc->state->encoder_mask |=
16405                                         drm_encoder_mask(&encoder->base);
16406                         }
16407
16408                 } else {
16409                         connector->base.dpms = DRM_MODE_DPMS_OFF;
16410                         connector->base.encoder = NULL;
16411                 }
16412                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
16413                               connector->base.base.id, connector->base.name,
16414                               enableddisabled(connector->base.encoder));
16415         }
16416         drm_connector_list_iter_end(&conn_iter);
16417
16418         for_each_intel_crtc(dev, crtc) {
16419                 struct intel_crtc_state *crtc_state =
16420                         to_intel_crtc_state(crtc->base.state);
16421                 int min_cdclk = 0;
16422
16423                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
16424                 if (crtc_state->base.active) {
16425                         intel_mode_from_pipe_config(&crtc->base.mode, crtc_state);
16426                         crtc->base.mode.hdisplay = crtc_state->pipe_src_w;
16427                         crtc->base.mode.vdisplay = crtc_state->pipe_src_h;
16428                         intel_mode_from_pipe_config(&crtc_state->base.adjusted_mode, crtc_state);
16429                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
16430
16431                         /*
16432                          * The initial mode needs to be set in order to keep
16433                          * the atomic core happy. It wants a valid mode if the
16434                          * crtc's enabled, so we do the above call.
16435                          *
16436                          * But we don't set all the derived state fully, hence
16437                          * set a flag to indicate that a full recalculation is
16438                          * needed on the next commit.
16439                          */
16440                         crtc_state->base.mode.private_flags = I915_MODE_FLAG_INHERITED;
16441
16442                         intel_crtc_compute_pixel_rate(crtc_state);
16443
16444                         if (dev_priv->display.modeset_calc_cdclk) {
16445                                 min_cdclk = intel_crtc_compute_min_cdclk(crtc_state);
16446                                 if (WARN_ON(min_cdclk < 0))
16447                                         min_cdclk = 0;
16448                         }
16449
16450                         drm_calc_timestamping_constants(&crtc->base,
16451                                                         &crtc_state->base.adjusted_mode);
16452                         update_scanline_offset(crtc_state);
16453                 }
16454
16455                 dev_priv->min_cdclk[crtc->pipe] = min_cdclk;
16456                 dev_priv->min_voltage_level[crtc->pipe] =
16457                         crtc_state->min_voltage_level;
16458
16459                 intel_pipe_config_sanity_check(dev_priv, crtc_state);
16460         }
16461 }
16462
16463 static void
16464 get_encoder_power_domains(struct drm_i915_private *dev_priv)
16465 {
16466         struct intel_encoder *encoder;
16467
16468         for_each_intel_encoder(&dev_priv->drm, encoder) {
16469                 struct intel_crtc_state *crtc_state;
16470
16471                 if (!encoder->get_power_domains)
16472                         continue;
16473
16474                 /*
16475                  * MST-primary and inactive encoders don't have a crtc state
16476                  * and neither of these require any power domain references.
16477                  */
16478                 if (!encoder->base.crtc)
16479                         continue;
16480
16481                 crtc_state = to_intel_crtc_state(encoder->base.crtc->state);
16482                 encoder->get_power_domains(encoder, crtc_state);
16483         }
16484 }
16485
16486 static void intel_early_display_was(struct drm_i915_private *dev_priv)
16487 {
16488         /* Display WA #1185 WaDisableDARBFClkGating:cnl,glk */
16489         if (IS_CANNONLAKE(dev_priv) || IS_GEMINILAKE(dev_priv))
16490                 I915_WRITE(GEN9_CLKGATE_DIS_0, I915_READ(GEN9_CLKGATE_DIS_0) |
16491                            DARBF_GATING_DIS);
16492
16493         if (IS_HASWELL(dev_priv)) {
16494                 /*
16495                  * WaRsPkgCStateDisplayPMReq:hsw
16496                  * System hang if this isn't done before disabling all planes!
16497                  */
16498                 I915_WRITE(CHICKEN_PAR1_1,
16499                            I915_READ(CHICKEN_PAR1_1) | FORCE_ARB_IDLE_PLANES);
16500         }
16501 }
16502
16503 static void ibx_sanitize_pch_hdmi_port(struct drm_i915_private *dev_priv,
16504                                        enum port port, i915_reg_t hdmi_reg)
16505 {
16506         u32 val = I915_READ(hdmi_reg);
16507
16508         if (val & SDVO_ENABLE ||
16509             (val & SDVO_PIPE_SEL_MASK) == SDVO_PIPE_SEL(PIPE_A))
16510                 return;
16511
16512         DRM_DEBUG_KMS("Sanitizing transcoder select for HDMI %c\n",
16513                       port_name(port));
16514
16515         val &= ~SDVO_PIPE_SEL_MASK;
16516         val |= SDVO_PIPE_SEL(PIPE_A);
16517
16518         I915_WRITE(hdmi_reg, val);
16519 }
16520
16521 static void ibx_sanitize_pch_dp_port(struct drm_i915_private *dev_priv,
16522                                      enum port port, i915_reg_t dp_reg)
16523 {
16524         u32 val = I915_READ(dp_reg);
16525
16526         if (val & DP_PORT_EN ||
16527             (val & DP_PIPE_SEL_MASK) == DP_PIPE_SEL(PIPE_A))
16528                 return;
16529
16530         DRM_DEBUG_KMS("Sanitizing transcoder select for DP %c\n",
16531                       port_name(port));
16532
16533         val &= ~DP_PIPE_SEL_MASK;
16534         val |= DP_PIPE_SEL(PIPE_A);
16535
16536         I915_WRITE(dp_reg, val);
16537 }
16538
16539 static void ibx_sanitize_pch_ports(struct drm_i915_private *dev_priv)
16540 {
16541         /*
16542          * The BIOS may select transcoder B on some of the PCH
16543          * ports even it doesn't enable the port. This would trip
16544          * assert_pch_dp_disabled() and assert_pch_hdmi_disabled().
16545          * Sanitize the transcoder select bits to prevent that. We
16546          * assume that the BIOS never actually enabled the port,
16547          * because if it did we'd actually have to toggle the port
16548          * on and back off to make the transcoder A select stick
16549          * (see. intel_dp_link_down(), intel_disable_hdmi(),
16550          * intel_disable_sdvo()).
16551          */
16552         ibx_sanitize_pch_dp_port(dev_priv, PORT_B, PCH_DP_B);
16553         ibx_sanitize_pch_dp_port(dev_priv, PORT_C, PCH_DP_C);
16554         ibx_sanitize_pch_dp_port(dev_priv, PORT_D, PCH_DP_D);
16555
16556         /* PCH SDVOB multiplex with HDMIB */
16557         ibx_sanitize_pch_hdmi_port(dev_priv, PORT_B, PCH_HDMIB);
16558         ibx_sanitize_pch_hdmi_port(dev_priv, PORT_C, PCH_HDMIC);
16559         ibx_sanitize_pch_hdmi_port(dev_priv, PORT_D, PCH_HDMID);
16560 }
16561
16562 /* Scan out the current hw modeset state,
16563  * and sanitizes it to the current state
16564  */
16565 static void
16566 intel_modeset_setup_hw_state(struct drm_device *dev,
16567                              struct drm_modeset_acquire_ctx *ctx)
16568 {
16569         struct drm_i915_private *dev_priv = to_i915(dev);
16570         struct intel_crtc_state *crtc_state;
16571         struct intel_encoder *encoder;
16572         struct intel_crtc *crtc;
16573         intel_wakeref_t wakeref;
16574         int i;
16575
16576         wakeref = intel_display_power_get(dev_priv, POWER_DOMAIN_INIT);
16577
16578         intel_early_display_was(dev_priv);
16579         intel_modeset_readout_hw_state(dev);
16580
16581         /* HW state is read out, now we need to sanitize this mess. */
16582         get_encoder_power_domains(dev_priv);
16583
16584         if (HAS_PCH_IBX(dev_priv))
16585                 ibx_sanitize_pch_ports(dev_priv);
16586
16587         /*
16588          * intel_sanitize_plane_mapping() may need to do vblank
16589          * waits, so we need vblank interrupts restored beforehand.
16590          */
16591         for_each_intel_crtc(&dev_priv->drm, crtc) {
16592                 crtc_state = to_intel_crtc_state(crtc->base.state);
16593
16594                 drm_crtc_vblank_reset(&crtc->base);
16595
16596                 if (crtc_state->base.active)
16597                         intel_crtc_vblank_on(crtc_state);
16598         }
16599
16600         intel_sanitize_plane_mapping(dev_priv);
16601
16602         for_each_intel_encoder(dev, encoder)
16603                 intel_sanitize_encoder(encoder);
16604
16605         for_each_intel_crtc(&dev_priv->drm, crtc) {
16606                 crtc_state = to_intel_crtc_state(crtc->base.state);
16607                 intel_sanitize_crtc(crtc, ctx);
16608                 intel_dump_pipe_config(crtc, crtc_state,
16609                                        "[setup_hw_state]");
16610         }
16611
16612         intel_modeset_update_connector_atomic_state(dev);
16613
16614         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
16615                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
16616
16617                 if (!pll->on || pll->active_mask)
16618                         continue;
16619
16620                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n",
16621                               pll->info->name);
16622
16623                 pll->info->funcs->disable(dev_priv, pll);
16624                 pll->on = false;
16625         }
16626
16627         if (IS_G4X(dev_priv)) {
16628                 g4x_wm_get_hw_state(dev_priv);
16629                 g4x_wm_sanitize(dev_priv);
16630         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
16631                 vlv_wm_get_hw_state(dev_priv);
16632                 vlv_wm_sanitize(dev_priv);
16633         } else if (INTEL_GEN(dev_priv) >= 9) {
16634                 skl_wm_get_hw_state(dev_priv);
16635         } else if (HAS_PCH_SPLIT(dev_priv)) {
16636                 ilk_wm_get_hw_state(dev_priv);
16637         }
16638
16639         for_each_intel_crtc(dev, crtc) {
16640                 u64 put_domains;
16641
16642                 crtc_state = to_intel_crtc_state(crtc->base.state);
16643                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc_state);
16644                 if (WARN_ON(put_domains))
16645                         modeset_put_power_domains(dev_priv, put_domains);
16646         }
16647
16648         intel_display_power_put(dev_priv, POWER_DOMAIN_INIT, wakeref);
16649
16650         intel_fbc_init_pipe_state(dev_priv);
16651 }
16652
16653 void intel_display_resume(struct drm_device *dev)
16654 {
16655         struct drm_i915_private *dev_priv = to_i915(dev);
16656         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
16657         struct drm_modeset_acquire_ctx ctx;
16658         int ret;
16659
16660         dev_priv->modeset_restore_state = NULL;
16661         if (state)
16662                 state->acquire_ctx = &ctx;
16663
16664         drm_modeset_acquire_init(&ctx, 0);
16665
16666         while (1) {
16667                 ret = drm_modeset_lock_all_ctx(dev, &ctx);
16668                 if (ret != -EDEADLK)
16669                         break;
16670
16671                 drm_modeset_backoff(&ctx);
16672         }
16673
16674         if (!ret)
16675                 ret = __intel_display_resume(dev, state, &ctx);
16676
16677         intel_enable_ipc(dev_priv);
16678         drm_modeset_drop_locks(&ctx);
16679         drm_modeset_acquire_fini(&ctx);
16680
16681         if (ret)
16682                 DRM_ERROR("Restoring old state failed with %i\n", ret);
16683         if (state)
16684                 drm_atomic_state_put(state);
16685 }
16686
16687 static void intel_hpd_poll_fini(struct drm_device *dev)
16688 {
16689         struct intel_connector *connector;
16690         struct drm_connector_list_iter conn_iter;
16691
16692         /* Kill all the work that may have been queued by hpd. */
16693         drm_connector_list_iter_begin(dev, &conn_iter);
16694         for_each_intel_connector_iter(connector, &conn_iter) {
16695                 if (connector->modeset_retry_work.func)
16696                         cancel_work_sync(&connector->modeset_retry_work);
16697                 if (connector->hdcp.shim) {
16698                         cancel_delayed_work_sync(&connector->hdcp.check_work);
16699                         cancel_work_sync(&connector->hdcp.prop_work);
16700                 }
16701         }
16702         drm_connector_list_iter_end(&conn_iter);
16703 }
16704
16705 void intel_modeset_cleanup(struct drm_device *dev)
16706 {
16707         struct drm_i915_private *dev_priv = to_i915(dev);
16708
16709         flush_workqueue(dev_priv->modeset_wq);
16710
16711         flush_work(&dev_priv->atomic_helper.free_work);
16712         WARN_ON(!llist_empty(&dev_priv->atomic_helper.free_list));
16713
16714         /*
16715          * Interrupts and polling as the first thing to avoid creating havoc.
16716          * Too much stuff here (turning of connectors, ...) would
16717          * experience fancy races otherwise.
16718          */
16719         intel_irq_uninstall(dev_priv);
16720
16721         /*
16722          * Due to the hpd irq storm handling the hotplug work can re-arm the
16723          * poll handlers. Hence disable polling after hpd handling is shut down.
16724          */
16725         intel_hpd_poll_fini(dev);
16726
16727         /* poll work can call into fbdev, hence clean that up afterwards */
16728         intel_fbdev_fini(dev_priv);
16729
16730         intel_unregister_dsm_handler();
16731
16732         intel_fbc_global_disable(dev_priv);
16733
16734         /* flush any delayed tasks or pending work */
16735         flush_scheduled_work();
16736
16737         intel_hdcp_component_fini(dev_priv);
16738
16739         drm_mode_config_cleanup(dev);
16740
16741         intel_overlay_cleanup(dev_priv);
16742
16743         intel_gmbus_teardown(dev_priv);
16744
16745         destroy_workqueue(dev_priv->modeset_wq);
16746
16747         intel_fbc_cleanup_cfb(dev_priv);
16748 }
16749
16750 /*
16751  * set vga decode state - true == enable VGA decode
16752  */
16753 int intel_modeset_vga_set_state(struct drm_i915_private *dev_priv, bool state)
16754 {
16755         unsigned reg = INTEL_GEN(dev_priv) >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
16756         u16 gmch_ctrl;
16757
16758         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
16759                 DRM_ERROR("failed to read control word\n");
16760                 return -EIO;
16761         }
16762
16763         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
16764                 return 0;
16765
16766         if (state)
16767                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
16768         else
16769                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
16770
16771         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
16772                 DRM_ERROR("failed to write control word\n");
16773                 return -EIO;
16774         }
16775
16776         return 0;
16777 }
16778
16779 #if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
16780
16781 struct intel_display_error_state {
16782
16783         u32 power_well_driver;
16784
16785         struct intel_cursor_error_state {
16786                 u32 control;
16787                 u32 position;
16788                 u32 base;
16789                 u32 size;
16790         } cursor[I915_MAX_PIPES];
16791
16792         struct intel_pipe_error_state {
16793                 bool power_domain_on;
16794                 u32 source;
16795                 u32 stat;
16796         } pipe[I915_MAX_PIPES];
16797
16798         struct intel_plane_error_state {
16799                 u32 control;
16800                 u32 stride;
16801                 u32 size;
16802                 u32 pos;
16803                 u32 addr;
16804                 u32 surface;
16805                 u32 tile_offset;
16806         } plane[I915_MAX_PIPES];
16807
16808         struct intel_transcoder_error_state {
16809                 bool available;
16810                 bool power_domain_on;
16811                 enum transcoder cpu_transcoder;
16812
16813                 u32 conf;
16814
16815                 u32 htotal;
16816                 u32 hblank;
16817                 u32 hsync;
16818                 u32 vtotal;
16819                 u32 vblank;
16820                 u32 vsync;
16821         } transcoder[4];
16822 };
16823
16824 struct intel_display_error_state *
16825 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
16826 {
16827         struct intel_display_error_state *error;
16828         int transcoders[] = {
16829                 TRANSCODER_A,
16830                 TRANSCODER_B,
16831                 TRANSCODER_C,
16832                 TRANSCODER_EDP,
16833         };
16834         int i;
16835
16836         BUILD_BUG_ON(ARRAY_SIZE(transcoders) != ARRAY_SIZE(error->transcoder));
16837
16838         if (!HAS_DISPLAY(dev_priv))
16839                 return NULL;
16840
16841         error = kzalloc(sizeof(*error), GFP_ATOMIC);
16842         if (error == NULL)
16843                 return NULL;
16844
16845         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
16846                 error->power_well_driver = I915_READ(HSW_PWR_WELL_CTL2);
16847
16848         for_each_pipe(dev_priv, i) {
16849                 error->pipe[i].power_domain_on =
16850                         __intel_display_power_is_enabled(dev_priv,
16851                                                          POWER_DOMAIN_PIPE(i));
16852                 if (!error->pipe[i].power_domain_on)
16853                         continue;
16854
16855                 error->cursor[i].control = I915_READ(CURCNTR(i));
16856                 error->cursor[i].position = I915_READ(CURPOS(i));
16857                 error->cursor[i].base = I915_READ(CURBASE(i));
16858
16859                 error->plane[i].control = I915_READ(DSPCNTR(i));
16860                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
16861                 if (INTEL_GEN(dev_priv) <= 3) {
16862                         error->plane[i].size = I915_READ(DSPSIZE(i));
16863                         error->plane[i].pos = I915_READ(DSPPOS(i));
16864                 }
16865                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
16866                         error->plane[i].addr = I915_READ(DSPADDR(i));
16867                 if (INTEL_GEN(dev_priv) >= 4) {
16868                         error->plane[i].surface = I915_READ(DSPSURF(i));
16869                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
16870                 }
16871
16872                 error->pipe[i].source = I915_READ(PIPESRC(i));
16873
16874                 if (HAS_GMCH(dev_priv))
16875                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
16876         }
16877
16878         for (i = 0; i < ARRAY_SIZE(error->transcoder); i++) {
16879                 enum transcoder cpu_transcoder = transcoders[i];
16880
16881                 if (!INTEL_INFO(dev_priv)->trans_offsets[cpu_transcoder])
16882                         continue;
16883
16884                 error->transcoder[i].available = true;
16885                 error->transcoder[i].power_domain_on =
16886                         __intel_display_power_is_enabled(dev_priv,
16887                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
16888                 if (!error->transcoder[i].power_domain_on)
16889                         continue;
16890
16891                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
16892
16893                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
16894                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
16895                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
16896                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
16897                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
16898                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
16899                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
16900         }
16901
16902         return error;
16903 }
16904
16905 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
16906
16907 void
16908 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
16909                                 struct intel_display_error_state *error)
16910 {
16911         struct drm_i915_private *dev_priv = m->i915;
16912         int i;
16913
16914         if (!error)
16915                 return;
16916
16917         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev_priv)->num_pipes);
16918         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
16919                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
16920                            error->power_well_driver);
16921         for_each_pipe(dev_priv, i) {
16922                 err_printf(m, "Pipe [%d]:\n", i);
16923                 err_printf(m, "  Power: %s\n",
16924                            onoff(error->pipe[i].power_domain_on));
16925                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
16926                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
16927
16928                 err_printf(m, "Plane [%d]:\n", i);
16929                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
16930                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
16931                 if (INTEL_GEN(dev_priv) <= 3) {
16932                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
16933                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
16934                 }
16935                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
16936                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
16937                 if (INTEL_GEN(dev_priv) >= 4) {
16938                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
16939                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
16940                 }
16941
16942                 err_printf(m, "Cursor [%d]:\n", i);
16943                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
16944                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
16945                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
16946         }
16947
16948         for (i = 0; i < ARRAY_SIZE(error->transcoder); i++) {
16949                 if (!error->transcoder[i].available)
16950                         continue;
16951
16952                 err_printf(m, "CPU transcoder: %s\n",
16953                            transcoder_name(error->transcoder[i].cpu_transcoder));
16954                 err_printf(m, "  Power: %s\n",
16955                            onoff(error->transcoder[i].power_domain_on));
16956                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
16957                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
16958                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
16959                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
16960                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
16961                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
16962                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
16963         }
16964 }
16965
16966 #endif