drm/i915: Overcome display engine stride limits via GTT remapping
[sfrench/cifs-2.6.git] / drivers / gpu / drm / i915 / intel_display.c
1 /*
2  * Copyright © 2006-2007 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *      Eric Anholt <eric@anholt.net>
25  */
26
27 #include <linux/i2c.h>
28 #include <linux/input.h>
29 #include <linux/intel-iommu.h>
30 #include <linux/kernel.h>
31 #include <linux/module.h>
32 #include <linux/reservation.h>
33 #include <linux/slab.h>
34 #include <linux/vgaarb.h>
35
36 #include <drm/drm_atomic.h>
37 #include <drm/drm_atomic_helper.h>
38 #include <drm/drm_atomic_uapi.h>
39 #include <drm/drm_dp_helper.h>
40 #include <drm/drm_edid.h>
41 #include <drm/drm_fourcc.h>
42 #include <drm/drm_plane_helper.h>
43 #include <drm/drm_probe_helper.h>
44 #include <drm/drm_rect.h>
45 #include <drm/i915_drm.h>
46
47 #include "i915_drv.h"
48 #include "i915_gem_clflush.h"
49 #include "i915_trace.h"
50 #include "intel_acpi.h"
51 #include "intel_atomic.h"
52 #include "intel_atomic_plane.h"
53 #include "intel_color.h"
54 #include "intel_cdclk.h"
55 #include "intel_crt.h"
56 #include "intel_ddi.h"
57 #include "intel_dp.h"
58 #include "intel_drv.h"
59 #include "intel_dsi.h"
60 #include "intel_dvo.h"
61 #include "intel_fbc.h"
62 #include "intel_fbdev.h"
63 #include "intel_fifo_underrun.h"
64 #include "intel_frontbuffer.h"
65 #include "intel_gmbus.h"
66 #include "intel_hdcp.h"
67 #include "intel_hdmi.h"
68 #include "intel_hotplug.h"
69 #include "intel_lvds.h"
70 #include "intel_overlay.h"
71 #include "intel_pipe_crc.h"
72 #include "intel_pm.h"
73 #include "intel_psr.h"
74 #include "intel_quirks.h"
75 #include "intel_sdvo.h"
76 #include "intel_sideband.h"
77 #include "intel_sprite.h"
78 #include "intel_tv.h"
79 #include "intel_vdsc.h"
80
81 /* Primary plane formats for gen <= 3 */
82 static const u32 i8xx_primary_formats[] = {
83         DRM_FORMAT_C8,
84         DRM_FORMAT_RGB565,
85         DRM_FORMAT_XRGB1555,
86         DRM_FORMAT_XRGB8888,
87 };
88
89 /* Primary plane formats for gen >= 4 */
90 static const u32 i965_primary_formats[] = {
91         DRM_FORMAT_C8,
92         DRM_FORMAT_RGB565,
93         DRM_FORMAT_XRGB8888,
94         DRM_FORMAT_XBGR8888,
95         DRM_FORMAT_XRGB2101010,
96         DRM_FORMAT_XBGR2101010,
97 };
98
99 static const u64 i9xx_format_modifiers[] = {
100         I915_FORMAT_MOD_X_TILED,
101         DRM_FORMAT_MOD_LINEAR,
102         DRM_FORMAT_MOD_INVALID
103 };
104
105 /* Cursor formats */
106 static const u32 intel_cursor_formats[] = {
107         DRM_FORMAT_ARGB8888,
108 };
109
110 static const u64 cursor_format_modifiers[] = {
111         DRM_FORMAT_MOD_LINEAR,
112         DRM_FORMAT_MOD_INVALID
113 };
114
115 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
116                                 struct intel_crtc_state *pipe_config);
117 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
118                                    struct intel_crtc_state *pipe_config);
119
120 static int intel_framebuffer_init(struct intel_framebuffer *ifb,
121                                   struct drm_i915_gem_object *obj,
122                                   struct drm_mode_fb_cmd2 *mode_cmd);
123 static void intel_set_pipe_timings(const struct intel_crtc_state *crtc_state);
124 static void intel_set_pipe_src_size(const struct intel_crtc_state *crtc_state);
125 static void intel_cpu_transcoder_set_m_n(const struct intel_crtc_state *crtc_state,
126                                          const struct intel_link_m_n *m_n,
127                                          const struct intel_link_m_n *m2_n2);
128 static void i9xx_set_pipeconf(const struct intel_crtc_state *crtc_state);
129 static void ironlake_set_pipeconf(const struct intel_crtc_state *crtc_state);
130 static void haswell_set_pipeconf(const struct intel_crtc_state *crtc_state);
131 static void bdw_set_pipemisc(const struct intel_crtc_state *crtc_state);
132 static void vlv_prepare_pll(struct intel_crtc *crtc,
133                             const struct intel_crtc_state *pipe_config);
134 static void chv_prepare_pll(struct intel_crtc *crtc,
135                             const struct intel_crtc_state *pipe_config);
136 static void intel_begin_crtc_commit(struct intel_atomic_state *, struct intel_crtc *);
137 static void intel_finish_crtc_commit(struct intel_atomic_state *, struct intel_crtc *);
138 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
139                                     struct intel_crtc_state *crtc_state);
140 static void skylake_pfit_enable(const struct intel_crtc_state *crtc_state);
141 static void ironlake_pfit_disable(const struct intel_crtc_state *old_crtc_state);
142 static void ironlake_pfit_enable(const struct intel_crtc_state *crtc_state);
143 static void intel_modeset_setup_hw_state(struct drm_device *dev,
144                                          struct drm_modeset_acquire_ctx *ctx);
145 static void intel_pre_disable_primary_noatomic(struct drm_crtc *crtc);
146
147 struct intel_limit {
148         struct {
149                 int min, max;
150         } dot, vco, n, m, m1, m2, p, p1;
151
152         struct {
153                 int dot_limit;
154                 int p2_slow, p2_fast;
155         } p2;
156 };
157
158 /* returns HPLL frequency in kHz */
159 int vlv_get_hpll_vco(struct drm_i915_private *dev_priv)
160 {
161         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
162
163         /* Obtain SKU information */
164         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
165                 CCK_FUSE_HPLL_FREQ_MASK;
166
167         return vco_freq[hpll_freq] * 1000;
168 }
169
170 int vlv_get_cck_clock(struct drm_i915_private *dev_priv,
171                       const char *name, u32 reg, int ref_freq)
172 {
173         u32 val;
174         int divider;
175
176         val = vlv_cck_read(dev_priv, reg);
177         divider = val & CCK_FREQUENCY_VALUES;
178
179         WARN((val & CCK_FREQUENCY_STATUS) !=
180              (divider << CCK_FREQUENCY_STATUS_SHIFT),
181              "%s change in progress\n", name);
182
183         return DIV_ROUND_CLOSEST(ref_freq << 1, divider + 1);
184 }
185
186 int vlv_get_cck_clock_hpll(struct drm_i915_private *dev_priv,
187                            const char *name, u32 reg)
188 {
189         int hpll;
190
191         vlv_cck_get(dev_priv);
192
193         if (dev_priv->hpll_freq == 0)
194                 dev_priv->hpll_freq = vlv_get_hpll_vco(dev_priv);
195
196         hpll = vlv_get_cck_clock(dev_priv, name, reg, dev_priv->hpll_freq);
197
198         vlv_cck_put(dev_priv);
199
200         return hpll;
201 }
202
203 static void intel_update_czclk(struct drm_i915_private *dev_priv)
204 {
205         if (!(IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)))
206                 return;
207
208         dev_priv->czclk_freq = vlv_get_cck_clock_hpll(dev_priv, "czclk",
209                                                       CCK_CZ_CLOCK_CONTROL);
210
211         DRM_DEBUG_DRIVER("CZ clock rate: %d kHz\n", dev_priv->czclk_freq);
212 }
213
214 static inline u32 /* units of 100MHz */
215 intel_fdi_link_freq(struct drm_i915_private *dev_priv,
216                     const struct intel_crtc_state *pipe_config)
217 {
218         if (HAS_DDI(dev_priv))
219                 return pipe_config->port_clock; /* SPLL */
220         else
221                 return dev_priv->fdi_pll_freq;
222 }
223
224 static const struct intel_limit intel_limits_i8xx_dac = {
225         .dot = { .min = 25000, .max = 350000 },
226         .vco = { .min = 908000, .max = 1512000 },
227         .n = { .min = 2, .max = 16 },
228         .m = { .min = 96, .max = 140 },
229         .m1 = { .min = 18, .max = 26 },
230         .m2 = { .min = 6, .max = 16 },
231         .p = { .min = 4, .max = 128 },
232         .p1 = { .min = 2, .max = 33 },
233         .p2 = { .dot_limit = 165000,
234                 .p2_slow = 4, .p2_fast = 2 },
235 };
236
237 static const struct intel_limit intel_limits_i8xx_dvo = {
238         .dot = { .min = 25000, .max = 350000 },
239         .vco = { .min = 908000, .max = 1512000 },
240         .n = { .min = 2, .max = 16 },
241         .m = { .min = 96, .max = 140 },
242         .m1 = { .min = 18, .max = 26 },
243         .m2 = { .min = 6, .max = 16 },
244         .p = { .min = 4, .max = 128 },
245         .p1 = { .min = 2, .max = 33 },
246         .p2 = { .dot_limit = 165000,
247                 .p2_slow = 4, .p2_fast = 4 },
248 };
249
250 static const struct intel_limit intel_limits_i8xx_lvds = {
251         .dot = { .min = 25000, .max = 350000 },
252         .vco = { .min = 908000, .max = 1512000 },
253         .n = { .min = 2, .max = 16 },
254         .m = { .min = 96, .max = 140 },
255         .m1 = { .min = 18, .max = 26 },
256         .m2 = { .min = 6, .max = 16 },
257         .p = { .min = 4, .max = 128 },
258         .p1 = { .min = 1, .max = 6 },
259         .p2 = { .dot_limit = 165000,
260                 .p2_slow = 14, .p2_fast = 7 },
261 };
262
263 static const struct intel_limit intel_limits_i9xx_sdvo = {
264         .dot = { .min = 20000, .max = 400000 },
265         .vco = { .min = 1400000, .max = 2800000 },
266         .n = { .min = 1, .max = 6 },
267         .m = { .min = 70, .max = 120 },
268         .m1 = { .min = 8, .max = 18 },
269         .m2 = { .min = 3, .max = 7 },
270         .p = { .min = 5, .max = 80 },
271         .p1 = { .min = 1, .max = 8 },
272         .p2 = { .dot_limit = 200000,
273                 .p2_slow = 10, .p2_fast = 5 },
274 };
275
276 static const struct intel_limit intel_limits_i9xx_lvds = {
277         .dot = { .min = 20000, .max = 400000 },
278         .vco = { .min = 1400000, .max = 2800000 },
279         .n = { .min = 1, .max = 6 },
280         .m = { .min = 70, .max = 120 },
281         .m1 = { .min = 8, .max = 18 },
282         .m2 = { .min = 3, .max = 7 },
283         .p = { .min = 7, .max = 98 },
284         .p1 = { .min = 1, .max = 8 },
285         .p2 = { .dot_limit = 112000,
286                 .p2_slow = 14, .p2_fast = 7 },
287 };
288
289
290 static const struct intel_limit intel_limits_g4x_sdvo = {
291         .dot = { .min = 25000, .max = 270000 },
292         .vco = { .min = 1750000, .max = 3500000},
293         .n = { .min = 1, .max = 4 },
294         .m = { .min = 104, .max = 138 },
295         .m1 = { .min = 17, .max = 23 },
296         .m2 = { .min = 5, .max = 11 },
297         .p = { .min = 10, .max = 30 },
298         .p1 = { .min = 1, .max = 3},
299         .p2 = { .dot_limit = 270000,
300                 .p2_slow = 10,
301                 .p2_fast = 10
302         },
303 };
304
305 static const struct intel_limit intel_limits_g4x_hdmi = {
306         .dot = { .min = 22000, .max = 400000 },
307         .vco = { .min = 1750000, .max = 3500000},
308         .n = { .min = 1, .max = 4 },
309         .m = { .min = 104, .max = 138 },
310         .m1 = { .min = 16, .max = 23 },
311         .m2 = { .min = 5, .max = 11 },
312         .p = { .min = 5, .max = 80 },
313         .p1 = { .min = 1, .max = 8},
314         .p2 = { .dot_limit = 165000,
315                 .p2_slow = 10, .p2_fast = 5 },
316 };
317
318 static const struct intel_limit intel_limits_g4x_single_channel_lvds = {
319         .dot = { .min = 20000, .max = 115000 },
320         .vco = { .min = 1750000, .max = 3500000 },
321         .n = { .min = 1, .max = 3 },
322         .m = { .min = 104, .max = 138 },
323         .m1 = { .min = 17, .max = 23 },
324         .m2 = { .min = 5, .max = 11 },
325         .p = { .min = 28, .max = 112 },
326         .p1 = { .min = 2, .max = 8 },
327         .p2 = { .dot_limit = 0,
328                 .p2_slow = 14, .p2_fast = 14
329         },
330 };
331
332 static const struct intel_limit intel_limits_g4x_dual_channel_lvds = {
333         .dot = { .min = 80000, .max = 224000 },
334         .vco = { .min = 1750000, .max = 3500000 },
335         .n = { .min = 1, .max = 3 },
336         .m = { .min = 104, .max = 138 },
337         .m1 = { .min = 17, .max = 23 },
338         .m2 = { .min = 5, .max = 11 },
339         .p = { .min = 14, .max = 42 },
340         .p1 = { .min = 2, .max = 6 },
341         .p2 = { .dot_limit = 0,
342                 .p2_slow = 7, .p2_fast = 7
343         },
344 };
345
346 static const struct intel_limit intel_limits_pineview_sdvo = {
347         .dot = { .min = 20000, .max = 400000},
348         .vco = { .min = 1700000, .max = 3500000 },
349         /* Pineview's Ncounter is a ring counter */
350         .n = { .min = 3, .max = 6 },
351         .m = { .min = 2, .max = 256 },
352         /* Pineview only has one combined m divider, which we treat as m2. */
353         .m1 = { .min = 0, .max = 0 },
354         .m2 = { .min = 0, .max = 254 },
355         .p = { .min = 5, .max = 80 },
356         .p1 = { .min = 1, .max = 8 },
357         .p2 = { .dot_limit = 200000,
358                 .p2_slow = 10, .p2_fast = 5 },
359 };
360
361 static const struct intel_limit intel_limits_pineview_lvds = {
362         .dot = { .min = 20000, .max = 400000 },
363         .vco = { .min = 1700000, .max = 3500000 },
364         .n = { .min = 3, .max = 6 },
365         .m = { .min = 2, .max = 256 },
366         .m1 = { .min = 0, .max = 0 },
367         .m2 = { .min = 0, .max = 254 },
368         .p = { .min = 7, .max = 112 },
369         .p1 = { .min = 1, .max = 8 },
370         .p2 = { .dot_limit = 112000,
371                 .p2_slow = 14, .p2_fast = 14 },
372 };
373
374 /* Ironlake / Sandybridge
375  *
376  * We calculate clock using (register_value + 2) for N/M1/M2, so here
377  * the range value for them is (actual_value - 2).
378  */
379 static const struct intel_limit intel_limits_ironlake_dac = {
380         .dot = { .min = 25000, .max = 350000 },
381         .vco = { .min = 1760000, .max = 3510000 },
382         .n = { .min = 1, .max = 5 },
383         .m = { .min = 79, .max = 127 },
384         .m1 = { .min = 12, .max = 22 },
385         .m2 = { .min = 5, .max = 9 },
386         .p = { .min = 5, .max = 80 },
387         .p1 = { .min = 1, .max = 8 },
388         .p2 = { .dot_limit = 225000,
389                 .p2_slow = 10, .p2_fast = 5 },
390 };
391
392 static const struct intel_limit intel_limits_ironlake_single_lvds = {
393         .dot = { .min = 25000, .max = 350000 },
394         .vco = { .min = 1760000, .max = 3510000 },
395         .n = { .min = 1, .max = 3 },
396         .m = { .min = 79, .max = 118 },
397         .m1 = { .min = 12, .max = 22 },
398         .m2 = { .min = 5, .max = 9 },
399         .p = { .min = 28, .max = 112 },
400         .p1 = { .min = 2, .max = 8 },
401         .p2 = { .dot_limit = 225000,
402                 .p2_slow = 14, .p2_fast = 14 },
403 };
404
405 static const struct intel_limit intel_limits_ironlake_dual_lvds = {
406         .dot = { .min = 25000, .max = 350000 },
407         .vco = { .min = 1760000, .max = 3510000 },
408         .n = { .min = 1, .max = 3 },
409         .m = { .min = 79, .max = 127 },
410         .m1 = { .min = 12, .max = 22 },
411         .m2 = { .min = 5, .max = 9 },
412         .p = { .min = 14, .max = 56 },
413         .p1 = { .min = 2, .max = 8 },
414         .p2 = { .dot_limit = 225000,
415                 .p2_slow = 7, .p2_fast = 7 },
416 };
417
418 /* LVDS 100mhz refclk limits. */
419 static const struct intel_limit intel_limits_ironlake_single_lvds_100m = {
420         .dot = { .min = 25000, .max = 350000 },
421         .vco = { .min = 1760000, .max = 3510000 },
422         .n = { .min = 1, .max = 2 },
423         .m = { .min = 79, .max = 126 },
424         .m1 = { .min = 12, .max = 22 },
425         .m2 = { .min = 5, .max = 9 },
426         .p = { .min = 28, .max = 112 },
427         .p1 = { .min = 2, .max = 8 },
428         .p2 = { .dot_limit = 225000,
429                 .p2_slow = 14, .p2_fast = 14 },
430 };
431
432 static const struct intel_limit intel_limits_ironlake_dual_lvds_100m = {
433         .dot = { .min = 25000, .max = 350000 },
434         .vco = { .min = 1760000, .max = 3510000 },
435         .n = { .min = 1, .max = 3 },
436         .m = { .min = 79, .max = 126 },
437         .m1 = { .min = 12, .max = 22 },
438         .m2 = { .min = 5, .max = 9 },
439         .p = { .min = 14, .max = 42 },
440         .p1 = { .min = 2, .max = 6 },
441         .p2 = { .dot_limit = 225000,
442                 .p2_slow = 7, .p2_fast = 7 },
443 };
444
445 static const struct intel_limit intel_limits_vlv = {
446          /*
447           * These are the data rate limits (measured in fast clocks)
448           * since those are the strictest limits we have. The fast
449           * clock and actual rate limits are more relaxed, so checking
450           * them would make no difference.
451           */
452         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
453         .vco = { .min = 4000000, .max = 6000000 },
454         .n = { .min = 1, .max = 7 },
455         .m1 = { .min = 2, .max = 3 },
456         .m2 = { .min = 11, .max = 156 },
457         .p1 = { .min = 2, .max = 3 },
458         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
459 };
460
461 static const struct intel_limit intel_limits_chv = {
462         /*
463          * These are the data rate limits (measured in fast clocks)
464          * since those are the strictest limits we have.  The fast
465          * clock and actual rate limits are more relaxed, so checking
466          * them would make no difference.
467          */
468         .dot = { .min = 25000 * 5, .max = 540000 * 5},
469         .vco = { .min = 4800000, .max = 6480000 },
470         .n = { .min = 1, .max = 1 },
471         .m1 = { .min = 2, .max = 2 },
472         .m2 = { .min = 24 << 22, .max = 175 << 22 },
473         .p1 = { .min = 2, .max = 4 },
474         .p2 = { .p2_slow = 1, .p2_fast = 14 },
475 };
476
477 static const struct intel_limit intel_limits_bxt = {
478         /* FIXME: find real dot limits */
479         .dot = { .min = 0, .max = INT_MAX },
480         .vco = { .min = 4800000, .max = 6700000 },
481         .n = { .min = 1, .max = 1 },
482         .m1 = { .min = 2, .max = 2 },
483         /* FIXME: find real m2 limits */
484         .m2 = { .min = 2 << 22, .max = 255 << 22 },
485         .p1 = { .min = 2, .max = 4 },
486         .p2 = { .p2_slow = 1, .p2_fast = 20 },
487 };
488
489 /* WA Display #0827: Gen9:all */
490 static void
491 skl_wa_827(struct drm_i915_private *dev_priv, int pipe, bool enable)
492 {
493         if (enable)
494                 I915_WRITE(CLKGATE_DIS_PSL(pipe),
495                            I915_READ(CLKGATE_DIS_PSL(pipe)) |
496                            DUPS1_GATING_DIS | DUPS2_GATING_DIS);
497         else
498                 I915_WRITE(CLKGATE_DIS_PSL(pipe),
499                            I915_READ(CLKGATE_DIS_PSL(pipe)) &
500                            ~(DUPS1_GATING_DIS | DUPS2_GATING_DIS));
501 }
502
503 /* Wa_2006604312:icl */
504 static void
505 icl_wa_scalerclkgating(struct drm_i915_private *dev_priv, enum pipe pipe,
506                        bool enable)
507 {
508         if (enable)
509                 I915_WRITE(CLKGATE_DIS_PSL(pipe),
510                            I915_READ(CLKGATE_DIS_PSL(pipe)) | DPFR_GATING_DIS);
511         else
512                 I915_WRITE(CLKGATE_DIS_PSL(pipe),
513                            I915_READ(CLKGATE_DIS_PSL(pipe)) & ~DPFR_GATING_DIS);
514 }
515
516 static bool
517 needs_modeset(const struct drm_crtc_state *state)
518 {
519         return drm_atomic_crtc_needs_modeset(state);
520 }
521
522 /*
523  * Platform specific helpers to calculate the port PLL loopback- (clock.m),
524  * and post-divider (clock.p) values, pre- (clock.vco) and post-divided fast
525  * (clock.dot) clock rates. This fast dot clock is fed to the port's IO logic.
526  * The helpers' return value is the rate of the clock that is fed to the
527  * display engine's pipe which can be the above fast dot clock rate or a
528  * divided-down version of it.
529  */
530 /* m1 is reserved as 0 in Pineview, n is a ring counter */
531 static int pnv_calc_dpll_params(int refclk, struct dpll *clock)
532 {
533         clock->m = clock->m2 + 2;
534         clock->p = clock->p1 * clock->p2;
535         if (WARN_ON(clock->n == 0 || clock->p == 0))
536                 return 0;
537         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
538         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
539
540         return clock->dot;
541 }
542
543 static u32 i9xx_dpll_compute_m(struct dpll *dpll)
544 {
545         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
546 }
547
548 static int i9xx_calc_dpll_params(int refclk, struct dpll *clock)
549 {
550         clock->m = i9xx_dpll_compute_m(clock);
551         clock->p = clock->p1 * clock->p2;
552         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
553                 return 0;
554         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
555         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
556
557         return clock->dot;
558 }
559
560 static int vlv_calc_dpll_params(int refclk, struct dpll *clock)
561 {
562         clock->m = clock->m1 * clock->m2;
563         clock->p = clock->p1 * clock->p2;
564         if (WARN_ON(clock->n == 0 || clock->p == 0))
565                 return 0;
566         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
567         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
568
569         return clock->dot / 5;
570 }
571
572 int chv_calc_dpll_params(int refclk, struct dpll *clock)
573 {
574         clock->m = clock->m1 * clock->m2;
575         clock->p = clock->p1 * clock->p2;
576         if (WARN_ON(clock->n == 0 || clock->p == 0))
577                 return 0;
578         clock->vco = DIV_ROUND_CLOSEST_ULL(mul_u32_u32(refclk, clock->m),
579                                            clock->n << 22);
580         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
581
582         return clock->dot / 5;
583 }
584
585 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
586
587 /*
588  * Returns whether the given set of divisors are valid for a given refclk with
589  * the given connectors.
590  */
591 static bool intel_PLL_is_valid(struct drm_i915_private *dev_priv,
592                                const struct intel_limit *limit,
593                                const struct dpll *clock)
594 {
595         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
596                 INTELPllInvalid("n out of range\n");
597         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
598                 INTELPllInvalid("p1 out of range\n");
599         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
600                 INTELPllInvalid("m2 out of range\n");
601         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
602                 INTELPllInvalid("m1 out of range\n");
603
604         if (!IS_PINEVIEW(dev_priv) && !IS_VALLEYVIEW(dev_priv) &&
605             !IS_CHERRYVIEW(dev_priv) && !IS_GEN9_LP(dev_priv))
606                 if (clock->m1 <= clock->m2)
607                         INTELPllInvalid("m1 <= m2\n");
608
609         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
610             !IS_GEN9_LP(dev_priv)) {
611                 if (clock->p < limit->p.min || limit->p.max < clock->p)
612                         INTELPllInvalid("p out of range\n");
613                 if (clock->m < limit->m.min || limit->m.max < clock->m)
614                         INTELPllInvalid("m out of range\n");
615         }
616
617         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
618                 INTELPllInvalid("vco out of range\n");
619         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
620          * connector, etc., rather than just a single range.
621          */
622         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
623                 INTELPllInvalid("dot out of range\n");
624
625         return true;
626 }
627
628 static int
629 i9xx_select_p2_div(const struct intel_limit *limit,
630                    const struct intel_crtc_state *crtc_state,
631                    int target)
632 {
633         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
634
635         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
636                 /*
637                  * For LVDS just rely on its current settings for dual-channel.
638                  * We haven't figured out how to reliably set up different
639                  * single/dual channel state, if we even can.
640                  */
641                 if (intel_is_dual_link_lvds(dev_priv))
642                         return limit->p2.p2_fast;
643                 else
644                         return limit->p2.p2_slow;
645         } else {
646                 if (target < limit->p2.dot_limit)
647                         return limit->p2.p2_slow;
648                 else
649                         return limit->p2.p2_fast;
650         }
651 }
652
653 /*
654  * Returns a set of divisors for the desired target clock with the given
655  * refclk, or FALSE.  The returned values represent the clock equation:
656  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
657  *
658  * Target and reference clocks are specified in kHz.
659  *
660  * If match_clock is provided, then best_clock P divider must match the P
661  * divider from @match_clock used for LVDS downclocking.
662  */
663 static bool
664 i9xx_find_best_dpll(const struct intel_limit *limit,
665                     struct intel_crtc_state *crtc_state,
666                     int target, int refclk, struct dpll *match_clock,
667                     struct dpll *best_clock)
668 {
669         struct drm_device *dev = crtc_state->base.crtc->dev;
670         struct dpll clock;
671         int err = target;
672
673         memset(best_clock, 0, sizeof(*best_clock));
674
675         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
676
677         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
678              clock.m1++) {
679                 for (clock.m2 = limit->m2.min;
680                      clock.m2 <= limit->m2.max; clock.m2++) {
681                         if (clock.m2 >= clock.m1)
682                                 break;
683                         for (clock.n = limit->n.min;
684                              clock.n <= limit->n.max; clock.n++) {
685                                 for (clock.p1 = limit->p1.min;
686                                         clock.p1 <= limit->p1.max; clock.p1++) {
687                                         int this_err;
688
689                                         i9xx_calc_dpll_params(refclk, &clock);
690                                         if (!intel_PLL_is_valid(to_i915(dev),
691                                                                 limit,
692                                                                 &clock))
693                                                 continue;
694                                         if (match_clock &&
695                                             clock.p != match_clock->p)
696                                                 continue;
697
698                                         this_err = abs(clock.dot - target);
699                                         if (this_err < err) {
700                                                 *best_clock = clock;
701                                                 err = this_err;
702                                         }
703                                 }
704                         }
705                 }
706         }
707
708         return (err != target);
709 }
710
711 /*
712  * Returns a set of divisors for the desired target clock with the given
713  * refclk, or FALSE.  The returned values represent the clock equation:
714  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
715  *
716  * Target and reference clocks are specified in kHz.
717  *
718  * If match_clock is provided, then best_clock P divider must match the P
719  * divider from @match_clock used for LVDS downclocking.
720  */
721 static bool
722 pnv_find_best_dpll(const struct intel_limit *limit,
723                    struct intel_crtc_state *crtc_state,
724                    int target, int refclk, struct dpll *match_clock,
725                    struct dpll *best_clock)
726 {
727         struct drm_device *dev = crtc_state->base.crtc->dev;
728         struct dpll clock;
729         int err = target;
730
731         memset(best_clock, 0, sizeof(*best_clock));
732
733         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
734
735         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
736              clock.m1++) {
737                 for (clock.m2 = limit->m2.min;
738                      clock.m2 <= limit->m2.max; clock.m2++) {
739                         for (clock.n = limit->n.min;
740                              clock.n <= limit->n.max; clock.n++) {
741                                 for (clock.p1 = limit->p1.min;
742                                         clock.p1 <= limit->p1.max; clock.p1++) {
743                                         int this_err;
744
745                                         pnv_calc_dpll_params(refclk, &clock);
746                                         if (!intel_PLL_is_valid(to_i915(dev),
747                                                                 limit,
748                                                                 &clock))
749                                                 continue;
750                                         if (match_clock &&
751                                             clock.p != match_clock->p)
752                                                 continue;
753
754                                         this_err = abs(clock.dot - target);
755                                         if (this_err < err) {
756                                                 *best_clock = clock;
757                                                 err = this_err;
758                                         }
759                                 }
760                         }
761                 }
762         }
763
764         return (err != target);
765 }
766
767 /*
768  * Returns a set of divisors for the desired target clock with the given
769  * refclk, or FALSE.  The returned values represent the clock equation:
770  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
771  *
772  * Target and reference clocks are specified in kHz.
773  *
774  * If match_clock is provided, then best_clock P divider must match the P
775  * divider from @match_clock used for LVDS downclocking.
776  */
777 static bool
778 g4x_find_best_dpll(const struct intel_limit *limit,
779                    struct intel_crtc_state *crtc_state,
780                    int target, int refclk, struct dpll *match_clock,
781                    struct dpll *best_clock)
782 {
783         struct drm_device *dev = crtc_state->base.crtc->dev;
784         struct dpll clock;
785         int max_n;
786         bool found = false;
787         /* approximately equals target * 0.00585 */
788         int err_most = (target >> 8) + (target >> 9);
789
790         memset(best_clock, 0, sizeof(*best_clock));
791
792         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
793
794         max_n = limit->n.max;
795         /* based on hardware requirement, prefer smaller n to precision */
796         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
797                 /* based on hardware requirement, prefere larger m1,m2 */
798                 for (clock.m1 = limit->m1.max;
799                      clock.m1 >= limit->m1.min; clock.m1--) {
800                         for (clock.m2 = limit->m2.max;
801                              clock.m2 >= limit->m2.min; clock.m2--) {
802                                 for (clock.p1 = limit->p1.max;
803                                      clock.p1 >= limit->p1.min; clock.p1--) {
804                                         int this_err;
805
806                                         i9xx_calc_dpll_params(refclk, &clock);
807                                         if (!intel_PLL_is_valid(to_i915(dev),
808                                                                 limit,
809                                                                 &clock))
810                                                 continue;
811
812                                         this_err = abs(clock.dot - target);
813                                         if (this_err < err_most) {
814                                                 *best_clock = clock;
815                                                 err_most = this_err;
816                                                 max_n = clock.n;
817                                                 found = true;
818                                         }
819                                 }
820                         }
821                 }
822         }
823         return found;
824 }
825
826 /*
827  * Check if the calculated PLL configuration is more optimal compared to the
828  * best configuration and error found so far. Return the calculated error.
829  */
830 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
831                                const struct dpll *calculated_clock,
832                                const struct dpll *best_clock,
833                                unsigned int best_error_ppm,
834                                unsigned int *error_ppm)
835 {
836         /*
837          * For CHV ignore the error and consider only the P value.
838          * Prefer a bigger P value based on HW requirements.
839          */
840         if (IS_CHERRYVIEW(to_i915(dev))) {
841                 *error_ppm = 0;
842
843                 return calculated_clock->p > best_clock->p;
844         }
845
846         if (WARN_ON_ONCE(!target_freq))
847                 return false;
848
849         *error_ppm = div_u64(1000000ULL *
850                                 abs(target_freq - calculated_clock->dot),
851                              target_freq);
852         /*
853          * Prefer a better P value over a better (smaller) error if the error
854          * is small. Ensure this preference for future configurations too by
855          * setting the error to 0.
856          */
857         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
858                 *error_ppm = 0;
859
860                 return true;
861         }
862
863         return *error_ppm + 10 < best_error_ppm;
864 }
865
866 /*
867  * Returns a set of divisors for the desired target clock with the given
868  * refclk, or FALSE.  The returned values represent the clock equation:
869  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
870  */
871 static bool
872 vlv_find_best_dpll(const struct intel_limit *limit,
873                    struct intel_crtc_state *crtc_state,
874                    int target, int refclk, struct dpll *match_clock,
875                    struct dpll *best_clock)
876 {
877         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
878         struct drm_device *dev = crtc->base.dev;
879         struct dpll clock;
880         unsigned int bestppm = 1000000;
881         /* min update 19.2 MHz */
882         int max_n = min(limit->n.max, refclk / 19200);
883         bool found = false;
884
885         target *= 5; /* fast clock */
886
887         memset(best_clock, 0, sizeof(*best_clock));
888
889         /* based on hardware requirement, prefer smaller n to precision */
890         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
891                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
892                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
893                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
894                                 clock.p = clock.p1 * clock.p2;
895                                 /* based on hardware requirement, prefer bigger m1,m2 values */
896                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
897                                         unsigned int ppm;
898
899                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
900                                                                      refclk * clock.m1);
901
902                                         vlv_calc_dpll_params(refclk, &clock);
903
904                                         if (!intel_PLL_is_valid(to_i915(dev),
905                                                                 limit,
906                                                                 &clock))
907                                                 continue;
908
909                                         if (!vlv_PLL_is_optimal(dev, target,
910                                                                 &clock,
911                                                                 best_clock,
912                                                                 bestppm, &ppm))
913                                                 continue;
914
915                                         *best_clock = clock;
916                                         bestppm = ppm;
917                                         found = true;
918                                 }
919                         }
920                 }
921         }
922
923         return found;
924 }
925
926 /*
927  * Returns a set of divisors for the desired target clock with the given
928  * refclk, or FALSE.  The returned values represent the clock equation:
929  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
930  */
931 static bool
932 chv_find_best_dpll(const struct intel_limit *limit,
933                    struct intel_crtc_state *crtc_state,
934                    int target, int refclk, struct dpll *match_clock,
935                    struct dpll *best_clock)
936 {
937         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
938         struct drm_device *dev = crtc->base.dev;
939         unsigned int best_error_ppm;
940         struct dpll clock;
941         u64 m2;
942         int found = false;
943
944         memset(best_clock, 0, sizeof(*best_clock));
945         best_error_ppm = 1000000;
946
947         /*
948          * Based on hardware doc, the n always set to 1, and m1 always
949          * set to 2.  If requires to support 200Mhz refclk, we need to
950          * revisit this because n may not 1 anymore.
951          */
952         clock.n = 1, clock.m1 = 2;
953         target *= 5;    /* fast clock */
954
955         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
956                 for (clock.p2 = limit->p2.p2_fast;
957                                 clock.p2 >= limit->p2.p2_slow;
958                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
959                         unsigned int error_ppm;
960
961                         clock.p = clock.p1 * clock.p2;
962
963                         m2 = DIV_ROUND_CLOSEST_ULL(mul_u32_u32(target, clock.p * clock.n) << 22,
964                                                    refclk * clock.m1);
965
966                         if (m2 > INT_MAX/clock.m1)
967                                 continue;
968
969                         clock.m2 = m2;
970
971                         chv_calc_dpll_params(refclk, &clock);
972
973                         if (!intel_PLL_is_valid(to_i915(dev), limit, &clock))
974                                 continue;
975
976                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
977                                                 best_error_ppm, &error_ppm))
978                                 continue;
979
980                         *best_clock = clock;
981                         best_error_ppm = error_ppm;
982                         found = true;
983                 }
984         }
985
986         return found;
987 }
988
989 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state,
990                         struct dpll *best_clock)
991 {
992         int refclk = 100000;
993         const struct intel_limit *limit = &intel_limits_bxt;
994
995         return chv_find_best_dpll(limit, crtc_state,
996                                   crtc_state->port_clock, refclk,
997                                   NULL, best_clock);
998 }
999
1000 bool intel_crtc_active(struct intel_crtc *crtc)
1001 {
1002         /* Be paranoid as we can arrive here with only partial
1003          * state retrieved from the hardware during setup.
1004          *
1005          * We can ditch the adjusted_mode.crtc_clock check as soon
1006          * as Haswell has gained clock readout/fastboot support.
1007          *
1008          * We can ditch the crtc->primary->state->fb check as soon as we can
1009          * properly reconstruct framebuffers.
1010          *
1011          * FIXME: The intel_crtc->active here should be switched to
1012          * crtc->state->active once we have proper CRTC states wired up
1013          * for atomic.
1014          */
1015         return crtc->active && crtc->base.primary->state->fb &&
1016                 crtc->config->base.adjusted_mode.crtc_clock;
1017 }
1018
1019 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
1020                                              enum pipe pipe)
1021 {
1022         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
1023
1024         return crtc->config->cpu_transcoder;
1025 }
1026
1027 static bool pipe_scanline_is_moving(struct drm_i915_private *dev_priv,
1028                                     enum pipe pipe)
1029 {
1030         i915_reg_t reg = PIPEDSL(pipe);
1031         u32 line1, line2;
1032         u32 line_mask;
1033
1034         if (IS_GEN(dev_priv, 2))
1035                 line_mask = DSL_LINEMASK_GEN2;
1036         else
1037                 line_mask = DSL_LINEMASK_GEN3;
1038
1039         line1 = I915_READ(reg) & line_mask;
1040         msleep(5);
1041         line2 = I915_READ(reg) & line_mask;
1042
1043         return line1 != line2;
1044 }
1045
1046 static void wait_for_pipe_scanline_moving(struct intel_crtc *crtc, bool state)
1047 {
1048         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1049         enum pipe pipe = crtc->pipe;
1050
1051         /* Wait for the display line to settle/start moving */
1052         if (wait_for(pipe_scanline_is_moving(dev_priv, pipe) == state, 100))
1053                 DRM_ERROR("pipe %c scanline %s wait timed out\n",
1054                           pipe_name(pipe), onoff(state));
1055 }
1056
1057 static void intel_wait_for_pipe_scanline_stopped(struct intel_crtc *crtc)
1058 {
1059         wait_for_pipe_scanline_moving(crtc, false);
1060 }
1061
1062 static void intel_wait_for_pipe_scanline_moving(struct intel_crtc *crtc)
1063 {
1064         wait_for_pipe_scanline_moving(crtc, true);
1065 }
1066
1067 static void
1068 intel_wait_for_pipe_off(const struct intel_crtc_state *old_crtc_state)
1069 {
1070         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
1071         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1072
1073         if (INTEL_GEN(dev_priv) >= 4) {
1074                 enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
1075                 i915_reg_t reg = PIPECONF(cpu_transcoder);
1076
1077                 /* Wait for the Pipe State to go off */
1078                 if (intel_wait_for_register(&dev_priv->uncore,
1079                                             reg, I965_PIPECONF_ACTIVE, 0,
1080                                             100))
1081                         WARN(1, "pipe_off wait timed out\n");
1082         } else {
1083                 intel_wait_for_pipe_scanline_stopped(crtc);
1084         }
1085 }
1086
1087 /* Only for pre-ILK configs */
1088 void assert_pll(struct drm_i915_private *dev_priv,
1089                 enum pipe pipe, bool state)
1090 {
1091         u32 val;
1092         bool cur_state;
1093
1094         val = I915_READ(DPLL(pipe));
1095         cur_state = !!(val & DPLL_VCO_ENABLE);
1096         I915_STATE_WARN(cur_state != state,
1097              "PLL state assertion failure (expected %s, current %s)\n",
1098                         onoff(state), onoff(cur_state));
1099 }
1100
1101 /* XXX: the dsi pll is shared between MIPI DSI ports */
1102 void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1103 {
1104         u32 val;
1105         bool cur_state;
1106
1107         vlv_cck_get(dev_priv);
1108         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1109         vlv_cck_put(dev_priv);
1110
1111         cur_state = val & DSI_PLL_VCO_EN;
1112         I915_STATE_WARN(cur_state != state,
1113              "DSI PLL state assertion failure (expected %s, current %s)\n",
1114                         onoff(state), onoff(cur_state));
1115 }
1116
1117 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1118                           enum pipe pipe, bool state)
1119 {
1120         bool cur_state;
1121         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1122                                                                       pipe);
1123
1124         if (HAS_DDI(dev_priv)) {
1125                 /* DDI does not have a specific FDI_TX register */
1126                 u32 val = I915_READ(TRANS_DDI_FUNC_CTL(cpu_transcoder));
1127                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1128         } else {
1129                 u32 val = I915_READ(FDI_TX_CTL(pipe));
1130                 cur_state = !!(val & FDI_TX_ENABLE);
1131         }
1132         I915_STATE_WARN(cur_state != state,
1133              "FDI TX state assertion failure (expected %s, current %s)\n",
1134                         onoff(state), onoff(cur_state));
1135 }
1136 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1137 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1138
1139 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1140                           enum pipe pipe, bool state)
1141 {
1142         u32 val;
1143         bool cur_state;
1144
1145         val = I915_READ(FDI_RX_CTL(pipe));
1146         cur_state = !!(val & FDI_RX_ENABLE);
1147         I915_STATE_WARN(cur_state != state,
1148              "FDI RX state assertion failure (expected %s, current %s)\n",
1149                         onoff(state), onoff(cur_state));
1150 }
1151 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1152 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1153
1154 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1155                                       enum pipe pipe)
1156 {
1157         u32 val;
1158
1159         /* ILK FDI PLL is always enabled */
1160         if (IS_GEN(dev_priv, 5))
1161                 return;
1162
1163         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1164         if (HAS_DDI(dev_priv))
1165                 return;
1166
1167         val = I915_READ(FDI_TX_CTL(pipe));
1168         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1169 }
1170
1171 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1172                        enum pipe pipe, bool state)
1173 {
1174         u32 val;
1175         bool cur_state;
1176
1177         val = I915_READ(FDI_RX_CTL(pipe));
1178         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1179         I915_STATE_WARN(cur_state != state,
1180              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1181                         onoff(state), onoff(cur_state));
1182 }
1183
1184 void assert_panel_unlocked(struct drm_i915_private *dev_priv, enum pipe pipe)
1185 {
1186         i915_reg_t pp_reg;
1187         u32 val;
1188         enum pipe panel_pipe = INVALID_PIPE;
1189         bool locked = true;
1190
1191         if (WARN_ON(HAS_DDI(dev_priv)))
1192                 return;
1193
1194         if (HAS_PCH_SPLIT(dev_priv)) {
1195                 u32 port_sel;
1196
1197                 pp_reg = PP_CONTROL(0);
1198                 port_sel = I915_READ(PP_ON_DELAYS(0)) & PANEL_PORT_SELECT_MASK;
1199
1200                 switch (port_sel) {
1201                 case PANEL_PORT_SELECT_LVDS:
1202                         intel_lvds_port_enabled(dev_priv, PCH_LVDS, &panel_pipe);
1203                         break;
1204                 case PANEL_PORT_SELECT_DPA:
1205                         intel_dp_port_enabled(dev_priv, DP_A, PORT_A, &panel_pipe);
1206                         break;
1207                 case PANEL_PORT_SELECT_DPC:
1208                         intel_dp_port_enabled(dev_priv, PCH_DP_C, PORT_C, &panel_pipe);
1209                         break;
1210                 case PANEL_PORT_SELECT_DPD:
1211                         intel_dp_port_enabled(dev_priv, PCH_DP_D, PORT_D, &panel_pipe);
1212                         break;
1213                 default:
1214                         MISSING_CASE(port_sel);
1215                         break;
1216                 }
1217         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
1218                 /* presumably write lock depends on pipe, not port select */
1219                 pp_reg = PP_CONTROL(pipe);
1220                 panel_pipe = pipe;
1221         } else {
1222                 u32 port_sel;
1223
1224                 pp_reg = PP_CONTROL(0);
1225                 port_sel = I915_READ(PP_ON_DELAYS(0)) & PANEL_PORT_SELECT_MASK;
1226
1227                 WARN_ON(port_sel != PANEL_PORT_SELECT_LVDS);
1228                 intel_lvds_port_enabled(dev_priv, LVDS, &panel_pipe);
1229         }
1230
1231         val = I915_READ(pp_reg);
1232         if (!(val & PANEL_POWER_ON) ||
1233             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1234                 locked = false;
1235
1236         I915_STATE_WARN(panel_pipe == pipe && locked,
1237              "panel assertion failure, pipe %c regs locked\n",
1238              pipe_name(pipe));
1239 }
1240
1241 void assert_pipe(struct drm_i915_private *dev_priv,
1242                  enum pipe pipe, bool state)
1243 {
1244         bool cur_state;
1245         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1246                                                                       pipe);
1247         enum intel_display_power_domain power_domain;
1248         intel_wakeref_t wakeref;
1249
1250         /* we keep both pipes enabled on 830 */
1251         if (IS_I830(dev_priv))
1252                 state = true;
1253
1254         power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
1255         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
1256         if (wakeref) {
1257                 u32 val = I915_READ(PIPECONF(cpu_transcoder));
1258                 cur_state = !!(val & PIPECONF_ENABLE);
1259
1260                 intel_display_power_put(dev_priv, power_domain, wakeref);
1261         } else {
1262                 cur_state = false;
1263         }
1264
1265         I915_STATE_WARN(cur_state != state,
1266              "pipe %c assertion failure (expected %s, current %s)\n",
1267                         pipe_name(pipe), onoff(state), onoff(cur_state));
1268 }
1269
1270 static void assert_plane(struct intel_plane *plane, bool state)
1271 {
1272         enum pipe pipe;
1273         bool cur_state;
1274
1275         cur_state = plane->get_hw_state(plane, &pipe);
1276
1277         I915_STATE_WARN(cur_state != state,
1278                         "%s assertion failure (expected %s, current %s)\n",
1279                         plane->base.name, onoff(state), onoff(cur_state));
1280 }
1281
1282 #define assert_plane_enabled(p) assert_plane(p, true)
1283 #define assert_plane_disabled(p) assert_plane(p, false)
1284
1285 static void assert_planes_disabled(struct intel_crtc *crtc)
1286 {
1287         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1288         struct intel_plane *plane;
1289
1290         for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, plane)
1291                 assert_plane_disabled(plane);
1292 }
1293
1294 static void assert_vblank_disabled(struct drm_crtc *crtc)
1295 {
1296         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1297                 drm_crtc_vblank_put(crtc);
1298 }
1299
1300 void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1301                                     enum pipe pipe)
1302 {
1303         u32 val;
1304         bool enabled;
1305
1306         val = I915_READ(PCH_TRANSCONF(pipe));
1307         enabled = !!(val & TRANS_ENABLE);
1308         I915_STATE_WARN(enabled,
1309              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1310              pipe_name(pipe));
1311 }
1312
1313 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1314                                    enum pipe pipe, enum port port,
1315                                    i915_reg_t dp_reg)
1316 {
1317         enum pipe port_pipe;
1318         bool state;
1319
1320         state = intel_dp_port_enabled(dev_priv, dp_reg, port, &port_pipe);
1321
1322         I915_STATE_WARN(state && port_pipe == pipe,
1323                         "PCH DP %c enabled on transcoder %c, should be disabled\n",
1324                         port_name(port), pipe_name(pipe));
1325
1326         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && !state && port_pipe == PIPE_B,
1327                         "IBX PCH DP %c still using transcoder B\n",
1328                         port_name(port));
1329 }
1330
1331 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1332                                      enum pipe pipe, enum port port,
1333                                      i915_reg_t hdmi_reg)
1334 {
1335         enum pipe port_pipe;
1336         bool state;
1337
1338         state = intel_sdvo_port_enabled(dev_priv, hdmi_reg, &port_pipe);
1339
1340         I915_STATE_WARN(state && port_pipe == pipe,
1341                         "PCH HDMI %c enabled on transcoder %c, should be disabled\n",
1342                         port_name(port), pipe_name(pipe));
1343
1344         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && !state && port_pipe == PIPE_B,
1345                         "IBX PCH HDMI %c still using transcoder B\n",
1346                         port_name(port));
1347 }
1348
1349 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1350                                       enum pipe pipe)
1351 {
1352         enum pipe port_pipe;
1353
1354         assert_pch_dp_disabled(dev_priv, pipe, PORT_B, PCH_DP_B);
1355         assert_pch_dp_disabled(dev_priv, pipe, PORT_C, PCH_DP_C);
1356         assert_pch_dp_disabled(dev_priv, pipe, PORT_D, PCH_DP_D);
1357
1358         I915_STATE_WARN(intel_crt_port_enabled(dev_priv, PCH_ADPA, &port_pipe) &&
1359                         port_pipe == pipe,
1360                         "PCH VGA enabled on transcoder %c, should be disabled\n",
1361                         pipe_name(pipe));
1362
1363         I915_STATE_WARN(intel_lvds_port_enabled(dev_priv, PCH_LVDS, &port_pipe) &&
1364                         port_pipe == pipe,
1365                         "PCH LVDS enabled on transcoder %c, should be disabled\n",
1366                         pipe_name(pipe));
1367
1368         /* PCH SDVOB multiplex with HDMIB */
1369         assert_pch_hdmi_disabled(dev_priv, pipe, PORT_B, PCH_HDMIB);
1370         assert_pch_hdmi_disabled(dev_priv, pipe, PORT_C, PCH_HDMIC);
1371         assert_pch_hdmi_disabled(dev_priv, pipe, PORT_D, PCH_HDMID);
1372 }
1373
1374 static void _vlv_enable_pll(struct intel_crtc *crtc,
1375                             const struct intel_crtc_state *pipe_config)
1376 {
1377         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1378         enum pipe pipe = crtc->pipe;
1379
1380         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1381         POSTING_READ(DPLL(pipe));
1382         udelay(150);
1383
1384         if (intel_wait_for_register(&dev_priv->uncore,
1385                                     DPLL(pipe),
1386                                     DPLL_LOCK_VLV,
1387                                     DPLL_LOCK_VLV,
1388                                     1))
1389                 DRM_ERROR("DPLL %d failed to lock\n", pipe);
1390 }
1391
1392 static void vlv_enable_pll(struct intel_crtc *crtc,
1393                            const struct intel_crtc_state *pipe_config)
1394 {
1395         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1396         enum pipe pipe = crtc->pipe;
1397
1398         assert_pipe_disabled(dev_priv, pipe);
1399
1400         /* PLL is protected by panel, make sure we can write it */
1401         assert_panel_unlocked(dev_priv, pipe);
1402
1403         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1404                 _vlv_enable_pll(crtc, pipe_config);
1405
1406         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1407         POSTING_READ(DPLL_MD(pipe));
1408 }
1409
1410
1411 static void _chv_enable_pll(struct intel_crtc *crtc,
1412                             const struct intel_crtc_state *pipe_config)
1413 {
1414         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1415         enum pipe pipe = crtc->pipe;
1416         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1417         u32 tmp;
1418
1419         vlv_dpio_get(dev_priv);
1420
1421         /* Enable back the 10bit clock to display controller */
1422         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1423         tmp |= DPIO_DCLKP_EN;
1424         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1425
1426         vlv_dpio_put(dev_priv);
1427
1428         /*
1429          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1430          */
1431         udelay(1);
1432
1433         /* Enable PLL */
1434         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1435
1436         /* Check PLL is locked */
1437         if (intel_wait_for_register(&dev_priv->uncore,
1438                                     DPLL(pipe), DPLL_LOCK_VLV, DPLL_LOCK_VLV,
1439                                     1))
1440                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1441 }
1442
1443 static void chv_enable_pll(struct intel_crtc *crtc,
1444                            const struct intel_crtc_state *pipe_config)
1445 {
1446         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1447         enum pipe pipe = crtc->pipe;
1448
1449         assert_pipe_disabled(dev_priv, pipe);
1450
1451         /* PLL is protected by panel, make sure we can write it */
1452         assert_panel_unlocked(dev_priv, pipe);
1453
1454         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1455                 _chv_enable_pll(crtc, pipe_config);
1456
1457         if (pipe != PIPE_A) {
1458                 /*
1459                  * WaPixelRepeatModeFixForC0:chv
1460                  *
1461                  * DPLLCMD is AWOL. Use chicken bits to propagate
1462                  * the value from DPLLBMD to either pipe B or C.
1463                  */
1464                 I915_WRITE(CBR4_VLV, CBR_DPLLBMD_PIPE(pipe));
1465                 I915_WRITE(DPLL_MD(PIPE_B), pipe_config->dpll_hw_state.dpll_md);
1466                 I915_WRITE(CBR4_VLV, 0);
1467                 dev_priv->chv_dpll_md[pipe] = pipe_config->dpll_hw_state.dpll_md;
1468
1469                 /*
1470                  * DPLLB VGA mode also seems to cause problems.
1471                  * We should always have it disabled.
1472                  */
1473                 WARN_ON((I915_READ(DPLL(PIPE_B)) & DPLL_VGA_MODE_DIS) == 0);
1474         } else {
1475                 I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1476                 POSTING_READ(DPLL_MD(pipe));
1477         }
1478 }
1479
1480 static bool i9xx_has_pps(struct drm_i915_private *dev_priv)
1481 {
1482         if (IS_I830(dev_priv))
1483                 return false;
1484
1485         return IS_PINEVIEW(dev_priv) || IS_MOBILE(dev_priv);
1486 }
1487
1488 static void i9xx_enable_pll(struct intel_crtc *crtc,
1489                             const struct intel_crtc_state *crtc_state)
1490 {
1491         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1492         i915_reg_t reg = DPLL(crtc->pipe);
1493         u32 dpll = crtc_state->dpll_hw_state.dpll;
1494         int i;
1495
1496         assert_pipe_disabled(dev_priv, crtc->pipe);
1497
1498         /* PLL is protected by panel, make sure we can write it */
1499         if (i9xx_has_pps(dev_priv))
1500                 assert_panel_unlocked(dev_priv, crtc->pipe);
1501
1502         /*
1503          * Apparently we need to have VGA mode enabled prior to changing
1504          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
1505          * dividers, even though the register value does change.
1506          */
1507         I915_WRITE(reg, dpll & ~DPLL_VGA_MODE_DIS);
1508         I915_WRITE(reg, dpll);
1509
1510         /* Wait for the clocks to stabilize. */
1511         POSTING_READ(reg);
1512         udelay(150);
1513
1514         if (INTEL_GEN(dev_priv) >= 4) {
1515                 I915_WRITE(DPLL_MD(crtc->pipe),
1516                            crtc_state->dpll_hw_state.dpll_md);
1517         } else {
1518                 /* The pixel multiplier can only be updated once the
1519                  * DPLL is enabled and the clocks are stable.
1520                  *
1521                  * So write it again.
1522                  */
1523                 I915_WRITE(reg, dpll);
1524         }
1525
1526         /* We do this three times for luck */
1527         for (i = 0; i < 3; i++) {
1528                 I915_WRITE(reg, dpll);
1529                 POSTING_READ(reg);
1530                 udelay(150); /* wait for warmup */
1531         }
1532 }
1533
1534 static void i9xx_disable_pll(const struct intel_crtc_state *crtc_state)
1535 {
1536         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
1537         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1538         enum pipe pipe = crtc->pipe;
1539
1540         /* Don't disable pipe or pipe PLLs if needed */
1541         if (IS_I830(dev_priv))
1542                 return;
1543
1544         /* Make sure the pipe isn't still relying on us */
1545         assert_pipe_disabled(dev_priv, pipe);
1546
1547         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1548         POSTING_READ(DPLL(pipe));
1549 }
1550
1551 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1552 {
1553         u32 val;
1554
1555         /* Make sure the pipe isn't still relying on us */
1556         assert_pipe_disabled(dev_priv, pipe);
1557
1558         val = DPLL_INTEGRATED_REF_CLK_VLV |
1559                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1560         if (pipe != PIPE_A)
1561                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1562
1563         I915_WRITE(DPLL(pipe), val);
1564         POSTING_READ(DPLL(pipe));
1565 }
1566
1567 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1568 {
1569         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1570         u32 val;
1571
1572         /* Make sure the pipe isn't still relying on us */
1573         assert_pipe_disabled(dev_priv, pipe);
1574
1575         val = DPLL_SSC_REF_CLK_CHV |
1576                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1577         if (pipe != PIPE_A)
1578                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1579
1580         I915_WRITE(DPLL(pipe), val);
1581         POSTING_READ(DPLL(pipe));
1582
1583         vlv_dpio_get(dev_priv);
1584
1585         /* Disable 10bit clock to display controller */
1586         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1587         val &= ~DPIO_DCLKP_EN;
1588         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1589
1590         vlv_dpio_put(dev_priv);
1591 }
1592
1593 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1594                          struct intel_digital_port *dport,
1595                          unsigned int expected_mask)
1596 {
1597         u32 port_mask;
1598         i915_reg_t dpll_reg;
1599
1600         switch (dport->base.port) {
1601         case PORT_B:
1602                 port_mask = DPLL_PORTB_READY_MASK;
1603                 dpll_reg = DPLL(0);
1604                 break;
1605         case PORT_C:
1606                 port_mask = DPLL_PORTC_READY_MASK;
1607                 dpll_reg = DPLL(0);
1608                 expected_mask <<= 4;
1609                 break;
1610         case PORT_D:
1611                 port_mask = DPLL_PORTD_READY_MASK;
1612                 dpll_reg = DPIO_PHY_STATUS;
1613                 break;
1614         default:
1615                 BUG();
1616         }
1617
1618         if (intel_wait_for_register(&dev_priv->uncore,
1619                                     dpll_reg, port_mask, expected_mask,
1620                                     1000))
1621                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1622                      port_name(dport->base.port),
1623                      I915_READ(dpll_reg) & port_mask, expected_mask);
1624 }
1625
1626 static void ironlake_enable_pch_transcoder(const struct intel_crtc_state *crtc_state)
1627 {
1628         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
1629         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1630         enum pipe pipe = crtc->pipe;
1631         i915_reg_t reg;
1632         u32 val, pipeconf_val;
1633
1634         /* Make sure PCH DPLL is enabled */
1635         assert_shared_dpll_enabled(dev_priv, crtc_state->shared_dpll);
1636
1637         /* FDI must be feeding us bits for PCH ports */
1638         assert_fdi_tx_enabled(dev_priv, pipe);
1639         assert_fdi_rx_enabled(dev_priv, pipe);
1640
1641         if (HAS_PCH_CPT(dev_priv)) {
1642                 /* Workaround: Set the timing override bit before enabling the
1643                  * pch transcoder. */
1644                 reg = TRANS_CHICKEN2(pipe);
1645                 val = I915_READ(reg);
1646                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1647                 I915_WRITE(reg, val);
1648         }
1649
1650         reg = PCH_TRANSCONF(pipe);
1651         val = I915_READ(reg);
1652         pipeconf_val = I915_READ(PIPECONF(pipe));
1653
1654         if (HAS_PCH_IBX(dev_priv)) {
1655                 /*
1656                  * Make the BPC in transcoder be consistent with
1657                  * that in pipeconf reg. For HDMI we must use 8bpc
1658                  * here for both 8bpc and 12bpc.
1659                  */
1660                 val &= ~PIPECONF_BPC_MASK;
1661                 if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
1662                         val |= PIPECONF_8BPC;
1663                 else
1664                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1665         }
1666
1667         val &= ~TRANS_INTERLACE_MASK;
1668         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK) {
1669                 if (HAS_PCH_IBX(dev_priv) &&
1670                     intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO))
1671                         val |= TRANS_LEGACY_INTERLACED_ILK;
1672                 else
1673                         val |= TRANS_INTERLACED;
1674         } else {
1675                 val |= TRANS_PROGRESSIVE;
1676         }
1677
1678         I915_WRITE(reg, val | TRANS_ENABLE);
1679         if (intel_wait_for_register(&dev_priv->uncore,
1680                                     reg, TRANS_STATE_ENABLE, TRANS_STATE_ENABLE,
1681                                     100))
1682                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1683 }
1684
1685 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1686                                       enum transcoder cpu_transcoder)
1687 {
1688         u32 val, pipeconf_val;
1689
1690         /* FDI must be feeding us bits for PCH ports */
1691         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1692         assert_fdi_rx_enabled(dev_priv, PIPE_A);
1693
1694         /* Workaround: set timing override bit. */
1695         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1696         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1697         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1698
1699         val = TRANS_ENABLE;
1700         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1701
1702         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1703             PIPECONF_INTERLACED_ILK)
1704                 val |= TRANS_INTERLACED;
1705         else
1706                 val |= TRANS_PROGRESSIVE;
1707
1708         I915_WRITE(LPT_TRANSCONF, val);
1709         if (intel_wait_for_register(&dev_priv->uncore,
1710                                     LPT_TRANSCONF,
1711                                     TRANS_STATE_ENABLE,
1712                                     TRANS_STATE_ENABLE,
1713                                     100))
1714                 DRM_ERROR("Failed to enable PCH transcoder\n");
1715 }
1716
1717 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1718                                             enum pipe pipe)
1719 {
1720         i915_reg_t reg;
1721         u32 val;
1722
1723         /* FDI relies on the transcoder */
1724         assert_fdi_tx_disabled(dev_priv, pipe);
1725         assert_fdi_rx_disabled(dev_priv, pipe);
1726
1727         /* Ports must be off as well */
1728         assert_pch_ports_disabled(dev_priv, pipe);
1729
1730         reg = PCH_TRANSCONF(pipe);
1731         val = I915_READ(reg);
1732         val &= ~TRANS_ENABLE;
1733         I915_WRITE(reg, val);
1734         /* wait for PCH transcoder off, transcoder state */
1735         if (intel_wait_for_register(&dev_priv->uncore,
1736                                     reg, TRANS_STATE_ENABLE, 0,
1737                                     50))
1738                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1739
1740         if (HAS_PCH_CPT(dev_priv)) {
1741                 /* Workaround: Clear the timing override chicken bit again. */
1742                 reg = TRANS_CHICKEN2(pipe);
1743                 val = I915_READ(reg);
1744                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1745                 I915_WRITE(reg, val);
1746         }
1747 }
1748
1749 void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1750 {
1751         u32 val;
1752
1753         val = I915_READ(LPT_TRANSCONF);
1754         val &= ~TRANS_ENABLE;
1755         I915_WRITE(LPT_TRANSCONF, val);
1756         /* wait for PCH transcoder off, transcoder state */
1757         if (intel_wait_for_register(&dev_priv->uncore,
1758                                     LPT_TRANSCONF, TRANS_STATE_ENABLE, 0,
1759                                     50))
1760                 DRM_ERROR("Failed to disable PCH transcoder\n");
1761
1762         /* Workaround: clear timing override bit. */
1763         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1764         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1765         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1766 }
1767
1768 enum pipe intel_crtc_pch_transcoder(struct intel_crtc *crtc)
1769 {
1770         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1771
1772         if (HAS_PCH_LPT(dev_priv))
1773                 return PIPE_A;
1774         else
1775                 return crtc->pipe;
1776 }
1777
1778 static u32 intel_crtc_max_vblank_count(const struct intel_crtc_state *crtc_state)
1779 {
1780         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
1781
1782         /*
1783          * On i965gm the hardware frame counter reads
1784          * zero when the TV encoder is enabled :(
1785          */
1786         if (IS_I965GM(dev_priv) &&
1787             (crtc_state->output_types & BIT(INTEL_OUTPUT_TVOUT)))
1788                 return 0;
1789
1790         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
1791                 return 0xffffffff; /* full 32 bit counter */
1792         else if (INTEL_GEN(dev_priv) >= 3)
1793                 return 0xffffff; /* only 24 bits of frame count */
1794         else
1795                 return 0; /* Gen2 doesn't have a hardware frame counter */
1796 }
1797
1798 static void intel_crtc_vblank_on(const struct intel_crtc_state *crtc_state)
1799 {
1800         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
1801
1802         drm_crtc_set_max_vblank_count(&crtc->base,
1803                                       intel_crtc_max_vblank_count(crtc_state));
1804         drm_crtc_vblank_on(&crtc->base);
1805 }
1806
1807 static void intel_enable_pipe(const struct intel_crtc_state *new_crtc_state)
1808 {
1809         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
1810         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1811         enum transcoder cpu_transcoder = new_crtc_state->cpu_transcoder;
1812         enum pipe pipe = crtc->pipe;
1813         i915_reg_t reg;
1814         u32 val;
1815
1816         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
1817
1818         assert_planes_disabled(crtc);
1819
1820         /*
1821          * A pipe without a PLL won't actually be able to drive bits from
1822          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
1823          * need the check.
1824          */
1825         if (HAS_GMCH(dev_priv)) {
1826                 if (intel_crtc_has_type(new_crtc_state, INTEL_OUTPUT_DSI))
1827                         assert_dsi_pll_enabled(dev_priv);
1828                 else
1829                         assert_pll_enabled(dev_priv, pipe);
1830         } else {
1831                 if (new_crtc_state->has_pch_encoder) {
1832                         /* if driving the PCH, we need FDI enabled */
1833                         assert_fdi_rx_pll_enabled(dev_priv,
1834                                                   intel_crtc_pch_transcoder(crtc));
1835                         assert_fdi_tx_pll_enabled(dev_priv,
1836                                                   (enum pipe) cpu_transcoder);
1837                 }
1838                 /* FIXME: assert CPU port conditions for SNB+ */
1839         }
1840
1841         trace_intel_pipe_enable(dev_priv, pipe);
1842
1843         reg = PIPECONF(cpu_transcoder);
1844         val = I915_READ(reg);
1845         if (val & PIPECONF_ENABLE) {
1846                 /* we keep both pipes enabled on 830 */
1847                 WARN_ON(!IS_I830(dev_priv));
1848                 return;
1849         }
1850
1851         I915_WRITE(reg, val | PIPECONF_ENABLE);
1852         POSTING_READ(reg);
1853
1854         /*
1855          * Until the pipe starts PIPEDSL reads will return a stale value,
1856          * which causes an apparent vblank timestamp jump when PIPEDSL
1857          * resets to its proper value. That also messes up the frame count
1858          * when it's derived from the timestamps. So let's wait for the
1859          * pipe to start properly before we call drm_crtc_vblank_on()
1860          */
1861         if (intel_crtc_max_vblank_count(new_crtc_state) == 0)
1862                 intel_wait_for_pipe_scanline_moving(crtc);
1863 }
1864
1865 static void intel_disable_pipe(const struct intel_crtc_state *old_crtc_state)
1866 {
1867         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
1868         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1869         enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
1870         enum pipe pipe = crtc->pipe;
1871         i915_reg_t reg;
1872         u32 val;
1873
1874         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
1875
1876         /*
1877          * Make sure planes won't keep trying to pump pixels to us,
1878          * or we might hang the display.
1879          */
1880         assert_planes_disabled(crtc);
1881
1882         trace_intel_pipe_disable(dev_priv, pipe);
1883
1884         reg = PIPECONF(cpu_transcoder);
1885         val = I915_READ(reg);
1886         if ((val & PIPECONF_ENABLE) == 0)
1887                 return;
1888
1889         /*
1890          * Double wide has implications for planes
1891          * so best keep it disabled when not needed.
1892          */
1893         if (old_crtc_state->double_wide)
1894                 val &= ~PIPECONF_DOUBLE_WIDE;
1895
1896         /* Don't disable pipe or pipe PLLs if needed */
1897         if (!IS_I830(dev_priv))
1898                 val &= ~PIPECONF_ENABLE;
1899
1900         I915_WRITE(reg, val);
1901         if ((val & PIPECONF_ENABLE) == 0)
1902                 intel_wait_for_pipe_off(old_crtc_state);
1903 }
1904
1905 static unsigned int intel_tile_size(const struct drm_i915_private *dev_priv)
1906 {
1907         return IS_GEN(dev_priv, 2) ? 2048 : 4096;
1908 }
1909
1910 static unsigned int
1911 intel_tile_width_bytes(const struct drm_framebuffer *fb, int color_plane)
1912 {
1913         struct drm_i915_private *dev_priv = to_i915(fb->dev);
1914         unsigned int cpp = fb->format->cpp[color_plane];
1915
1916         switch (fb->modifier) {
1917         case DRM_FORMAT_MOD_LINEAR:
1918                 return 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 static
2502 u32 intel_plane_fb_max_stride(struct drm_i915_private *dev_priv,
2503                               u32 pixel_format, u64 modifier)
2504 {
2505         struct intel_crtc *crtc;
2506         struct intel_plane *plane;
2507
2508         /*
2509          * We assume the primary plane for pipe A has
2510          * the highest stride limits of them all.
2511          */
2512         crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_A);
2513         plane = to_intel_plane(crtc->base.primary);
2514
2515         return plane->max_stride(plane, pixel_format, modifier,
2516                                  DRM_MODE_ROTATE_0);
2517 }
2518
2519 static
2520 u32 intel_fb_max_stride(struct drm_i915_private *dev_priv,
2521                         u32 pixel_format, u64 modifier)
2522 {
2523         return intel_plane_fb_max_stride(dev_priv, pixel_format, modifier);
2524 }
2525
2526 static u32
2527 intel_fb_stride_alignment(const struct drm_framebuffer *fb, int color_plane)
2528 {
2529         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2530
2531         if (fb->modifier == DRM_FORMAT_MOD_LINEAR) {
2532                 u32 max_stride = intel_plane_fb_max_stride(dev_priv,
2533                                                            fb->format->format,
2534                                                            fb->modifier);
2535
2536                 /*
2537                  * To make remapping with linear generally feasible
2538                  * we need the stride to be page aligned.
2539                  */
2540                 if (fb->pitches[color_plane] > max_stride)
2541                         return intel_tile_size(dev_priv);
2542                 else
2543                         return 64;
2544         } else {
2545                 return intel_tile_width_bytes(fb, color_plane);
2546         }
2547 }
2548
2549 bool intel_plane_can_remap(const struct intel_plane_state *plane_state)
2550 {
2551         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2552         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
2553         const struct drm_framebuffer *fb = plane_state->base.fb;
2554         int i;
2555
2556         /* We don't want to deal with remapping with cursors */
2557         if (plane->id == PLANE_CURSOR)
2558                 return false;
2559
2560         /*
2561          * The display engine limits already match/exceed the
2562          * render engine limits, so not much point in remapping.
2563          * Would also need to deal with the fence POT alignment
2564          * and gen2 2KiB GTT tile size.
2565          */
2566         if (INTEL_GEN(dev_priv) < 4)
2567                 return false;
2568
2569         /*
2570          * The new CCS hash mode isn't compatible with remapping as
2571          * the virtual address of the pages affects the compressed data.
2572          */
2573         if (is_ccs_modifier(fb->modifier))
2574                 return false;
2575
2576         /* Linear needs a page aligned stride for remapping */
2577         if (fb->modifier == DRM_FORMAT_MOD_LINEAR) {
2578                 unsigned int alignment = intel_tile_size(dev_priv) - 1;
2579
2580                 for (i = 0; i < fb->format->num_planes; i++) {
2581                         if (fb->pitches[i] & alignment)
2582                                 return false;
2583                 }
2584         }
2585
2586         return true;
2587 }
2588
2589 static bool intel_plane_needs_remap(const struct intel_plane_state *plane_state)
2590 {
2591         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2592         const struct drm_framebuffer *fb = plane_state->base.fb;
2593         unsigned int rotation = plane_state->base.rotation;
2594         u32 stride, max_stride;
2595
2596         /*
2597          * No remapping for invisible planes since we don't have
2598          * an actual source viewport to remap.
2599          */
2600         if (!plane_state->base.visible)
2601                 return false;
2602
2603         if (!intel_plane_can_remap(plane_state))
2604                 return false;
2605
2606         /*
2607          * FIXME: aux plane limits on gen9+ are
2608          * unclear in Bspec, for now no checking.
2609          */
2610         stride = intel_fb_pitch(fb, 0, rotation);
2611         max_stride = plane->max_stride(plane, fb->format->format,
2612                                        fb->modifier, rotation);
2613
2614         return stride > max_stride;
2615 }
2616
2617 static int
2618 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2619                    struct drm_framebuffer *fb)
2620 {
2621         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
2622         struct intel_rotation_info *rot_info = &intel_fb->rot_info;
2623         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2624         u32 gtt_offset_rotated = 0;
2625         unsigned int max_size = 0;
2626         int i, num_planes = fb->format->num_planes;
2627         unsigned int tile_size = intel_tile_size(dev_priv);
2628
2629         for (i = 0; i < num_planes; i++) {
2630                 unsigned int width, height;
2631                 unsigned int cpp, size;
2632                 u32 offset;
2633                 int x, y;
2634                 int ret;
2635
2636                 cpp = fb->format->cpp[i];
2637                 width = drm_framebuffer_plane_width(fb->width, fb, i);
2638                 height = drm_framebuffer_plane_height(fb->height, fb, i);
2639
2640                 ret = intel_fb_offset_to_xy(&x, &y, fb, i);
2641                 if (ret) {
2642                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2643                                       i, fb->offsets[i]);
2644                         return ret;
2645                 }
2646
2647                 if (is_ccs_modifier(fb->modifier) && i == 1) {
2648                         int hsub = fb->format->hsub;
2649                         int vsub = fb->format->vsub;
2650                         int tile_width, tile_height;
2651                         int main_x, main_y;
2652                         int ccs_x, ccs_y;
2653
2654                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2655                         tile_width *= hsub;
2656                         tile_height *= vsub;
2657
2658                         ccs_x = (x * hsub) % tile_width;
2659                         ccs_y = (y * vsub) % tile_height;
2660                         main_x = intel_fb->normal[0].x % tile_width;
2661                         main_y = intel_fb->normal[0].y % tile_height;
2662
2663                         /*
2664                          * CCS doesn't have its own x/y offset register, so the intra CCS tile
2665                          * x/y offsets must match between CCS and the main surface.
2666                          */
2667                         if (main_x != ccs_x || main_y != ccs_y) {
2668                                 DRM_DEBUG_KMS("Bad CCS x/y (main %d,%d ccs %d,%d) full (main %d,%d ccs %d,%d)\n",
2669                                               main_x, main_y,
2670                                               ccs_x, ccs_y,
2671                                               intel_fb->normal[0].x,
2672                                               intel_fb->normal[0].y,
2673                                               x, y);
2674                                 return -EINVAL;
2675                         }
2676                 }
2677
2678                 /*
2679                  * The fence (if used) is aligned to the start of the object
2680                  * so having the framebuffer wrap around across the edge of the
2681                  * fenced region doesn't really work. We have no API to configure
2682                  * the fence start offset within the object (nor could we probably
2683                  * on gen2/3). So it's just easier if we just require that the
2684                  * fb layout agrees with the fence layout. We already check that the
2685                  * fb stride matches the fence stride elsewhere.
2686                  */
2687                 if (i == 0 && i915_gem_object_is_tiled(obj) &&
2688                     (x + width) * cpp > fb->pitches[i]) {
2689                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2690                                       i, fb->offsets[i]);
2691                         return -EINVAL;
2692                 }
2693
2694                 /*
2695                  * First pixel of the framebuffer from
2696                  * the start of the normal gtt mapping.
2697                  */
2698                 intel_fb->normal[i].x = x;
2699                 intel_fb->normal[i].y = y;
2700
2701                 offset = intel_compute_aligned_offset(dev_priv, &x, &y, fb, i,
2702                                                       fb->pitches[i],
2703                                                       DRM_MODE_ROTATE_0,
2704                                                       tile_size);
2705                 offset /= tile_size;
2706
2707                 if (!is_surface_linear(fb->modifier, i)) {
2708                         unsigned int tile_width, tile_height;
2709                         unsigned int pitch_tiles;
2710                         struct drm_rect r;
2711
2712                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2713
2714                         rot_info->plane[i].offset = offset;
2715                         rot_info->plane[i].stride = DIV_ROUND_UP(fb->pitches[i], tile_width * cpp);
2716                         rot_info->plane[i].width = DIV_ROUND_UP(x + width, tile_width);
2717                         rot_info->plane[i].height = DIV_ROUND_UP(y + height, tile_height);
2718
2719                         intel_fb->rotated[i].pitch =
2720                                 rot_info->plane[i].height * tile_height;
2721
2722                         /* how many tiles does this plane need */
2723                         size = rot_info->plane[i].stride * rot_info->plane[i].height;
2724                         /*
2725                          * If the plane isn't horizontally tile aligned,
2726                          * we need one more tile.
2727                          */
2728                         if (x != 0)
2729                                 size++;
2730
2731                         /* rotate the x/y offsets to match the GTT view */
2732                         r.x1 = x;
2733                         r.y1 = y;
2734                         r.x2 = x + width;
2735                         r.y2 = y + height;
2736                         drm_rect_rotate(&r,
2737                                         rot_info->plane[i].width * tile_width,
2738                                         rot_info->plane[i].height * tile_height,
2739                                         DRM_MODE_ROTATE_270);
2740                         x = r.x1;
2741                         y = r.y1;
2742
2743                         /* rotate the tile dimensions to match the GTT view */
2744                         pitch_tiles = intel_fb->rotated[i].pitch / tile_height;
2745                         swap(tile_width, tile_height);
2746
2747                         /*
2748                          * We only keep the x/y offsets, so push all of the
2749                          * gtt offset into the x/y offsets.
2750                          */
2751                         intel_adjust_tile_offset(&x, &y,
2752                                                  tile_width, tile_height,
2753                                                  tile_size, pitch_tiles,
2754                                                  gtt_offset_rotated * tile_size, 0);
2755
2756                         gtt_offset_rotated += rot_info->plane[i].width * rot_info->plane[i].height;
2757
2758                         /*
2759                          * First pixel of the framebuffer from
2760                          * the start of the rotated gtt mapping.
2761                          */
2762                         intel_fb->rotated[i].x = x;
2763                         intel_fb->rotated[i].y = y;
2764                 } else {
2765                         size = DIV_ROUND_UP((y + height) * fb->pitches[i] +
2766                                             x * cpp, tile_size);
2767                 }
2768
2769                 /* how many tiles in total needed in the bo */
2770                 max_size = max(max_size, offset + size);
2771         }
2772
2773         if (mul_u32_u32(max_size, tile_size) > obj->base.size) {
2774                 DRM_DEBUG_KMS("fb too big for bo (need %llu bytes, have %zu bytes)\n",
2775                               mul_u32_u32(max_size, tile_size), obj->base.size);
2776                 return -EINVAL;
2777         }
2778
2779         return 0;
2780 }
2781
2782 static void
2783 intel_plane_remap_gtt(struct intel_plane_state *plane_state)
2784 {
2785         struct drm_i915_private *dev_priv =
2786                 to_i915(plane_state->base.plane->dev);
2787         struct drm_framebuffer *fb = plane_state->base.fb;
2788         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
2789         struct intel_rotation_info *info = &plane_state->view.rotated;
2790         unsigned int rotation = plane_state->base.rotation;
2791         int i, num_planes = fb->format->num_planes;
2792         unsigned int tile_size = intel_tile_size(dev_priv);
2793         unsigned int src_x, src_y;
2794         unsigned int src_w, src_h;
2795         u32 gtt_offset = 0;
2796
2797         memset(&plane_state->view, 0, sizeof(plane_state->view));
2798         plane_state->view.type = drm_rotation_90_or_270(rotation) ?
2799                 I915_GGTT_VIEW_ROTATED : I915_GGTT_VIEW_REMAPPED;
2800
2801         src_x = plane_state->base.src.x1 >> 16;
2802         src_y = plane_state->base.src.y1 >> 16;
2803         src_w = drm_rect_width(&plane_state->base.src) >> 16;
2804         src_h = drm_rect_height(&plane_state->base.src) >> 16;
2805
2806         WARN_ON(is_ccs_modifier(fb->modifier));
2807
2808         /* Make src coordinates relative to the viewport */
2809         drm_rect_translate(&plane_state->base.src,
2810                            -(src_x << 16), -(src_y << 16));
2811
2812         /* Rotate src coordinates to match rotated GTT view */
2813         if (drm_rotation_90_or_270(rotation))
2814                 drm_rect_rotate(&plane_state->base.src,
2815                                 src_w << 16, src_h << 16,
2816                                 DRM_MODE_ROTATE_270);
2817
2818         for (i = 0; i < num_planes; i++) {
2819                 unsigned int hsub = i ? fb->format->hsub : 1;
2820                 unsigned int vsub = i ? fb->format->vsub : 1;
2821                 unsigned int cpp = fb->format->cpp[i];
2822                 unsigned int tile_width, tile_height;
2823                 unsigned int width, height;
2824                 unsigned int pitch_tiles;
2825                 unsigned int x, y;
2826                 u32 offset;
2827
2828                 intel_tile_dims(fb, i, &tile_width, &tile_height);
2829
2830                 x = src_x / hsub;
2831                 y = src_y / vsub;
2832                 width = src_w / hsub;
2833                 height = src_h / vsub;
2834
2835                 /*
2836                  * First pixel of the src viewport from the
2837                  * start of the normal gtt mapping.
2838                  */
2839                 x += intel_fb->normal[i].x;
2840                 y += intel_fb->normal[i].y;
2841
2842                 offset = intel_compute_aligned_offset(dev_priv, &x, &y,
2843                                                       fb, i, fb->pitches[i],
2844                                                       DRM_MODE_ROTATE_0, tile_size);
2845                 offset /= tile_size;
2846
2847                 info->plane[i].offset = offset;
2848                 info->plane[i].stride = DIV_ROUND_UP(fb->pitches[i],
2849                                                      tile_width * cpp);
2850                 info->plane[i].width = DIV_ROUND_UP(x + width, tile_width);
2851                 info->plane[i].height = DIV_ROUND_UP(y + height, tile_height);
2852
2853                 if (drm_rotation_90_or_270(rotation)) {
2854                         struct drm_rect r;
2855
2856                         /* rotate the x/y offsets to match the GTT view */
2857                         r.x1 = x;
2858                         r.y1 = y;
2859                         r.x2 = x + width;
2860                         r.y2 = y + height;
2861                         drm_rect_rotate(&r,
2862                                         info->plane[i].width * tile_width,
2863                                         info->plane[i].height * tile_height,
2864                                         DRM_MODE_ROTATE_270);
2865                         x = r.x1;
2866                         y = r.y1;
2867
2868                         pitch_tiles = info->plane[i].height;
2869                         plane_state->color_plane[i].stride = pitch_tiles * tile_height;
2870
2871                         /* rotate the tile dimensions to match the GTT view */
2872                         swap(tile_width, tile_height);
2873                 } else {
2874                         pitch_tiles = info->plane[i].width;
2875                         plane_state->color_plane[i].stride = pitch_tiles * tile_width * cpp;
2876                 }
2877
2878                 /*
2879                  * We only keep the x/y offsets, so push all of the
2880                  * gtt offset into the x/y offsets.
2881                  */
2882                 intel_adjust_tile_offset(&x, &y,
2883                                          tile_width, tile_height,
2884                                          tile_size, pitch_tiles,
2885                                          gtt_offset * tile_size, 0);
2886
2887                 gtt_offset += info->plane[i].width * info->plane[i].height;
2888
2889                 plane_state->color_plane[i].offset = 0;
2890                 plane_state->color_plane[i].x = x;
2891                 plane_state->color_plane[i].y = y;
2892         }
2893 }
2894
2895 static int
2896 intel_plane_compute_gtt(struct intel_plane_state *plane_state)
2897 {
2898         const struct intel_framebuffer *fb =
2899                 to_intel_framebuffer(plane_state->base.fb);
2900         unsigned int rotation = plane_state->base.rotation;
2901         int i, num_planes;
2902
2903         if (!fb)
2904                 return 0;
2905
2906         num_planes = fb->base.format->num_planes;
2907
2908         if (intel_plane_needs_remap(plane_state)) {
2909                 intel_plane_remap_gtt(plane_state);
2910
2911                 /*
2912                  * Sometimes even remapping can't overcome
2913                  * the stride limitations :( Can happen with
2914                  * big plane sizes and suitably misaligned
2915                  * offsets.
2916                  */
2917                 return intel_plane_check_stride(plane_state);
2918         }
2919
2920         intel_fill_fb_ggtt_view(&plane_state->view, &fb->base, rotation);
2921
2922         for (i = 0; i < num_planes; i++) {
2923                 plane_state->color_plane[i].stride = intel_fb_pitch(&fb->base, i, rotation);
2924                 plane_state->color_plane[i].offset = 0;
2925
2926                 if (drm_rotation_90_or_270(rotation)) {
2927                         plane_state->color_plane[i].x = fb->rotated[i].x;
2928                         plane_state->color_plane[i].y = fb->rotated[i].y;
2929                 } else {
2930                         plane_state->color_plane[i].x = fb->normal[i].x;
2931                         plane_state->color_plane[i].y = fb->normal[i].y;
2932                 }
2933         }
2934
2935         /* Rotate src coordinates to match rotated GTT view */
2936         if (drm_rotation_90_or_270(rotation))
2937                 drm_rect_rotate(&plane_state->base.src,
2938                                 fb->base.width << 16, fb->base.height << 16,
2939                                 DRM_MODE_ROTATE_270);
2940
2941         return intel_plane_check_stride(plane_state);
2942 }
2943
2944 static int i9xx_format_to_fourcc(int format)
2945 {
2946         switch (format) {
2947         case DISPPLANE_8BPP:
2948                 return DRM_FORMAT_C8;
2949         case DISPPLANE_BGRX555:
2950                 return DRM_FORMAT_XRGB1555;
2951         case DISPPLANE_BGRX565:
2952                 return DRM_FORMAT_RGB565;
2953         default:
2954         case DISPPLANE_BGRX888:
2955                 return DRM_FORMAT_XRGB8888;
2956         case DISPPLANE_RGBX888:
2957                 return DRM_FORMAT_XBGR8888;
2958         case DISPPLANE_BGRX101010:
2959                 return DRM_FORMAT_XRGB2101010;
2960         case DISPPLANE_RGBX101010:
2961                 return DRM_FORMAT_XBGR2101010;
2962         }
2963 }
2964
2965 int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2966 {
2967         switch (format) {
2968         case PLANE_CTL_FORMAT_RGB_565:
2969                 return DRM_FORMAT_RGB565;
2970         case PLANE_CTL_FORMAT_NV12:
2971                 return DRM_FORMAT_NV12;
2972         case PLANE_CTL_FORMAT_P010:
2973                 return DRM_FORMAT_P010;
2974         case PLANE_CTL_FORMAT_P012:
2975                 return DRM_FORMAT_P012;
2976         case PLANE_CTL_FORMAT_P016:
2977                 return DRM_FORMAT_P016;
2978         case PLANE_CTL_FORMAT_Y210:
2979                 return DRM_FORMAT_Y210;
2980         case PLANE_CTL_FORMAT_Y212:
2981                 return DRM_FORMAT_Y212;
2982         case PLANE_CTL_FORMAT_Y216:
2983                 return DRM_FORMAT_Y216;
2984         case PLANE_CTL_FORMAT_Y410:
2985                 return DRM_FORMAT_XVYU2101010;
2986         case PLANE_CTL_FORMAT_Y412:
2987                 return DRM_FORMAT_XVYU12_16161616;
2988         case PLANE_CTL_FORMAT_Y416:
2989                 return DRM_FORMAT_XVYU16161616;
2990         default:
2991         case PLANE_CTL_FORMAT_XRGB_8888:
2992                 if (rgb_order) {
2993                         if (alpha)
2994                                 return DRM_FORMAT_ABGR8888;
2995                         else
2996                                 return DRM_FORMAT_XBGR8888;
2997                 } else {
2998                         if (alpha)
2999                                 return DRM_FORMAT_ARGB8888;
3000                         else
3001                                 return DRM_FORMAT_XRGB8888;
3002                 }
3003         case PLANE_CTL_FORMAT_XRGB_2101010:
3004                 if (rgb_order)
3005                         return DRM_FORMAT_XBGR2101010;
3006                 else
3007                         return DRM_FORMAT_XRGB2101010;
3008         case PLANE_CTL_FORMAT_XRGB_16161616F:
3009                 if (rgb_order) {
3010                         if (alpha)
3011                                 return DRM_FORMAT_ABGR16161616F;
3012                         else
3013                                 return DRM_FORMAT_XBGR16161616F;
3014                 } else {
3015                         if (alpha)
3016                                 return DRM_FORMAT_ARGB16161616F;
3017                         else
3018                                 return DRM_FORMAT_XRGB16161616F;
3019                 }
3020         }
3021 }
3022
3023 static bool
3024 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
3025                               struct intel_initial_plane_config *plane_config)
3026 {
3027         struct drm_device *dev = crtc->base.dev;
3028         struct drm_i915_private *dev_priv = to_i915(dev);
3029         struct drm_i915_gem_object *obj = NULL;
3030         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
3031         struct drm_framebuffer *fb = &plane_config->fb->base;
3032         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
3033         u32 size_aligned = round_up(plane_config->base + plane_config->size,
3034                                     PAGE_SIZE);
3035
3036         size_aligned -= base_aligned;
3037
3038         if (plane_config->size == 0)
3039                 return false;
3040
3041         /* If the FB is too big, just don't use it since fbdev is not very
3042          * important and we should probably use that space with FBC or other
3043          * features. */
3044         if (size_aligned * 2 > dev_priv->stolen_usable_size)
3045                 return false;
3046
3047         switch (fb->modifier) {
3048         case DRM_FORMAT_MOD_LINEAR:
3049         case I915_FORMAT_MOD_X_TILED:
3050         case I915_FORMAT_MOD_Y_TILED:
3051                 break;
3052         default:
3053                 DRM_DEBUG_DRIVER("Unsupported modifier for initial FB: 0x%llx\n",
3054                                  fb->modifier);
3055                 return false;
3056         }
3057
3058         mutex_lock(&dev->struct_mutex);
3059         obj = i915_gem_object_create_stolen_for_preallocated(dev_priv,
3060                                                              base_aligned,
3061                                                              base_aligned,
3062                                                              size_aligned);
3063         mutex_unlock(&dev->struct_mutex);
3064         if (!obj)
3065                 return false;
3066
3067         switch (plane_config->tiling) {
3068         case I915_TILING_NONE:
3069                 break;
3070         case I915_TILING_X:
3071         case I915_TILING_Y:
3072                 obj->tiling_and_stride = fb->pitches[0] | plane_config->tiling;
3073                 break;
3074         default:
3075                 MISSING_CASE(plane_config->tiling);
3076                 return false;
3077         }
3078
3079         mode_cmd.pixel_format = fb->format->format;
3080         mode_cmd.width = fb->width;
3081         mode_cmd.height = fb->height;
3082         mode_cmd.pitches[0] = fb->pitches[0];
3083         mode_cmd.modifier[0] = fb->modifier;
3084         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
3085
3086         if (intel_framebuffer_init(to_intel_framebuffer(fb), obj, &mode_cmd)) {
3087                 DRM_DEBUG_KMS("intel fb init failed\n");
3088                 goto out_unref_obj;
3089         }
3090
3091
3092         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
3093         return true;
3094
3095 out_unref_obj:
3096         i915_gem_object_put(obj);
3097         return false;
3098 }
3099
3100 static void
3101 intel_set_plane_visible(struct intel_crtc_state *crtc_state,
3102                         struct intel_plane_state *plane_state,
3103                         bool visible)
3104 {
3105         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
3106
3107         plane_state->base.visible = visible;
3108
3109         if (visible)
3110                 crtc_state->base.plane_mask |= drm_plane_mask(&plane->base);
3111         else
3112                 crtc_state->base.plane_mask &= ~drm_plane_mask(&plane->base);
3113 }
3114
3115 static void fixup_active_planes(struct intel_crtc_state *crtc_state)
3116 {
3117         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
3118         struct drm_plane *plane;
3119
3120         /*
3121          * Active_planes aliases if multiple "primary" or cursor planes
3122          * have been used on the same (or wrong) pipe. plane_mask uses
3123          * unique ids, hence we can use that to reconstruct active_planes.
3124          */
3125         crtc_state->active_planes = 0;
3126
3127         drm_for_each_plane_mask(plane, &dev_priv->drm,
3128                                 crtc_state->base.plane_mask)
3129                 crtc_state->active_planes |= BIT(to_intel_plane(plane)->id);
3130 }
3131
3132 static void intel_plane_disable_noatomic(struct intel_crtc *crtc,
3133                                          struct intel_plane *plane)
3134 {
3135         struct intel_crtc_state *crtc_state =
3136                 to_intel_crtc_state(crtc->base.state);
3137         struct intel_plane_state *plane_state =
3138                 to_intel_plane_state(plane->base.state);
3139
3140         DRM_DEBUG_KMS("Disabling [PLANE:%d:%s] on [CRTC:%d:%s]\n",
3141                       plane->base.base.id, plane->base.name,
3142                       crtc->base.base.id, crtc->base.name);
3143
3144         intel_set_plane_visible(crtc_state, plane_state, false);
3145         fixup_active_planes(crtc_state);
3146
3147         if (plane->id == PLANE_PRIMARY)
3148                 intel_pre_disable_primary_noatomic(&crtc->base);
3149
3150         intel_disable_plane(plane, crtc_state);
3151 }
3152
3153 static void
3154 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
3155                              struct intel_initial_plane_config *plane_config)
3156 {
3157         struct drm_device *dev = intel_crtc->base.dev;
3158         struct drm_i915_private *dev_priv = to_i915(dev);
3159         struct drm_crtc *c;
3160         struct drm_i915_gem_object *obj;
3161         struct drm_plane *primary = intel_crtc->base.primary;
3162         struct drm_plane_state *plane_state = primary->state;
3163         struct intel_plane *intel_plane = to_intel_plane(primary);
3164         struct intel_plane_state *intel_state =
3165                 to_intel_plane_state(plane_state);
3166         struct drm_framebuffer *fb;
3167
3168         if (!plane_config->fb)
3169                 return;
3170
3171         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
3172                 fb = &plane_config->fb->base;
3173                 goto valid_fb;
3174         }
3175
3176         kfree(plane_config->fb);
3177
3178         /*
3179          * Failed to alloc the obj, check to see if we should share
3180          * an fb with another CRTC instead
3181          */
3182         for_each_crtc(dev, c) {
3183                 struct intel_plane_state *state;
3184
3185                 if (c == &intel_crtc->base)
3186                         continue;
3187
3188                 if (!to_intel_crtc(c)->active)
3189                         continue;
3190
3191                 state = to_intel_plane_state(c->primary->state);
3192                 if (!state->vma)
3193                         continue;
3194
3195                 if (intel_plane_ggtt_offset(state) == plane_config->base) {
3196                         fb = state->base.fb;
3197                         drm_framebuffer_get(fb);
3198                         goto valid_fb;
3199                 }
3200         }
3201
3202         /*
3203          * We've failed to reconstruct the BIOS FB.  Current display state
3204          * indicates that the primary plane is visible, but has a NULL FB,
3205          * which will lead to problems later if we don't fix it up.  The
3206          * simplest solution is to just disable the primary plane now and
3207          * pretend the BIOS never had it enabled.
3208          */
3209         intel_plane_disable_noatomic(intel_crtc, intel_plane);
3210
3211         return;
3212
3213 valid_fb:
3214         intel_state->base.rotation = plane_config->rotation;
3215         intel_fill_fb_ggtt_view(&intel_state->view, fb,
3216                                 intel_state->base.rotation);
3217         intel_state->color_plane[0].stride =
3218                 intel_fb_pitch(fb, 0, intel_state->base.rotation);
3219
3220         mutex_lock(&dev->struct_mutex);
3221         intel_state->vma =
3222                 intel_pin_and_fence_fb_obj(fb,
3223                                            &intel_state->view,
3224                                            intel_plane_uses_fence(intel_state),
3225                                            &intel_state->flags);
3226         mutex_unlock(&dev->struct_mutex);
3227         if (IS_ERR(intel_state->vma)) {
3228                 DRM_ERROR("failed to pin boot fb on pipe %d: %li\n",
3229                           intel_crtc->pipe, PTR_ERR(intel_state->vma));
3230
3231                 intel_state->vma = NULL;
3232                 drm_framebuffer_put(fb);
3233                 return;
3234         }
3235
3236         obj = intel_fb_obj(fb);
3237         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
3238
3239         plane_state->src_x = 0;
3240         plane_state->src_y = 0;
3241         plane_state->src_w = fb->width << 16;
3242         plane_state->src_h = fb->height << 16;
3243
3244         plane_state->crtc_x = 0;
3245         plane_state->crtc_y = 0;
3246         plane_state->crtc_w = fb->width;
3247         plane_state->crtc_h = fb->height;
3248
3249         intel_state->base.src = drm_plane_state_src(plane_state);
3250         intel_state->base.dst = drm_plane_state_dest(plane_state);
3251
3252         if (i915_gem_object_is_tiled(obj))
3253                 dev_priv->preserve_bios_swizzle = true;
3254
3255         plane_state->fb = fb;
3256         plane_state->crtc = &intel_crtc->base;
3257
3258         atomic_or(to_intel_plane(primary)->frontbuffer_bit,
3259                   &obj->frontbuffer_bits);
3260 }
3261
3262 static int skl_max_plane_width(const struct drm_framebuffer *fb,
3263                                int color_plane,
3264                                unsigned int rotation)
3265 {
3266         int cpp = fb->format->cpp[color_plane];
3267
3268         switch (fb->modifier) {
3269         case DRM_FORMAT_MOD_LINEAR:
3270         case I915_FORMAT_MOD_X_TILED:
3271                 return 4096;
3272         case I915_FORMAT_MOD_Y_TILED_CCS:
3273         case I915_FORMAT_MOD_Yf_TILED_CCS:
3274                 /* FIXME AUX plane? */
3275         case I915_FORMAT_MOD_Y_TILED:
3276         case I915_FORMAT_MOD_Yf_TILED:
3277                 if (cpp == 8)
3278                         return 2048;
3279                 else
3280                         return 4096;
3281         default:
3282                 MISSING_CASE(fb->modifier);
3283                 return 2048;
3284         }
3285 }
3286
3287 static int glk_max_plane_width(const struct drm_framebuffer *fb,
3288                                int color_plane,
3289                                unsigned int rotation)
3290 {
3291         int cpp = fb->format->cpp[color_plane];
3292
3293         switch (fb->modifier) {
3294         case DRM_FORMAT_MOD_LINEAR:
3295         case I915_FORMAT_MOD_X_TILED:
3296                 if (cpp == 8)
3297                         return 4096;
3298                 else
3299                         return 5120;
3300         case I915_FORMAT_MOD_Y_TILED_CCS:
3301         case I915_FORMAT_MOD_Yf_TILED_CCS:
3302                 /* FIXME AUX plane? */
3303         case I915_FORMAT_MOD_Y_TILED:
3304         case I915_FORMAT_MOD_Yf_TILED:
3305                 if (cpp == 8)
3306                         return 2048;
3307                 else
3308                         return 5120;
3309         default:
3310                 MISSING_CASE(fb->modifier);
3311                 return 2048;
3312         }
3313 }
3314
3315 static int icl_max_plane_width(const struct drm_framebuffer *fb,
3316                                int color_plane,
3317                                unsigned int rotation)
3318 {
3319         return 5120;
3320 }
3321
3322 static bool skl_check_main_ccs_coordinates(struct intel_plane_state *plane_state,
3323                                            int main_x, int main_y, u32 main_offset)
3324 {
3325         const struct drm_framebuffer *fb = plane_state->base.fb;
3326         int hsub = fb->format->hsub;
3327         int vsub = fb->format->vsub;
3328         int aux_x = plane_state->color_plane[1].x;
3329         int aux_y = plane_state->color_plane[1].y;
3330         u32 aux_offset = plane_state->color_plane[1].offset;
3331         u32 alignment = intel_surf_alignment(fb, 1);
3332
3333         while (aux_offset >= main_offset && aux_y <= main_y) {
3334                 int x, y;
3335
3336                 if (aux_x == main_x && aux_y == main_y)
3337                         break;
3338
3339                 if (aux_offset == 0)
3340                         break;
3341
3342                 x = aux_x / hsub;
3343                 y = aux_y / vsub;
3344                 aux_offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 1,
3345                                                                aux_offset, aux_offset - alignment);
3346                 aux_x = x * hsub + aux_x % hsub;
3347                 aux_y = y * vsub + aux_y % vsub;
3348         }
3349
3350         if (aux_x != main_x || aux_y != main_y)
3351                 return false;
3352
3353         plane_state->color_plane[1].offset = aux_offset;
3354         plane_state->color_plane[1].x = aux_x;
3355         plane_state->color_plane[1].y = aux_y;
3356
3357         return true;
3358 }
3359
3360 static int skl_check_main_surface(struct intel_plane_state *plane_state)
3361 {
3362         struct drm_i915_private *dev_priv = to_i915(plane_state->base.plane->dev);
3363         const struct drm_framebuffer *fb = plane_state->base.fb;
3364         unsigned int rotation = plane_state->base.rotation;
3365         int x = plane_state->base.src.x1 >> 16;
3366         int y = plane_state->base.src.y1 >> 16;
3367         int w = drm_rect_width(&plane_state->base.src) >> 16;
3368         int h = drm_rect_height(&plane_state->base.src) >> 16;
3369         int max_width;
3370         int max_height = 4096;
3371         u32 alignment, offset, aux_offset = plane_state->color_plane[1].offset;
3372
3373         if (INTEL_GEN(dev_priv) >= 11)
3374                 max_width = icl_max_plane_width(fb, 0, rotation);
3375         else if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv))
3376                 max_width = glk_max_plane_width(fb, 0, rotation);
3377         else
3378                 max_width = skl_max_plane_width(fb, 0, rotation);
3379
3380         if (w > max_width || h > max_height) {
3381                 DRM_DEBUG_KMS("requested Y/RGB source size %dx%d too big (limit %dx%d)\n",
3382                               w, h, max_width, max_height);
3383                 return -EINVAL;
3384         }
3385
3386         intel_add_fb_offsets(&x, &y, plane_state, 0);
3387         offset = intel_plane_compute_aligned_offset(&x, &y, plane_state, 0);
3388         alignment = intel_surf_alignment(fb, 0);
3389
3390         /*
3391          * AUX surface offset is specified as the distance from the
3392          * main surface offset, and it must be non-negative. Make
3393          * sure that is what we will get.
3394          */
3395         if (offset > aux_offset)
3396                 offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 0,
3397                                                            offset, aux_offset & ~(alignment - 1));
3398
3399         /*
3400          * When using an X-tiled surface, the plane blows up
3401          * if the x offset + width exceed the stride.
3402          *
3403          * TODO: linear and Y-tiled seem fine, Yf untested,
3404          */
3405         if (fb->modifier == I915_FORMAT_MOD_X_TILED) {
3406                 int cpp = fb->format->cpp[0];
3407
3408                 while ((x + w) * cpp > plane_state->color_plane[0].stride) {
3409                         if (offset == 0) {
3410                                 DRM_DEBUG_KMS("Unable to find suitable display surface offset due to X-tiling\n");
3411                                 return -EINVAL;
3412                         }
3413
3414                         offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 0,
3415                                                                    offset, offset - alignment);
3416                 }
3417         }
3418
3419         /*
3420          * CCS AUX surface doesn't have its own x/y offsets, we must make sure
3421          * they match with the main surface x/y offsets.
3422          */
3423         if (is_ccs_modifier(fb->modifier)) {
3424                 while (!skl_check_main_ccs_coordinates(plane_state, x, y, offset)) {
3425                         if (offset == 0)
3426                                 break;
3427
3428                         offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 0,
3429                                                                    offset, offset - alignment);
3430                 }
3431
3432                 if (x != plane_state->color_plane[1].x || y != plane_state->color_plane[1].y) {
3433                         DRM_DEBUG_KMS("Unable to find suitable display surface offset due to CCS\n");
3434                         return -EINVAL;
3435                 }
3436         }
3437
3438         plane_state->color_plane[0].offset = offset;
3439         plane_state->color_plane[0].x = x;
3440         plane_state->color_plane[0].y = y;
3441
3442         /*
3443          * Put the final coordinates back so that the src
3444          * coordinate checks will see the right values.
3445          */
3446         drm_rect_translate(&plane_state->base.src,
3447                            (x << 16) - plane_state->base.src.x1,
3448                            (y << 16) - plane_state->base.src.y1);
3449
3450         return 0;
3451 }
3452
3453 static int skl_check_nv12_aux_surface(struct intel_plane_state *plane_state)
3454 {
3455         const struct drm_framebuffer *fb = plane_state->base.fb;
3456         unsigned int rotation = plane_state->base.rotation;
3457         int max_width = skl_max_plane_width(fb, 1, rotation);
3458         int max_height = 4096;
3459         int x = plane_state->base.src.x1 >> 17;
3460         int y = plane_state->base.src.y1 >> 17;
3461         int w = drm_rect_width(&plane_state->base.src) >> 17;
3462         int h = drm_rect_height(&plane_state->base.src) >> 17;
3463         u32 offset;
3464
3465         intel_add_fb_offsets(&x, &y, plane_state, 1);
3466         offset = intel_plane_compute_aligned_offset(&x, &y, plane_state, 1);
3467
3468         /* FIXME not quite sure how/if these apply to the chroma plane */
3469         if (w > max_width || h > max_height) {
3470                 DRM_DEBUG_KMS("CbCr source size %dx%d too big (limit %dx%d)\n",
3471                               w, h, max_width, max_height);
3472                 return -EINVAL;
3473         }
3474
3475         plane_state->color_plane[1].offset = offset;
3476         plane_state->color_plane[1].x = x;
3477         plane_state->color_plane[1].y = y;
3478
3479         return 0;
3480 }
3481
3482 static int skl_check_ccs_aux_surface(struct intel_plane_state *plane_state)
3483 {
3484         const struct drm_framebuffer *fb = plane_state->base.fb;
3485         int src_x = plane_state->base.src.x1 >> 16;
3486         int src_y = plane_state->base.src.y1 >> 16;
3487         int hsub = fb->format->hsub;
3488         int vsub = fb->format->vsub;
3489         int x = src_x / hsub;
3490         int y = src_y / vsub;
3491         u32 offset;
3492
3493         intel_add_fb_offsets(&x, &y, plane_state, 1);
3494         offset = intel_plane_compute_aligned_offset(&x, &y, plane_state, 1);
3495
3496         plane_state->color_plane[1].offset = offset;
3497         plane_state->color_plane[1].x = x * hsub + src_x % hsub;
3498         plane_state->color_plane[1].y = y * vsub + src_y % vsub;
3499
3500         return 0;
3501 }
3502
3503 int skl_check_plane_surface(struct intel_plane_state *plane_state)
3504 {
3505         const struct drm_framebuffer *fb = plane_state->base.fb;
3506         int ret;
3507
3508         ret = intel_plane_compute_gtt(plane_state);
3509         if (ret)
3510                 return ret;
3511
3512         if (!plane_state->base.visible)
3513                 return 0;
3514
3515         /*
3516          * Handle the AUX surface first since
3517          * the main surface setup depends on it.
3518          */
3519         if (is_planar_yuv_format(fb->format->format)) {
3520                 ret = skl_check_nv12_aux_surface(plane_state);
3521                 if (ret)
3522                         return ret;
3523         } else if (is_ccs_modifier(fb->modifier)) {
3524                 ret = skl_check_ccs_aux_surface(plane_state);
3525                 if (ret)
3526                         return ret;
3527         } else {
3528                 plane_state->color_plane[1].offset = ~0xfff;
3529                 plane_state->color_plane[1].x = 0;
3530                 plane_state->color_plane[1].y = 0;
3531         }
3532
3533         ret = skl_check_main_surface(plane_state);
3534         if (ret)
3535                 return ret;
3536
3537         return 0;
3538 }
3539
3540 unsigned int
3541 i9xx_plane_max_stride(struct intel_plane *plane,
3542                       u32 pixel_format, u64 modifier,
3543                       unsigned int rotation)
3544 {
3545         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3546
3547         if (!HAS_GMCH(dev_priv)) {
3548                 return 32*1024;
3549         } else if (INTEL_GEN(dev_priv) >= 4) {
3550                 if (modifier == I915_FORMAT_MOD_X_TILED)
3551                         return 16*1024;
3552                 else
3553                         return 32*1024;
3554         } else if (INTEL_GEN(dev_priv) >= 3) {
3555                 if (modifier == I915_FORMAT_MOD_X_TILED)
3556                         return 8*1024;
3557                 else
3558                         return 16*1024;
3559         } else {
3560                 if (plane->i9xx_plane == PLANE_C)
3561                         return 4*1024;
3562                 else
3563                         return 8*1024;
3564         }
3565 }
3566
3567 static u32 i9xx_plane_ctl_crtc(const struct intel_crtc_state *crtc_state)
3568 {
3569         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
3570         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
3571         u32 dspcntr = 0;
3572
3573         if (crtc_state->gamma_enable)
3574                 dspcntr |= DISPPLANE_GAMMA_ENABLE;
3575
3576         if (crtc_state->csc_enable)
3577                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
3578
3579         if (INTEL_GEN(dev_priv) < 5)
3580                 dspcntr |= DISPPLANE_SEL_PIPE(crtc->pipe);
3581
3582         return dspcntr;
3583 }
3584
3585 static u32 i9xx_plane_ctl(const struct intel_crtc_state *crtc_state,
3586                           const struct intel_plane_state *plane_state)
3587 {
3588         struct drm_i915_private *dev_priv =
3589                 to_i915(plane_state->base.plane->dev);
3590         const struct drm_framebuffer *fb = plane_state->base.fb;
3591         unsigned int rotation = plane_state->base.rotation;
3592         u32 dspcntr;
3593
3594         dspcntr = DISPLAY_PLANE_ENABLE;
3595
3596         if (IS_G4X(dev_priv) || IS_GEN(dev_priv, 5) ||
3597             IS_GEN(dev_priv, 6) || IS_IVYBRIDGE(dev_priv))
3598                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
3599
3600         switch (fb->format->format) {
3601         case DRM_FORMAT_C8:
3602                 dspcntr |= DISPPLANE_8BPP;
3603                 break;
3604         case DRM_FORMAT_XRGB1555:
3605                 dspcntr |= DISPPLANE_BGRX555;
3606                 break;
3607         case DRM_FORMAT_RGB565:
3608                 dspcntr |= DISPPLANE_BGRX565;
3609                 break;
3610         case DRM_FORMAT_XRGB8888:
3611                 dspcntr |= DISPPLANE_BGRX888;
3612                 break;
3613         case DRM_FORMAT_XBGR8888:
3614                 dspcntr |= DISPPLANE_RGBX888;
3615                 break;
3616         case DRM_FORMAT_XRGB2101010:
3617                 dspcntr |= DISPPLANE_BGRX101010;
3618                 break;
3619         case DRM_FORMAT_XBGR2101010:
3620                 dspcntr |= DISPPLANE_RGBX101010;
3621                 break;
3622         default:
3623                 MISSING_CASE(fb->format->format);
3624                 return 0;
3625         }
3626
3627         if (INTEL_GEN(dev_priv) >= 4 &&
3628             fb->modifier == I915_FORMAT_MOD_X_TILED)
3629                 dspcntr |= DISPPLANE_TILED;
3630
3631         if (rotation & DRM_MODE_ROTATE_180)
3632                 dspcntr |= DISPPLANE_ROTATE_180;
3633
3634         if (rotation & DRM_MODE_REFLECT_X)
3635                 dspcntr |= DISPPLANE_MIRROR;
3636
3637         return dspcntr;
3638 }
3639
3640 int i9xx_check_plane_surface(struct intel_plane_state *plane_state)
3641 {
3642         struct drm_i915_private *dev_priv =
3643                 to_i915(plane_state->base.plane->dev);
3644         int src_x, src_y;
3645         u32 offset;
3646         int ret;
3647
3648         ret = intel_plane_compute_gtt(plane_state);
3649         if (ret)
3650                 return ret;
3651
3652         if (!plane_state->base.visible)
3653                 return 0;
3654
3655         src_x = plane_state->base.src.x1 >> 16;
3656         src_y = plane_state->base.src.y1 >> 16;
3657
3658         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
3659
3660         if (INTEL_GEN(dev_priv) >= 4)
3661                 offset = intel_plane_compute_aligned_offset(&src_x, &src_y,
3662                                                             plane_state, 0);
3663         else
3664                 offset = 0;
3665
3666         /*
3667          * Put the final coordinates back so that the src
3668          * coordinate checks will see the right values.
3669          */
3670         drm_rect_translate(&plane_state->base.src,
3671                            (src_x << 16) - plane_state->base.src.x1,
3672                            (src_y << 16) - plane_state->base.src.y1);
3673
3674         /* HSW/BDW do this automagically in hardware */
3675         if (!IS_HASWELL(dev_priv) && !IS_BROADWELL(dev_priv)) {
3676                 unsigned int rotation = plane_state->base.rotation;
3677                 int src_w = drm_rect_width(&plane_state->base.src) >> 16;
3678                 int src_h = drm_rect_height(&plane_state->base.src) >> 16;
3679
3680                 if (rotation & DRM_MODE_ROTATE_180) {
3681                         src_x += src_w - 1;
3682                         src_y += src_h - 1;
3683                 } else if (rotation & DRM_MODE_REFLECT_X) {
3684                         src_x += src_w - 1;
3685                 }
3686         }
3687
3688         plane_state->color_plane[0].offset = offset;
3689         plane_state->color_plane[0].x = src_x;
3690         plane_state->color_plane[0].y = src_y;
3691
3692         return 0;
3693 }
3694
3695 static int
3696 i9xx_plane_check(struct intel_crtc_state *crtc_state,
3697                  struct intel_plane_state *plane_state)
3698 {
3699         int ret;
3700
3701         ret = chv_plane_check_rotation(plane_state);
3702         if (ret)
3703                 return ret;
3704
3705         ret = drm_atomic_helper_check_plane_state(&plane_state->base,
3706                                                   &crtc_state->base,
3707                                                   DRM_PLANE_HELPER_NO_SCALING,
3708                                                   DRM_PLANE_HELPER_NO_SCALING,
3709                                                   false, true);
3710         if (ret)
3711                 return ret;
3712
3713         ret = i9xx_check_plane_surface(plane_state);
3714         if (ret)
3715                 return ret;
3716
3717         if (!plane_state->base.visible)
3718                 return 0;
3719
3720         ret = intel_plane_check_src_coordinates(plane_state);
3721         if (ret)
3722                 return ret;
3723
3724         plane_state->ctl = i9xx_plane_ctl(crtc_state, plane_state);
3725
3726         return 0;
3727 }
3728
3729 static void i9xx_update_plane(struct intel_plane *plane,
3730                               const struct intel_crtc_state *crtc_state,
3731                               const struct intel_plane_state *plane_state)
3732 {
3733         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3734         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3735         u32 linear_offset;
3736         int x = plane_state->color_plane[0].x;
3737         int y = plane_state->color_plane[0].y;
3738         unsigned long irqflags;
3739         u32 dspaddr_offset;
3740         u32 dspcntr;
3741
3742         dspcntr = plane_state->ctl | i9xx_plane_ctl_crtc(crtc_state);
3743
3744         linear_offset = intel_fb_xy_to_linear(x, y, plane_state, 0);
3745
3746         if (INTEL_GEN(dev_priv) >= 4)
3747                 dspaddr_offset = plane_state->color_plane[0].offset;
3748         else
3749                 dspaddr_offset = linear_offset;
3750
3751         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3752
3753         I915_WRITE_FW(DSPSTRIDE(i9xx_plane), plane_state->color_plane[0].stride);
3754
3755         if (INTEL_GEN(dev_priv) < 4) {
3756                 /* pipesrc and dspsize control the size that is scaled from,
3757                  * which should always be the user's requested size.
3758                  */
3759                 I915_WRITE_FW(DSPPOS(i9xx_plane), 0);
3760                 I915_WRITE_FW(DSPSIZE(i9xx_plane),
3761                               ((crtc_state->pipe_src_h - 1) << 16) |
3762                               (crtc_state->pipe_src_w - 1));
3763         } else if (IS_CHERRYVIEW(dev_priv) && i9xx_plane == PLANE_B) {
3764                 I915_WRITE_FW(PRIMPOS(i9xx_plane), 0);
3765                 I915_WRITE_FW(PRIMSIZE(i9xx_plane),
3766                               ((crtc_state->pipe_src_h - 1) << 16) |
3767                               (crtc_state->pipe_src_w - 1));
3768                 I915_WRITE_FW(PRIMCNSTALPHA(i9xx_plane), 0);
3769         }
3770
3771         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
3772                 I915_WRITE_FW(DSPOFFSET(i9xx_plane), (y << 16) | x);
3773         } else if (INTEL_GEN(dev_priv) >= 4) {
3774                 I915_WRITE_FW(DSPLINOFF(i9xx_plane), linear_offset);
3775                 I915_WRITE_FW(DSPTILEOFF(i9xx_plane), (y << 16) | x);
3776         }
3777
3778         /*
3779          * The control register self-arms if the plane was previously
3780          * disabled. Try to make the plane enable atomic by writing
3781          * the control register just before the surface register.
3782          */
3783         I915_WRITE_FW(DSPCNTR(i9xx_plane), dspcntr);
3784         if (INTEL_GEN(dev_priv) >= 4)
3785                 I915_WRITE_FW(DSPSURF(i9xx_plane),
3786                               intel_plane_ggtt_offset(plane_state) +
3787                               dspaddr_offset);
3788         else
3789                 I915_WRITE_FW(DSPADDR(i9xx_plane),
3790                               intel_plane_ggtt_offset(plane_state) +
3791                               dspaddr_offset);
3792
3793         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3794 }
3795
3796 static void i9xx_disable_plane(struct intel_plane *plane,
3797                                const struct intel_crtc_state *crtc_state)
3798 {
3799         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3800         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3801         unsigned long irqflags;
3802         u32 dspcntr;
3803
3804         /*
3805          * DSPCNTR pipe gamma enable on g4x+ and pipe csc
3806          * enable on ilk+ affect the pipe bottom color as
3807          * well, so we must configure them even if the plane
3808          * is disabled.
3809          *
3810          * On pre-g4x there is no way to gamma correct the
3811          * pipe bottom color but we'll keep on doing this
3812          * anyway so that the crtc state readout works correctly.
3813          */
3814         dspcntr = i9xx_plane_ctl_crtc(crtc_state);
3815
3816         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3817
3818         I915_WRITE_FW(DSPCNTR(i9xx_plane), dspcntr);
3819         if (INTEL_GEN(dev_priv) >= 4)
3820                 I915_WRITE_FW(DSPSURF(i9xx_plane), 0);
3821         else
3822                 I915_WRITE_FW(DSPADDR(i9xx_plane), 0);
3823
3824         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3825 }
3826
3827 static bool i9xx_plane_get_hw_state(struct intel_plane *plane,
3828                                     enum pipe *pipe)
3829 {
3830         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3831         enum intel_display_power_domain power_domain;
3832         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3833         intel_wakeref_t wakeref;
3834         bool ret;
3835         u32 val;
3836
3837         /*
3838          * Not 100% correct for planes that can move between pipes,
3839          * but that's only the case for gen2-4 which don't have any
3840          * display power wells.
3841          */
3842         power_domain = POWER_DOMAIN_PIPE(plane->pipe);
3843         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
3844         if (!wakeref)
3845                 return false;
3846
3847         val = I915_READ(DSPCNTR(i9xx_plane));
3848
3849         ret = val & DISPLAY_PLANE_ENABLE;
3850
3851         if (INTEL_GEN(dev_priv) >= 5)
3852                 *pipe = plane->pipe;
3853         else
3854                 *pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
3855                         DISPPLANE_SEL_PIPE_SHIFT;
3856
3857         intel_display_power_put(dev_priv, power_domain, wakeref);
3858
3859         return ret;
3860 }
3861
3862 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
3863 {
3864         struct drm_device *dev = intel_crtc->base.dev;
3865         struct drm_i915_private *dev_priv = to_i915(dev);
3866
3867         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
3868         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
3869         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
3870 }
3871
3872 /*
3873  * This function detaches (aka. unbinds) unused scalers in hardware
3874  */
3875 static void skl_detach_scalers(const struct intel_crtc_state *crtc_state)
3876 {
3877         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
3878         const struct intel_crtc_scaler_state *scaler_state =
3879                 &crtc_state->scaler_state;
3880         int i;
3881
3882         /* loop through and disable scalers that aren't in use */
3883         for (i = 0; i < intel_crtc->num_scalers; i++) {
3884                 if (!scaler_state->scalers[i].in_use)
3885                         skl_detach_scaler(intel_crtc, i);
3886         }
3887 }
3888
3889 static unsigned int skl_plane_stride_mult(const struct drm_framebuffer *fb,
3890                                           int color_plane, unsigned int rotation)
3891 {
3892         /*
3893          * The stride is either expressed as a multiple of 64 bytes chunks for
3894          * linear buffers or in number of tiles for tiled buffers.
3895          */
3896         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
3897                 return 64;
3898         else if (drm_rotation_90_or_270(rotation))
3899                 return intel_tile_height(fb, color_plane);
3900         else
3901                 return intel_tile_width_bytes(fb, color_plane);
3902 }
3903
3904 u32 skl_plane_stride(const struct intel_plane_state *plane_state,
3905                      int color_plane)
3906 {
3907         const struct drm_framebuffer *fb = plane_state->base.fb;
3908         unsigned int rotation = plane_state->base.rotation;
3909         u32 stride = plane_state->color_plane[color_plane].stride;
3910
3911         if (color_plane >= fb->format->num_planes)
3912                 return 0;
3913
3914         return stride / skl_plane_stride_mult(fb, color_plane, rotation);
3915 }
3916
3917 static u32 skl_plane_ctl_format(u32 pixel_format)
3918 {
3919         switch (pixel_format) {
3920         case DRM_FORMAT_C8:
3921                 return PLANE_CTL_FORMAT_INDEXED;
3922         case DRM_FORMAT_RGB565:
3923                 return PLANE_CTL_FORMAT_RGB_565;
3924         case DRM_FORMAT_XBGR8888:
3925         case DRM_FORMAT_ABGR8888:
3926                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
3927         case DRM_FORMAT_XRGB8888:
3928         case DRM_FORMAT_ARGB8888:
3929                 return PLANE_CTL_FORMAT_XRGB_8888;
3930         case DRM_FORMAT_XRGB2101010:
3931                 return PLANE_CTL_FORMAT_XRGB_2101010;
3932         case DRM_FORMAT_XBGR2101010:
3933                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
3934         case DRM_FORMAT_XBGR16161616F:
3935         case DRM_FORMAT_ABGR16161616F:
3936                 return PLANE_CTL_FORMAT_XRGB_16161616F | PLANE_CTL_ORDER_RGBX;
3937         case DRM_FORMAT_XRGB16161616F:
3938         case DRM_FORMAT_ARGB16161616F:
3939                 return PLANE_CTL_FORMAT_XRGB_16161616F;
3940         case DRM_FORMAT_YUYV:
3941                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
3942         case DRM_FORMAT_YVYU:
3943                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
3944         case DRM_FORMAT_UYVY:
3945                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
3946         case DRM_FORMAT_VYUY:
3947                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
3948         case DRM_FORMAT_NV12:
3949                 return PLANE_CTL_FORMAT_NV12;
3950         case DRM_FORMAT_P010:
3951                 return PLANE_CTL_FORMAT_P010;
3952         case DRM_FORMAT_P012:
3953                 return PLANE_CTL_FORMAT_P012;
3954         case DRM_FORMAT_P016:
3955                 return PLANE_CTL_FORMAT_P016;
3956         case DRM_FORMAT_Y210:
3957                 return PLANE_CTL_FORMAT_Y210;
3958         case DRM_FORMAT_Y212:
3959                 return PLANE_CTL_FORMAT_Y212;
3960         case DRM_FORMAT_Y216:
3961                 return PLANE_CTL_FORMAT_Y216;
3962         case DRM_FORMAT_XVYU2101010:
3963                 return PLANE_CTL_FORMAT_Y410;
3964         case DRM_FORMAT_XVYU12_16161616:
3965                 return PLANE_CTL_FORMAT_Y412;
3966         case DRM_FORMAT_XVYU16161616:
3967                 return PLANE_CTL_FORMAT_Y416;
3968         default:
3969                 MISSING_CASE(pixel_format);
3970         }
3971
3972         return 0;
3973 }
3974
3975 static u32 skl_plane_ctl_alpha(const struct intel_plane_state *plane_state)
3976 {
3977         if (!plane_state->base.fb->format->has_alpha)
3978                 return PLANE_CTL_ALPHA_DISABLE;
3979
3980         switch (plane_state->base.pixel_blend_mode) {
3981         case DRM_MODE_BLEND_PIXEL_NONE:
3982                 return PLANE_CTL_ALPHA_DISABLE;
3983         case DRM_MODE_BLEND_PREMULTI:
3984                 return PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3985         case DRM_MODE_BLEND_COVERAGE:
3986                 return PLANE_CTL_ALPHA_HW_PREMULTIPLY;
3987         default:
3988                 MISSING_CASE(plane_state->base.pixel_blend_mode);
3989                 return PLANE_CTL_ALPHA_DISABLE;
3990         }
3991 }
3992
3993 static u32 glk_plane_color_ctl_alpha(const struct intel_plane_state *plane_state)
3994 {
3995         if (!plane_state->base.fb->format->has_alpha)
3996                 return PLANE_COLOR_ALPHA_DISABLE;
3997
3998         switch (plane_state->base.pixel_blend_mode) {
3999         case DRM_MODE_BLEND_PIXEL_NONE:
4000                 return PLANE_COLOR_ALPHA_DISABLE;
4001         case DRM_MODE_BLEND_PREMULTI:
4002                 return PLANE_COLOR_ALPHA_SW_PREMULTIPLY;
4003         case DRM_MODE_BLEND_COVERAGE:
4004                 return PLANE_COLOR_ALPHA_HW_PREMULTIPLY;
4005         default:
4006                 MISSING_CASE(plane_state->base.pixel_blend_mode);
4007                 return PLANE_COLOR_ALPHA_DISABLE;
4008         }
4009 }
4010
4011 static u32 skl_plane_ctl_tiling(u64 fb_modifier)
4012 {
4013         switch (fb_modifier) {
4014         case DRM_FORMAT_MOD_LINEAR:
4015                 break;
4016         case I915_FORMAT_MOD_X_TILED:
4017                 return PLANE_CTL_TILED_X;
4018         case I915_FORMAT_MOD_Y_TILED:
4019                 return PLANE_CTL_TILED_Y;
4020         case I915_FORMAT_MOD_Y_TILED_CCS:
4021                 return PLANE_CTL_TILED_Y | PLANE_CTL_RENDER_DECOMPRESSION_ENABLE;
4022         case I915_FORMAT_MOD_Yf_TILED:
4023                 return PLANE_CTL_TILED_YF;
4024         case I915_FORMAT_MOD_Yf_TILED_CCS:
4025                 return PLANE_CTL_TILED_YF | PLANE_CTL_RENDER_DECOMPRESSION_ENABLE;
4026         default:
4027                 MISSING_CASE(fb_modifier);
4028         }
4029
4030         return 0;
4031 }
4032
4033 static u32 skl_plane_ctl_rotate(unsigned int rotate)
4034 {
4035         switch (rotate) {
4036         case DRM_MODE_ROTATE_0:
4037                 break;
4038         /*
4039          * DRM_MODE_ROTATE_ is counter clockwise to stay compatible with Xrandr
4040          * while i915 HW rotation is clockwise, thats why this swapping.
4041          */
4042         case DRM_MODE_ROTATE_90:
4043                 return PLANE_CTL_ROTATE_270;
4044         case DRM_MODE_ROTATE_180:
4045                 return PLANE_CTL_ROTATE_180;
4046         case DRM_MODE_ROTATE_270:
4047                 return PLANE_CTL_ROTATE_90;
4048         default:
4049                 MISSING_CASE(rotate);
4050         }
4051
4052         return 0;
4053 }
4054
4055 static u32 cnl_plane_ctl_flip(unsigned int reflect)
4056 {
4057         switch (reflect) {
4058         case 0:
4059                 break;
4060         case DRM_MODE_REFLECT_X:
4061                 return PLANE_CTL_FLIP_HORIZONTAL;
4062         case DRM_MODE_REFLECT_Y:
4063         default:
4064                 MISSING_CASE(reflect);
4065         }
4066
4067         return 0;
4068 }
4069
4070 u32 skl_plane_ctl_crtc(const struct intel_crtc_state *crtc_state)
4071 {
4072         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
4073         u32 plane_ctl = 0;
4074
4075         if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv))
4076                 return plane_ctl;
4077
4078         if (crtc_state->gamma_enable)
4079                 plane_ctl |= PLANE_CTL_PIPE_GAMMA_ENABLE;
4080
4081         if (crtc_state->csc_enable)
4082                 plane_ctl |= PLANE_CTL_PIPE_CSC_ENABLE;
4083
4084         return plane_ctl;
4085 }
4086
4087 u32 skl_plane_ctl(const struct intel_crtc_state *crtc_state,
4088                   const struct intel_plane_state *plane_state)
4089 {
4090         struct drm_i915_private *dev_priv =
4091                 to_i915(plane_state->base.plane->dev);
4092         const struct drm_framebuffer *fb = plane_state->base.fb;
4093         unsigned int rotation = plane_state->base.rotation;
4094         const struct drm_intel_sprite_colorkey *key = &plane_state->ckey;
4095         u32 plane_ctl;
4096
4097         plane_ctl = PLANE_CTL_ENABLE;
4098
4099         if (INTEL_GEN(dev_priv) < 10 && !IS_GEMINILAKE(dev_priv)) {
4100                 plane_ctl |= skl_plane_ctl_alpha(plane_state);
4101                 plane_ctl |= PLANE_CTL_PLANE_GAMMA_DISABLE;
4102
4103                 if (plane_state->base.color_encoding == DRM_COLOR_YCBCR_BT709)
4104                         plane_ctl |= PLANE_CTL_YUV_TO_RGB_CSC_FORMAT_BT709;
4105
4106                 if (plane_state->base.color_range == DRM_COLOR_YCBCR_FULL_RANGE)
4107                         plane_ctl |= PLANE_CTL_YUV_RANGE_CORRECTION_DISABLE;
4108         }
4109
4110         plane_ctl |= skl_plane_ctl_format(fb->format->format);
4111         plane_ctl |= skl_plane_ctl_tiling(fb->modifier);
4112         plane_ctl |= skl_plane_ctl_rotate(rotation & DRM_MODE_ROTATE_MASK);
4113
4114         if (INTEL_GEN(dev_priv) >= 10)
4115                 plane_ctl |= cnl_plane_ctl_flip(rotation &
4116                                                 DRM_MODE_REFLECT_MASK);
4117
4118         if (key->flags & I915_SET_COLORKEY_DESTINATION)
4119                 plane_ctl |= PLANE_CTL_KEY_ENABLE_DESTINATION;
4120         else if (key->flags & I915_SET_COLORKEY_SOURCE)
4121                 plane_ctl |= PLANE_CTL_KEY_ENABLE_SOURCE;
4122
4123         return plane_ctl;
4124 }
4125
4126 u32 glk_plane_color_ctl_crtc(const struct intel_crtc_state *crtc_state)
4127 {
4128         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
4129         u32 plane_color_ctl = 0;
4130
4131         if (INTEL_GEN(dev_priv) >= 11)
4132                 return plane_color_ctl;
4133
4134         if (crtc_state->gamma_enable)
4135                 plane_color_ctl |= PLANE_COLOR_PIPE_GAMMA_ENABLE;
4136
4137         if (crtc_state->csc_enable)
4138                 plane_color_ctl |= PLANE_COLOR_PIPE_CSC_ENABLE;
4139
4140         return plane_color_ctl;
4141 }
4142
4143 u32 glk_plane_color_ctl(const struct intel_crtc_state *crtc_state,
4144                         const struct intel_plane_state *plane_state)
4145 {
4146         struct drm_i915_private *dev_priv =
4147                 to_i915(plane_state->base.plane->dev);
4148         const struct drm_framebuffer *fb = plane_state->base.fb;
4149         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
4150         u32 plane_color_ctl = 0;
4151
4152         plane_color_ctl |= PLANE_COLOR_PLANE_GAMMA_DISABLE;
4153         plane_color_ctl |= glk_plane_color_ctl_alpha(plane_state);
4154
4155         if (fb->format->is_yuv && !icl_is_hdr_plane(dev_priv, plane->id)) {
4156                 if (plane_state->base.color_encoding == DRM_COLOR_YCBCR_BT709)
4157                         plane_color_ctl |= PLANE_COLOR_CSC_MODE_YUV709_TO_RGB709;
4158                 else
4159                         plane_color_ctl |= PLANE_COLOR_CSC_MODE_YUV601_TO_RGB709;
4160
4161                 if (plane_state->base.color_range == DRM_COLOR_YCBCR_FULL_RANGE)
4162                         plane_color_ctl |= PLANE_COLOR_YUV_RANGE_CORRECTION_DISABLE;
4163         } else if (fb->format->is_yuv) {
4164                 plane_color_ctl |= PLANE_COLOR_INPUT_CSC_ENABLE;
4165         }
4166
4167         return plane_color_ctl;
4168 }
4169
4170 static int
4171 __intel_display_resume(struct drm_device *dev,
4172                        struct drm_atomic_state *state,
4173                        struct drm_modeset_acquire_ctx *ctx)
4174 {
4175         struct drm_crtc_state *crtc_state;
4176         struct drm_crtc *crtc;
4177         int i, ret;
4178
4179         intel_modeset_setup_hw_state(dev, ctx);
4180         i915_redisable_vga(to_i915(dev));
4181
4182         if (!state)
4183                 return 0;
4184
4185         /*
4186          * We've duplicated the state, pointers to the old state are invalid.
4187          *
4188          * Don't attempt to use the old state until we commit the duplicated state.
4189          */
4190         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
4191                 /*
4192                  * Force recalculation even if we restore
4193                  * current state. With fast modeset this may not result
4194                  * in a modeset when the state is compatible.
4195                  */
4196                 crtc_state->mode_changed = true;
4197         }
4198
4199         /* ignore any reset values/BIOS leftovers in the WM registers */
4200         if (!HAS_GMCH(to_i915(dev)))
4201                 to_intel_atomic_state(state)->skip_intermediate_wm = true;
4202
4203         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
4204
4205         WARN_ON(ret == -EDEADLK);
4206         return ret;
4207 }
4208
4209 static bool gpu_reset_clobbers_display(struct drm_i915_private *dev_priv)
4210 {
4211         return (INTEL_INFO(dev_priv)->gpu_reset_clobbers_display &&
4212                 intel_has_gpu_reset(dev_priv));
4213 }
4214
4215 void intel_prepare_reset(struct drm_i915_private *dev_priv)
4216 {
4217         struct drm_device *dev = &dev_priv->drm;
4218         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
4219         struct drm_atomic_state *state;
4220         int ret;
4221
4222         /* reset doesn't touch the display */
4223         if (!i915_modparams.force_reset_modeset_test &&
4224             !gpu_reset_clobbers_display(dev_priv))
4225                 return;
4226
4227         /* We have a modeset vs reset deadlock, defensively unbreak it. */
4228         set_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
4229         wake_up_all(&dev_priv->gpu_error.wait_queue);
4230
4231         if (atomic_read(&dev_priv->gpu_error.pending_fb_pin)) {
4232                 DRM_DEBUG_KMS("Modeset potentially stuck, unbreaking through wedging\n");
4233                 i915_gem_set_wedged(dev_priv);
4234         }
4235
4236         /*
4237          * Need mode_config.mutex so that we don't
4238          * trample ongoing ->detect() and whatnot.
4239          */
4240         mutex_lock(&dev->mode_config.mutex);
4241         drm_modeset_acquire_init(ctx, 0);
4242         while (1) {
4243                 ret = drm_modeset_lock_all_ctx(dev, ctx);
4244                 if (ret != -EDEADLK)
4245                         break;
4246
4247                 drm_modeset_backoff(ctx);
4248         }
4249         /*
4250          * Disabling the crtcs gracefully seems nicer. Also the
4251          * g33 docs say we should at least disable all the planes.
4252          */
4253         state = drm_atomic_helper_duplicate_state(dev, ctx);
4254         if (IS_ERR(state)) {
4255                 ret = PTR_ERR(state);
4256                 DRM_ERROR("Duplicating state failed with %i\n", ret);
4257                 return;
4258         }
4259
4260         ret = drm_atomic_helper_disable_all(dev, ctx);
4261         if (ret) {
4262                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
4263                 drm_atomic_state_put(state);
4264                 return;
4265         }
4266
4267         dev_priv->modeset_restore_state = state;
4268         state->acquire_ctx = ctx;
4269 }
4270
4271 void intel_finish_reset(struct drm_i915_private *dev_priv)
4272 {
4273         struct drm_device *dev = &dev_priv->drm;
4274         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
4275         struct drm_atomic_state *state;
4276         int ret;
4277
4278         /* reset doesn't touch the display */
4279         if (!test_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags))
4280                 return;
4281
4282         state = fetch_and_zero(&dev_priv->modeset_restore_state);
4283         if (!state)
4284                 goto unlock;
4285
4286         /* reset doesn't touch the display */
4287         if (!gpu_reset_clobbers_display(dev_priv)) {
4288                 /* for testing only restore the display */
4289                 ret = __intel_display_resume(dev, state, ctx);
4290                 if (ret)
4291                         DRM_ERROR("Restoring old state failed with %i\n", ret);
4292         } else {
4293                 /*
4294                  * The display has been reset as well,
4295                  * so need a full re-initialization.
4296                  */
4297                 intel_pps_unlock_regs_wa(dev_priv);
4298                 intel_modeset_init_hw(dev);
4299                 intel_init_clock_gating(dev_priv);
4300
4301                 spin_lock_irq(&dev_priv->irq_lock);
4302                 if (dev_priv->display.hpd_irq_setup)
4303                         dev_priv->display.hpd_irq_setup(dev_priv);
4304                 spin_unlock_irq(&dev_priv->irq_lock);
4305
4306                 ret = __intel_display_resume(dev, state, ctx);
4307                 if (ret)
4308                         DRM_ERROR("Restoring old state failed with %i\n", ret);
4309
4310                 intel_hpd_init(dev_priv);
4311         }
4312
4313         drm_atomic_state_put(state);
4314 unlock:
4315         drm_modeset_drop_locks(ctx);
4316         drm_modeset_acquire_fini(ctx);
4317         mutex_unlock(&dev->mode_config.mutex);
4318
4319         clear_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
4320 }
4321
4322 static void icl_set_pipe_chicken(struct intel_crtc *crtc)
4323 {
4324         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4325         enum pipe pipe = crtc->pipe;
4326         u32 tmp;
4327
4328         tmp = I915_READ(PIPE_CHICKEN(pipe));
4329
4330         /*
4331          * Display WA #1153: icl
4332          * enable hardware to bypass the alpha math
4333          * and rounding for per-pixel values 00 and 0xff
4334          */
4335         tmp |= PER_PIXEL_ALPHA_BYPASS_EN;
4336         /*
4337          * Display WA # 1605353570: icl
4338          * Set the pixel rounding bit to 1 for allowing
4339          * passthrough of Frame buffer pixels unmodified
4340          * across pipe
4341          */
4342         tmp |= PIXEL_ROUNDING_TRUNC_FB_PASSTHRU;
4343         I915_WRITE(PIPE_CHICKEN(pipe), tmp);
4344 }
4345
4346 static void intel_update_pipe_config(const struct intel_crtc_state *old_crtc_state,
4347                                      const struct intel_crtc_state *new_crtc_state)
4348 {
4349         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
4350         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4351
4352         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
4353         crtc->base.mode = new_crtc_state->base.mode;
4354
4355         /*
4356          * Update pipe size and adjust fitter if needed: the reason for this is
4357          * that in compute_mode_changes we check the native mode (not the pfit
4358          * mode) to see if we can flip rather than do a full mode set. In the
4359          * fastboot case, we'll flip, but if we don't update the pipesrc and
4360          * pfit state, we'll end up with a big fb scanned out into the wrong
4361          * sized surface.
4362          */
4363
4364         I915_WRITE(PIPESRC(crtc->pipe),
4365                    ((new_crtc_state->pipe_src_w - 1) << 16) |
4366                    (new_crtc_state->pipe_src_h - 1));
4367
4368         /* on skylake this is done by detaching scalers */
4369         if (INTEL_GEN(dev_priv) >= 9) {
4370                 skl_detach_scalers(new_crtc_state);
4371
4372                 if (new_crtc_state->pch_pfit.enabled)
4373                         skylake_pfit_enable(new_crtc_state);
4374         } else if (HAS_PCH_SPLIT(dev_priv)) {
4375                 if (new_crtc_state->pch_pfit.enabled)
4376                         ironlake_pfit_enable(new_crtc_state);
4377                 else if (old_crtc_state->pch_pfit.enabled)
4378                         ironlake_pfit_disable(old_crtc_state);
4379         }
4380
4381         if (INTEL_GEN(dev_priv) >= 11)
4382                 icl_set_pipe_chicken(crtc);
4383 }
4384
4385 static void intel_fdi_normal_train(struct intel_crtc *crtc)
4386 {
4387         struct drm_device *dev = crtc->base.dev;
4388         struct drm_i915_private *dev_priv = to_i915(dev);
4389         int pipe = crtc->pipe;
4390         i915_reg_t reg;
4391         u32 temp;
4392
4393         /* enable normal train */
4394         reg = FDI_TX_CTL(pipe);
4395         temp = I915_READ(reg);
4396         if (IS_IVYBRIDGE(dev_priv)) {
4397                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
4398                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
4399         } else {
4400                 temp &= ~FDI_LINK_TRAIN_NONE;
4401                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
4402         }
4403         I915_WRITE(reg, temp);
4404
4405         reg = FDI_RX_CTL(pipe);
4406         temp = I915_READ(reg);
4407         if (HAS_PCH_CPT(dev_priv)) {
4408                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4409                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
4410         } else {
4411                 temp &= ~FDI_LINK_TRAIN_NONE;
4412                 temp |= FDI_LINK_TRAIN_NONE;
4413         }
4414         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
4415
4416         /* wait one idle pattern time */
4417         POSTING_READ(reg);
4418         udelay(1000);
4419
4420         /* IVB wants error correction enabled */
4421         if (IS_IVYBRIDGE(dev_priv))
4422                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
4423                            FDI_FE_ERRC_ENABLE);
4424 }
4425
4426 /* The FDI link training functions for ILK/Ibexpeak. */
4427 static void ironlake_fdi_link_train(struct intel_crtc *crtc,
4428                                     const struct intel_crtc_state *crtc_state)
4429 {
4430         struct drm_device *dev = crtc->base.dev;
4431         struct drm_i915_private *dev_priv = to_i915(dev);
4432         int pipe = crtc->pipe;
4433         i915_reg_t reg;
4434         u32 temp, tries;
4435
4436         /* FDI needs bits from pipe first */
4437         assert_pipe_enabled(dev_priv, pipe);
4438
4439         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4440            for train result */
4441         reg = FDI_RX_IMR(pipe);
4442         temp = I915_READ(reg);
4443         temp &= ~FDI_RX_SYMBOL_LOCK;
4444         temp &= ~FDI_RX_BIT_LOCK;
4445         I915_WRITE(reg, temp);
4446         I915_READ(reg);
4447         udelay(150);
4448
4449         /* enable CPU FDI TX and PCH FDI RX */
4450         reg = FDI_TX_CTL(pipe);
4451         temp = I915_READ(reg);
4452         temp &= ~FDI_DP_PORT_WIDTH_MASK;
4453         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4454         temp &= ~FDI_LINK_TRAIN_NONE;
4455         temp |= FDI_LINK_TRAIN_PATTERN_1;
4456         I915_WRITE(reg, temp | FDI_TX_ENABLE);
4457
4458         reg = FDI_RX_CTL(pipe);
4459         temp = I915_READ(reg);
4460         temp &= ~FDI_LINK_TRAIN_NONE;
4461         temp |= FDI_LINK_TRAIN_PATTERN_1;
4462         I915_WRITE(reg, temp | FDI_RX_ENABLE);
4463
4464         POSTING_READ(reg);
4465         udelay(150);
4466
4467         /* Ironlake workaround, enable clock pointer after FDI enable*/
4468         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
4469         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
4470                    FDI_RX_PHASE_SYNC_POINTER_EN);
4471
4472         reg = FDI_RX_IIR(pipe);
4473         for (tries = 0; tries < 5; tries++) {
4474                 temp = I915_READ(reg);
4475                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4476
4477                 if ((temp & FDI_RX_BIT_LOCK)) {
4478                         DRM_DEBUG_KMS("FDI train 1 done.\n");
4479                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4480                         break;
4481                 }
4482         }
4483         if (tries == 5)
4484                 DRM_ERROR("FDI train 1 fail!\n");
4485
4486         /* Train 2 */
4487         reg = FDI_TX_CTL(pipe);
4488         temp = I915_READ(reg);
4489         temp &= ~FDI_LINK_TRAIN_NONE;
4490         temp |= FDI_LINK_TRAIN_PATTERN_2;
4491         I915_WRITE(reg, temp);
4492
4493         reg = FDI_RX_CTL(pipe);
4494         temp = I915_READ(reg);
4495         temp &= ~FDI_LINK_TRAIN_NONE;
4496         temp |= FDI_LINK_TRAIN_PATTERN_2;
4497         I915_WRITE(reg, temp);
4498
4499         POSTING_READ(reg);
4500         udelay(150);
4501
4502         reg = FDI_RX_IIR(pipe);
4503         for (tries = 0; tries < 5; tries++) {
4504                 temp = I915_READ(reg);
4505                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4506
4507                 if (temp & FDI_RX_SYMBOL_LOCK) {
4508                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4509                         DRM_DEBUG_KMS("FDI train 2 done.\n");
4510                         break;
4511                 }
4512         }
4513         if (tries == 5)
4514                 DRM_ERROR("FDI train 2 fail!\n");
4515
4516         DRM_DEBUG_KMS("FDI train done\n");
4517
4518 }
4519
4520 static const int snb_b_fdi_train_param[] = {
4521         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
4522         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
4523         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
4524         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
4525 };
4526
4527 /* The FDI link training functions for SNB/Cougarpoint. */
4528 static void gen6_fdi_link_train(struct intel_crtc *crtc,
4529                                 const struct intel_crtc_state *crtc_state)
4530 {
4531         struct drm_device *dev = crtc->base.dev;
4532         struct drm_i915_private *dev_priv = to_i915(dev);
4533         int pipe = crtc->pipe;
4534         i915_reg_t reg;
4535         u32 temp, i, retry;
4536
4537         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4538            for train result */
4539         reg = FDI_RX_IMR(pipe);
4540         temp = I915_READ(reg);
4541         temp &= ~FDI_RX_SYMBOL_LOCK;
4542         temp &= ~FDI_RX_BIT_LOCK;
4543         I915_WRITE(reg, temp);
4544
4545         POSTING_READ(reg);
4546         udelay(150);
4547
4548         /* enable CPU FDI TX and PCH FDI RX */
4549         reg = FDI_TX_CTL(pipe);
4550         temp = I915_READ(reg);
4551         temp &= ~FDI_DP_PORT_WIDTH_MASK;
4552         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4553         temp &= ~FDI_LINK_TRAIN_NONE;
4554         temp |= FDI_LINK_TRAIN_PATTERN_1;
4555         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4556         /* SNB-B */
4557         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
4558         I915_WRITE(reg, temp | FDI_TX_ENABLE);
4559
4560         I915_WRITE(FDI_RX_MISC(pipe),
4561                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4562
4563         reg = FDI_RX_CTL(pipe);
4564         temp = I915_READ(reg);
4565         if (HAS_PCH_CPT(dev_priv)) {
4566                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4567                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4568         } else {
4569                 temp &= ~FDI_LINK_TRAIN_NONE;
4570                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4571         }
4572         I915_WRITE(reg, temp | FDI_RX_ENABLE);
4573
4574         POSTING_READ(reg);
4575         udelay(150);
4576
4577         for (i = 0; i < 4; i++) {
4578                 reg = FDI_TX_CTL(pipe);
4579                 temp = I915_READ(reg);
4580                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4581                 temp |= snb_b_fdi_train_param[i];
4582                 I915_WRITE(reg, temp);
4583
4584                 POSTING_READ(reg);
4585                 udelay(500);
4586
4587                 for (retry = 0; retry < 5; retry++) {
4588                         reg = FDI_RX_IIR(pipe);
4589                         temp = I915_READ(reg);
4590                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4591                         if (temp & FDI_RX_BIT_LOCK) {
4592                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4593                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
4594                                 break;
4595                         }
4596                         udelay(50);
4597                 }
4598                 if (retry < 5)
4599                         break;
4600         }
4601         if (i == 4)
4602                 DRM_ERROR("FDI train 1 fail!\n");
4603
4604         /* Train 2 */
4605         reg = FDI_TX_CTL(pipe);
4606         temp = I915_READ(reg);
4607         temp &= ~FDI_LINK_TRAIN_NONE;
4608         temp |= FDI_LINK_TRAIN_PATTERN_2;
4609         if (IS_GEN(dev_priv, 6)) {
4610                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4611                 /* SNB-B */
4612                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
4613         }
4614         I915_WRITE(reg, temp);
4615
4616         reg = FDI_RX_CTL(pipe);
4617         temp = I915_READ(reg);
4618         if (HAS_PCH_CPT(dev_priv)) {
4619                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4620                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4621         } else {
4622                 temp &= ~FDI_LINK_TRAIN_NONE;
4623                 temp |= FDI_LINK_TRAIN_PATTERN_2;
4624         }
4625         I915_WRITE(reg, temp);
4626
4627         POSTING_READ(reg);
4628         udelay(150);
4629
4630         for (i = 0; i < 4; i++) {
4631                 reg = FDI_TX_CTL(pipe);
4632                 temp = I915_READ(reg);
4633                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4634                 temp |= snb_b_fdi_train_param[i];
4635                 I915_WRITE(reg, temp);
4636
4637                 POSTING_READ(reg);
4638                 udelay(500);
4639
4640                 for (retry = 0; retry < 5; retry++) {
4641                         reg = FDI_RX_IIR(pipe);
4642                         temp = I915_READ(reg);
4643                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4644                         if (temp & FDI_RX_SYMBOL_LOCK) {
4645                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4646                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
4647                                 break;
4648                         }
4649                         udelay(50);
4650                 }
4651                 if (retry < 5)
4652                         break;
4653         }
4654         if (i == 4)
4655                 DRM_ERROR("FDI train 2 fail!\n");
4656
4657         DRM_DEBUG_KMS("FDI train done.\n");
4658 }
4659
4660 /* Manual link training for Ivy Bridge A0 parts */
4661 static void ivb_manual_fdi_link_train(struct intel_crtc *crtc,
4662                                       const struct intel_crtc_state *crtc_state)
4663 {
4664         struct drm_device *dev = crtc->base.dev;
4665         struct drm_i915_private *dev_priv = to_i915(dev);
4666         int pipe = crtc->pipe;
4667         i915_reg_t reg;
4668         u32 temp, i, j;
4669
4670         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4671            for train result */
4672         reg = FDI_RX_IMR(pipe);
4673         temp = I915_READ(reg);
4674         temp &= ~FDI_RX_SYMBOL_LOCK;
4675         temp &= ~FDI_RX_BIT_LOCK;
4676         I915_WRITE(reg, temp);
4677
4678         POSTING_READ(reg);
4679         udelay(150);
4680
4681         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
4682                       I915_READ(FDI_RX_IIR(pipe)));
4683
4684         /* Try each vswing and preemphasis setting twice before moving on */
4685         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
4686                 /* disable first in case we need to retry */
4687                 reg = FDI_TX_CTL(pipe);
4688                 temp = I915_READ(reg);
4689                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
4690                 temp &= ~FDI_TX_ENABLE;
4691                 I915_WRITE(reg, temp);
4692
4693                 reg = FDI_RX_CTL(pipe);
4694                 temp = I915_READ(reg);
4695                 temp &= ~FDI_LINK_TRAIN_AUTO;
4696                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4697                 temp &= ~FDI_RX_ENABLE;
4698                 I915_WRITE(reg, temp);
4699
4700                 /* enable CPU FDI TX and PCH FDI RX */
4701                 reg = FDI_TX_CTL(pipe);
4702                 temp = I915_READ(reg);
4703                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
4704                 temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4705                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
4706                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4707                 temp |= snb_b_fdi_train_param[j/2];
4708                 temp |= FDI_COMPOSITE_SYNC;
4709                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
4710
4711                 I915_WRITE(FDI_RX_MISC(pipe),
4712                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4713
4714                 reg = FDI_RX_CTL(pipe);
4715                 temp = I915_READ(reg);
4716                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4717                 temp |= FDI_COMPOSITE_SYNC;
4718                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
4719
4720                 POSTING_READ(reg);
4721                 udelay(1); /* should be 0.5us */
4722
4723                 for (i = 0; i < 4; i++) {
4724                         reg = FDI_RX_IIR(pipe);
4725                         temp = I915_READ(reg);
4726                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4727
4728                         if (temp & FDI_RX_BIT_LOCK ||
4729                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
4730                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4731                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
4732                                               i);
4733                                 break;
4734                         }
4735                         udelay(1); /* should be 0.5us */
4736                 }
4737                 if (i == 4) {
4738                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
4739                         continue;
4740                 }
4741
4742                 /* Train 2 */
4743                 reg = FDI_TX_CTL(pipe);
4744                 temp = I915_READ(reg);
4745                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
4746                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
4747                 I915_WRITE(reg, temp);
4748
4749                 reg = FDI_RX_CTL(pipe);
4750                 temp = I915_READ(reg);
4751                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4752                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4753                 I915_WRITE(reg, temp);
4754
4755                 POSTING_READ(reg);
4756                 udelay(2); /* should be 1.5us */
4757
4758                 for (i = 0; i < 4; i++) {
4759                         reg = FDI_RX_IIR(pipe);
4760                         temp = I915_READ(reg);
4761                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4762
4763                         if (temp & FDI_RX_SYMBOL_LOCK ||
4764                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
4765                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4766                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
4767                                               i);
4768                                 goto train_done;
4769                         }
4770                         udelay(2); /* should be 1.5us */
4771                 }
4772                 if (i == 4)
4773                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
4774         }
4775
4776 train_done:
4777         DRM_DEBUG_KMS("FDI train done.\n");
4778 }
4779
4780 static void ironlake_fdi_pll_enable(const struct intel_crtc_state *crtc_state)
4781 {
4782         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
4783         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
4784         int pipe = intel_crtc->pipe;
4785         i915_reg_t reg;
4786         u32 temp;
4787
4788         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
4789         reg = FDI_RX_CTL(pipe);
4790         temp = I915_READ(reg);
4791         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
4792         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4793         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4794         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
4795
4796         POSTING_READ(reg);
4797         udelay(200);
4798
4799         /* Switch from Rawclk to PCDclk */
4800         temp = I915_READ(reg);
4801         I915_WRITE(reg, temp | FDI_PCDCLK);
4802
4803         POSTING_READ(reg);
4804         udelay(200);
4805
4806         /* Enable CPU FDI TX PLL, always on for Ironlake */
4807         reg = FDI_TX_CTL(pipe);
4808         temp = I915_READ(reg);
4809         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
4810                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
4811
4812                 POSTING_READ(reg);
4813                 udelay(100);
4814         }
4815 }
4816
4817 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
4818 {
4819         struct drm_device *dev = intel_crtc->base.dev;
4820         struct drm_i915_private *dev_priv = to_i915(dev);
4821         int pipe = intel_crtc->pipe;
4822         i915_reg_t reg;
4823         u32 temp;
4824
4825         /* Switch from PCDclk to Rawclk */
4826         reg = FDI_RX_CTL(pipe);
4827         temp = I915_READ(reg);
4828         I915_WRITE(reg, temp & ~FDI_PCDCLK);
4829
4830         /* Disable CPU FDI TX PLL */
4831         reg = FDI_TX_CTL(pipe);
4832         temp = I915_READ(reg);
4833         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
4834
4835         POSTING_READ(reg);
4836         udelay(100);
4837
4838         reg = FDI_RX_CTL(pipe);
4839         temp = I915_READ(reg);
4840         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
4841
4842         /* Wait for the clocks to turn off. */
4843         POSTING_READ(reg);
4844         udelay(100);
4845 }
4846
4847 static void ironlake_fdi_disable(struct drm_crtc *crtc)
4848 {
4849         struct drm_device *dev = crtc->dev;
4850         struct drm_i915_private *dev_priv = to_i915(dev);
4851         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4852         int pipe = intel_crtc->pipe;
4853         i915_reg_t reg;
4854         u32 temp;
4855
4856         /* disable CPU FDI tx and PCH FDI rx */
4857         reg = FDI_TX_CTL(pipe);
4858         temp = I915_READ(reg);
4859         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
4860         POSTING_READ(reg);
4861
4862         reg = FDI_RX_CTL(pipe);
4863         temp = I915_READ(reg);
4864         temp &= ~(0x7 << 16);
4865         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4866         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
4867
4868         POSTING_READ(reg);
4869         udelay(100);
4870
4871         /* Ironlake workaround, disable clock pointer after downing FDI */
4872         if (HAS_PCH_IBX(dev_priv))
4873                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
4874
4875         /* still set train pattern 1 */
4876         reg = FDI_TX_CTL(pipe);
4877         temp = I915_READ(reg);
4878         temp &= ~FDI_LINK_TRAIN_NONE;
4879         temp |= FDI_LINK_TRAIN_PATTERN_1;
4880         I915_WRITE(reg, temp);
4881
4882         reg = FDI_RX_CTL(pipe);
4883         temp = I915_READ(reg);
4884         if (HAS_PCH_CPT(dev_priv)) {
4885                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4886                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4887         } else {
4888                 temp &= ~FDI_LINK_TRAIN_NONE;
4889                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4890         }
4891         /* BPC in FDI rx is consistent with that in PIPECONF */
4892         temp &= ~(0x07 << 16);
4893         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4894         I915_WRITE(reg, temp);
4895
4896         POSTING_READ(reg);
4897         udelay(100);
4898 }
4899
4900 bool intel_has_pending_fb_unpin(struct drm_i915_private *dev_priv)
4901 {
4902         struct drm_crtc *crtc;
4903         bool cleanup_done;
4904
4905         drm_for_each_crtc(crtc, &dev_priv->drm) {
4906                 struct drm_crtc_commit *commit;
4907                 spin_lock(&crtc->commit_lock);
4908                 commit = list_first_entry_or_null(&crtc->commit_list,
4909                                                   struct drm_crtc_commit, commit_entry);
4910                 cleanup_done = commit ?
4911                         try_wait_for_completion(&commit->cleanup_done) : true;
4912                 spin_unlock(&crtc->commit_lock);
4913
4914                 if (cleanup_done)
4915                         continue;
4916
4917                 drm_crtc_wait_one_vblank(crtc);
4918
4919                 return true;
4920         }
4921
4922         return false;
4923 }
4924
4925 void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
4926 {
4927         u32 temp;
4928
4929         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
4930
4931         mutex_lock(&dev_priv->sb_lock);
4932
4933         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4934         temp |= SBI_SSCCTL_DISABLE;
4935         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4936
4937         mutex_unlock(&dev_priv->sb_lock);
4938 }
4939
4940 /* Program iCLKIP clock to the desired frequency */
4941 static void lpt_program_iclkip(const struct intel_crtc_state *crtc_state)
4942 {
4943         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4944         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4945         int clock = crtc_state->base.adjusted_mode.crtc_clock;
4946         u32 divsel, phaseinc, auxdiv, phasedir = 0;
4947         u32 temp;
4948
4949         lpt_disable_iclkip(dev_priv);
4950
4951         /* The iCLK virtual clock root frequency is in MHz,
4952          * but the adjusted_mode->crtc_clock in in KHz. To get the
4953          * divisors, it is necessary to divide one by another, so we
4954          * convert the virtual clock precision to KHz here for higher
4955          * precision.
4956          */
4957         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
4958                 u32 iclk_virtual_root_freq = 172800 * 1000;
4959                 u32 iclk_pi_range = 64;
4960                 u32 desired_divisor;
4961
4962                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4963                                                     clock << auxdiv);
4964                 divsel = (desired_divisor / iclk_pi_range) - 2;
4965                 phaseinc = desired_divisor % iclk_pi_range;
4966
4967                 /*
4968                  * Near 20MHz is a corner case which is
4969                  * out of range for the 7-bit divisor
4970                  */
4971                 if (divsel <= 0x7f)
4972                         break;
4973         }
4974
4975         /* This should not happen with any sane values */
4976         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
4977                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
4978         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
4979                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
4980
4981         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
4982                         clock,
4983                         auxdiv,
4984                         divsel,
4985                         phasedir,
4986                         phaseinc);
4987
4988         mutex_lock(&dev_priv->sb_lock);
4989
4990         /* Program SSCDIVINTPHASE6 */
4991         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4992         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
4993         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
4994         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
4995         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
4996         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
4997         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
4998         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
4999
5000         /* Program SSCAUXDIV */
5001         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
5002         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
5003         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
5004         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
5005
5006         /* Enable modulator and associated divider */
5007         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
5008         temp &= ~SBI_SSCCTL_DISABLE;
5009         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
5010
5011         mutex_unlock(&dev_priv->sb_lock);
5012
5013         /* Wait for initialization time */
5014         udelay(24);
5015
5016         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
5017 }
5018
5019 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
5020 {
5021         u32 divsel, phaseinc, auxdiv;
5022         u32 iclk_virtual_root_freq = 172800 * 1000;
5023         u32 iclk_pi_range = 64;
5024         u32 desired_divisor;
5025         u32 temp;
5026
5027         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
5028                 return 0;
5029
5030         mutex_lock(&dev_priv->sb_lock);
5031
5032         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
5033         if (temp & SBI_SSCCTL_DISABLE) {
5034                 mutex_unlock(&dev_priv->sb_lock);
5035                 return 0;
5036         }
5037
5038         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
5039         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
5040                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
5041         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
5042                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
5043
5044         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
5045         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
5046                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
5047
5048         mutex_unlock(&dev_priv->sb_lock);
5049
5050         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
5051
5052         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
5053                                  desired_divisor << auxdiv);
5054 }
5055
5056 static void ironlake_pch_transcoder_set_timings(const struct intel_crtc_state *crtc_state,
5057                                                 enum pipe pch_transcoder)
5058 {
5059         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5060         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5061         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
5062
5063         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
5064                    I915_READ(HTOTAL(cpu_transcoder)));
5065         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
5066                    I915_READ(HBLANK(cpu_transcoder)));
5067         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
5068                    I915_READ(HSYNC(cpu_transcoder)));
5069
5070         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
5071                    I915_READ(VTOTAL(cpu_transcoder)));
5072         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
5073                    I915_READ(VBLANK(cpu_transcoder)));
5074         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
5075                    I915_READ(VSYNC(cpu_transcoder)));
5076         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
5077                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
5078 }
5079
5080 static void cpt_set_fdi_bc_bifurcation(struct drm_i915_private *dev_priv, bool enable)
5081 {
5082         u32 temp;
5083
5084         temp = I915_READ(SOUTH_CHICKEN1);
5085         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
5086                 return;
5087
5088         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
5089         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
5090
5091         temp &= ~FDI_BC_BIFURCATION_SELECT;
5092         if (enable)
5093                 temp |= FDI_BC_BIFURCATION_SELECT;
5094
5095         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
5096         I915_WRITE(SOUTH_CHICKEN1, temp);
5097         POSTING_READ(SOUTH_CHICKEN1);
5098 }
5099
5100 static void ivybridge_update_fdi_bc_bifurcation(const struct intel_crtc_state *crtc_state)
5101 {
5102         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5103         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5104
5105         switch (crtc->pipe) {
5106         case PIPE_A:
5107                 break;
5108         case PIPE_B:
5109                 if (crtc_state->fdi_lanes > 2)
5110                         cpt_set_fdi_bc_bifurcation(dev_priv, false);
5111                 else
5112                         cpt_set_fdi_bc_bifurcation(dev_priv, true);
5113
5114                 break;
5115         case PIPE_C:
5116                 cpt_set_fdi_bc_bifurcation(dev_priv, true);
5117
5118                 break;
5119         default:
5120                 BUG();
5121         }
5122 }
5123
5124 /*
5125  * Finds the encoder associated with the given CRTC. This can only be
5126  * used when we know that the CRTC isn't feeding multiple encoders!
5127  */
5128 static struct intel_encoder *
5129 intel_get_crtc_new_encoder(const struct intel_atomic_state *state,
5130                            const struct intel_crtc_state *crtc_state)
5131 {
5132         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5133         const struct drm_connector_state *connector_state;
5134         const struct drm_connector *connector;
5135         struct intel_encoder *encoder = NULL;
5136         int num_encoders = 0;
5137         int i;
5138
5139         for_each_new_connector_in_state(&state->base, connector, connector_state, i) {
5140                 if (connector_state->crtc != &crtc->base)
5141                         continue;
5142
5143                 encoder = to_intel_encoder(connector_state->best_encoder);
5144                 num_encoders++;
5145         }
5146
5147         WARN(num_encoders != 1, "%d encoders for pipe %c\n",
5148              num_encoders, pipe_name(crtc->pipe));
5149
5150         return encoder;
5151 }
5152
5153 /*
5154  * Enable PCH resources required for PCH ports:
5155  *   - PCH PLLs
5156  *   - FDI training & RX/TX
5157  *   - update transcoder timings
5158  *   - DP transcoding bits
5159  *   - transcoder
5160  */
5161 static void ironlake_pch_enable(const struct intel_atomic_state *state,
5162                                 const struct intel_crtc_state *crtc_state)
5163 {
5164         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5165         struct drm_device *dev = crtc->base.dev;
5166         struct drm_i915_private *dev_priv = to_i915(dev);
5167         int pipe = crtc->pipe;
5168         u32 temp;
5169
5170         assert_pch_transcoder_disabled(dev_priv, pipe);
5171
5172         if (IS_IVYBRIDGE(dev_priv))
5173                 ivybridge_update_fdi_bc_bifurcation(crtc_state);
5174
5175         /* Write the TU size bits before fdi link training, so that error
5176          * detection works. */
5177         I915_WRITE(FDI_RX_TUSIZE1(pipe),
5178                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
5179
5180         /* For PCH output, training FDI link */
5181         dev_priv->display.fdi_link_train(crtc, crtc_state);
5182
5183         /* We need to program the right clock selection before writing the pixel
5184          * mutliplier into the DPLL. */
5185         if (HAS_PCH_CPT(dev_priv)) {
5186                 u32 sel;
5187
5188                 temp = I915_READ(PCH_DPLL_SEL);
5189                 temp |= TRANS_DPLL_ENABLE(pipe);
5190                 sel = TRANS_DPLLB_SEL(pipe);
5191                 if (crtc_state->shared_dpll ==
5192                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
5193                         temp |= sel;
5194                 else
5195                         temp &= ~sel;
5196                 I915_WRITE(PCH_DPLL_SEL, temp);
5197         }
5198
5199         /* XXX: pch pll's can be enabled any time before we enable the PCH
5200          * transcoder, and we actually should do this to not upset any PCH
5201          * transcoder that already use the clock when we share it.
5202          *
5203          * Note that enable_shared_dpll tries to do the right thing, but
5204          * get_shared_dpll unconditionally resets the pll - we need that to have
5205          * the right LVDS enable sequence. */
5206         intel_enable_shared_dpll(crtc_state);
5207
5208         /* set transcoder timing, panel must allow it */
5209         assert_panel_unlocked(dev_priv, pipe);
5210         ironlake_pch_transcoder_set_timings(crtc_state, pipe);
5211
5212         intel_fdi_normal_train(crtc);
5213
5214         /* For PCH DP, enable TRANS_DP_CTL */
5215         if (HAS_PCH_CPT(dev_priv) &&
5216             intel_crtc_has_dp_encoder(crtc_state)) {
5217                 const struct drm_display_mode *adjusted_mode =
5218                         &crtc_state->base.adjusted_mode;
5219                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
5220                 i915_reg_t reg = TRANS_DP_CTL(pipe);
5221                 enum port port;
5222
5223                 temp = I915_READ(reg);
5224                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
5225                           TRANS_DP_SYNC_MASK |
5226                           TRANS_DP_BPC_MASK);
5227                 temp |= TRANS_DP_OUTPUT_ENABLE;
5228                 temp |= bpc << 9; /* same format but at 11:9 */
5229
5230                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
5231                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
5232                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
5233                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
5234
5235                 port = intel_get_crtc_new_encoder(state, crtc_state)->port;
5236                 WARN_ON(port < PORT_B || port > PORT_D);
5237                 temp |= TRANS_DP_PORT_SEL(port);
5238
5239                 I915_WRITE(reg, temp);
5240         }
5241
5242         ironlake_enable_pch_transcoder(crtc_state);
5243 }
5244
5245 static void lpt_pch_enable(const struct intel_atomic_state *state,
5246                            const struct intel_crtc_state *crtc_state)
5247 {
5248         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5249         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5250         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
5251
5252         assert_pch_transcoder_disabled(dev_priv, PIPE_A);
5253
5254         lpt_program_iclkip(crtc_state);
5255
5256         /* Set transcoder timing. */
5257         ironlake_pch_transcoder_set_timings(crtc_state, PIPE_A);
5258
5259         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
5260 }
5261
5262 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
5263 {
5264         struct drm_i915_private *dev_priv = to_i915(dev);
5265         i915_reg_t dslreg = PIPEDSL(pipe);
5266         u32 temp;
5267
5268         temp = I915_READ(dslreg);
5269         udelay(500);
5270         if (wait_for(I915_READ(dslreg) != temp, 5)) {
5271                 if (wait_for(I915_READ(dslreg) != temp, 5))
5272                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
5273         }
5274 }
5275
5276 /*
5277  * The hardware phase 0.0 refers to the center of the pixel.
5278  * We want to start from the top/left edge which is phase
5279  * -0.5. That matches how the hardware calculates the scaling
5280  * factors (from top-left of the first pixel to bottom-right
5281  * of the last pixel, as opposed to the pixel centers).
5282  *
5283  * For 4:2:0 subsampled chroma planes we obviously have to
5284  * adjust that so that the chroma sample position lands in
5285  * the right spot.
5286  *
5287  * Note that for packed YCbCr 4:2:2 formats there is no way to
5288  * control chroma siting. The hardware simply replicates the
5289  * chroma samples for both of the luma samples, and thus we don't
5290  * actually get the expected MPEG2 chroma siting convention :(
5291  * The same behaviour is observed on pre-SKL platforms as well.
5292  *
5293  * Theory behind the formula (note that we ignore sub-pixel
5294  * source coordinates):
5295  * s = source sample position
5296  * d = destination sample position
5297  *
5298  * Downscaling 4:1:
5299  * -0.5
5300  * | 0.0
5301  * | |     1.5 (initial phase)
5302  * | |     |
5303  * v v     v
5304  * | s | s | s | s |
5305  * |       d       |
5306  *
5307  * Upscaling 1:4:
5308  * -0.5
5309  * | -0.375 (initial phase)
5310  * | |     0.0
5311  * | |     |
5312  * v v     v
5313  * |       s       |
5314  * | d | d | d | d |
5315  */
5316 u16 skl_scaler_calc_phase(int sub, int scale, bool chroma_cosited)
5317 {
5318         int phase = -0x8000;
5319         u16 trip = 0;
5320
5321         if (chroma_cosited)
5322                 phase += (sub - 1) * 0x8000 / sub;
5323
5324         phase += scale / (2 * sub);
5325
5326         /*
5327          * Hardware initial phase limited to [-0.5:1.5].
5328          * Since the max hardware scale factor is 3.0, we
5329          * should never actually excdeed 1.0 here.
5330          */
5331         WARN_ON(phase < -0x8000 || phase > 0x18000);
5332
5333         if (phase < 0)
5334                 phase = 0x10000 + phase;
5335         else
5336                 trip = PS_PHASE_TRIP;
5337
5338         return ((phase >> 2) & PS_PHASE_MASK) | trip;
5339 }
5340
5341 #define SKL_MIN_SRC_W 8
5342 #define SKL_MAX_SRC_W 4096
5343 #define SKL_MIN_SRC_H 8
5344 #define SKL_MAX_SRC_H 4096
5345 #define SKL_MIN_DST_W 8
5346 #define SKL_MAX_DST_W 4096
5347 #define SKL_MIN_DST_H 8
5348 #define SKL_MAX_DST_H 4096
5349 #define ICL_MAX_SRC_W 5120
5350 #define ICL_MAX_SRC_H 4096
5351 #define ICL_MAX_DST_W 5120
5352 #define ICL_MAX_DST_H 4096
5353 #define SKL_MIN_YUV_420_SRC_W 16
5354 #define SKL_MIN_YUV_420_SRC_H 16
5355
5356 static int
5357 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
5358                   unsigned int scaler_user, int *scaler_id,
5359                   int src_w, int src_h, int dst_w, int dst_h,
5360                   const struct drm_format_info *format, bool need_scaler)
5361 {
5362         struct intel_crtc_scaler_state *scaler_state =
5363                 &crtc_state->scaler_state;
5364         struct intel_crtc *intel_crtc =
5365                 to_intel_crtc(crtc_state->base.crtc);
5366         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
5367         const struct drm_display_mode *adjusted_mode =
5368                 &crtc_state->base.adjusted_mode;
5369
5370         /*
5371          * Src coordinates are already rotated by 270 degrees for
5372          * the 90/270 degree plane rotation cases (to match the
5373          * GTT mapping), hence no need to account for rotation here.
5374          */
5375         if (src_w != dst_w || src_h != dst_h)
5376                 need_scaler = true;
5377
5378         /*
5379          * Scaling/fitting not supported in IF-ID mode in GEN9+
5380          * TODO: Interlace fetch mode doesn't support YUV420 planar formats.
5381          * Once NV12 is enabled, handle it here while allocating scaler
5382          * for NV12.
5383          */
5384         if (INTEL_GEN(dev_priv) >= 9 && crtc_state->base.enable &&
5385             need_scaler && adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
5386                 DRM_DEBUG_KMS("Pipe/Plane scaling not supported with IF-ID mode\n");
5387                 return -EINVAL;
5388         }
5389
5390         /*
5391          * if plane is being disabled or scaler is no more required or force detach
5392          *  - free scaler binded to this plane/crtc
5393          *  - in order to do this, update crtc->scaler_usage
5394          *
5395          * Here scaler state in crtc_state is set free so that
5396          * scaler can be assigned to other user. Actual register
5397          * update to free the scaler is done in plane/panel-fit programming.
5398          * For this purpose crtc/plane_state->scaler_id isn't reset here.
5399          */
5400         if (force_detach || !need_scaler) {
5401                 if (*scaler_id >= 0) {
5402                         scaler_state->scaler_users &= ~(1 << scaler_user);
5403                         scaler_state->scalers[*scaler_id].in_use = 0;
5404
5405                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
5406                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
5407                                 intel_crtc->pipe, scaler_user, *scaler_id,
5408                                 scaler_state->scaler_users);
5409                         *scaler_id = -1;
5410                 }
5411                 return 0;
5412         }
5413
5414         if (format && is_planar_yuv_format(format->format) &&
5415             (src_h < SKL_MIN_YUV_420_SRC_H || src_w < SKL_MIN_YUV_420_SRC_W)) {
5416                 DRM_DEBUG_KMS("Planar YUV: src dimensions not met\n");
5417                 return -EINVAL;
5418         }
5419
5420         /* range checks */
5421         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
5422             dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
5423             (INTEL_GEN(dev_priv) >= 11 &&
5424              (src_w > ICL_MAX_SRC_W || src_h > ICL_MAX_SRC_H ||
5425               dst_w > ICL_MAX_DST_W || dst_h > ICL_MAX_DST_H)) ||
5426             (INTEL_GEN(dev_priv) < 11 &&
5427              (src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
5428               dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H))) {
5429                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
5430                         "size is out of scaler range\n",
5431                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
5432                 return -EINVAL;
5433         }
5434
5435         /* mark this plane as a scaler user in crtc_state */
5436         scaler_state->scaler_users |= (1 << scaler_user);
5437         DRM_DEBUG_KMS("scaler_user index %u.%u: "
5438                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
5439                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
5440                 scaler_state->scaler_users);
5441
5442         return 0;
5443 }
5444
5445 /**
5446  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
5447  *
5448  * @state: crtc's scaler state
5449  *
5450  * Return
5451  *     0 - scaler_usage updated successfully
5452  *    error - requested scaling cannot be supported or other error condition
5453  */
5454 int skl_update_scaler_crtc(struct intel_crtc_state *state)
5455 {
5456         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
5457         bool need_scaler = false;
5458
5459         if (state->output_format == INTEL_OUTPUT_FORMAT_YCBCR420)
5460                 need_scaler = true;
5461
5462         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
5463                                  &state->scaler_state.scaler_id,
5464                                  state->pipe_src_w, state->pipe_src_h,
5465                                  adjusted_mode->crtc_hdisplay,
5466                                  adjusted_mode->crtc_vdisplay, NULL, need_scaler);
5467 }
5468
5469 /**
5470  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
5471  * @crtc_state: crtc's scaler state
5472  * @plane_state: atomic plane state to update
5473  *
5474  * Return
5475  *     0 - scaler_usage updated successfully
5476  *    error - requested scaling cannot be supported or other error condition
5477  */
5478 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
5479                                    struct intel_plane_state *plane_state)
5480 {
5481         struct intel_plane *intel_plane =
5482                 to_intel_plane(plane_state->base.plane);
5483         struct drm_i915_private *dev_priv = to_i915(intel_plane->base.dev);
5484         struct drm_framebuffer *fb = plane_state->base.fb;
5485         int ret;
5486         bool force_detach = !fb || !plane_state->base.visible;
5487         bool need_scaler = false;
5488
5489         /* Pre-gen11 and SDR planes always need a scaler for planar formats. */
5490         if (!icl_is_hdr_plane(dev_priv, intel_plane->id) &&
5491             fb && is_planar_yuv_format(fb->format->format))
5492                 need_scaler = true;
5493
5494         ret = skl_update_scaler(crtc_state, force_detach,
5495                                 drm_plane_index(&intel_plane->base),
5496                                 &plane_state->scaler_id,
5497                                 drm_rect_width(&plane_state->base.src) >> 16,
5498                                 drm_rect_height(&plane_state->base.src) >> 16,
5499                                 drm_rect_width(&plane_state->base.dst),
5500                                 drm_rect_height(&plane_state->base.dst),
5501                                 fb ? fb->format : NULL, need_scaler);
5502
5503         if (ret || plane_state->scaler_id < 0)
5504                 return ret;
5505
5506         /* check colorkey */
5507         if (plane_state->ckey.flags) {
5508                 DRM_DEBUG_KMS("[PLANE:%d:%s] scaling with color key not allowed",
5509                               intel_plane->base.base.id,
5510                               intel_plane->base.name);
5511                 return -EINVAL;
5512         }
5513
5514         /* Check src format */
5515         switch (fb->format->format) {
5516         case DRM_FORMAT_RGB565:
5517         case DRM_FORMAT_XBGR8888:
5518         case DRM_FORMAT_XRGB8888:
5519         case DRM_FORMAT_ABGR8888:
5520         case DRM_FORMAT_ARGB8888:
5521         case DRM_FORMAT_XRGB2101010:
5522         case DRM_FORMAT_XBGR2101010:
5523         case DRM_FORMAT_XBGR16161616F:
5524         case DRM_FORMAT_ABGR16161616F:
5525         case DRM_FORMAT_XRGB16161616F:
5526         case DRM_FORMAT_ARGB16161616F:
5527         case DRM_FORMAT_YUYV:
5528         case DRM_FORMAT_YVYU:
5529         case DRM_FORMAT_UYVY:
5530         case DRM_FORMAT_VYUY:
5531         case DRM_FORMAT_NV12:
5532         case DRM_FORMAT_P010:
5533         case DRM_FORMAT_P012:
5534         case DRM_FORMAT_P016:
5535         case DRM_FORMAT_Y210:
5536         case DRM_FORMAT_Y212:
5537         case DRM_FORMAT_Y216:
5538         case DRM_FORMAT_XVYU2101010:
5539         case DRM_FORMAT_XVYU12_16161616:
5540         case DRM_FORMAT_XVYU16161616:
5541                 break;
5542         default:
5543                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d unsupported scaling format 0x%x\n",
5544                               intel_plane->base.base.id, intel_plane->base.name,
5545                               fb->base.id, fb->format->format);
5546                 return -EINVAL;
5547         }
5548
5549         return 0;
5550 }
5551
5552 static void skylake_scaler_disable(struct intel_crtc *crtc)
5553 {
5554         int i;
5555
5556         for (i = 0; i < crtc->num_scalers; i++)
5557                 skl_detach_scaler(crtc, i);
5558 }
5559
5560 static void skylake_pfit_enable(const struct intel_crtc_state *crtc_state)
5561 {
5562         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5563         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5564         enum pipe pipe = crtc->pipe;
5565         const struct intel_crtc_scaler_state *scaler_state =
5566                 &crtc_state->scaler_state;
5567
5568         if (crtc_state->pch_pfit.enabled) {
5569                 u16 uv_rgb_hphase, uv_rgb_vphase;
5570                 int pfit_w, pfit_h, hscale, vscale;
5571                 int id;
5572
5573                 if (WARN_ON(crtc_state->scaler_state.scaler_id < 0))
5574                         return;
5575
5576                 pfit_w = (crtc_state->pch_pfit.size >> 16) & 0xFFFF;
5577                 pfit_h = crtc_state->pch_pfit.size & 0xFFFF;
5578
5579                 hscale = (crtc_state->pipe_src_w << 16) / pfit_w;
5580                 vscale = (crtc_state->pipe_src_h << 16) / pfit_h;
5581
5582                 uv_rgb_hphase = skl_scaler_calc_phase(1, hscale, false);
5583                 uv_rgb_vphase = skl_scaler_calc_phase(1, vscale, false);
5584
5585                 id = scaler_state->scaler_id;
5586                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
5587                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
5588                 I915_WRITE_FW(SKL_PS_VPHASE(pipe, id),
5589                               PS_Y_PHASE(0) | PS_UV_RGB_PHASE(uv_rgb_vphase));
5590                 I915_WRITE_FW(SKL_PS_HPHASE(pipe, id),
5591                               PS_Y_PHASE(0) | PS_UV_RGB_PHASE(uv_rgb_hphase));
5592                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc_state->pch_pfit.pos);
5593                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc_state->pch_pfit.size);
5594         }
5595 }
5596
5597 static void ironlake_pfit_enable(const struct intel_crtc_state *crtc_state)
5598 {
5599         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5600         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5601         int pipe = crtc->pipe;
5602
5603         if (crtc_state->pch_pfit.enabled) {
5604                 /* Force use of hard-coded filter coefficients
5605                  * as some pre-programmed values are broken,
5606                  * e.g. x201.
5607                  */
5608                 if (IS_IVYBRIDGE(dev_priv) || IS_HASWELL(dev_priv))
5609                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
5610                                                  PF_PIPE_SEL_IVB(pipe));
5611                 else
5612                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
5613                 I915_WRITE(PF_WIN_POS(pipe), crtc_state->pch_pfit.pos);
5614                 I915_WRITE(PF_WIN_SZ(pipe), crtc_state->pch_pfit.size);
5615         }
5616 }
5617
5618 void hsw_enable_ips(const struct intel_crtc_state *crtc_state)
5619 {
5620         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5621         struct drm_device *dev = crtc->base.dev;
5622         struct drm_i915_private *dev_priv = to_i915(dev);
5623
5624         if (!crtc_state->ips_enabled)
5625                 return;
5626
5627         /*
5628          * We can only enable IPS after we enable a plane and wait for a vblank
5629          * This function is called from post_plane_update, which is run after
5630          * a vblank wait.
5631          */
5632         WARN_ON(!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)));
5633
5634         if (IS_BROADWELL(dev_priv)) {
5635                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL,
5636                                                 IPS_ENABLE | IPS_PCODE_CONTROL));
5637                 /* Quoting Art Runyan: "its not safe to expect any particular
5638                  * value in IPS_CTL bit 31 after enabling IPS through the
5639                  * mailbox." Moreover, the mailbox may return a bogus state,
5640                  * so we need to just enable it and continue on.
5641                  */
5642         } else {
5643                 I915_WRITE(IPS_CTL, IPS_ENABLE);
5644                 /* The bit only becomes 1 in the next vblank, so this wait here
5645                  * is essentially intel_wait_for_vblank. If we don't have this
5646                  * and don't wait for vblanks until the end of crtc_enable, then
5647                  * the HW state readout code will complain that the expected
5648                  * IPS_CTL value is not the one we read. */
5649                 if (intel_wait_for_register(&dev_priv->uncore,
5650                                             IPS_CTL, IPS_ENABLE, IPS_ENABLE,
5651                                             50))
5652                         DRM_ERROR("Timed out waiting for IPS enable\n");
5653         }
5654 }
5655
5656 void hsw_disable_ips(const struct intel_crtc_state *crtc_state)
5657 {
5658         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5659         struct drm_device *dev = crtc->base.dev;
5660         struct drm_i915_private *dev_priv = to_i915(dev);
5661
5662         if (!crtc_state->ips_enabled)
5663                 return;
5664
5665         if (IS_BROADWELL(dev_priv)) {
5666                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
5667                 /*
5668                  * Wait for PCODE to finish disabling IPS. The BSpec specified
5669                  * 42ms timeout value leads to occasional timeouts so use 100ms
5670                  * instead.
5671                  */
5672                 if (intel_wait_for_register(&dev_priv->uncore,
5673                                             IPS_CTL, IPS_ENABLE, 0,
5674                                             100))
5675                         DRM_ERROR("Timed out waiting for IPS disable\n");
5676         } else {
5677                 I915_WRITE(IPS_CTL, 0);
5678                 POSTING_READ(IPS_CTL);
5679         }
5680
5681         /* We need to wait for a vblank before we can disable the plane. */
5682         intel_wait_for_vblank(dev_priv, crtc->pipe);
5683 }
5684
5685 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
5686 {
5687         if (intel_crtc->overlay) {
5688                 struct drm_device *dev = intel_crtc->base.dev;
5689
5690                 mutex_lock(&dev->struct_mutex);
5691                 (void) intel_overlay_switch_off(intel_crtc->overlay);
5692                 mutex_unlock(&dev->struct_mutex);
5693         }
5694
5695         /* Let userspace switch the overlay on again. In most cases userspace
5696          * has to recompute where to put it anyway.
5697          */
5698 }
5699
5700 /**
5701  * intel_post_enable_primary - Perform operations after enabling primary plane
5702  * @crtc: the CRTC whose primary plane was just enabled
5703  * @new_crtc_state: the enabling state
5704  *
5705  * Performs potentially sleeping operations that must be done after the primary
5706  * plane is enabled, such as updating FBC and IPS.  Note that this may be
5707  * called due to an explicit primary plane update, or due to an implicit
5708  * re-enable that is caused when a sprite plane is updated to no longer
5709  * completely hide the primary plane.
5710  */
5711 static void
5712 intel_post_enable_primary(struct drm_crtc *crtc,
5713                           const struct intel_crtc_state *new_crtc_state)
5714 {
5715         struct drm_device *dev = crtc->dev;
5716         struct drm_i915_private *dev_priv = to_i915(dev);
5717         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5718         int pipe = intel_crtc->pipe;
5719
5720         /*
5721          * Gen2 reports pipe underruns whenever all planes are disabled.
5722          * So don't enable underrun reporting before at least some planes
5723          * are enabled.
5724          * FIXME: Need to fix the logic to work when we turn off all planes
5725          * but leave the pipe running.
5726          */
5727         if (IS_GEN(dev_priv, 2))
5728                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5729
5730         /* Underruns don't always raise interrupts, so check manually. */
5731         intel_check_cpu_fifo_underruns(dev_priv);
5732         intel_check_pch_fifo_underruns(dev_priv);
5733 }
5734
5735 /* FIXME get rid of this and use pre_plane_update */
5736 static void
5737 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
5738 {
5739         struct drm_device *dev = crtc->dev;
5740         struct drm_i915_private *dev_priv = to_i915(dev);
5741         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5742         int pipe = intel_crtc->pipe;
5743
5744         /*
5745          * Gen2 reports pipe underruns whenever all planes are disabled.
5746          * So disable underrun reporting before all the planes get disabled.
5747          */
5748         if (IS_GEN(dev_priv, 2))
5749                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5750
5751         hsw_disable_ips(to_intel_crtc_state(crtc->state));
5752
5753         /*
5754          * Vblank time updates from the shadow to live plane control register
5755          * are blocked if the memory self-refresh mode is active at that
5756          * moment. So to make sure the plane gets truly disabled, disable
5757          * first the self-refresh mode. The self-refresh enable bit in turn
5758          * will be checked/applied by the HW only at the next frame start
5759          * event which is after the vblank start event, so we need to have a
5760          * wait-for-vblank between disabling the plane and the pipe.
5761          */
5762         if (HAS_GMCH(dev_priv) &&
5763             intel_set_memory_cxsr(dev_priv, false))
5764                 intel_wait_for_vblank(dev_priv, pipe);
5765 }
5766
5767 static bool hsw_pre_update_disable_ips(const struct intel_crtc_state *old_crtc_state,
5768                                        const struct intel_crtc_state *new_crtc_state)
5769 {
5770         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
5771         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5772
5773         if (!old_crtc_state->ips_enabled)
5774                 return false;
5775
5776         if (needs_modeset(&new_crtc_state->base))
5777                 return true;
5778
5779         /*
5780          * Workaround : Do not read or write the pipe palette/gamma data while
5781          * GAMMA_MODE is configured for split gamma and IPS_CTL has IPS enabled.
5782          *
5783          * Disable IPS before we program the LUT.
5784          */
5785         if (IS_HASWELL(dev_priv) &&
5786             (new_crtc_state->base.color_mgmt_changed ||
5787              new_crtc_state->update_pipe) &&
5788             new_crtc_state->gamma_mode == GAMMA_MODE_MODE_SPLIT)
5789                 return true;
5790
5791         return !new_crtc_state->ips_enabled;
5792 }
5793
5794 static bool hsw_post_update_enable_ips(const struct intel_crtc_state *old_crtc_state,
5795                                        const struct intel_crtc_state *new_crtc_state)
5796 {
5797         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
5798         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5799
5800         if (!new_crtc_state->ips_enabled)
5801                 return false;
5802
5803         if (needs_modeset(&new_crtc_state->base))
5804                 return true;
5805
5806         /*
5807          * Workaround : Do not read or write the pipe palette/gamma data while
5808          * GAMMA_MODE is configured for split gamma and IPS_CTL has IPS enabled.
5809          *
5810          * Re-enable IPS after the LUT has been programmed.
5811          */
5812         if (IS_HASWELL(dev_priv) &&
5813             (new_crtc_state->base.color_mgmt_changed ||
5814              new_crtc_state->update_pipe) &&
5815             new_crtc_state->gamma_mode == GAMMA_MODE_MODE_SPLIT)
5816                 return true;
5817
5818         /*
5819          * We can't read out IPS on broadwell, assume the worst and
5820          * forcibly enable IPS on the first fastset.
5821          */
5822         if (new_crtc_state->update_pipe &&
5823             old_crtc_state->base.adjusted_mode.private_flags & I915_MODE_FLAG_INHERITED)
5824                 return true;
5825
5826         return !old_crtc_state->ips_enabled;
5827 }
5828
5829 static bool needs_nv12_wa(struct drm_i915_private *dev_priv,
5830                           const struct intel_crtc_state *crtc_state)
5831 {
5832         if (!crtc_state->nv12_planes)
5833                 return false;
5834
5835         /* WA Display #0827: Gen9:all */
5836         if (IS_GEN(dev_priv, 9) && !IS_GEMINILAKE(dev_priv))
5837                 return true;
5838
5839         return false;
5840 }
5841
5842 static bool needs_scalerclk_wa(struct drm_i915_private *dev_priv,
5843                                const struct intel_crtc_state *crtc_state)
5844 {
5845         /* Wa_2006604312:icl */
5846         if (crtc_state->scaler_state.scaler_users > 0 && IS_ICELAKE(dev_priv))
5847                 return true;
5848
5849         return false;
5850 }
5851
5852 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
5853 {
5854         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5855         struct drm_device *dev = crtc->base.dev;
5856         struct drm_i915_private *dev_priv = to_i915(dev);
5857         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5858         struct intel_crtc_state *pipe_config =
5859                 intel_atomic_get_new_crtc_state(to_intel_atomic_state(old_state),
5860                                                 crtc);
5861         struct drm_plane *primary = crtc->base.primary;
5862         struct drm_plane_state *old_primary_state =
5863                 drm_atomic_get_old_plane_state(old_state, primary);
5864
5865         intel_frontbuffer_flip(to_i915(crtc->base.dev), pipe_config->fb_bits);
5866
5867         if (pipe_config->update_wm_post && pipe_config->base.active)
5868                 intel_update_watermarks(crtc);
5869
5870         if (hsw_post_update_enable_ips(old_crtc_state, pipe_config))
5871                 hsw_enable_ips(pipe_config);
5872
5873         if (old_primary_state) {
5874                 struct drm_plane_state *new_primary_state =
5875                         drm_atomic_get_new_plane_state(old_state, primary);
5876
5877                 intel_fbc_post_update(crtc);
5878
5879                 if (new_primary_state->visible &&
5880                     (needs_modeset(&pipe_config->base) ||
5881                      !old_primary_state->visible))
5882                         intel_post_enable_primary(&crtc->base, pipe_config);
5883         }
5884
5885         if (needs_nv12_wa(dev_priv, old_crtc_state) &&
5886             !needs_nv12_wa(dev_priv, pipe_config))
5887                 skl_wa_827(dev_priv, crtc->pipe, false);
5888
5889         if (needs_scalerclk_wa(dev_priv, old_crtc_state) &&
5890             !needs_scalerclk_wa(dev_priv, pipe_config))
5891                 icl_wa_scalerclkgating(dev_priv, crtc->pipe, false);
5892 }
5893
5894 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state,
5895                                    struct intel_crtc_state *pipe_config)
5896 {
5897         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5898         struct drm_device *dev = crtc->base.dev;
5899         struct drm_i915_private *dev_priv = to_i915(dev);
5900         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5901         struct drm_plane *primary = crtc->base.primary;
5902         struct drm_plane_state *old_primary_state =
5903                 drm_atomic_get_old_plane_state(old_state, primary);
5904         bool modeset = needs_modeset(&pipe_config->base);
5905         struct intel_atomic_state *old_intel_state =
5906                 to_intel_atomic_state(old_state);
5907
5908         if (hsw_pre_update_disable_ips(old_crtc_state, pipe_config))
5909                 hsw_disable_ips(old_crtc_state);
5910
5911         if (old_primary_state) {
5912                 struct intel_plane_state *new_primary_state =
5913                         intel_atomic_get_new_plane_state(old_intel_state,
5914                                                          to_intel_plane(primary));
5915
5916                 intel_fbc_pre_update(crtc, pipe_config, new_primary_state);
5917                 /*
5918                  * Gen2 reports pipe underruns whenever all planes are disabled.
5919                  * So disable underrun reporting before all the planes get disabled.
5920                  */
5921                 if (IS_GEN(dev_priv, 2) && old_primary_state->visible &&
5922                     (modeset || !new_primary_state->base.visible))
5923                         intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, false);
5924         }
5925
5926         /* Display WA 827 */
5927         if (!needs_nv12_wa(dev_priv, old_crtc_state) &&
5928             needs_nv12_wa(dev_priv, pipe_config))
5929                 skl_wa_827(dev_priv, crtc->pipe, true);
5930
5931         /* Wa_2006604312:icl */
5932         if (!needs_scalerclk_wa(dev_priv, old_crtc_state) &&
5933             needs_scalerclk_wa(dev_priv, pipe_config))
5934                 icl_wa_scalerclkgating(dev_priv, crtc->pipe, true);
5935
5936         /*
5937          * Vblank time updates from the shadow to live plane control register
5938          * are blocked if the memory self-refresh mode is active at that
5939          * moment. So to make sure the plane gets truly disabled, disable
5940          * first the self-refresh mode. The self-refresh enable bit in turn
5941          * will be checked/applied by the HW only at the next frame start
5942          * event which is after the vblank start event, so we need to have a
5943          * wait-for-vblank between disabling the plane and the pipe.
5944          */
5945         if (HAS_GMCH(dev_priv) && old_crtc_state->base.active &&
5946             pipe_config->disable_cxsr && intel_set_memory_cxsr(dev_priv, false))
5947                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5948
5949         /*
5950          * IVB workaround: must disable low power watermarks for at least
5951          * one frame before enabling scaling.  LP watermarks can be re-enabled
5952          * when scaling is disabled.
5953          *
5954          * WaCxSRDisabledForSpriteScaling:ivb
5955          */
5956         if (pipe_config->disable_lp_wm && ilk_disable_lp_wm(dev) &&
5957             old_crtc_state->base.active)
5958                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5959
5960         /*
5961          * If we're doing a modeset, we're done.  No need to do any pre-vblank
5962          * watermark programming here.
5963          */
5964         if (needs_modeset(&pipe_config->base))
5965                 return;
5966
5967         /*
5968          * For platforms that support atomic watermarks, program the
5969          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
5970          * will be the intermediate values that are safe for both pre- and
5971          * post- vblank; when vblank happens, the 'active' values will be set
5972          * to the final 'target' values and we'll do this again to get the
5973          * optimal watermarks.  For gen9+ platforms, the values we program here
5974          * will be the final target values which will get automatically latched
5975          * at vblank time; no further programming will be necessary.
5976          *
5977          * If a platform hasn't been transitioned to atomic watermarks yet,
5978          * we'll continue to update watermarks the old way, if flags tell
5979          * us to.
5980          */
5981         if (dev_priv->display.initial_watermarks != NULL)
5982                 dev_priv->display.initial_watermarks(old_intel_state,
5983                                                      pipe_config);
5984         else if (pipe_config->update_wm_pre)
5985                 intel_update_watermarks(crtc);
5986 }
5987
5988 static void intel_crtc_disable_planes(struct intel_atomic_state *state,
5989                                       struct intel_crtc *crtc)
5990 {
5991         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5992         const struct intel_crtc_state *new_crtc_state =
5993                 intel_atomic_get_new_crtc_state(state, crtc);
5994         unsigned int update_mask = new_crtc_state->update_planes;
5995         const struct intel_plane_state *old_plane_state;
5996         struct intel_plane *plane;
5997         unsigned fb_bits = 0;
5998         int i;
5999
6000         intel_crtc_dpms_overlay_disable(crtc);
6001
6002         for_each_old_intel_plane_in_state(state, plane, old_plane_state, i) {
6003                 if (crtc->pipe != plane->pipe ||
6004                     !(update_mask & BIT(plane->id)))
6005                         continue;
6006
6007                 intel_disable_plane(plane, new_crtc_state);
6008
6009                 if (old_plane_state->base.visible)
6010                         fb_bits |= plane->frontbuffer_bit;
6011         }
6012
6013         intel_frontbuffer_flip(dev_priv, fb_bits);
6014 }
6015
6016 static void intel_encoders_pre_pll_enable(struct drm_crtc *crtc,
6017                                           struct intel_crtc_state *crtc_state,
6018                                           struct drm_atomic_state *old_state)
6019 {
6020         struct drm_connector_state *conn_state;
6021         struct drm_connector *conn;
6022         int i;
6023
6024         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
6025                 struct intel_encoder *encoder =
6026                         to_intel_encoder(conn_state->best_encoder);
6027
6028                 if (conn_state->crtc != crtc)
6029                         continue;
6030
6031                 if (encoder->pre_pll_enable)
6032                         encoder->pre_pll_enable(encoder, crtc_state, conn_state);
6033         }
6034 }
6035
6036 static void intel_encoders_pre_enable(struct drm_crtc *crtc,
6037                                       struct intel_crtc_state *crtc_state,
6038                                       struct drm_atomic_state *old_state)
6039 {
6040         struct drm_connector_state *conn_state;
6041         struct drm_connector *conn;
6042         int i;
6043
6044         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
6045                 struct intel_encoder *encoder =
6046                         to_intel_encoder(conn_state->best_encoder);
6047
6048                 if (conn_state->crtc != crtc)
6049                         continue;
6050
6051                 if (encoder->pre_enable)
6052                         encoder->pre_enable(encoder, crtc_state, conn_state);
6053         }
6054 }
6055
6056 static void intel_encoders_enable(struct drm_crtc *crtc,
6057                                   struct intel_crtc_state *crtc_state,
6058                                   struct drm_atomic_state *old_state)
6059 {
6060         struct drm_connector_state *conn_state;
6061         struct drm_connector *conn;
6062         int i;
6063
6064         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
6065                 struct intel_encoder *encoder =
6066                         to_intel_encoder(conn_state->best_encoder);
6067
6068                 if (conn_state->crtc != crtc)
6069                         continue;
6070
6071                 if (encoder->enable)
6072                         encoder->enable(encoder, crtc_state, conn_state);
6073                 intel_opregion_notify_encoder(encoder, true);
6074         }
6075 }
6076
6077 static void intel_encoders_disable(struct drm_crtc *crtc,
6078                                    struct intel_crtc_state *old_crtc_state,
6079                                    struct drm_atomic_state *old_state)
6080 {
6081         struct drm_connector_state *old_conn_state;
6082         struct drm_connector *conn;
6083         int i;
6084
6085         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
6086                 struct intel_encoder *encoder =
6087                         to_intel_encoder(old_conn_state->best_encoder);
6088
6089                 if (old_conn_state->crtc != crtc)
6090                         continue;
6091
6092                 intel_opregion_notify_encoder(encoder, false);
6093                 if (encoder->disable)
6094                         encoder->disable(encoder, old_crtc_state, old_conn_state);
6095         }
6096 }
6097
6098 static void intel_encoders_post_disable(struct drm_crtc *crtc,
6099                                         struct intel_crtc_state *old_crtc_state,
6100                                         struct drm_atomic_state *old_state)
6101 {
6102         struct drm_connector_state *old_conn_state;
6103         struct drm_connector *conn;
6104         int i;
6105
6106         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
6107                 struct intel_encoder *encoder =
6108                         to_intel_encoder(old_conn_state->best_encoder);
6109
6110                 if (old_conn_state->crtc != crtc)
6111                         continue;
6112
6113                 if (encoder->post_disable)
6114                         encoder->post_disable(encoder, old_crtc_state, old_conn_state);
6115         }
6116 }
6117
6118 static void intel_encoders_post_pll_disable(struct drm_crtc *crtc,
6119                                             struct intel_crtc_state *old_crtc_state,
6120                                             struct drm_atomic_state *old_state)
6121 {
6122         struct drm_connector_state *old_conn_state;
6123         struct drm_connector *conn;
6124         int i;
6125
6126         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
6127                 struct intel_encoder *encoder =
6128                         to_intel_encoder(old_conn_state->best_encoder);
6129
6130                 if (old_conn_state->crtc != crtc)
6131                         continue;
6132
6133                 if (encoder->post_pll_disable)
6134                         encoder->post_pll_disable(encoder, old_crtc_state, old_conn_state);
6135         }
6136 }
6137
6138 static void intel_encoders_update_pipe(struct drm_crtc *crtc,
6139                                        struct intel_crtc_state *crtc_state,
6140                                        struct drm_atomic_state *old_state)
6141 {
6142         struct drm_connector_state *conn_state;
6143         struct drm_connector *conn;
6144         int i;
6145
6146         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
6147                 struct intel_encoder *encoder =
6148                         to_intel_encoder(conn_state->best_encoder);
6149
6150                 if (conn_state->crtc != crtc)
6151                         continue;
6152
6153                 if (encoder->update_pipe)
6154                         encoder->update_pipe(encoder, crtc_state, conn_state);
6155         }
6156 }
6157
6158 static void intel_disable_primary_plane(const struct intel_crtc_state *crtc_state)
6159 {
6160         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6161         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
6162
6163         plane->disable_plane(plane, crtc_state);
6164 }
6165
6166 static void ironlake_crtc_enable(struct intel_crtc_state *pipe_config,
6167                                  struct drm_atomic_state *old_state)
6168 {
6169         struct drm_crtc *crtc = pipe_config->base.crtc;
6170         struct drm_device *dev = crtc->dev;
6171         struct drm_i915_private *dev_priv = to_i915(dev);
6172         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6173         int pipe = intel_crtc->pipe;
6174         struct intel_atomic_state *old_intel_state =
6175                 to_intel_atomic_state(old_state);
6176
6177         if (WARN_ON(intel_crtc->active))
6178                 return;
6179
6180         /*
6181          * Sometimes spurious CPU pipe underruns happen during FDI
6182          * training, at least with VGA+HDMI cloning. Suppress them.
6183          *
6184          * On ILK we get an occasional spurious CPU pipe underruns
6185          * between eDP port A enable and vdd enable. Also PCH port
6186          * enable seems to result in the occasional CPU pipe underrun.
6187          *
6188          * Spurious PCH underruns also occur during PCH enabling.
6189          */
6190         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6191         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
6192
6193         if (pipe_config->has_pch_encoder)
6194                 intel_prepare_shared_dpll(pipe_config);
6195
6196         if (intel_crtc_has_dp_encoder(pipe_config))
6197                 intel_dp_set_m_n(pipe_config, M1_N1);
6198
6199         intel_set_pipe_timings(pipe_config);
6200         intel_set_pipe_src_size(pipe_config);
6201
6202         if (pipe_config->has_pch_encoder) {
6203                 intel_cpu_transcoder_set_m_n(pipe_config,
6204                                              &pipe_config->fdi_m_n, NULL);
6205         }
6206
6207         ironlake_set_pipeconf(pipe_config);
6208
6209         intel_crtc->active = true;
6210
6211         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6212
6213         if (pipe_config->has_pch_encoder) {
6214                 /* Note: FDI PLL enabling _must_ be done before we enable the
6215                  * cpu pipes, hence this is separate from all the other fdi/pch
6216                  * enabling. */
6217                 ironlake_fdi_pll_enable(pipe_config);
6218         } else {
6219                 assert_fdi_tx_disabled(dev_priv, pipe);
6220                 assert_fdi_rx_disabled(dev_priv, pipe);
6221         }
6222
6223         ironlake_pfit_enable(pipe_config);
6224
6225         /*
6226          * On ILK+ LUT must be loaded before the pipe is running but with
6227          * clocks enabled
6228          */
6229         intel_color_load_luts(pipe_config);
6230         intel_color_commit(pipe_config);
6231         /* update DSPCNTR to configure gamma for pipe bottom color */
6232         intel_disable_primary_plane(pipe_config);
6233
6234         if (dev_priv->display.initial_watermarks != NULL)
6235                 dev_priv->display.initial_watermarks(old_intel_state, pipe_config);
6236         intel_enable_pipe(pipe_config);
6237
6238         if (pipe_config->has_pch_encoder)
6239                 ironlake_pch_enable(old_intel_state, pipe_config);
6240
6241         assert_vblank_disabled(crtc);
6242         intel_crtc_vblank_on(pipe_config);
6243
6244         intel_encoders_enable(crtc, pipe_config, old_state);
6245
6246         if (HAS_PCH_CPT(dev_priv))
6247                 cpt_verify_modeset(dev, intel_crtc->pipe);
6248
6249         /*
6250          * Must wait for vblank to avoid spurious PCH FIFO underruns.
6251          * And a second vblank wait is needed at least on ILK with
6252          * some interlaced HDMI modes. Let's do the double wait always
6253          * in case there are more corner cases we don't know about.
6254          */
6255         if (pipe_config->has_pch_encoder) {
6256                 intel_wait_for_vblank(dev_priv, pipe);
6257                 intel_wait_for_vblank(dev_priv, pipe);
6258         }
6259         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6260         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
6261 }
6262
6263 /* IPS only exists on ULT machines and is tied to pipe A. */
6264 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
6265 {
6266         return HAS_IPS(to_i915(crtc->base.dev)) && crtc->pipe == PIPE_A;
6267 }
6268
6269 static void glk_pipe_scaler_clock_gating_wa(struct drm_i915_private *dev_priv,
6270                                             enum pipe pipe, bool apply)
6271 {
6272         u32 val = I915_READ(CLKGATE_DIS_PSL(pipe));
6273         u32 mask = DPF_GATING_DIS | DPF_RAM_GATING_DIS | DPFR_GATING_DIS;
6274
6275         if (apply)
6276                 val |= mask;
6277         else
6278                 val &= ~mask;
6279
6280         I915_WRITE(CLKGATE_DIS_PSL(pipe), val);
6281 }
6282
6283 static void icl_pipe_mbus_enable(struct intel_crtc *crtc)
6284 {
6285         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6286         enum pipe pipe = crtc->pipe;
6287         u32 val;
6288
6289         val = MBUS_DBOX_A_CREDIT(2);
6290         val |= MBUS_DBOX_BW_CREDIT(1);
6291         val |= MBUS_DBOX_B_CREDIT(8);
6292
6293         I915_WRITE(PIPE_MBUS_DBOX_CTL(pipe), val);
6294 }
6295
6296 static void haswell_crtc_enable(struct intel_crtc_state *pipe_config,
6297                                 struct drm_atomic_state *old_state)
6298 {
6299         struct drm_crtc *crtc = pipe_config->base.crtc;
6300         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6301         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6302         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
6303         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
6304         struct intel_atomic_state *old_intel_state =
6305                 to_intel_atomic_state(old_state);
6306         bool psl_clkgate_wa;
6307
6308         if (WARN_ON(intel_crtc->active))
6309                 return;
6310
6311         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
6312
6313         if (pipe_config->shared_dpll)
6314                 intel_enable_shared_dpll(pipe_config);
6315
6316         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6317
6318         if (intel_crtc_has_dp_encoder(pipe_config))
6319                 intel_dp_set_m_n(pipe_config, M1_N1);
6320
6321         if (!transcoder_is_dsi(cpu_transcoder))
6322                 intel_set_pipe_timings(pipe_config);
6323
6324         intel_set_pipe_src_size(pipe_config);
6325
6326         if (cpu_transcoder != TRANSCODER_EDP &&
6327             !transcoder_is_dsi(cpu_transcoder)) {
6328                 I915_WRITE(PIPE_MULT(cpu_transcoder),
6329                            pipe_config->pixel_multiplier - 1);
6330         }
6331
6332         if (pipe_config->has_pch_encoder) {
6333                 intel_cpu_transcoder_set_m_n(pipe_config,
6334                                              &pipe_config->fdi_m_n, NULL);
6335         }
6336
6337         if (!transcoder_is_dsi(cpu_transcoder))
6338                 haswell_set_pipeconf(pipe_config);
6339
6340         if (INTEL_GEN(dev_priv) >= 9 || IS_BROADWELL(dev_priv))
6341                 bdw_set_pipemisc(pipe_config);
6342
6343         intel_crtc->active = true;
6344
6345         /* Display WA #1180: WaDisableScalarClockGating: glk, cnl */
6346         psl_clkgate_wa = (IS_GEMINILAKE(dev_priv) || IS_CANNONLAKE(dev_priv)) &&
6347                          pipe_config->pch_pfit.enabled;
6348         if (psl_clkgate_wa)
6349                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, true);
6350
6351         if (INTEL_GEN(dev_priv) >= 9)
6352                 skylake_pfit_enable(pipe_config);
6353         else
6354                 ironlake_pfit_enable(pipe_config);
6355
6356         /*
6357          * On ILK+ LUT must be loaded before the pipe is running but with
6358          * clocks enabled
6359          */
6360         intel_color_load_luts(pipe_config);
6361         intel_color_commit(pipe_config);
6362         /* update DSPCNTR to configure gamma/csc for pipe bottom color */
6363         if (INTEL_GEN(dev_priv) < 9)
6364                 intel_disable_primary_plane(pipe_config);
6365
6366         if (INTEL_GEN(dev_priv) >= 11)
6367                 icl_set_pipe_chicken(intel_crtc);
6368
6369         intel_ddi_set_pipe_settings(pipe_config);
6370         if (!transcoder_is_dsi(cpu_transcoder))
6371                 intel_ddi_enable_transcoder_func(pipe_config);
6372
6373         if (dev_priv->display.initial_watermarks != NULL)
6374                 dev_priv->display.initial_watermarks(old_intel_state, pipe_config);
6375
6376         if (INTEL_GEN(dev_priv) >= 11)
6377                 icl_pipe_mbus_enable(intel_crtc);
6378
6379         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
6380         if (!transcoder_is_dsi(cpu_transcoder))
6381                 intel_enable_pipe(pipe_config);
6382
6383         if (pipe_config->has_pch_encoder)
6384                 lpt_pch_enable(old_intel_state, pipe_config);
6385
6386         if (intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DP_MST))
6387                 intel_ddi_set_vc_payload_alloc(pipe_config, true);
6388
6389         assert_vblank_disabled(crtc);
6390         intel_crtc_vblank_on(pipe_config);
6391
6392         intel_encoders_enable(crtc, pipe_config, old_state);
6393
6394         if (psl_clkgate_wa) {
6395                 intel_wait_for_vblank(dev_priv, pipe);
6396                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, false);
6397         }
6398
6399         /* If we change the relative order between pipe/planes enabling, we need
6400          * to change the workaround. */
6401         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
6402         if (IS_HASWELL(dev_priv) && hsw_workaround_pipe != INVALID_PIPE) {
6403                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
6404                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
6405         }
6406 }
6407
6408 static void ironlake_pfit_disable(const struct intel_crtc_state *old_crtc_state)
6409 {
6410         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
6411         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6412         enum pipe pipe = crtc->pipe;
6413
6414         /* To avoid upsetting the power well on haswell only disable the pfit if
6415          * it's in use. The hw state code will make sure we get this right. */
6416         if (old_crtc_state->pch_pfit.enabled) {
6417                 I915_WRITE(PF_CTL(pipe), 0);
6418                 I915_WRITE(PF_WIN_POS(pipe), 0);
6419                 I915_WRITE(PF_WIN_SZ(pipe), 0);
6420         }
6421 }
6422
6423 static void ironlake_crtc_disable(struct intel_crtc_state *old_crtc_state,
6424                                   struct drm_atomic_state *old_state)
6425 {
6426         struct drm_crtc *crtc = old_crtc_state->base.crtc;
6427         struct drm_device *dev = crtc->dev;
6428         struct drm_i915_private *dev_priv = to_i915(dev);
6429         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6430         int pipe = intel_crtc->pipe;
6431
6432         /*
6433          * Sometimes spurious CPU pipe underruns happen when the
6434          * pipe is already disabled, but FDI RX/TX is still enabled.
6435          * Happens at least with VGA+HDMI cloning. Suppress them.
6436          */
6437         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6438         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
6439
6440         intel_encoders_disable(crtc, old_crtc_state, old_state);
6441
6442         drm_crtc_vblank_off(crtc);
6443         assert_vblank_disabled(crtc);
6444
6445         intel_disable_pipe(old_crtc_state);
6446
6447         ironlake_pfit_disable(old_crtc_state);
6448
6449         if (old_crtc_state->has_pch_encoder)
6450                 ironlake_fdi_disable(crtc);
6451
6452         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
6453
6454         if (old_crtc_state->has_pch_encoder) {
6455                 ironlake_disable_pch_transcoder(dev_priv, pipe);
6456
6457                 if (HAS_PCH_CPT(dev_priv)) {
6458                         i915_reg_t reg;
6459                         u32 temp;
6460
6461                         /* disable TRANS_DP_CTL */
6462                         reg = TRANS_DP_CTL(pipe);
6463                         temp = I915_READ(reg);
6464                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
6465                                   TRANS_DP_PORT_SEL_MASK);
6466                         temp |= TRANS_DP_PORT_SEL_NONE;
6467                         I915_WRITE(reg, temp);
6468
6469                         /* disable DPLL_SEL */
6470                         temp = I915_READ(PCH_DPLL_SEL);
6471                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
6472                         I915_WRITE(PCH_DPLL_SEL, temp);
6473                 }
6474
6475                 ironlake_fdi_pll_disable(intel_crtc);
6476         }
6477
6478         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6479         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
6480 }
6481
6482 static void haswell_crtc_disable(struct intel_crtc_state *old_crtc_state,
6483                                  struct drm_atomic_state *old_state)
6484 {
6485         struct drm_crtc *crtc = old_crtc_state->base.crtc;
6486         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6487         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6488         enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
6489
6490         intel_encoders_disable(crtc, old_crtc_state, old_state);
6491
6492         drm_crtc_vblank_off(crtc);
6493         assert_vblank_disabled(crtc);
6494
6495         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
6496         if (!transcoder_is_dsi(cpu_transcoder))
6497                 intel_disable_pipe(old_crtc_state);
6498
6499         if (intel_crtc_has_type(old_crtc_state, INTEL_OUTPUT_DP_MST))
6500                 intel_ddi_set_vc_payload_alloc(old_crtc_state, false);
6501
6502         if (!transcoder_is_dsi(cpu_transcoder))
6503                 intel_ddi_disable_transcoder_func(old_crtc_state);
6504
6505         intel_dsc_disable(old_crtc_state);
6506
6507         if (INTEL_GEN(dev_priv) >= 9)
6508                 skylake_scaler_disable(intel_crtc);
6509         else
6510                 ironlake_pfit_disable(old_crtc_state);
6511
6512         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
6513
6514         intel_encoders_post_pll_disable(crtc, old_crtc_state, old_state);
6515 }
6516
6517 static void i9xx_pfit_enable(const struct intel_crtc_state *crtc_state)
6518 {
6519         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6520         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6521
6522         if (!crtc_state->gmch_pfit.control)
6523                 return;
6524
6525         /*
6526          * The panel fitter should only be adjusted whilst the pipe is disabled,
6527          * according to register description and PRM.
6528          */
6529         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
6530         assert_pipe_disabled(dev_priv, crtc->pipe);
6531
6532         I915_WRITE(PFIT_PGM_RATIOS, crtc_state->gmch_pfit.pgm_ratios);
6533         I915_WRITE(PFIT_CONTROL, crtc_state->gmch_pfit.control);
6534
6535         /* Border color in case we don't scale up to the full screen. Black by
6536          * default, change to something else for debugging. */
6537         I915_WRITE(BCLRPAT(crtc->pipe), 0);
6538 }
6539
6540 bool intel_port_is_combophy(struct drm_i915_private *dev_priv, enum port port)
6541 {
6542         if (port == PORT_NONE)
6543                 return false;
6544
6545         if (IS_ELKHARTLAKE(dev_priv))
6546                 return port <= PORT_C;
6547
6548         if (INTEL_GEN(dev_priv) >= 11)
6549                 return port <= PORT_B;
6550
6551         return false;
6552 }
6553
6554 bool intel_port_is_tc(struct drm_i915_private *dev_priv, enum port port)
6555 {
6556         if (INTEL_GEN(dev_priv) >= 11 && !IS_ELKHARTLAKE(dev_priv))
6557                 return port >= PORT_C && port <= PORT_F;
6558
6559         return false;
6560 }
6561
6562 enum tc_port intel_port_to_tc(struct drm_i915_private *dev_priv, enum port port)
6563 {
6564         if (!intel_port_is_tc(dev_priv, port))
6565                 return PORT_TC_NONE;
6566
6567         return port - PORT_C;
6568 }
6569
6570 enum intel_display_power_domain intel_port_to_power_domain(enum port port)
6571 {
6572         switch (port) {
6573         case PORT_A:
6574                 return POWER_DOMAIN_PORT_DDI_A_LANES;
6575         case PORT_B:
6576                 return POWER_DOMAIN_PORT_DDI_B_LANES;
6577         case PORT_C:
6578                 return POWER_DOMAIN_PORT_DDI_C_LANES;
6579         case PORT_D:
6580                 return POWER_DOMAIN_PORT_DDI_D_LANES;
6581         case PORT_E:
6582                 return POWER_DOMAIN_PORT_DDI_E_LANES;
6583         case PORT_F:
6584                 return POWER_DOMAIN_PORT_DDI_F_LANES;
6585         default:
6586                 MISSING_CASE(port);
6587                 return POWER_DOMAIN_PORT_OTHER;
6588         }
6589 }
6590
6591 enum intel_display_power_domain
6592 intel_aux_power_domain(struct intel_digital_port *dig_port)
6593 {
6594         switch (dig_port->aux_ch) {
6595         case AUX_CH_A:
6596                 return POWER_DOMAIN_AUX_A;
6597         case AUX_CH_B:
6598                 return POWER_DOMAIN_AUX_B;
6599         case AUX_CH_C:
6600                 return POWER_DOMAIN_AUX_C;
6601         case AUX_CH_D:
6602                 return POWER_DOMAIN_AUX_D;
6603         case AUX_CH_E:
6604                 return POWER_DOMAIN_AUX_E;
6605         case AUX_CH_F:
6606                 return POWER_DOMAIN_AUX_F;
6607         default:
6608                 MISSING_CASE(dig_port->aux_ch);
6609                 return POWER_DOMAIN_AUX_A;
6610         }
6611 }
6612
6613 static u64 get_crtc_power_domains(struct drm_crtc *crtc,
6614                                   struct intel_crtc_state *crtc_state)
6615 {
6616         struct drm_device *dev = crtc->dev;
6617         struct drm_i915_private *dev_priv = to_i915(dev);
6618         struct drm_encoder *encoder;
6619         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6620         enum pipe pipe = intel_crtc->pipe;
6621         u64 mask;
6622         enum transcoder transcoder = crtc_state->cpu_transcoder;
6623
6624         if (!crtc_state->base.active)
6625                 return 0;
6626
6627         mask = BIT_ULL(POWER_DOMAIN_PIPE(pipe));
6628         mask |= BIT_ULL(POWER_DOMAIN_TRANSCODER(transcoder));
6629         if (crtc_state->pch_pfit.enabled ||
6630             crtc_state->pch_pfit.force_thru)
6631                 mask |= BIT_ULL(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
6632
6633         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
6634                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6635
6636                 mask |= BIT_ULL(intel_encoder->power_domain);
6637         }
6638
6639         if (HAS_DDI(dev_priv) && crtc_state->has_audio)
6640                 mask |= BIT_ULL(POWER_DOMAIN_AUDIO);
6641
6642         if (crtc_state->shared_dpll)
6643                 mask |= BIT_ULL(POWER_DOMAIN_DISPLAY_CORE);
6644
6645         return mask;
6646 }
6647
6648 static u64
6649 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
6650                                struct intel_crtc_state *crtc_state)
6651 {
6652         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6653         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6654         enum intel_display_power_domain domain;
6655         u64 domains, new_domains, old_domains;
6656
6657         old_domains = intel_crtc->enabled_power_domains;
6658         intel_crtc->enabled_power_domains = new_domains =
6659                 get_crtc_power_domains(crtc, crtc_state);
6660
6661         domains = new_domains & ~old_domains;
6662
6663         for_each_power_domain(domain, domains)
6664                 intel_display_power_get(dev_priv, domain);
6665
6666         return old_domains & ~new_domains;
6667 }
6668
6669 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
6670                                       u64 domains)
6671 {
6672         enum intel_display_power_domain domain;
6673
6674         for_each_power_domain(domain, domains)
6675                 intel_display_power_put_unchecked(dev_priv, domain);
6676 }
6677
6678 static void valleyview_crtc_enable(struct intel_crtc_state *pipe_config,
6679                                    struct drm_atomic_state *old_state)
6680 {
6681         struct intel_atomic_state *old_intel_state =
6682                 to_intel_atomic_state(old_state);
6683         struct drm_crtc *crtc = pipe_config->base.crtc;
6684         struct drm_device *dev = crtc->dev;
6685         struct drm_i915_private *dev_priv = to_i915(dev);
6686         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6687         int pipe = intel_crtc->pipe;
6688
6689         if (WARN_ON(intel_crtc->active))
6690                 return;
6691
6692         if (intel_crtc_has_dp_encoder(pipe_config))
6693                 intel_dp_set_m_n(pipe_config, M1_N1);
6694
6695         intel_set_pipe_timings(pipe_config);
6696         intel_set_pipe_src_size(pipe_config);
6697
6698         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
6699                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6700                 I915_WRITE(CHV_CANVAS(pipe), 0);
6701         }
6702
6703         i9xx_set_pipeconf(pipe_config);
6704
6705         intel_crtc->active = true;
6706
6707         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6708
6709         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
6710
6711         if (IS_CHERRYVIEW(dev_priv)) {
6712                 chv_prepare_pll(intel_crtc, pipe_config);
6713                 chv_enable_pll(intel_crtc, pipe_config);
6714         } else {
6715                 vlv_prepare_pll(intel_crtc, pipe_config);
6716                 vlv_enable_pll(intel_crtc, pipe_config);
6717         }
6718
6719         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6720
6721         i9xx_pfit_enable(pipe_config);
6722
6723         intel_color_load_luts(pipe_config);
6724         intel_color_commit(pipe_config);
6725         /* update DSPCNTR to configure gamma for pipe bottom color */
6726         intel_disable_primary_plane(pipe_config);
6727
6728         dev_priv->display.initial_watermarks(old_intel_state,
6729                                              pipe_config);
6730         intel_enable_pipe(pipe_config);
6731
6732         assert_vblank_disabled(crtc);
6733         intel_crtc_vblank_on(pipe_config);
6734
6735         intel_encoders_enable(crtc, pipe_config, old_state);
6736 }
6737
6738 static void i9xx_set_pll_dividers(const struct intel_crtc_state *crtc_state)
6739 {
6740         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6741         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6742
6743         I915_WRITE(FP0(crtc->pipe), crtc_state->dpll_hw_state.fp0);
6744         I915_WRITE(FP1(crtc->pipe), crtc_state->dpll_hw_state.fp1);
6745 }
6746
6747 static void i9xx_crtc_enable(struct intel_crtc_state *pipe_config,
6748                              struct drm_atomic_state *old_state)
6749 {
6750         struct intel_atomic_state *old_intel_state =
6751                 to_intel_atomic_state(old_state);
6752         struct drm_crtc *crtc = pipe_config->base.crtc;
6753         struct drm_device *dev = crtc->dev;
6754         struct drm_i915_private *dev_priv = to_i915(dev);
6755         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6756         enum pipe pipe = intel_crtc->pipe;
6757
6758         if (WARN_ON(intel_crtc->active))
6759                 return;
6760
6761         i9xx_set_pll_dividers(pipe_config);
6762
6763         if (intel_crtc_has_dp_encoder(pipe_config))
6764                 intel_dp_set_m_n(pipe_config, M1_N1);
6765
6766         intel_set_pipe_timings(pipe_config);
6767         intel_set_pipe_src_size(pipe_config);
6768
6769         i9xx_set_pipeconf(pipe_config);
6770
6771         intel_crtc->active = true;
6772
6773         if (!IS_GEN(dev_priv, 2))
6774                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6775
6776         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6777
6778         i9xx_enable_pll(intel_crtc, pipe_config);
6779
6780         i9xx_pfit_enable(pipe_config);
6781
6782         intel_color_load_luts(pipe_config);
6783         intel_color_commit(pipe_config);
6784         /* update DSPCNTR to configure gamma for pipe bottom color */
6785         intel_disable_primary_plane(pipe_config);
6786
6787         if (dev_priv->display.initial_watermarks != NULL)
6788                 dev_priv->display.initial_watermarks(old_intel_state,
6789                                                      pipe_config);
6790         else
6791                 intel_update_watermarks(intel_crtc);
6792         intel_enable_pipe(pipe_config);
6793
6794         assert_vblank_disabled(crtc);
6795         intel_crtc_vblank_on(pipe_config);
6796
6797         intel_encoders_enable(crtc, pipe_config, old_state);
6798 }
6799
6800 static void i9xx_pfit_disable(const struct intel_crtc_state *old_crtc_state)
6801 {
6802         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
6803         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6804
6805         if (!old_crtc_state->gmch_pfit.control)
6806                 return;
6807
6808         assert_pipe_disabled(dev_priv, crtc->pipe);
6809
6810         DRM_DEBUG_KMS("disabling pfit, current: 0x%08x\n",
6811                       I915_READ(PFIT_CONTROL));
6812         I915_WRITE(PFIT_CONTROL, 0);
6813 }
6814
6815 static void i9xx_crtc_disable(struct intel_crtc_state *old_crtc_state,
6816                               struct drm_atomic_state *old_state)
6817 {
6818         struct drm_crtc *crtc = old_crtc_state->base.crtc;
6819         struct drm_device *dev = crtc->dev;
6820         struct drm_i915_private *dev_priv = to_i915(dev);
6821         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6822         int pipe = intel_crtc->pipe;
6823
6824         /*
6825          * On gen2 planes are double buffered but the pipe isn't, so we must
6826          * wait for planes to fully turn off before disabling the pipe.
6827          */
6828         if (IS_GEN(dev_priv, 2))
6829                 intel_wait_for_vblank(dev_priv, pipe);
6830
6831         intel_encoders_disable(crtc, old_crtc_state, old_state);
6832
6833         drm_crtc_vblank_off(crtc);
6834         assert_vblank_disabled(crtc);
6835
6836         intel_disable_pipe(old_crtc_state);
6837
6838         i9xx_pfit_disable(old_crtc_state);
6839
6840         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
6841
6842         if (!intel_crtc_has_type(old_crtc_state, INTEL_OUTPUT_DSI)) {
6843                 if (IS_CHERRYVIEW(dev_priv))
6844                         chv_disable_pll(dev_priv, pipe);
6845                 else if (IS_VALLEYVIEW(dev_priv))
6846                         vlv_disable_pll(dev_priv, pipe);
6847                 else
6848                         i9xx_disable_pll(old_crtc_state);
6849         }
6850
6851         intel_encoders_post_pll_disable(crtc, old_crtc_state, old_state);
6852
6853         if (!IS_GEN(dev_priv, 2))
6854                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6855
6856         if (!dev_priv->display.initial_watermarks)
6857                 intel_update_watermarks(intel_crtc);
6858
6859         /* clock the pipe down to 640x480@60 to potentially save power */
6860         if (IS_I830(dev_priv))
6861                 i830_enable_pipe(dev_priv, pipe);
6862 }
6863
6864 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc,
6865                                         struct drm_modeset_acquire_ctx *ctx)
6866 {
6867         struct intel_encoder *encoder;
6868         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6869         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6870         enum intel_display_power_domain domain;
6871         struct intel_plane *plane;
6872         u64 domains;
6873         struct drm_atomic_state *state;
6874         struct intel_crtc_state *crtc_state;
6875         int ret;
6876
6877         if (!intel_crtc->active)
6878                 return;
6879
6880         for_each_intel_plane_on_crtc(&dev_priv->drm, intel_crtc, plane) {
6881                 const struct intel_plane_state *plane_state =
6882                         to_intel_plane_state(plane->base.state);
6883
6884                 if (plane_state->base.visible)
6885                         intel_plane_disable_noatomic(intel_crtc, plane);
6886         }
6887
6888         state = drm_atomic_state_alloc(crtc->dev);
6889         if (!state) {
6890                 DRM_DEBUG_KMS("failed to disable [CRTC:%d:%s], out of memory",
6891                               crtc->base.id, crtc->name);
6892                 return;
6893         }
6894
6895         state->acquire_ctx = ctx;
6896
6897         /* Everything's already locked, -EDEADLK can't happen. */
6898         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
6899         ret = drm_atomic_add_affected_connectors(state, crtc);
6900
6901         WARN_ON(IS_ERR(crtc_state) || ret);
6902
6903         dev_priv->display.crtc_disable(crtc_state, state);
6904
6905         drm_atomic_state_put(state);
6906
6907         DRM_DEBUG_KMS("[CRTC:%d:%s] hw state adjusted, was enabled, now disabled\n",
6908                       crtc->base.id, crtc->name);
6909
6910         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
6911         crtc->state->active = false;
6912         intel_crtc->active = false;
6913         crtc->enabled = false;
6914         crtc->state->connector_mask = 0;
6915         crtc->state->encoder_mask = 0;
6916
6917         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
6918                 encoder->base.crtc = NULL;
6919
6920         intel_fbc_disable(intel_crtc);
6921         intel_update_watermarks(intel_crtc);
6922         intel_disable_shared_dpll(to_intel_crtc_state(crtc->state));
6923
6924         domains = intel_crtc->enabled_power_domains;
6925         for_each_power_domain(domain, domains)
6926                 intel_display_power_put_unchecked(dev_priv, domain);
6927         intel_crtc->enabled_power_domains = 0;
6928
6929         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6930         dev_priv->min_cdclk[intel_crtc->pipe] = 0;
6931         dev_priv->min_voltage_level[intel_crtc->pipe] = 0;
6932 }
6933
6934 /*
6935  * turn all crtc's off, but do not adjust state
6936  * This has to be paired with a call to intel_modeset_setup_hw_state.
6937  */
6938 int intel_display_suspend(struct drm_device *dev)
6939 {
6940         struct drm_i915_private *dev_priv = to_i915(dev);
6941         struct drm_atomic_state *state;
6942         int ret;
6943
6944         state = drm_atomic_helper_suspend(dev);
6945         ret = PTR_ERR_OR_ZERO(state);
6946         if (ret)
6947                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6948         else
6949                 dev_priv->modeset_restore_state = state;
6950         return ret;
6951 }
6952
6953 void intel_encoder_destroy(struct drm_encoder *encoder)
6954 {
6955         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6956
6957         drm_encoder_cleanup(encoder);
6958         kfree(intel_encoder);
6959 }
6960
6961 /* Cross check the actual hw state with our own modeset state tracking (and it's
6962  * internal consistency). */
6963 static void intel_connector_verify_state(struct drm_crtc_state *crtc_state,
6964                                          struct drm_connector_state *conn_state)
6965 {
6966         struct intel_connector *connector = to_intel_connector(conn_state->connector);
6967
6968         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6969                       connector->base.base.id,
6970                       connector->base.name);
6971
6972         if (connector->get_hw_state(connector)) {
6973                 struct intel_encoder *encoder = connector->encoder;
6974
6975                 I915_STATE_WARN(!crtc_state,
6976                          "connector enabled without attached crtc\n");
6977
6978                 if (!crtc_state)
6979                         return;
6980
6981                 I915_STATE_WARN(!crtc_state->active,
6982                       "connector is active, but attached crtc isn't\n");
6983
6984                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6985                         return;
6986
6987                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6988                         "atomic encoder doesn't match attached encoder\n");
6989
6990                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6991                         "attached encoder crtc differs from connector crtc\n");
6992         } else {
6993                 I915_STATE_WARN(crtc_state && crtc_state->active,
6994                         "attached crtc is active, but connector isn't\n");
6995                 I915_STATE_WARN(!crtc_state && conn_state->best_encoder,
6996                         "best encoder set without crtc!\n");
6997         }
6998 }
6999
7000 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
7001 {
7002         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
7003                 return crtc_state->fdi_lanes;
7004
7005         return 0;
7006 }
7007
7008 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
7009                                      struct intel_crtc_state *pipe_config)
7010 {
7011         struct drm_i915_private *dev_priv = to_i915(dev);
7012         struct drm_atomic_state *state = pipe_config->base.state;
7013         struct intel_crtc *other_crtc;
7014         struct intel_crtc_state *other_crtc_state;
7015
7016         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
7017                       pipe_name(pipe), pipe_config->fdi_lanes);
7018         if (pipe_config->fdi_lanes > 4) {
7019                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
7020                               pipe_name(pipe), pipe_config->fdi_lanes);
7021                 return -EINVAL;
7022         }
7023
7024         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
7025                 if (pipe_config->fdi_lanes > 2) {
7026                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
7027                                       pipe_config->fdi_lanes);
7028                         return -EINVAL;
7029                 } else {
7030                         return 0;
7031                 }
7032         }
7033
7034         if (INTEL_INFO(dev_priv)->num_pipes == 2)
7035                 return 0;
7036
7037         /* Ivybridge 3 pipe is really complicated */
7038         switch (pipe) {
7039         case PIPE_A:
7040                 return 0;
7041         case PIPE_B:
7042                 if (pipe_config->fdi_lanes <= 2)
7043                         return 0;
7044
7045                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_C);
7046                 other_crtc_state =
7047                         intel_atomic_get_crtc_state(state, other_crtc);
7048                 if (IS_ERR(other_crtc_state))
7049                         return PTR_ERR(other_crtc_state);
7050
7051                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
7052                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
7053                                       pipe_name(pipe), pipe_config->fdi_lanes);
7054                         return -EINVAL;
7055                 }
7056                 return 0;
7057         case PIPE_C:
7058                 if (pipe_config->fdi_lanes > 2) {
7059                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
7060                                       pipe_name(pipe), pipe_config->fdi_lanes);
7061                         return -EINVAL;
7062                 }
7063
7064                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_B);
7065                 other_crtc_state =
7066                         intel_atomic_get_crtc_state(state, other_crtc);
7067                 if (IS_ERR(other_crtc_state))
7068                         return PTR_ERR(other_crtc_state);
7069
7070                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
7071                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
7072                         return -EINVAL;
7073                 }
7074                 return 0;
7075         default:
7076                 BUG();
7077         }
7078 }
7079
7080 #define RETRY 1
7081 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
7082                                        struct intel_crtc_state *pipe_config)
7083 {
7084         struct drm_device *dev = intel_crtc->base.dev;
7085         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
7086         int lane, link_bw, fdi_dotclock, ret;
7087         bool needs_recompute = false;
7088
7089 retry:
7090         /* FDI is a binary signal running at ~2.7GHz, encoding
7091          * each output octet as 10 bits. The actual frequency
7092          * is stored as a divider into a 100MHz clock, and the
7093          * mode pixel clock is stored in units of 1KHz.
7094          * Hence the bw of each lane in terms of the mode signal
7095          * is:
7096          */
7097         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
7098
7099         fdi_dotclock = adjusted_mode->crtc_clock;
7100
7101         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
7102                                            pipe_config->pipe_bpp);
7103
7104         pipe_config->fdi_lanes = lane;
7105
7106         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
7107                                link_bw, &pipe_config->fdi_m_n, false);
7108
7109         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
7110         if (ret == -EDEADLK)
7111                 return ret;
7112
7113         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
7114                 pipe_config->pipe_bpp -= 2*3;
7115                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
7116                               pipe_config->pipe_bpp);
7117                 needs_recompute = true;
7118                 pipe_config->bw_constrained = true;
7119
7120                 goto retry;
7121         }
7122
7123         if (needs_recompute)
7124                 return RETRY;
7125
7126         return ret;
7127 }
7128
7129 bool hsw_crtc_state_ips_capable(const struct intel_crtc_state *crtc_state)
7130 {
7131         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
7132         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7133
7134         /* IPS only exists on ULT machines and is tied to pipe A. */
7135         if (!hsw_crtc_supports_ips(crtc))
7136                 return false;
7137
7138         if (!i915_modparams.enable_ips)
7139                 return false;
7140
7141         if (crtc_state->pipe_bpp > 24)
7142                 return false;
7143
7144         /*
7145          * We compare against max which means we must take
7146          * the increased cdclk requirement into account when
7147          * calculating the new cdclk.
7148          *
7149          * Should measure whether using a lower cdclk w/o IPS
7150          */
7151         if (IS_BROADWELL(dev_priv) &&
7152             crtc_state->pixel_rate > dev_priv->max_cdclk_freq * 95 / 100)
7153                 return false;
7154
7155         return true;
7156 }
7157
7158 static bool hsw_compute_ips_config(struct intel_crtc_state *crtc_state)
7159 {
7160         struct drm_i915_private *dev_priv =
7161                 to_i915(crtc_state->base.crtc->dev);
7162         struct intel_atomic_state *intel_state =
7163                 to_intel_atomic_state(crtc_state->base.state);
7164
7165         if (!hsw_crtc_state_ips_capable(crtc_state))
7166                 return false;
7167
7168         /*
7169          * When IPS gets enabled, the pipe CRC changes. Since IPS gets
7170          * enabled and disabled dynamically based on package C states,
7171          * user space can't make reliable use of the CRCs, so let's just
7172          * completely disable it.
7173          */
7174         if (crtc_state->crc_enabled)
7175                 return false;
7176
7177         /* IPS should be fine as long as at least one plane is enabled. */
7178         if (!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)))
7179                 return false;
7180
7181         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
7182         if (IS_BROADWELL(dev_priv) &&
7183             crtc_state->pixel_rate > intel_state->cdclk.logical.cdclk * 95 / 100)
7184                 return false;
7185
7186         return true;
7187 }
7188
7189 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
7190 {
7191         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7192
7193         /* GDG double wide on either pipe, otherwise pipe A only */
7194         return INTEL_GEN(dev_priv) < 4 &&
7195                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
7196 }
7197
7198 static u32 ilk_pipe_pixel_rate(const struct intel_crtc_state *pipe_config)
7199 {
7200         u32 pixel_rate;
7201
7202         pixel_rate = pipe_config->base.adjusted_mode.crtc_clock;
7203
7204         /*
7205          * We only use IF-ID interlacing. If we ever use
7206          * PF-ID we'll need to adjust the pixel_rate here.
7207          */
7208
7209         if (pipe_config->pch_pfit.enabled) {
7210                 u64 pipe_w, pipe_h, pfit_w, pfit_h;
7211                 u32 pfit_size = pipe_config->pch_pfit.size;
7212
7213                 pipe_w = pipe_config->pipe_src_w;
7214                 pipe_h = pipe_config->pipe_src_h;
7215
7216                 pfit_w = (pfit_size >> 16) & 0xFFFF;
7217                 pfit_h = pfit_size & 0xFFFF;
7218                 if (pipe_w < pfit_w)
7219                         pipe_w = pfit_w;
7220                 if (pipe_h < pfit_h)
7221                         pipe_h = pfit_h;
7222
7223                 if (WARN_ON(!pfit_w || !pfit_h))
7224                         return pixel_rate;
7225
7226                 pixel_rate = div_u64(mul_u32_u32(pixel_rate, pipe_w * pipe_h),
7227                                      pfit_w * pfit_h);
7228         }
7229
7230         return pixel_rate;
7231 }
7232
7233 static void intel_crtc_compute_pixel_rate(struct intel_crtc_state *crtc_state)
7234 {
7235         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
7236
7237         if (HAS_GMCH(dev_priv))
7238                 /* FIXME calculate proper pipe pixel rate for GMCH pfit */
7239                 crtc_state->pixel_rate =
7240                         crtc_state->base.adjusted_mode.crtc_clock;
7241         else
7242                 crtc_state->pixel_rate =
7243                         ilk_pipe_pixel_rate(crtc_state);
7244 }
7245
7246 static int intel_crtc_compute_config(struct intel_crtc *crtc,
7247                                      struct intel_crtc_state *pipe_config)
7248 {
7249         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7250         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
7251         int clock_limit = dev_priv->max_dotclk_freq;
7252
7253         if (INTEL_GEN(dev_priv) < 4) {
7254                 clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
7255
7256                 /*
7257                  * Enable double wide mode when the dot clock
7258                  * is > 90% of the (display) core speed.
7259                  */
7260                 if (intel_crtc_supports_double_wide(crtc) &&
7261                     adjusted_mode->crtc_clock > clock_limit) {
7262                         clock_limit = dev_priv->max_dotclk_freq;
7263                         pipe_config->double_wide = true;
7264                 }
7265         }
7266
7267         if (adjusted_mode->crtc_clock > clock_limit) {
7268                 DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
7269                               adjusted_mode->crtc_clock, clock_limit,
7270                               yesno(pipe_config->double_wide));
7271                 return -EINVAL;
7272         }
7273
7274         if ((pipe_config->output_format == INTEL_OUTPUT_FORMAT_YCBCR420 ||
7275              pipe_config->output_format == INTEL_OUTPUT_FORMAT_YCBCR444) &&
7276              pipe_config->base.ctm) {
7277                 /*
7278                  * There is only one pipe CSC unit per pipe, and we need that
7279                  * for output conversion from RGB->YCBCR. So if CTM is already
7280                  * applied we can't support YCBCR420 output.
7281                  */
7282                 DRM_DEBUG_KMS("YCBCR420 and CTM together are not possible\n");
7283                 return -EINVAL;
7284         }
7285
7286         /*
7287          * Pipe horizontal size must be even in:
7288          * - DVO ganged mode
7289          * - LVDS dual channel mode
7290          * - Double wide pipe
7291          */
7292         if (pipe_config->pipe_src_w & 1) {
7293                 if (pipe_config->double_wide) {
7294                         DRM_DEBUG_KMS("Odd pipe source width not supported with double wide pipe\n");
7295                         return -EINVAL;
7296                 }
7297
7298                 if (intel_crtc_has_type(pipe_config, INTEL_OUTPUT_LVDS) &&
7299                     intel_is_dual_link_lvds(dev_priv)) {
7300                         DRM_DEBUG_KMS("Odd pipe source width not supported with dual link LVDS\n");
7301                         return -EINVAL;
7302                 }
7303         }
7304
7305         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
7306          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
7307          */
7308         if ((INTEL_GEN(dev_priv) > 4 || IS_G4X(dev_priv)) &&
7309                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
7310                 return -EINVAL;
7311
7312         intel_crtc_compute_pixel_rate(pipe_config);
7313
7314         if (pipe_config->has_pch_encoder)
7315                 return ironlake_fdi_compute_config(crtc, pipe_config);
7316
7317         return 0;
7318 }
7319
7320 static void
7321 intel_reduce_m_n_ratio(u32 *num, u32 *den)
7322 {
7323         while (*num > DATA_LINK_M_N_MASK ||
7324                *den > DATA_LINK_M_N_MASK) {
7325                 *num >>= 1;
7326                 *den >>= 1;
7327         }
7328 }
7329
7330 static void compute_m_n(unsigned int m, unsigned int n,
7331                         u32 *ret_m, u32 *ret_n,
7332                         bool constant_n)
7333 {
7334         /*
7335          * Several DP dongles in particular seem to be fussy about
7336          * too large link M/N values. Give N value as 0x8000 that
7337          * should be acceptable by specific devices. 0x8000 is the
7338          * specified fixed N value for asynchronous clock mode,
7339          * which the devices expect also in synchronous clock mode.
7340          */
7341         if (constant_n)
7342                 *ret_n = 0x8000;
7343         else
7344                 *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
7345
7346         *ret_m = div_u64(mul_u32_u32(m, *ret_n), n);
7347         intel_reduce_m_n_ratio(ret_m, ret_n);
7348 }
7349
7350 void
7351 intel_link_compute_m_n(u16 bits_per_pixel, int nlanes,
7352                        int pixel_clock, int link_clock,
7353                        struct intel_link_m_n *m_n,
7354                        bool constant_n)
7355 {
7356         m_n->tu = 64;
7357
7358         compute_m_n(bits_per_pixel * pixel_clock,
7359                     link_clock * nlanes * 8,
7360                     &m_n->gmch_m, &m_n->gmch_n,
7361                     constant_n);
7362
7363         compute_m_n(pixel_clock, link_clock,
7364                     &m_n->link_m, &m_n->link_n,
7365                     constant_n);
7366 }
7367
7368 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
7369 {
7370         if (i915_modparams.panel_use_ssc >= 0)
7371                 return i915_modparams.panel_use_ssc != 0;
7372         return dev_priv->vbt.lvds_use_ssc
7373                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
7374 }
7375
7376 static u32 pnv_dpll_compute_fp(struct dpll *dpll)
7377 {
7378         return (1 << dpll->n) << 16 | dpll->m2;
7379 }
7380
7381 static u32 i9xx_dpll_compute_fp(struct dpll *dpll)
7382 {
7383         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
7384 }
7385
7386 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
7387                                      struct intel_crtc_state *crtc_state,
7388                                      struct dpll *reduced_clock)
7389 {
7390         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7391         u32 fp, fp2 = 0;
7392
7393         if (IS_PINEVIEW(dev_priv)) {
7394                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
7395                 if (reduced_clock)
7396                         fp2 = pnv_dpll_compute_fp(reduced_clock);
7397         } else {
7398                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
7399                 if (reduced_clock)
7400                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
7401         }
7402
7403         crtc_state->dpll_hw_state.fp0 = fp;
7404
7405         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7406             reduced_clock) {
7407                 crtc_state->dpll_hw_state.fp1 = fp2;
7408         } else {
7409                 crtc_state->dpll_hw_state.fp1 = fp;
7410         }
7411 }
7412
7413 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
7414                 pipe)
7415 {
7416         u32 reg_val;
7417
7418         /*
7419          * PLLB opamp always calibrates to max value of 0x3f, force enable it
7420          * and set it to a reasonable value instead.
7421          */
7422         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7423         reg_val &= 0xffffff00;
7424         reg_val |= 0x00000030;
7425         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7426
7427         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7428         reg_val &= 0x00ffffff;
7429         reg_val |= 0x8c000000;
7430         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7431
7432         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7433         reg_val &= 0xffffff00;
7434         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7435
7436         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7437         reg_val &= 0x00ffffff;
7438         reg_val |= 0xb0000000;
7439         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7440 }
7441
7442 static void intel_pch_transcoder_set_m_n(const struct intel_crtc_state *crtc_state,
7443                                          const struct intel_link_m_n *m_n)
7444 {
7445         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
7446         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7447         enum pipe pipe = crtc->pipe;
7448
7449         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7450         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
7451         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
7452         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
7453 }
7454
7455 static bool transcoder_has_m2_n2(struct drm_i915_private *dev_priv,
7456                                  enum transcoder transcoder)
7457 {
7458         if (IS_HASWELL(dev_priv))
7459                 return transcoder == TRANSCODER_EDP;
7460
7461         /*
7462          * Strictly speaking some registers are available before
7463          * gen7, but we only support DRRS on gen7+
7464          */
7465         return IS_GEN(dev_priv, 7) || IS_CHERRYVIEW(dev_priv);
7466 }
7467
7468 static void intel_cpu_transcoder_set_m_n(const struct intel_crtc_state *crtc_state,
7469                                          const struct intel_link_m_n *m_n,
7470                                          const struct intel_link_m_n *m2_n2)
7471 {
7472         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
7473         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7474         enum pipe pipe = crtc->pipe;
7475         enum transcoder transcoder = crtc_state->cpu_transcoder;
7476
7477         if (INTEL_GEN(dev_priv) >= 5) {
7478                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
7479                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
7480                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
7481                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
7482                 /*
7483                  *  M2_N2 registers are set only if DRRS is supported
7484                  * (to make sure the registers are not unnecessarily accessed).
7485                  */
7486                 if (m2_n2 && crtc_state->has_drrs &&
7487                     transcoder_has_m2_n2(dev_priv, transcoder)) {
7488                         I915_WRITE(PIPE_DATA_M2(transcoder),
7489                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
7490                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
7491                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
7492                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
7493                 }
7494         } else {
7495                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7496                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
7497                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
7498                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
7499         }
7500 }
7501
7502 void intel_dp_set_m_n(const struct intel_crtc_state *crtc_state, enum link_m_n_set m_n)
7503 {
7504         const struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
7505
7506         if (m_n == M1_N1) {
7507                 dp_m_n = &crtc_state->dp_m_n;
7508                 dp_m2_n2 = &crtc_state->dp_m2_n2;
7509         } else if (m_n == M2_N2) {
7510
7511                 /*
7512                  * M2_N2 registers are not supported. Hence m2_n2 divider value
7513                  * needs to be programmed into M1_N1.
7514                  */
7515                 dp_m_n = &crtc_state->dp_m2_n2;
7516         } else {
7517                 DRM_ERROR("Unsupported divider value\n");
7518                 return;
7519         }
7520
7521         if (crtc_state->has_pch_encoder)
7522                 intel_pch_transcoder_set_m_n(crtc_state, &crtc_state->dp_m_n);
7523         else
7524                 intel_cpu_transcoder_set_m_n(crtc_state, dp_m_n, dp_m2_n2);
7525 }
7526
7527 static void vlv_compute_dpll(struct intel_crtc *crtc,
7528                              struct intel_crtc_state *pipe_config)
7529 {
7530         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
7531                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7532         if (crtc->pipe != PIPE_A)
7533                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7534
7535         /* DPLL not used with DSI, but still need the rest set up */
7536         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
7537                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
7538                         DPLL_EXT_BUFFER_ENABLE_VLV;
7539
7540         pipe_config->dpll_hw_state.dpll_md =
7541                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7542 }
7543
7544 static void chv_compute_dpll(struct intel_crtc *crtc,
7545                              struct intel_crtc_state *pipe_config)
7546 {
7547         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
7548                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7549         if (crtc->pipe != PIPE_A)
7550                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7551
7552         /* DPLL not used with DSI, but still need the rest set up */
7553         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
7554                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE;
7555
7556         pipe_config->dpll_hw_state.dpll_md =
7557                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7558 }
7559
7560 static void vlv_prepare_pll(struct intel_crtc *crtc,
7561                             const struct intel_crtc_state *pipe_config)
7562 {
7563         struct drm_device *dev = crtc->base.dev;
7564         struct drm_i915_private *dev_priv = to_i915(dev);
7565         enum pipe pipe = crtc->pipe;
7566         u32 mdiv;
7567         u32 bestn, bestm1, bestm2, bestp1, bestp2;
7568         u32 coreclk, reg_val;
7569
7570         /* Enable Refclk */
7571         I915_WRITE(DPLL(pipe),
7572                    pipe_config->dpll_hw_state.dpll &
7573                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
7574
7575         /* No need to actually set up the DPLL with DSI */
7576         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7577                 return;
7578
7579         vlv_dpio_get(dev_priv);
7580
7581         bestn = pipe_config->dpll.n;
7582         bestm1 = pipe_config->dpll.m1;
7583         bestm2 = pipe_config->dpll.m2;
7584         bestp1 = pipe_config->dpll.p1;
7585         bestp2 = pipe_config->dpll.p2;
7586
7587         /* See eDP HDMI DPIO driver vbios notes doc */
7588
7589         /* PLL B needs special handling */
7590         if (pipe == PIPE_B)
7591                 vlv_pllb_recal_opamp(dev_priv, pipe);
7592
7593         /* Set up Tx target for periodic Rcomp update */
7594         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
7595
7596         /* Disable target IRef on PLL */
7597         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
7598         reg_val &= 0x00ffffff;
7599         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
7600
7601         /* Disable fast lock */
7602         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
7603
7604         /* Set idtafcrecal before PLL is enabled */
7605         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
7606         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
7607         mdiv |= ((bestn << DPIO_N_SHIFT));
7608         mdiv |= (1 << DPIO_K_SHIFT);
7609
7610         /*
7611          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
7612          * but we don't support that).
7613          * Note: don't use the DAC post divider as it seems unstable.
7614          */
7615         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
7616         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7617
7618         mdiv |= DPIO_ENABLE_CALIBRATION;
7619         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7620
7621         /* Set HBR and RBR LPF coefficients */
7622         if (pipe_config->port_clock == 162000 ||
7623             intel_crtc_has_type(pipe_config, INTEL_OUTPUT_ANALOG) ||
7624             intel_crtc_has_type(pipe_config, INTEL_OUTPUT_HDMI))
7625                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7626                                  0x009f0003);
7627         else
7628                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7629                                  0x00d0000f);
7630
7631         if (intel_crtc_has_dp_encoder(pipe_config)) {
7632                 /* Use SSC source */
7633                 if (pipe == PIPE_A)
7634                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7635                                          0x0df40000);
7636                 else
7637                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7638                                          0x0df70000);
7639         } else { /* HDMI or VGA */
7640                 /* Use bend source */
7641                 if (pipe == PIPE_A)
7642                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7643                                          0x0df70000);
7644                 else
7645                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7646                                          0x0df40000);
7647         }
7648
7649         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
7650         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
7651         if (intel_crtc_has_dp_encoder(pipe_config))
7652                 coreclk |= 0x01000000;
7653         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
7654
7655         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
7656
7657         vlv_dpio_put(dev_priv);
7658 }
7659
7660 static void chv_prepare_pll(struct intel_crtc *crtc,
7661                             const struct intel_crtc_state *pipe_config)
7662 {
7663         struct drm_device *dev = crtc->base.dev;
7664         struct drm_i915_private *dev_priv = to_i915(dev);
7665         enum pipe pipe = crtc->pipe;
7666         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7667         u32 loopfilter, tribuf_calcntr;
7668         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
7669         u32 dpio_val;
7670         int vco;
7671
7672         /* Enable Refclk and SSC */
7673         I915_WRITE(DPLL(pipe),
7674                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
7675
7676         /* No need to actually set up the DPLL with DSI */
7677         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7678                 return;
7679
7680         bestn = pipe_config->dpll.n;
7681         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
7682         bestm1 = pipe_config->dpll.m1;
7683         bestm2 = pipe_config->dpll.m2 >> 22;
7684         bestp1 = pipe_config->dpll.p1;
7685         bestp2 = pipe_config->dpll.p2;
7686         vco = pipe_config->dpll.vco;
7687         dpio_val = 0;
7688         loopfilter = 0;
7689
7690         vlv_dpio_get(dev_priv);
7691
7692         /* p1 and p2 divider */
7693         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
7694                         5 << DPIO_CHV_S1_DIV_SHIFT |
7695                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
7696                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
7697                         1 << DPIO_CHV_K_DIV_SHIFT);
7698
7699         /* Feedback post-divider - m2 */
7700         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
7701
7702         /* Feedback refclk divider - n and m1 */
7703         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
7704                         DPIO_CHV_M1_DIV_BY_2 |
7705                         1 << DPIO_CHV_N_DIV_SHIFT);
7706
7707         /* M2 fraction division */
7708         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
7709
7710         /* M2 fraction division enable */
7711         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7712         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
7713         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
7714         if (bestm2_frac)
7715                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
7716         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
7717
7718         /* Program digital lock detect threshold */
7719         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
7720         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
7721                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
7722         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
7723         if (!bestm2_frac)
7724                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
7725         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
7726
7727         /* Loop filter */
7728         if (vco == 5400000) {
7729                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
7730                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
7731                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
7732                 tribuf_calcntr = 0x9;
7733         } else if (vco <= 6200000) {
7734                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
7735                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
7736                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7737                 tribuf_calcntr = 0x9;
7738         } else if (vco <= 6480000) {
7739                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7740                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7741                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7742                 tribuf_calcntr = 0x8;
7743         } else {
7744                 /* Not supported. Apply the same limits as in the max case */
7745                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7746                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7747                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7748                 tribuf_calcntr = 0;
7749         }
7750         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
7751
7752         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
7753         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
7754         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
7755         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
7756
7757         /* AFC Recal */
7758         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
7759                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
7760                         DPIO_AFC_RECAL);
7761
7762         vlv_dpio_put(dev_priv);
7763 }
7764
7765 /**
7766  * vlv_force_pll_on - forcibly enable just the PLL
7767  * @dev_priv: i915 private structure
7768  * @pipe: pipe PLL to enable
7769  * @dpll: PLL configuration
7770  *
7771  * Enable the PLL for @pipe using the supplied @dpll config. To be used
7772  * in cases where we need the PLL enabled even when @pipe is not going to
7773  * be enabled.
7774  */
7775 int vlv_force_pll_on(struct drm_i915_private *dev_priv, enum pipe pipe,
7776                      const struct dpll *dpll)
7777 {
7778         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
7779         struct intel_crtc_state *pipe_config;
7780
7781         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
7782         if (!pipe_config)
7783                 return -ENOMEM;
7784
7785         pipe_config->base.crtc = &crtc->base;
7786         pipe_config->pixel_multiplier = 1;
7787         pipe_config->dpll = *dpll;
7788
7789         if (IS_CHERRYVIEW(dev_priv)) {
7790                 chv_compute_dpll(crtc, pipe_config);
7791                 chv_prepare_pll(crtc, pipe_config);
7792                 chv_enable_pll(crtc, pipe_config);
7793         } else {
7794                 vlv_compute_dpll(crtc, pipe_config);
7795                 vlv_prepare_pll(crtc, pipe_config);
7796                 vlv_enable_pll(crtc, pipe_config);
7797         }
7798
7799         kfree(pipe_config);
7800
7801         return 0;
7802 }
7803
7804 /**
7805  * vlv_force_pll_off - forcibly disable just the PLL
7806  * @dev_priv: i915 private structure
7807  * @pipe: pipe PLL to disable
7808  *
7809  * Disable the PLL for @pipe. To be used in cases where we need
7810  * the PLL enabled even when @pipe is not going to be enabled.
7811  */
7812 void vlv_force_pll_off(struct drm_i915_private *dev_priv, enum pipe pipe)
7813 {
7814         if (IS_CHERRYVIEW(dev_priv))
7815                 chv_disable_pll(dev_priv, pipe);
7816         else
7817                 vlv_disable_pll(dev_priv, pipe);
7818 }
7819
7820 static void i9xx_compute_dpll(struct intel_crtc *crtc,
7821                               struct intel_crtc_state *crtc_state,
7822                               struct dpll *reduced_clock)
7823 {
7824         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7825         u32 dpll;
7826         struct dpll *clock = &crtc_state->dpll;
7827
7828         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7829
7830         dpll = DPLL_VGA_MODE_DIS;
7831
7832         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
7833                 dpll |= DPLLB_MODE_LVDS;
7834         else
7835                 dpll |= DPLLB_MODE_DAC_SERIAL;
7836
7837         if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
7838             IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
7839                 dpll |= (crtc_state->pixel_multiplier - 1)
7840                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7841         }
7842
7843         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7844             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
7845                 dpll |= DPLL_SDVO_HIGH_SPEED;
7846
7847         if (intel_crtc_has_dp_encoder(crtc_state))
7848                 dpll |= DPLL_SDVO_HIGH_SPEED;
7849
7850         /* compute bitmask from p1 value */
7851         if (IS_PINEVIEW(dev_priv))
7852                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7853         else {
7854                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7855                 if (IS_G4X(dev_priv) && reduced_clock)
7856                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7857         }
7858         switch (clock->p2) {
7859         case 5:
7860                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7861                 break;
7862         case 7:
7863                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7864                 break;
7865         case 10:
7866                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7867                 break;
7868         case 14:
7869                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7870                 break;
7871         }
7872         if (INTEL_GEN(dev_priv) >= 4)
7873                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7874
7875         if (crtc_state->sdvo_tv_clock)
7876                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7877         else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7878                  intel_panel_use_ssc(dev_priv))
7879                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7880         else
7881                 dpll |= PLL_REF_INPUT_DREFCLK;
7882
7883         dpll |= DPLL_VCO_ENABLE;
7884         crtc_state->dpll_hw_state.dpll = dpll;
7885
7886         if (INTEL_GEN(dev_priv) >= 4) {
7887                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7888                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7889                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7890         }
7891 }
7892
7893 static void i8xx_compute_dpll(struct intel_crtc *crtc,
7894                               struct intel_crtc_state *crtc_state,
7895                               struct dpll *reduced_clock)
7896 {
7897         struct drm_device *dev = crtc->base.dev;
7898         struct drm_i915_private *dev_priv = to_i915(dev);
7899         u32 dpll;
7900         struct dpll *clock = &crtc_state->dpll;
7901
7902         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7903
7904         dpll = DPLL_VGA_MODE_DIS;
7905
7906         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7907                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7908         } else {
7909                 if (clock->p1 == 2)
7910                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7911                 else
7912                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7913                 if (clock->p2 == 4)
7914                         dpll |= PLL_P2_DIVIDE_BY_4;
7915         }
7916
7917         /*
7918          * Bspec:
7919          * "[Almador Errata}: For the correct operation of the muxed DVO pins
7920          *  (GDEVSELB/I2Cdata, GIRDBY/I2CClk) and (GFRAMEB/DVI_Data,
7921          *  GTRDYB/DVI_Clk): Bit 31 (DPLL VCO Enable) and Bit 30 (2X Clock
7922          *  Enable) must be set to “1” in both the DPLL A Control Register
7923          *  (06014h-06017h) and DPLL B Control Register (06018h-0601Bh)."
7924          *
7925          * For simplicity We simply keep both bits always enabled in
7926          * both DPLLS. The spec says we should disable the DVO 2X clock
7927          * when not needed, but this seems to work fine in practice.
7928          */
7929         if (IS_I830(dev_priv) ||
7930             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO))
7931                 dpll |= DPLL_DVO_2X_MODE;
7932
7933         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7934             intel_panel_use_ssc(dev_priv))
7935                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7936         else
7937                 dpll |= PLL_REF_INPUT_DREFCLK;
7938
7939         dpll |= DPLL_VCO_ENABLE;
7940         crtc_state->dpll_hw_state.dpll = dpll;
7941 }
7942
7943 static void intel_set_pipe_timings(const struct intel_crtc_state *crtc_state)
7944 {
7945         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
7946         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7947         enum pipe pipe = crtc->pipe;
7948         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
7949         const struct drm_display_mode *adjusted_mode = &crtc_state->base.adjusted_mode;
7950         u32 crtc_vtotal, crtc_vblank_end;
7951         int vsyncshift = 0;
7952
7953         /* We need to be careful not to changed the adjusted mode, for otherwise
7954          * the hw state checker will get angry at the mismatch. */
7955         crtc_vtotal = adjusted_mode->crtc_vtotal;
7956         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7957
7958         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7959                 /* the chip adds 2 halflines automatically */
7960                 crtc_vtotal -= 1;
7961                 crtc_vblank_end -= 1;
7962
7963                 if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO))
7964                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7965                 else
7966                         vsyncshift = adjusted_mode->crtc_hsync_start -
7967                                 adjusted_mode->crtc_htotal / 2;
7968                 if (vsyncshift < 0)
7969                         vsyncshift += adjusted_mode->crtc_htotal;
7970         }
7971
7972         if (INTEL_GEN(dev_priv) > 3)
7973                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7974
7975         I915_WRITE(HTOTAL(cpu_transcoder),
7976                    (adjusted_mode->crtc_hdisplay - 1) |
7977                    ((adjusted_mode->crtc_htotal - 1) << 16));
7978         I915_WRITE(HBLANK(cpu_transcoder),
7979                    (adjusted_mode->crtc_hblank_start - 1) |
7980                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7981         I915_WRITE(HSYNC(cpu_transcoder),
7982                    (adjusted_mode->crtc_hsync_start - 1) |
7983                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7984
7985         I915_WRITE(VTOTAL(cpu_transcoder),
7986                    (adjusted_mode->crtc_vdisplay - 1) |
7987                    ((crtc_vtotal - 1) << 16));
7988         I915_WRITE(VBLANK(cpu_transcoder),
7989                    (adjusted_mode->crtc_vblank_start - 1) |
7990                    ((crtc_vblank_end - 1) << 16));
7991         I915_WRITE(VSYNC(cpu_transcoder),
7992                    (adjusted_mode->crtc_vsync_start - 1) |
7993                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7994
7995         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7996          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7997          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7998          * bits. */
7999         if (IS_HASWELL(dev_priv) && cpu_transcoder == TRANSCODER_EDP &&
8000             (pipe == PIPE_B || pipe == PIPE_C))
8001                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
8002
8003 }
8004
8005 static void intel_set_pipe_src_size(const struct intel_crtc_state *crtc_state)
8006 {
8007         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
8008         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8009         enum pipe pipe = crtc->pipe;
8010
8011         /* pipesrc controls the size that is scaled from, which should
8012          * always be the user's requested size.
8013          */
8014         I915_WRITE(PIPESRC(pipe),
8015                    ((crtc_state->pipe_src_w - 1) << 16) |
8016                    (crtc_state->pipe_src_h - 1));
8017 }
8018
8019 static void intel_get_pipe_timings(struct intel_crtc *crtc,
8020                                    struct intel_crtc_state *pipe_config)
8021 {
8022         struct drm_device *dev = crtc->base.dev;
8023         struct drm_i915_private *dev_priv = to_i915(dev);
8024         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
8025         u32 tmp;
8026
8027         tmp = I915_READ(HTOTAL(cpu_transcoder));
8028         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
8029         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
8030
8031         if (!transcoder_is_dsi(cpu_transcoder)) {
8032                 tmp = I915_READ(HBLANK(cpu_transcoder));
8033                 pipe_config->base.adjusted_mode.crtc_hblank_start =
8034                                                         (tmp & 0xffff) + 1;
8035                 pipe_config->base.adjusted_mode.crtc_hblank_end =
8036                                                 ((tmp >> 16) & 0xffff) + 1;
8037         }
8038         tmp = I915_READ(HSYNC(cpu_transcoder));
8039         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
8040         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
8041
8042         tmp = I915_READ(VTOTAL(cpu_transcoder));
8043         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
8044         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
8045
8046         if (!transcoder_is_dsi(cpu_transcoder)) {
8047                 tmp = I915_READ(VBLANK(cpu_transcoder));
8048                 pipe_config->base.adjusted_mode.crtc_vblank_start =
8049                                                         (tmp & 0xffff) + 1;
8050                 pipe_config->base.adjusted_mode.crtc_vblank_end =
8051                                                 ((tmp >> 16) & 0xffff) + 1;
8052         }
8053         tmp = I915_READ(VSYNC(cpu_transcoder));
8054         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
8055         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
8056
8057         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
8058                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
8059                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
8060                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
8061         }
8062 }
8063
8064 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
8065                                     struct intel_crtc_state *pipe_config)
8066 {
8067         struct drm_device *dev = crtc->base.dev;
8068         struct drm_i915_private *dev_priv = to_i915(dev);
8069         u32 tmp;
8070
8071         tmp = I915_READ(PIPESRC(crtc->pipe));
8072         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
8073         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
8074
8075         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
8076         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
8077 }
8078
8079 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
8080                                  struct intel_crtc_state *pipe_config)
8081 {
8082         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
8083         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
8084         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
8085         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
8086
8087         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
8088         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
8089         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
8090         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
8091
8092         mode->flags = pipe_config->base.adjusted_mode.flags;
8093         mode->type = DRM_MODE_TYPE_DRIVER;
8094
8095         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
8096
8097         mode->hsync = drm_mode_hsync(mode);
8098         mode->vrefresh = drm_mode_vrefresh(mode);
8099         drm_mode_set_name(mode);
8100 }
8101
8102 static void i9xx_set_pipeconf(const struct intel_crtc_state *crtc_state)
8103 {
8104         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
8105         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8106         u32 pipeconf;
8107
8108         pipeconf = 0;
8109
8110         /* we keep both pipes enabled on 830 */
8111         if (IS_I830(dev_priv))
8112                 pipeconf |= I915_READ(PIPECONF(crtc->pipe)) & PIPECONF_ENABLE;
8113
8114         if (crtc_state->double_wide)
8115                 pipeconf |= PIPECONF_DOUBLE_WIDE;
8116
8117         /* only g4x and later have fancy bpc/dither controls */
8118         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
8119             IS_CHERRYVIEW(dev_priv)) {
8120                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
8121                 if (crtc_state->dither && crtc_state->pipe_bpp != 30)
8122                         pipeconf |= PIPECONF_DITHER_EN |
8123                                     PIPECONF_DITHER_TYPE_SP;
8124
8125                 switch (crtc_state->pipe_bpp) {
8126                 case 18:
8127                         pipeconf |= PIPECONF_6BPC;
8128                         break;
8129                 case 24:
8130                         pipeconf |= PIPECONF_8BPC;
8131                         break;
8132                 case 30:
8133                         pipeconf |= PIPECONF_10BPC;
8134                         break;
8135                 default:
8136                         /* Case prevented by intel_choose_pipe_bpp_dither. */
8137                         BUG();
8138                 }
8139         }
8140
8141         if (crtc_state->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
8142                 if (INTEL_GEN(dev_priv) < 4 ||
8143                     intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO))
8144                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
8145                 else
8146                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
8147         } else {
8148                 pipeconf |= PIPECONF_PROGRESSIVE;
8149         }
8150
8151         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
8152              crtc_state->limited_color_range)
8153                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
8154
8155         pipeconf |= PIPECONF_GAMMA_MODE(crtc_state->gamma_mode);
8156
8157         I915_WRITE(PIPECONF(crtc->pipe), pipeconf);
8158         POSTING_READ(PIPECONF(crtc->pipe));
8159 }
8160
8161 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
8162                                    struct intel_crtc_state *crtc_state)
8163 {
8164         struct drm_device *dev = crtc->base.dev;
8165         struct drm_i915_private *dev_priv = to_i915(dev);
8166         const struct intel_limit *limit;
8167         int refclk = 48000;
8168
8169         memset(&crtc_state->dpll_hw_state, 0,
8170                sizeof(crtc_state->dpll_hw_state));
8171
8172         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8173                 if (intel_panel_use_ssc(dev_priv)) {
8174                         refclk = dev_priv->vbt.lvds_ssc_freq;
8175                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8176                 }
8177
8178                 limit = &intel_limits_i8xx_lvds;
8179         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO)) {
8180                 limit = &intel_limits_i8xx_dvo;
8181         } else {
8182                 limit = &intel_limits_i8xx_dac;
8183         }
8184
8185         if (!crtc_state->clock_set &&
8186             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8187                                  refclk, NULL, &crtc_state->dpll)) {
8188                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8189                 return -EINVAL;
8190         }
8191
8192         i8xx_compute_dpll(crtc, crtc_state, NULL);
8193
8194         return 0;
8195 }
8196
8197 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
8198                                   struct intel_crtc_state *crtc_state)
8199 {
8200         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8201         const struct intel_limit *limit;
8202         int refclk = 96000;
8203
8204         memset(&crtc_state->dpll_hw_state, 0,
8205                sizeof(crtc_state->dpll_hw_state));
8206
8207         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8208                 if (intel_panel_use_ssc(dev_priv)) {
8209                         refclk = dev_priv->vbt.lvds_ssc_freq;
8210                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8211                 }
8212
8213                 if (intel_is_dual_link_lvds(dev_priv))
8214                         limit = &intel_limits_g4x_dual_channel_lvds;
8215                 else
8216                         limit = &intel_limits_g4x_single_channel_lvds;
8217         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI) ||
8218                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
8219                 limit = &intel_limits_g4x_hdmi;
8220         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO)) {
8221                 limit = &intel_limits_g4x_sdvo;
8222         } else {
8223                 /* The option is for other outputs */
8224                 limit = &intel_limits_i9xx_sdvo;
8225         }
8226
8227         if (!crtc_state->clock_set &&
8228             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8229                                 refclk, NULL, &crtc_state->dpll)) {
8230                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8231                 return -EINVAL;
8232         }
8233
8234         i9xx_compute_dpll(crtc, crtc_state, NULL);
8235
8236         return 0;
8237 }
8238
8239 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
8240                                   struct intel_crtc_state *crtc_state)
8241 {
8242         struct drm_device *dev = crtc->base.dev;
8243         struct drm_i915_private *dev_priv = to_i915(dev);
8244         const struct intel_limit *limit;
8245         int refclk = 96000;
8246
8247         memset(&crtc_state->dpll_hw_state, 0,
8248                sizeof(crtc_state->dpll_hw_state));
8249
8250         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8251                 if (intel_panel_use_ssc(dev_priv)) {
8252                         refclk = dev_priv->vbt.lvds_ssc_freq;
8253                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8254                 }
8255
8256                 limit = &intel_limits_pineview_lvds;
8257         } else {
8258                 limit = &intel_limits_pineview_sdvo;
8259         }
8260
8261         if (!crtc_state->clock_set &&
8262             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8263                                 refclk, NULL, &crtc_state->dpll)) {
8264                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8265                 return -EINVAL;
8266         }
8267
8268         i9xx_compute_dpll(crtc, crtc_state, NULL);
8269
8270         return 0;
8271 }
8272
8273 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
8274                                    struct intel_crtc_state *crtc_state)
8275 {
8276         struct drm_device *dev = crtc->base.dev;
8277         struct drm_i915_private *dev_priv = to_i915(dev);
8278         const struct intel_limit *limit;
8279         int refclk = 96000;
8280
8281         memset(&crtc_state->dpll_hw_state, 0,
8282                sizeof(crtc_state->dpll_hw_state));
8283
8284         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8285                 if (intel_panel_use_ssc(dev_priv)) {
8286                         refclk = dev_priv->vbt.lvds_ssc_freq;
8287                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
8288                 }
8289
8290                 limit = &intel_limits_i9xx_lvds;
8291         } else {
8292                 limit = &intel_limits_i9xx_sdvo;
8293         }
8294
8295         if (!crtc_state->clock_set &&
8296             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8297                                  refclk, NULL, &crtc_state->dpll)) {
8298                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8299                 return -EINVAL;
8300         }
8301
8302         i9xx_compute_dpll(crtc, crtc_state, NULL);
8303
8304         return 0;
8305 }
8306
8307 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
8308                                   struct intel_crtc_state *crtc_state)
8309 {
8310         int refclk = 100000;
8311         const struct intel_limit *limit = &intel_limits_chv;
8312
8313         memset(&crtc_state->dpll_hw_state, 0,
8314                sizeof(crtc_state->dpll_hw_state));
8315
8316         if (!crtc_state->clock_set &&
8317             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8318                                 refclk, NULL, &crtc_state->dpll)) {
8319                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8320                 return -EINVAL;
8321         }
8322
8323         chv_compute_dpll(crtc, crtc_state);
8324
8325         return 0;
8326 }
8327
8328 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
8329                                   struct intel_crtc_state *crtc_state)
8330 {
8331         int refclk = 100000;
8332         const struct intel_limit *limit = &intel_limits_vlv;
8333
8334         memset(&crtc_state->dpll_hw_state, 0,
8335                sizeof(crtc_state->dpll_hw_state));
8336
8337         if (!crtc_state->clock_set &&
8338             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8339                                 refclk, NULL, &crtc_state->dpll)) {
8340                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8341                 return -EINVAL;
8342         }
8343
8344         vlv_compute_dpll(crtc, crtc_state);
8345
8346         return 0;
8347 }
8348
8349 static bool i9xx_has_pfit(struct drm_i915_private *dev_priv)
8350 {
8351         if (IS_I830(dev_priv))
8352                 return false;
8353
8354         return INTEL_GEN(dev_priv) >= 4 ||
8355                 IS_PINEVIEW(dev_priv) || IS_MOBILE(dev_priv);
8356 }
8357
8358 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
8359                                  struct intel_crtc_state *pipe_config)
8360 {
8361         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8362         u32 tmp;
8363
8364         if (!i9xx_has_pfit(dev_priv))
8365                 return;
8366
8367         tmp = I915_READ(PFIT_CONTROL);
8368         if (!(tmp & PFIT_ENABLE))
8369                 return;
8370
8371         /* Check whether the pfit is attached to our pipe. */
8372         if (INTEL_GEN(dev_priv) < 4) {
8373                 if (crtc->pipe != PIPE_B)
8374                         return;
8375         } else {
8376                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
8377                         return;
8378         }
8379
8380         pipe_config->gmch_pfit.control = tmp;
8381         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
8382 }
8383
8384 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
8385                                struct intel_crtc_state *pipe_config)
8386 {
8387         struct drm_device *dev = crtc->base.dev;
8388         struct drm_i915_private *dev_priv = to_i915(dev);
8389         int pipe = pipe_config->cpu_transcoder;
8390         struct dpll clock;
8391         u32 mdiv;
8392         int refclk = 100000;
8393
8394         /* In case of DSI, DPLL will not be used */
8395         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
8396                 return;
8397
8398         vlv_dpio_get(dev_priv);
8399         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
8400         vlv_dpio_put(dev_priv);
8401
8402         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
8403         clock.m2 = mdiv & DPIO_M2DIV_MASK;
8404         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
8405         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
8406         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
8407
8408         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
8409 }
8410
8411 static void
8412 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
8413                               struct intel_initial_plane_config *plane_config)
8414 {
8415         struct drm_device *dev = crtc->base.dev;
8416         struct drm_i915_private *dev_priv = to_i915(dev);
8417         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
8418         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
8419         enum pipe pipe;
8420         u32 val, base, offset;
8421         int fourcc, pixel_format;
8422         unsigned int aligned_height;
8423         struct drm_framebuffer *fb;
8424         struct intel_framebuffer *intel_fb;
8425
8426         if (!plane->get_hw_state(plane, &pipe))
8427                 return;
8428
8429         WARN_ON(pipe != crtc->pipe);
8430
8431         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8432         if (!intel_fb) {
8433                 DRM_DEBUG_KMS("failed to alloc fb\n");
8434                 return;
8435         }
8436
8437         fb = &intel_fb->base;
8438
8439         fb->dev = dev;
8440
8441         val = I915_READ(DSPCNTR(i9xx_plane));
8442
8443         if (INTEL_GEN(dev_priv) >= 4) {
8444                 if (val & DISPPLANE_TILED) {
8445                         plane_config->tiling = I915_TILING_X;
8446                         fb->modifier = I915_FORMAT_MOD_X_TILED;
8447                 }
8448
8449                 if (val & DISPPLANE_ROTATE_180)
8450                         plane_config->rotation = DRM_MODE_ROTATE_180;
8451         }
8452
8453         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B &&
8454             val & DISPPLANE_MIRROR)
8455                 plane_config->rotation |= DRM_MODE_REFLECT_X;
8456
8457         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
8458         fourcc = i9xx_format_to_fourcc(pixel_format);
8459         fb->format = drm_format_info(fourcc);
8460
8461         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
8462                 offset = I915_READ(DSPOFFSET(i9xx_plane));
8463                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
8464         } else if (INTEL_GEN(dev_priv) >= 4) {
8465                 if (plane_config->tiling)
8466                         offset = I915_READ(DSPTILEOFF(i9xx_plane));
8467                 else
8468                         offset = I915_READ(DSPLINOFF(i9xx_plane));
8469                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
8470         } else {
8471                 base = I915_READ(DSPADDR(i9xx_plane));
8472         }
8473         plane_config->base = base;
8474
8475         val = I915_READ(PIPESRC(pipe));
8476         fb->width = ((val >> 16) & 0xfff) + 1;
8477         fb->height = ((val >> 0) & 0xfff) + 1;
8478
8479         val = I915_READ(DSPSTRIDE(i9xx_plane));
8480         fb->pitches[0] = val & 0xffffffc0;
8481
8482         aligned_height = intel_fb_align_height(fb, 0, fb->height);
8483
8484         plane_config->size = fb->pitches[0] * aligned_height;
8485
8486         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8487                       crtc->base.name, plane->base.name, fb->width, fb->height,
8488                       fb->format->cpp[0] * 8, base, fb->pitches[0],
8489                       plane_config->size);
8490
8491         plane_config->fb = intel_fb;
8492 }
8493
8494 static void chv_crtc_clock_get(struct intel_crtc *crtc,
8495                                struct intel_crtc_state *pipe_config)
8496 {
8497         struct drm_device *dev = crtc->base.dev;
8498         struct drm_i915_private *dev_priv = to_i915(dev);
8499         int pipe = pipe_config->cpu_transcoder;
8500         enum dpio_channel port = vlv_pipe_to_channel(pipe);
8501         struct dpll clock;
8502         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
8503         int refclk = 100000;
8504
8505         /* In case of DSI, DPLL will not be used */
8506         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
8507                 return;
8508
8509         vlv_dpio_get(dev_priv);
8510         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
8511         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
8512         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
8513         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
8514         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
8515         vlv_dpio_put(dev_priv);
8516
8517         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
8518         clock.m2 = (pll_dw0 & 0xff) << 22;
8519         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
8520                 clock.m2 |= pll_dw2 & 0x3fffff;
8521         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
8522         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
8523         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
8524
8525         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
8526 }
8527
8528 static void intel_get_crtc_ycbcr_config(struct intel_crtc *crtc,
8529                                         struct intel_crtc_state *pipe_config)
8530 {
8531         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8532         enum intel_output_format output = INTEL_OUTPUT_FORMAT_RGB;
8533
8534         pipe_config->lspcon_downsampling = false;
8535
8536         if (IS_BROADWELL(dev_priv) || INTEL_GEN(dev_priv) >= 9) {
8537                 u32 tmp = I915_READ(PIPEMISC(crtc->pipe));
8538
8539                 if (tmp & PIPEMISC_OUTPUT_COLORSPACE_YUV) {
8540                         bool ycbcr420_enabled = tmp & PIPEMISC_YUV420_ENABLE;
8541                         bool blend = tmp & PIPEMISC_YUV420_MODE_FULL_BLEND;
8542
8543                         if (ycbcr420_enabled) {
8544                                 /* We support 4:2:0 in full blend mode only */
8545                                 if (!blend)
8546                                         output = INTEL_OUTPUT_FORMAT_INVALID;
8547                                 else if (!(IS_GEMINILAKE(dev_priv) ||
8548                                            INTEL_GEN(dev_priv) >= 10))
8549                                         output = INTEL_OUTPUT_FORMAT_INVALID;
8550                                 else
8551                                         output = INTEL_OUTPUT_FORMAT_YCBCR420;
8552                         } else {
8553                                 /*
8554                                  * Currently there is no interface defined to
8555                                  * check user preference between RGB/YCBCR444
8556                                  * or YCBCR420. So the only possible case for
8557                                  * YCBCR444 usage is driving YCBCR420 output
8558                                  * with LSPCON, when pipe is configured for
8559                                  * YCBCR444 output and LSPCON takes care of
8560                                  * downsampling it.
8561                                  */
8562                                 pipe_config->lspcon_downsampling = true;
8563                                 output = INTEL_OUTPUT_FORMAT_YCBCR444;
8564                         }
8565                 }
8566         }
8567
8568         pipe_config->output_format = output;
8569 }
8570
8571 static void i9xx_get_pipe_color_config(struct intel_crtc_state *crtc_state)
8572 {
8573         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
8574         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
8575         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8576         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
8577         u32 tmp;
8578
8579         tmp = I915_READ(DSPCNTR(i9xx_plane));
8580
8581         if (tmp & DISPPLANE_GAMMA_ENABLE)
8582                 crtc_state->gamma_enable = true;
8583
8584         if (!HAS_GMCH(dev_priv) &&
8585             tmp & DISPPLANE_PIPE_CSC_ENABLE)
8586                 crtc_state->csc_enable = true;
8587 }
8588
8589 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
8590                                  struct intel_crtc_state *pipe_config)
8591 {
8592         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8593         enum intel_display_power_domain power_domain;
8594         intel_wakeref_t wakeref;
8595         u32 tmp;
8596         bool ret;
8597
8598         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8599         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
8600         if (!wakeref)
8601                 return false;
8602
8603         pipe_config->output_format = INTEL_OUTPUT_FORMAT_RGB;
8604         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8605         pipe_config->shared_dpll = NULL;
8606
8607         ret = false;
8608
8609         tmp = I915_READ(PIPECONF(crtc->pipe));
8610         if (!(tmp & PIPECONF_ENABLE))
8611                 goto out;
8612
8613         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
8614             IS_CHERRYVIEW(dev_priv)) {
8615                 switch (tmp & PIPECONF_BPC_MASK) {
8616                 case PIPECONF_6BPC:
8617                         pipe_config->pipe_bpp = 18;
8618                         break;
8619                 case PIPECONF_8BPC:
8620                         pipe_config->pipe_bpp = 24;
8621                         break;
8622                 case PIPECONF_10BPC:
8623                         pipe_config->pipe_bpp = 30;
8624                         break;
8625                 default:
8626                         break;
8627                 }
8628         }
8629
8630         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
8631             (tmp & PIPECONF_COLOR_RANGE_SELECT))
8632                 pipe_config->limited_color_range = true;
8633
8634         pipe_config->gamma_mode = (tmp & PIPECONF_GAMMA_MODE_MASK_I9XX) >>
8635                 PIPECONF_GAMMA_MODE_SHIFT;
8636
8637         if (IS_CHERRYVIEW(dev_priv))
8638                 pipe_config->cgm_mode = I915_READ(CGM_PIPE_MODE(crtc->pipe));
8639
8640         i9xx_get_pipe_color_config(pipe_config);
8641
8642         if (INTEL_GEN(dev_priv) < 4)
8643                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
8644
8645         intel_get_pipe_timings(crtc, pipe_config);
8646         intel_get_pipe_src_size(crtc, pipe_config);
8647
8648         i9xx_get_pfit_config(crtc, pipe_config);
8649
8650         if (INTEL_GEN(dev_priv) >= 4) {
8651                 /* No way to read it out on pipes B and C */
8652                 if (IS_CHERRYVIEW(dev_priv) && crtc->pipe != PIPE_A)
8653                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
8654                 else
8655                         tmp = I915_READ(DPLL_MD(crtc->pipe));
8656                 pipe_config->pixel_multiplier =
8657                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
8658                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
8659                 pipe_config->dpll_hw_state.dpll_md = tmp;
8660         } else if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
8661                    IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
8662                 tmp = I915_READ(DPLL(crtc->pipe));
8663                 pipe_config->pixel_multiplier =
8664                         ((tmp & SDVO_MULTIPLIER_MASK)
8665                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
8666         } else {
8667                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
8668                  * port and will be fixed up in the encoder->get_config
8669                  * function. */
8670                 pipe_config->pixel_multiplier = 1;
8671         }
8672         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
8673         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
8674                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
8675                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
8676         } else {
8677                 /* Mask out read-only status bits. */
8678                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
8679                                                      DPLL_PORTC_READY_MASK |
8680                                                      DPLL_PORTB_READY_MASK);
8681         }
8682
8683         if (IS_CHERRYVIEW(dev_priv))
8684                 chv_crtc_clock_get(crtc, pipe_config);
8685         else if (IS_VALLEYVIEW(dev_priv))
8686                 vlv_crtc_clock_get(crtc, pipe_config);
8687         else
8688                 i9xx_crtc_clock_get(crtc, pipe_config);
8689
8690         /*
8691          * Normally the dotclock is filled in by the encoder .get_config()
8692          * but in case the pipe is enabled w/o any ports we need a sane
8693          * default.
8694          */
8695         pipe_config->base.adjusted_mode.crtc_clock =
8696                 pipe_config->port_clock / pipe_config->pixel_multiplier;
8697
8698         ret = true;
8699
8700 out:
8701         intel_display_power_put(dev_priv, power_domain, wakeref);
8702
8703         return ret;
8704 }
8705
8706 static void ironlake_init_pch_refclk(struct drm_i915_private *dev_priv)
8707 {
8708         struct intel_encoder *encoder;
8709         int i;
8710         u32 val, final;
8711         bool has_lvds = false;
8712         bool has_cpu_edp = false;
8713         bool has_panel = false;
8714         bool has_ck505 = false;
8715         bool can_ssc = false;
8716         bool using_ssc_source = false;
8717
8718         /* We need to take the global config into account */
8719         for_each_intel_encoder(&dev_priv->drm, encoder) {
8720                 switch (encoder->type) {
8721                 case INTEL_OUTPUT_LVDS:
8722                         has_panel = true;
8723                         has_lvds = true;
8724                         break;
8725                 case INTEL_OUTPUT_EDP:
8726                         has_panel = true;
8727                         if (encoder->port == PORT_A)
8728                                 has_cpu_edp = true;
8729                         break;
8730                 default:
8731                         break;
8732                 }
8733         }
8734
8735         if (HAS_PCH_IBX(dev_priv)) {
8736                 has_ck505 = dev_priv->vbt.display_clock_mode;
8737                 can_ssc = has_ck505;
8738         } else {
8739                 has_ck505 = false;
8740                 can_ssc = true;
8741         }
8742
8743         /* Check if any DPLLs are using the SSC source */
8744         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
8745                 u32 temp = I915_READ(PCH_DPLL(i));
8746
8747                 if (!(temp & DPLL_VCO_ENABLE))
8748                         continue;
8749
8750                 if ((temp & PLL_REF_INPUT_MASK) ==
8751                     PLLB_REF_INPUT_SPREADSPECTRUMIN) {
8752                         using_ssc_source = true;
8753                         break;
8754                 }
8755         }
8756
8757         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d using_ssc_source %d\n",
8758                       has_panel, has_lvds, has_ck505, using_ssc_source);
8759
8760         /* Ironlake: try to setup display ref clock before DPLL
8761          * enabling. This is only under driver's control after
8762          * PCH B stepping, previous chipset stepping should be
8763          * ignoring this setting.
8764          */
8765         val = I915_READ(PCH_DREF_CONTROL);
8766
8767         /* As we must carefully and slowly disable/enable each source in turn,
8768          * compute the final state we want first and check if we need to
8769          * make any changes at all.
8770          */
8771         final = val;
8772         final &= ~DREF_NONSPREAD_SOURCE_MASK;
8773         if (has_ck505)
8774                 final |= DREF_NONSPREAD_CK505_ENABLE;
8775         else
8776                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
8777
8778         final &= ~DREF_SSC_SOURCE_MASK;
8779         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8780         final &= ~DREF_SSC1_ENABLE;
8781
8782         if (has_panel) {
8783                 final |= DREF_SSC_SOURCE_ENABLE;
8784
8785                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
8786                         final |= DREF_SSC1_ENABLE;
8787
8788                 if (has_cpu_edp) {
8789                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
8790                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8791                         else
8792                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8793                 } else
8794                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8795         } else if (using_ssc_source) {
8796                 final |= DREF_SSC_SOURCE_ENABLE;
8797                 final |= DREF_SSC1_ENABLE;
8798         }
8799
8800         if (final == val)
8801                 return;
8802
8803         /* Always enable nonspread source */
8804         val &= ~DREF_NONSPREAD_SOURCE_MASK;
8805
8806         if (has_ck505)
8807                 val |= DREF_NONSPREAD_CK505_ENABLE;
8808         else
8809                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
8810
8811         if (has_panel) {
8812                 val &= ~DREF_SSC_SOURCE_MASK;
8813                 val |= DREF_SSC_SOURCE_ENABLE;
8814
8815                 /* SSC must be turned on before enabling the CPU output  */
8816                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8817                         DRM_DEBUG_KMS("Using SSC on panel\n");
8818                         val |= DREF_SSC1_ENABLE;
8819                 } else
8820                         val &= ~DREF_SSC1_ENABLE;
8821
8822                 /* Get SSC going before enabling the outputs */
8823                 I915_WRITE(PCH_DREF_CONTROL, val);
8824                 POSTING_READ(PCH_DREF_CONTROL);
8825                 udelay(200);
8826
8827                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8828
8829                 /* Enable CPU source on CPU attached eDP */
8830                 if (has_cpu_edp) {
8831                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8832                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
8833                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8834                         } else
8835                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8836                 } else
8837                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8838
8839                 I915_WRITE(PCH_DREF_CONTROL, val);
8840                 POSTING_READ(PCH_DREF_CONTROL);
8841                 udelay(200);
8842         } else {
8843                 DRM_DEBUG_KMS("Disabling CPU source output\n");
8844
8845                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8846
8847                 /* Turn off CPU output */
8848                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8849
8850                 I915_WRITE(PCH_DREF_CONTROL, val);
8851                 POSTING_READ(PCH_DREF_CONTROL);
8852                 udelay(200);
8853
8854                 if (!using_ssc_source) {
8855                         DRM_DEBUG_KMS("Disabling SSC source\n");
8856
8857                         /* Turn off the SSC source */
8858                         val &= ~DREF_SSC_SOURCE_MASK;
8859                         val |= DREF_SSC_SOURCE_DISABLE;
8860
8861                         /* Turn off SSC1 */
8862                         val &= ~DREF_SSC1_ENABLE;
8863
8864                         I915_WRITE(PCH_DREF_CONTROL, val);
8865                         POSTING_READ(PCH_DREF_CONTROL);
8866                         udelay(200);
8867                 }
8868         }
8869
8870         BUG_ON(val != final);
8871 }
8872
8873 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
8874 {
8875         u32 tmp;
8876
8877         tmp = I915_READ(SOUTH_CHICKEN2);
8878         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
8879         I915_WRITE(SOUTH_CHICKEN2, tmp);
8880
8881         if (wait_for_us(I915_READ(SOUTH_CHICKEN2) &
8882                         FDI_MPHY_IOSFSB_RESET_STATUS, 100))
8883                 DRM_ERROR("FDI mPHY reset assert timeout\n");
8884
8885         tmp = I915_READ(SOUTH_CHICKEN2);
8886         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
8887         I915_WRITE(SOUTH_CHICKEN2, tmp);
8888
8889         if (wait_for_us((I915_READ(SOUTH_CHICKEN2) &
8890                          FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
8891                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
8892 }
8893
8894 /* WaMPhyProgramming:hsw */
8895 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
8896 {
8897         u32 tmp;
8898
8899         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
8900         tmp &= ~(0xFF << 24);
8901         tmp |= (0x12 << 24);
8902         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
8903
8904         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
8905         tmp |= (1 << 11);
8906         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
8907
8908         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
8909         tmp |= (1 << 11);
8910         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
8911
8912         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
8913         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8914         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
8915
8916         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
8917         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8918         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
8919
8920         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
8921         tmp &= ~(7 << 13);
8922         tmp |= (5 << 13);
8923         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
8924
8925         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
8926         tmp &= ~(7 << 13);
8927         tmp |= (5 << 13);
8928         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
8929
8930         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
8931         tmp &= ~0xFF;
8932         tmp |= 0x1C;
8933         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
8934
8935         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
8936         tmp &= ~0xFF;
8937         tmp |= 0x1C;
8938         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
8939
8940         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
8941         tmp &= ~(0xFF << 16);
8942         tmp |= (0x1C << 16);
8943         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
8944
8945         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
8946         tmp &= ~(0xFF << 16);
8947         tmp |= (0x1C << 16);
8948         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
8949
8950         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8951         tmp |= (1 << 27);
8952         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8953
8954         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8955         tmp |= (1 << 27);
8956         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8957
8958         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8959         tmp &= ~(0xF << 28);
8960         tmp |= (4 << 28);
8961         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8962
8963         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
8964         tmp &= ~(0xF << 28);
8965         tmp |= (4 << 28);
8966         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
8967 }
8968
8969 /* Implements 3 different sequences from BSpec chapter "Display iCLK
8970  * Programming" based on the parameters passed:
8971  * - Sequence to enable CLKOUT_DP
8972  * - Sequence to enable CLKOUT_DP without spread
8973  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
8974  */
8975 static void lpt_enable_clkout_dp(struct drm_i915_private *dev_priv,
8976                                  bool with_spread, bool with_fdi)
8977 {
8978         u32 reg, tmp;
8979
8980         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
8981                 with_spread = true;
8982         if (WARN(HAS_PCH_LPT_LP(dev_priv) &&
8983             with_fdi, "LP PCH doesn't have FDI\n"))
8984                 with_fdi = false;
8985
8986         mutex_lock(&dev_priv->sb_lock);
8987
8988         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8989         tmp &= ~SBI_SSCCTL_DISABLE;
8990         tmp |= SBI_SSCCTL_PATHALT;
8991         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8992
8993         udelay(24);
8994
8995         if (with_spread) {
8996                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8997                 tmp &= ~SBI_SSCCTL_PATHALT;
8998                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8999
9000                 if (with_fdi) {
9001                         lpt_reset_fdi_mphy(dev_priv);
9002                         lpt_program_fdi_mphy(dev_priv);
9003                 }
9004         }
9005
9006         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
9007         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
9008         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
9009         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
9010
9011         mutex_unlock(&dev_priv->sb_lock);
9012 }
9013
9014 /* Sequence to disable CLKOUT_DP */
9015 void lpt_disable_clkout_dp(struct drm_i915_private *dev_priv)
9016 {
9017         u32 reg, tmp;
9018
9019         mutex_lock(&dev_priv->sb_lock);
9020
9021         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
9022         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
9023         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
9024         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
9025
9026         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
9027         if (!(tmp & SBI_SSCCTL_DISABLE)) {
9028                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
9029                         tmp |= SBI_SSCCTL_PATHALT;
9030                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
9031                         udelay(32);
9032                 }
9033                 tmp |= SBI_SSCCTL_DISABLE;
9034                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
9035         }
9036
9037         mutex_unlock(&dev_priv->sb_lock);
9038 }
9039
9040 #define BEND_IDX(steps) ((50 + (steps)) / 5)
9041
9042 static const u16 sscdivintphase[] = {
9043         [BEND_IDX( 50)] = 0x3B23,
9044         [BEND_IDX( 45)] = 0x3B23,
9045         [BEND_IDX( 40)] = 0x3C23,
9046         [BEND_IDX( 35)] = 0x3C23,
9047         [BEND_IDX( 30)] = 0x3D23,
9048         [BEND_IDX( 25)] = 0x3D23,
9049         [BEND_IDX( 20)] = 0x3E23,
9050         [BEND_IDX( 15)] = 0x3E23,
9051         [BEND_IDX( 10)] = 0x3F23,
9052         [BEND_IDX(  5)] = 0x3F23,
9053         [BEND_IDX(  0)] = 0x0025,
9054         [BEND_IDX( -5)] = 0x0025,
9055         [BEND_IDX(-10)] = 0x0125,
9056         [BEND_IDX(-15)] = 0x0125,
9057         [BEND_IDX(-20)] = 0x0225,
9058         [BEND_IDX(-25)] = 0x0225,
9059         [BEND_IDX(-30)] = 0x0325,
9060         [BEND_IDX(-35)] = 0x0325,
9061         [BEND_IDX(-40)] = 0x0425,
9062         [BEND_IDX(-45)] = 0x0425,
9063         [BEND_IDX(-50)] = 0x0525,
9064 };
9065
9066 /*
9067  * Bend CLKOUT_DP
9068  * steps -50 to 50 inclusive, in steps of 5
9069  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
9070  * change in clock period = -(steps / 10) * 5.787 ps
9071  */
9072 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
9073 {
9074         u32 tmp;
9075         int idx = BEND_IDX(steps);
9076
9077         if (WARN_ON(steps % 5 != 0))
9078                 return;
9079
9080         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
9081                 return;
9082
9083         mutex_lock(&dev_priv->sb_lock);
9084
9085         if (steps % 10 != 0)
9086                 tmp = 0xAAAAAAAB;
9087         else
9088                 tmp = 0x00000000;
9089         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
9090
9091         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
9092         tmp &= 0xffff0000;
9093         tmp |= sscdivintphase[idx];
9094         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
9095
9096         mutex_unlock(&dev_priv->sb_lock);
9097 }
9098
9099 #undef BEND_IDX
9100
9101 static void lpt_init_pch_refclk(struct drm_i915_private *dev_priv)
9102 {
9103         struct intel_encoder *encoder;
9104         bool has_vga = false;
9105
9106         for_each_intel_encoder(&dev_priv->drm, encoder) {
9107                 switch (encoder->type) {
9108                 case INTEL_OUTPUT_ANALOG:
9109                         has_vga = true;
9110                         break;
9111                 default:
9112                         break;
9113                 }
9114         }
9115
9116         if (has_vga) {
9117                 lpt_bend_clkout_dp(dev_priv, 0);
9118                 lpt_enable_clkout_dp(dev_priv, true, true);
9119         } else {
9120                 lpt_disable_clkout_dp(dev_priv);
9121         }
9122 }
9123
9124 /*
9125  * Initialize reference clocks when the driver loads
9126  */
9127 void intel_init_pch_refclk(struct drm_i915_private *dev_priv)
9128 {
9129         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv))
9130                 ironlake_init_pch_refclk(dev_priv);
9131         else if (HAS_PCH_LPT(dev_priv))
9132                 lpt_init_pch_refclk(dev_priv);
9133 }
9134
9135 static void ironlake_set_pipeconf(const struct intel_crtc_state *crtc_state)
9136 {
9137         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
9138         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9139         enum pipe pipe = crtc->pipe;
9140         u32 val;
9141
9142         val = 0;
9143
9144         switch (crtc_state->pipe_bpp) {
9145         case 18:
9146                 val |= PIPECONF_6BPC;
9147                 break;
9148         case 24:
9149                 val |= PIPECONF_8BPC;
9150                 break;
9151         case 30:
9152                 val |= PIPECONF_10BPC;
9153                 break;
9154         case 36:
9155                 val |= PIPECONF_12BPC;
9156                 break;
9157         default:
9158                 /* Case prevented by intel_choose_pipe_bpp_dither. */
9159                 BUG();
9160         }
9161
9162         if (crtc_state->dither)
9163                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
9164
9165         if (crtc_state->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
9166                 val |= PIPECONF_INTERLACED_ILK;
9167         else
9168                 val |= PIPECONF_PROGRESSIVE;
9169
9170         if (crtc_state->limited_color_range)
9171                 val |= PIPECONF_COLOR_RANGE_SELECT;
9172
9173         val |= PIPECONF_GAMMA_MODE(crtc_state->gamma_mode);
9174
9175         I915_WRITE(PIPECONF(pipe), val);
9176         POSTING_READ(PIPECONF(pipe));
9177 }
9178
9179 static void haswell_set_pipeconf(const struct intel_crtc_state *crtc_state)
9180 {
9181         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
9182         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9183         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
9184         u32 val = 0;
9185
9186         if (IS_HASWELL(dev_priv) && crtc_state->dither)
9187                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
9188
9189         if (crtc_state->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
9190                 val |= PIPECONF_INTERLACED_ILK;
9191         else
9192                 val |= PIPECONF_PROGRESSIVE;
9193
9194         I915_WRITE(PIPECONF(cpu_transcoder), val);
9195         POSTING_READ(PIPECONF(cpu_transcoder));
9196 }
9197
9198 static void bdw_set_pipemisc(const struct intel_crtc_state *crtc_state)
9199 {
9200         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
9201         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9202         u32 val = 0;
9203
9204         switch (crtc_state->pipe_bpp) {
9205         case 18:
9206                 val |= PIPEMISC_DITHER_6_BPC;
9207                 break;
9208         case 24:
9209                 val |= PIPEMISC_DITHER_8_BPC;
9210                 break;
9211         case 30:
9212                 val |= PIPEMISC_DITHER_10_BPC;
9213                 break;
9214         case 36:
9215                 val |= PIPEMISC_DITHER_12_BPC;
9216                 break;
9217         default:
9218                 MISSING_CASE(crtc_state->pipe_bpp);
9219                 break;
9220         }
9221
9222         if (crtc_state->dither)
9223                 val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
9224
9225         if (crtc_state->output_format == INTEL_OUTPUT_FORMAT_YCBCR420 ||
9226             crtc_state->output_format == INTEL_OUTPUT_FORMAT_YCBCR444)
9227                 val |= PIPEMISC_OUTPUT_COLORSPACE_YUV;
9228
9229         if (crtc_state->output_format == INTEL_OUTPUT_FORMAT_YCBCR420)
9230                 val |= PIPEMISC_YUV420_ENABLE |
9231                         PIPEMISC_YUV420_MODE_FULL_BLEND;
9232
9233         if (INTEL_GEN(dev_priv) >= 11 &&
9234             (crtc_state->active_planes & ~(icl_hdr_plane_mask() |
9235                                            BIT(PLANE_CURSOR))) == 0)
9236                 val |= PIPEMISC_HDR_MODE_PRECISION;
9237
9238         I915_WRITE(PIPEMISC(crtc->pipe), val);
9239 }
9240
9241 int bdw_get_pipemisc_bpp(struct intel_crtc *crtc)
9242 {
9243         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9244         u32 tmp;
9245
9246         tmp = I915_READ(PIPEMISC(crtc->pipe));
9247
9248         switch (tmp & PIPEMISC_DITHER_BPC_MASK) {
9249         case PIPEMISC_DITHER_6_BPC:
9250                 return 18;
9251         case PIPEMISC_DITHER_8_BPC:
9252                 return 24;
9253         case PIPEMISC_DITHER_10_BPC:
9254                 return 30;
9255         case PIPEMISC_DITHER_12_BPC:
9256                 return 36;
9257         default:
9258                 MISSING_CASE(tmp);
9259                 return 0;
9260         }
9261 }
9262
9263 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
9264 {
9265         /*
9266          * Account for spread spectrum to avoid
9267          * oversubscribing the link. Max center spread
9268          * is 2.5%; use 5% for safety's sake.
9269          */
9270         u32 bps = target_clock * bpp * 21 / 20;
9271         return DIV_ROUND_UP(bps, link_bw * 8);
9272 }
9273
9274 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
9275 {
9276         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
9277 }
9278
9279 static void ironlake_compute_dpll(struct intel_crtc *crtc,
9280                                   struct intel_crtc_state *crtc_state,
9281                                   struct dpll *reduced_clock)
9282 {
9283         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9284         u32 dpll, fp, fp2;
9285         int factor;
9286
9287         /* Enable autotuning of the PLL clock (if permissible) */
9288         factor = 21;
9289         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
9290                 if ((intel_panel_use_ssc(dev_priv) &&
9291                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
9292                     (HAS_PCH_IBX(dev_priv) &&
9293                      intel_is_dual_link_lvds(dev_priv)))
9294                         factor = 25;
9295         } else if (crtc_state->sdvo_tv_clock) {
9296                 factor = 20;
9297         }
9298
9299         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
9300
9301         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
9302                 fp |= FP_CB_TUNE;
9303
9304         if (reduced_clock) {
9305                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
9306
9307                 if (reduced_clock->m < factor * reduced_clock->n)
9308                         fp2 |= FP_CB_TUNE;
9309         } else {
9310                 fp2 = fp;
9311         }
9312
9313         dpll = 0;
9314
9315         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
9316                 dpll |= DPLLB_MODE_LVDS;
9317         else
9318                 dpll |= DPLLB_MODE_DAC_SERIAL;
9319
9320         dpll |= (crtc_state->pixel_multiplier - 1)
9321                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
9322
9323         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
9324             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
9325                 dpll |= DPLL_SDVO_HIGH_SPEED;
9326
9327         if (intel_crtc_has_dp_encoder(crtc_state))
9328                 dpll |= DPLL_SDVO_HIGH_SPEED;
9329
9330         /*
9331          * The high speed IO clock is only really required for
9332          * SDVO/HDMI/DP, but we also enable it for CRT to make it
9333          * possible to share the DPLL between CRT and HDMI. Enabling
9334          * the clock needlessly does no real harm, except use up a
9335          * bit of power potentially.
9336          *
9337          * We'll limit this to IVB with 3 pipes, since it has only two
9338          * DPLLs and so DPLL sharing is the only way to get three pipes
9339          * driving PCH ports at the same time. On SNB we could do this,
9340          * and potentially avoid enabling the second DPLL, but it's not
9341          * clear if it''s a win or loss power wise. No point in doing
9342          * this on ILK at all since it has a fixed DPLL<->pipe mapping.
9343          */
9344         if (INTEL_INFO(dev_priv)->num_pipes == 3 &&
9345             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG))
9346                 dpll |= DPLL_SDVO_HIGH_SPEED;
9347
9348         /* compute bitmask from p1 value */
9349         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
9350         /* also FPA1 */
9351         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
9352
9353         switch (crtc_state->dpll.p2) {
9354         case 5:
9355                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
9356                 break;
9357         case 7:
9358                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
9359                 break;
9360         case 10:
9361                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
9362                 break;
9363         case 14:
9364                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
9365                 break;
9366         }
9367
9368         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
9369             intel_panel_use_ssc(dev_priv))
9370                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
9371         else
9372                 dpll |= PLL_REF_INPUT_DREFCLK;
9373
9374         dpll |= DPLL_VCO_ENABLE;
9375
9376         crtc_state->dpll_hw_state.dpll = dpll;
9377         crtc_state->dpll_hw_state.fp0 = fp;
9378         crtc_state->dpll_hw_state.fp1 = fp2;
9379 }
9380
9381 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
9382                                        struct intel_crtc_state *crtc_state)
9383 {
9384         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9385         const struct intel_limit *limit;
9386         int refclk = 120000;
9387
9388         memset(&crtc_state->dpll_hw_state, 0,
9389                sizeof(crtc_state->dpll_hw_state));
9390
9391         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
9392         if (!crtc_state->has_pch_encoder)
9393                 return 0;
9394
9395         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
9396                 if (intel_panel_use_ssc(dev_priv)) {
9397                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
9398                                       dev_priv->vbt.lvds_ssc_freq);
9399                         refclk = dev_priv->vbt.lvds_ssc_freq;
9400                 }
9401
9402                 if (intel_is_dual_link_lvds(dev_priv)) {
9403                         if (refclk == 100000)
9404                                 limit = &intel_limits_ironlake_dual_lvds_100m;
9405                         else
9406                                 limit = &intel_limits_ironlake_dual_lvds;
9407                 } else {
9408                         if (refclk == 100000)
9409                                 limit = &intel_limits_ironlake_single_lvds_100m;
9410                         else
9411                                 limit = &intel_limits_ironlake_single_lvds;
9412                 }
9413         } else {
9414                 limit = &intel_limits_ironlake_dac;
9415         }
9416
9417         if (!crtc_state->clock_set &&
9418             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
9419                                 refclk, NULL, &crtc_state->dpll)) {
9420                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
9421                 return -EINVAL;
9422         }
9423
9424         ironlake_compute_dpll(crtc, crtc_state, NULL);
9425
9426         if (!intel_get_shared_dpll(crtc_state, NULL)) {
9427                 DRM_DEBUG_KMS("failed to find PLL for pipe %c\n",
9428                               pipe_name(crtc->pipe));
9429                 return -EINVAL;
9430         }
9431
9432         return 0;
9433 }
9434
9435 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
9436                                          struct intel_link_m_n *m_n)
9437 {
9438         struct drm_device *dev = crtc->base.dev;
9439         struct drm_i915_private *dev_priv = to_i915(dev);
9440         enum pipe pipe = crtc->pipe;
9441
9442         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
9443         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
9444         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
9445                 & ~TU_SIZE_MASK;
9446         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
9447         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
9448                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9449 }
9450
9451 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
9452                                          enum transcoder transcoder,
9453                                          struct intel_link_m_n *m_n,
9454                                          struct intel_link_m_n *m2_n2)
9455 {
9456         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9457         enum pipe pipe = crtc->pipe;
9458
9459         if (INTEL_GEN(dev_priv) >= 5) {
9460                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
9461                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
9462                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
9463                         & ~TU_SIZE_MASK;
9464                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
9465                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
9466                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9467
9468                 if (m2_n2 && transcoder_has_m2_n2(dev_priv, transcoder)) {
9469                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
9470                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
9471                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
9472                                         & ~TU_SIZE_MASK;
9473                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
9474                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
9475                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9476                 }
9477         } else {
9478                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
9479                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
9480                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
9481                         & ~TU_SIZE_MASK;
9482                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
9483                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
9484                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9485         }
9486 }
9487
9488 void intel_dp_get_m_n(struct intel_crtc *crtc,
9489                       struct intel_crtc_state *pipe_config)
9490 {
9491         if (pipe_config->has_pch_encoder)
9492                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
9493         else
9494                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9495                                              &pipe_config->dp_m_n,
9496                                              &pipe_config->dp_m2_n2);
9497 }
9498
9499 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
9500                                         struct intel_crtc_state *pipe_config)
9501 {
9502         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9503                                      &pipe_config->fdi_m_n, NULL);
9504 }
9505
9506 static void skylake_get_pfit_config(struct intel_crtc *crtc,
9507                                     struct intel_crtc_state *pipe_config)
9508 {
9509         struct drm_device *dev = crtc->base.dev;
9510         struct drm_i915_private *dev_priv = to_i915(dev);
9511         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
9512         u32 ps_ctrl = 0;
9513         int id = -1;
9514         int i;
9515
9516         /* find scaler attached to this pipe */
9517         for (i = 0; i < crtc->num_scalers; i++) {
9518                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
9519                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
9520                         id = i;
9521                         pipe_config->pch_pfit.enabled = true;
9522                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
9523                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
9524                         scaler_state->scalers[i].in_use = true;
9525                         break;
9526                 }
9527         }
9528
9529         scaler_state->scaler_id = id;
9530         if (id >= 0) {
9531                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
9532         } else {
9533                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
9534         }
9535 }
9536
9537 static void
9538 skylake_get_initial_plane_config(struct intel_crtc *crtc,
9539                                  struct intel_initial_plane_config *plane_config)
9540 {
9541         struct drm_device *dev = crtc->base.dev;
9542         struct drm_i915_private *dev_priv = to_i915(dev);
9543         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
9544         enum plane_id plane_id = plane->id;
9545         enum pipe pipe;
9546         u32 val, base, offset, stride_mult, tiling, alpha;
9547         int fourcc, pixel_format;
9548         unsigned int aligned_height;
9549         struct drm_framebuffer *fb;
9550         struct intel_framebuffer *intel_fb;
9551
9552         if (!plane->get_hw_state(plane, &pipe))
9553                 return;
9554
9555         WARN_ON(pipe != crtc->pipe);
9556
9557         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9558         if (!intel_fb) {
9559                 DRM_DEBUG_KMS("failed to alloc fb\n");
9560                 return;
9561         }
9562
9563         fb = &intel_fb->base;
9564
9565         fb->dev = dev;
9566
9567         val = I915_READ(PLANE_CTL(pipe, plane_id));
9568
9569         if (INTEL_GEN(dev_priv) >= 11)
9570                 pixel_format = val & ICL_PLANE_CTL_FORMAT_MASK;
9571         else
9572                 pixel_format = val & PLANE_CTL_FORMAT_MASK;
9573
9574         if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv)) {
9575                 alpha = I915_READ(PLANE_COLOR_CTL(pipe, plane_id));
9576                 alpha &= PLANE_COLOR_ALPHA_MASK;
9577         } else {
9578                 alpha = val & PLANE_CTL_ALPHA_MASK;
9579         }
9580
9581         fourcc = skl_format_to_fourcc(pixel_format,
9582                                       val & PLANE_CTL_ORDER_RGBX, alpha);
9583         fb->format = drm_format_info(fourcc);
9584
9585         tiling = val & PLANE_CTL_TILED_MASK;
9586         switch (tiling) {
9587         case PLANE_CTL_TILED_LINEAR:
9588                 fb->modifier = DRM_FORMAT_MOD_LINEAR;
9589                 break;
9590         case PLANE_CTL_TILED_X:
9591                 plane_config->tiling = I915_TILING_X;
9592                 fb->modifier = I915_FORMAT_MOD_X_TILED;
9593                 break;
9594         case PLANE_CTL_TILED_Y:
9595                 plane_config->tiling = I915_TILING_Y;
9596                 if (val & PLANE_CTL_RENDER_DECOMPRESSION_ENABLE)
9597                         fb->modifier = I915_FORMAT_MOD_Y_TILED_CCS;
9598                 else
9599                         fb->modifier = I915_FORMAT_MOD_Y_TILED;
9600                 break;
9601         case PLANE_CTL_TILED_YF:
9602                 if (val & PLANE_CTL_RENDER_DECOMPRESSION_ENABLE)
9603                         fb->modifier = I915_FORMAT_MOD_Yf_TILED_CCS;
9604                 else
9605                         fb->modifier = I915_FORMAT_MOD_Yf_TILED;
9606                 break;
9607         default:
9608                 MISSING_CASE(tiling);
9609                 goto error;
9610         }
9611
9612         /*
9613          * DRM_MODE_ROTATE_ is counter clockwise to stay compatible with Xrandr
9614          * while i915 HW rotation is clockwise, thats why this swapping.
9615          */
9616         switch (val & PLANE_CTL_ROTATE_MASK) {
9617         case PLANE_CTL_ROTATE_0:
9618                 plane_config->rotation = DRM_MODE_ROTATE_0;
9619                 break;
9620         case PLANE_CTL_ROTATE_90:
9621                 plane_config->rotation = DRM_MODE_ROTATE_270;
9622                 break;
9623         case PLANE_CTL_ROTATE_180:
9624                 plane_config->rotation = DRM_MODE_ROTATE_180;
9625                 break;
9626         case PLANE_CTL_ROTATE_270:
9627                 plane_config->rotation = DRM_MODE_ROTATE_90;
9628                 break;
9629         }
9630
9631         if (INTEL_GEN(dev_priv) >= 10 &&
9632             val & PLANE_CTL_FLIP_HORIZONTAL)
9633                 plane_config->rotation |= DRM_MODE_REFLECT_X;
9634
9635         base = I915_READ(PLANE_SURF(pipe, plane_id)) & 0xfffff000;
9636         plane_config->base = base;
9637
9638         offset = I915_READ(PLANE_OFFSET(pipe, plane_id));
9639
9640         val = I915_READ(PLANE_SIZE(pipe, plane_id));
9641         fb->height = ((val >> 16) & 0xfff) + 1;
9642         fb->width = ((val >> 0) & 0x1fff) + 1;
9643
9644         val = I915_READ(PLANE_STRIDE(pipe, plane_id));
9645         stride_mult = skl_plane_stride_mult(fb, 0, DRM_MODE_ROTATE_0);
9646         fb->pitches[0] = (val & 0x3ff) * stride_mult;
9647
9648         aligned_height = intel_fb_align_height(fb, 0, fb->height);
9649
9650         plane_config->size = fb->pitches[0] * aligned_height;
9651
9652         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9653                       crtc->base.name, plane->base.name, fb->width, fb->height,
9654                       fb->format->cpp[0] * 8, base, fb->pitches[0],
9655                       plane_config->size);
9656
9657         plane_config->fb = intel_fb;
9658         return;
9659
9660 error:
9661         kfree(intel_fb);
9662 }
9663
9664 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
9665                                      struct intel_crtc_state *pipe_config)
9666 {
9667         struct drm_device *dev = crtc->base.dev;
9668         struct drm_i915_private *dev_priv = to_i915(dev);
9669         u32 tmp;
9670
9671         tmp = I915_READ(PF_CTL(crtc->pipe));
9672
9673         if (tmp & PF_ENABLE) {
9674                 pipe_config->pch_pfit.enabled = true;
9675                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
9676                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
9677
9678                 /* We currently do not free assignements of panel fitters on
9679                  * ivb/hsw (since we don't use the higher upscaling modes which
9680                  * differentiates them) so just WARN about this case for now. */
9681                 if (IS_GEN(dev_priv, 7)) {
9682                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
9683                                 PF_PIPE_SEL_IVB(crtc->pipe));
9684                 }
9685         }
9686 }
9687
9688 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
9689                                      struct intel_crtc_state *pipe_config)
9690 {
9691         struct drm_device *dev = crtc->base.dev;
9692         struct drm_i915_private *dev_priv = to_i915(dev);
9693         enum intel_display_power_domain power_domain;
9694         intel_wakeref_t wakeref;
9695         u32 tmp;
9696         bool ret;
9697
9698         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9699         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
9700         if (!wakeref)
9701                 return false;
9702
9703         pipe_config->output_format = INTEL_OUTPUT_FORMAT_RGB;
9704         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9705         pipe_config->shared_dpll = NULL;
9706
9707         ret = false;
9708         tmp = I915_READ(PIPECONF(crtc->pipe));
9709         if (!(tmp & PIPECONF_ENABLE))
9710                 goto out;
9711
9712         switch (tmp & PIPECONF_BPC_MASK) {
9713         case PIPECONF_6BPC:
9714                 pipe_config->pipe_bpp = 18;
9715                 break;
9716         case PIPECONF_8BPC:
9717                 pipe_config->pipe_bpp = 24;
9718                 break;
9719         case PIPECONF_10BPC:
9720                 pipe_config->pipe_bpp = 30;
9721                 break;
9722         case PIPECONF_12BPC:
9723                 pipe_config->pipe_bpp = 36;
9724                 break;
9725         default:
9726                 break;
9727         }
9728
9729         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
9730                 pipe_config->limited_color_range = true;
9731
9732         pipe_config->gamma_mode = (tmp & PIPECONF_GAMMA_MODE_MASK_ILK) >>
9733                 PIPECONF_GAMMA_MODE_SHIFT;
9734
9735         pipe_config->csc_mode = I915_READ(PIPE_CSC_MODE(crtc->pipe));
9736
9737         i9xx_get_pipe_color_config(pipe_config);
9738
9739         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
9740                 struct intel_shared_dpll *pll;
9741                 enum intel_dpll_id pll_id;
9742
9743                 pipe_config->has_pch_encoder = true;
9744
9745                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
9746                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9747                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9748
9749                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9750
9751                 if (HAS_PCH_IBX(dev_priv)) {
9752                         /*
9753                          * The pipe->pch transcoder and pch transcoder->pll
9754                          * mapping is fixed.
9755                          */
9756                         pll_id = (enum intel_dpll_id) crtc->pipe;
9757                 } else {
9758                         tmp = I915_READ(PCH_DPLL_SEL);
9759                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
9760                                 pll_id = DPLL_ID_PCH_PLL_B;
9761                         else
9762                                 pll_id= DPLL_ID_PCH_PLL_A;
9763                 }
9764
9765                 pipe_config->shared_dpll =
9766                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
9767                 pll = pipe_config->shared_dpll;
9768
9769                 WARN_ON(!pll->info->funcs->get_hw_state(dev_priv, pll,
9770                                                 &pipe_config->dpll_hw_state));
9771
9772                 tmp = pipe_config->dpll_hw_state.dpll;
9773                 pipe_config->pixel_multiplier =
9774                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
9775                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
9776
9777                 ironlake_pch_clock_get(crtc, pipe_config);
9778         } else {
9779                 pipe_config->pixel_multiplier = 1;
9780         }
9781
9782         intel_get_pipe_timings(crtc, pipe_config);
9783         intel_get_pipe_src_size(crtc, pipe_config);
9784
9785         ironlake_get_pfit_config(crtc, pipe_config);
9786
9787         ret = true;
9788
9789 out:
9790         intel_display_power_put(dev_priv, power_domain, wakeref);
9791
9792         return ret;
9793 }
9794 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9795                                       struct intel_crtc_state *crtc_state)
9796 {
9797         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9798         struct intel_atomic_state *state =
9799                 to_intel_atomic_state(crtc_state->base.state);
9800
9801         if (!intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DSI) ||
9802             INTEL_GEN(dev_priv) >= 11) {
9803                 struct intel_encoder *encoder =
9804                         intel_get_crtc_new_encoder(state, crtc_state);
9805
9806                 if (!intel_get_shared_dpll(crtc_state, encoder)) {
9807                         DRM_DEBUG_KMS("failed to find PLL for pipe %c\n",
9808                                       pipe_name(crtc->pipe));
9809                         return -EINVAL;
9810                 }
9811         }
9812
9813         return 0;
9814 }
9815
9816 static void cannonlake_get_ddi_pll(struct drm_i915_private *dev_priv,
9817                                    enum port port,
9818                                    struct intel_crtc_state *pipe_config)
9819 {
9820         enum intel_dpll_id id;
9821         u32 temp;
9822
9823         temp = I915_READ(DPCLKA_CFGCR0) & DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
9824         id = temp >> DPCLKA_CFGCR0_DDI_CLK_SEL_SHIFT(port);
9825
9826         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL2))
9827                 return;
9828
9829         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9830 }
9831
9832 static void icelake_get_ddi_pll(struct drm_i915_private *dev_priv,
9833                                 enum port port,
9834                                 struct intel_crtc_state *pipe_config)
9835 {
9836         enum intel_dpll_id id;
9837         u32 temp;
9838
9839         /* TODO: TBT pll not implemented. */
9840         if (intel_port_is_combophy(dev_priv, port)) {
9841                 temp = I915_READ(DPCLKA_CFGCR0_ICL) &
9842                        DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
9843                 id = temp >> DPCLKA_CFGCR0_DDI_CLK_SEL_SHIFT(port);
9844         } else if (intel_port_is_tc(dev_priv, port)) {
9845                 id = icl_tc_port_to_pll_id(intel_port_to_tc(dev_priv, port));
9846         } else {
9847                 WARN(1, "Invalid port %x\n", port);
9848                 return;
9849         }
9850
9851         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9852 }
9853
9854 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9855                                 enum port port,
9856                                 struct intel_crtc_state *pipe_config)
9857 {
9858         enum intel_dpll_id id;
9859
9860         switch (port) {
9861         case PORT_A:
9862                 id = DPLL_ID_SKL_DPLL0;
9863                 break;
9864         case PORT_B:
9865                 id = DPLL_ID_SKL_DPLL1;
9866                 break;
9867         case PORT_C:
9868                 id = DPLL_ID_SKL_DPLL2;
9869                 break;
9870         default:
9871                 DRM_ERROR("Incorrect port type\n");
9872                 return;
9873         }
9874
9875         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9876 }
9877
9878 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9879                                 enum port port,
9880                                 struct intel_crtc_state *pipe_config)
9881 {
9882         enum intel_dpll_id id;
9883         u32 temp;
9884
9885         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9886         id = temp >> (port * 3 + 1);
9887
9888         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL3))
9889                 return;
9890
9891         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9892 }
9893
9894 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9895                                 enum port port,
9896                                 struct intel_crtc_state *pipe_config)
9897 {
9898         enum intel_dpll_id id;
9899         u32 ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9900
9901         switch (ddi_pll_sel) {
9902         case PORT_CLK_SEL_WRPLL1:
9903                 id = DPLL_ID_WRPLL1;
9904                 break;
9905         case PORT_CLK_SEL_WRPLL2:
9906                 id = DPLL_ID_WRPLL2;
9907                 break;
9908         case PORT_CLK_SEL_SPLL:
9909                 id = DPLL_ID_SPLL;
9910                 break;
9911         case PORT_CLK_SEL_LCPLL_810:
9912                 id = DPLL_ID_LCPLL_810;
9913                 break;
9914         case PORT_CLK_SEL_LCPLL_1350:
9915                 id = DPLL_ID_LCPLL_1350;
9916                 break;
9917         case PORT_CLK_SEL_LCPLL_2700:
9918                 id = DPLL_ID_LCPLL_2700;
9919                 break;
9920         default:
9921                 MISSING_CASE(ddi_pll_sel);
9922                 /* fall through */
9923         case PORT_CLK_SEL_NONE:
9924                 return;
9925         }
9926
9927         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9928 }
9929
9930 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
9931                                      struct intel_crtc_state *pipe_config,
9932                                      u64 *power_domain_mask,
9933                                      intel_wakeref_t *wakerefs)
9934 {
9935         struct drm_device *dev = crtc->base.dev;
9936         struct drm_i915_private *dev_priv = to_i915(dev);
9937         enum intel_display_power_domain power_domain;
9938         unsigned long panel_transcoder_mask = 0;
9939         unsigned long enabled_panel_transcoders = 0;
9940         enum transcoder panel_transcoder;
9941         intel_wakeref_t wf;
9942         u32 tmp;
9943
9944         if (INTEL_GEN(dev_priv) >= 11)
9945                 panel_transcoder_mask |=
9946                         BIT(TRANSCODER_DSI_0) | BIT(TRANSCODER_DSI_1);
9947
9948         if (HAS_TRANSCODER_EDP(dev_priv))
9949                 panel_transcoder_mask |= BIT(TRANSCODER_EDP);
9950
9951         /*
9952          * The pipe->transcoder mapping is fixed with the exception of the eDP
9953          * and DSI transcoders handled below.
9954          */
9955         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9956
9957         /*
9958          * XXX: Do intel_display_power_get_if_enabled before reading this (for
9959          * consistency and less surprising code; it's in always on power).
9960          */
9961         for_each_set_bit(panel_transcoder,
9962                          &panel_transcoder_mask,
9963                          ARRAY_SIZE(INTEL_INFO(dev_priv)->trans_offsets)) {
9964                 bool force_thru = false;
9965                 enum pipe trans_pipe;
9966
9967                 tmp = I915_READ(TRANS_DDI_FUNC_CTL(panel_transcoder));
9968                 if (!(tmp & TRANS_DDI_FUNC_ENABLE))
9969                         continue;
9970
9971                 /*
9972                  * Log all enabled ones, only use the first one.
9973                  *
9974                  * FIXME: This won't work for two separate DSI displays.
9975                  */
9976                 enabled_panel_transcoders |= BIT(panel_transcoder);
9977                 if (enabled_panel_transcoders != BIT(panel_transcoder))
9978                         continue;
9979
9980                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9981                 default:
9982                         WARN(1, "unknown pipe linked to transcoder %s\n",
9983                              transcoder_name(panel_transcoder));
9984                         /* fall through */
9985                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9986                         force_thru = true;
9987                         /* fall through */
9988                 case TRANS_DDI_EDP_INPUT_A_ON:
9989                         trans_pipe = PIPE_A;
9990                         break;
9991                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
9992                         trans_pipe = PIPE_B;
9993                         break;
9994                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
9995                         trans_pipe = PIPE_C;
9996                         break;
9997                 }
9998
9999                 if (trans_pipe == crtc->pipe) {
10000                         pipe_config->cpu_transcoder = panel_transcoder;
10001                         pipe_config->pch_pfit.force_thru = force_thru;
10002                 }
10003         }
10004
10005         /*
10006          * Valid combos: none, eDP, DSI0, DSI1, DSI0+DSI1
10007          */
10008         WARN_ON((enabled_panel_transcoders & BIT(TRANSCODER_EDP)) &&
10009                 enabled_panel_transcoders != BIT(TRANSCODER_EDP));
10010
10011         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
10012         WARN_ON(*power_domain_mask & BIT_ULL(power_domain));
10013
10014         wf = intel_display_power_get_if_enabled(dev_priv, power_domain);
10015         if (!wf)
10016                 return false;
10017
10018         wakerefs[power_domain] = wf;
10019         *power_domain_mask |= BIT_ULL(power_domain);
10020
10021         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
10022
10023         return tmp & PIPECONF_ENABLE;
10024 }
10025
10026 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
10027                                          struct intel_crtc_state *pipe_config,
10028                                          u64 *power_domain_mask,
10029                                          intel_wakeref_t *wakerefs)
10030 {
10031         struct drm_device *dev = crtc->base.dev;
10032         struct drm_i915_private *dev_priv = to_i915(dev);
10033         enum intel_display_power_domain power_domain;
10034         enum transcoder cpu_transcoder;
10035         intel_wakeref_t wf;
10036         enum port port;
10037         u32 tmp;
10038
10039         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
10040                 if (port == PORT_A)
10041                         cpu_transcoder = TRANSCODER_DSI_A;
10042                 else
10043                         cpu_transcoder = TRANSCODER_DSI_C;
10044
10045                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
10046                 WARN_ON(*power_domain_mask & BIT_ULL(power_domain));
10047
10048                 wf = intel_display_power_get_if_enabled(dev_priv, power_domain);
10049                 if (!wf)
10050                         continue;
10051
10052                 wakerefs[power_domain] = wf;
10053                 *power_domain_mask |= BIT_ULL(power_domain);
10054
10055                 /*
10056                  * The PLL needs to be enabled with a valid divider
10057                  * configuration, otherwise accessing DSI registers will hang
10058                  * the machine. See BSpec North Display Engine
10059                  * registers/MIPI[BXT]. We can break out here early, since we
10060                  * need the same DSI PLL to be enabled for both DSI ports.
10061                  */
10062                 if (!bxt_dsi_pll_is_enabled(dev_priv))
10063                         break;
10064
10065                 /* XXX: this works for video mode only */
10066                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
10067                 if (!(tmp & DPI_ENABLE))
10068                         continue;
10069
10070                 tmp = I915_READ(MIPI_CTRL(port));
10071                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
10072                         continue;
10073
10074                 pipe_config->cpu_transcoder = cpu_transcoder;
10075                 break;
10076         }
10077
10078         return transcoder_is_dsi(pipe_config->cpu_transcoder);
10079 }
10080
10081 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
10082                                        struct intel_crtc_state *pipe_config)
10083 {
10084         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10085         struct intel_shared_dpll *pll;
10086         enum port port;
10087         u32 tmp;
10088
10089         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
10090
10091         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
10092
10093         if (INTEL_GEN(dev_priv) >= 11)
10094                 icelake_get_ddi_pll(dev_priv, port, pipe_config);
10095         else if (IS_CANNONLAKE(dev_priv))
10096                 cannonlake_get_ddi_pll(dev_priv, port, pipe_config);
10097         else if (IS_GEN9_BC(dev_priv))
10098                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
10099         else if (IS_GEN9_LP(dev_priv))
10100                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
10101         else
10102                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
10103
10104         pll = pipe_config->shared_dpll;
10105         if (pll) {
10106                 WARN_ON(!pll->info->funcs->get_hw_state(dev_priv, pll,
10107                                                 &pipe_config->dpll_hw_state));
10108         }
10109
10110         /*
10111          * Haswell has only FDI/PCH transcoder A. It is which is connected to
10112          * DDI E. So just check whether this pipe is wired to DDI E and whether
10113          * the PCH transcoder is on.
10114          */
10115         if (INTEL_GEN(dev_priv) < 9 &&
10116             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
10117                 pipe_config->has_pch_encoder = true;
10118
10119                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
10120                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
10121                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
10122
10123                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
10124         }
10125 }
10126
10127 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
10128                                     struct intel_crtc_state *pipe_config)
10129 {
10130         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10131         intel_wakeref_t wakerefs[POWER_DOMAIN_NUM], wf;
10132         enum intel_display_power_domain power_domain;
10133         u64 power_domain_mask;
10134         bool active;
10135
10136         intel_crtc_init_scalers(crtc, pipe_config);
10137
10138         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
10139         wf = intel_display_power_get_if_enabled(dev_priv, power_domain);
10140         if (!wf)
10141                 return false;
10142
10143         wakerefs[power_domain] = wf;
10144         power_domain_mask = BIT_ULL(power_domain);
10145
10146         pipe_config->shared_dpll = NULL;
10147
10148         active = hsw_get_transcoder_state(crtc, pipe_config,
10149                                           &power_domain_mask, wakerefs);
10150
10151         if (IS_GEN9_LP(dev_priv) &&
10152             bxt_get_dsi_transcoder_state(crtc, pipe_config,
10153                                          &power_domain_mask, wakerefs)) {
10154                 WARN_ON(active);
10155                 active = true;
10156         }
10157
10158         if (!active)
10159                 goto out;
10160
10161         if (!transcoder_is_dsi(pipe_config->cpu_transcoder) ||
10162             INTEL_GEN(dev_priv) >= 11) {
10163                 haswell_get_ddi_port_state(crtc, pipe_config);
10164                 intel_get_pipe_timings(crtc, pipe_config);
10165         }
10166
10167         intel_get_pipe_src_size(crtc, pipe_config);
10168         intel_get_crtc_ycbcr_config(crtc, pipe_config);
10169
10170         pipe_config->gamma_mode = I915_READ(GAMMA_MODE(crtc->pipe));
10171
10172         pipe_config->csc_mode = I915_READ(PIPE_CSC_MODE(crtc->pipe));
10173
10174         if (INTEL_GEN(dev_priv) >= 9) {
10175                 u32 tmp = I915_READ(SKL_BOTTOM_COLOR(crtc->pipe));
10176
10177                 if (tmp & SKL_BOTTOM_COLOR_GAMMA_ENABLE)
10178                         pipe_config->gamma_enable = true;
10179
10180                 if (tmp & SKL_BOTTOM_COLOR_CSC_ENABLE)
10181                         pipe_config->csc_enable = true;
10182         } else {
10183                 i9xx_get_pipe_color_config(pipe_config);
10184         }
10185
10186         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
10187         WARN_ON(power_domain_mask & BIT_ULL(power_domain));
10188
10189         wf = intel_display_power_get_if_enabled(dev_priv, power_domain);
10190         if (wf) {
10191                 wakerefs[power_domain] = wf;
10192                 power_domain_mask |= BIT_ULL(power_domain);
10193
10194                 if (INTEL_GEN(dev_priv) >= 9)
10195                         skylake_get_pfit_config(crtc, pipe_config);
10196                 else
10197                         ironlake_get_pfit_config(crtc, pipe_config);
10198         }
10199
10200         if (hsw_crtc_supports_ips(crtc)) {
10201                 if (IS_HASWELL(dev_priv))
10202                         pipe_config->ips_enabled = I915_READ(IPS_CTL) & IPS_ENABLE;
10203                 else {
10204                         /*
10205                          * We cannot readout IPS state on broadwell, set to
10206                          * true so we can set it to a defined state on first
10207                          * commit.
10208                          */
10209                         pipe_config->ips_enabled = true;
10210                 }
10211         }
10212
10213         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
10214             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
10215                 pipe_config->pixel_multiplier =
10216                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
10217         } else {
10218                 pipe_config->pixel_multiplier = 1;
10219         }
10220
10221 out:
10222         for_each_power_domain(power_domain, power_domain_mask)
10223                 intel_display_power_put(dev_priv,
10224                                         power_domain, wakerefs[power_domain]);
10225
10226         return active;
10227 }
10228
10229 static u32 intel_cursor_base(const struct intel_plane_state *plane_state)
10230 {
10231         struct drm_i915_private *dev_priv =
10232                 to_i915(plane_state->base.plane->dev);
10233         const struct drm_framebuffer *fb = plane_state->base.fb;
10234         const struct drm_i915_gem_object *obj = intel_fb_obj(fb);
10235         u32 base;
10236
10237         if (INTEL_INFO(dev_priv)->display.cursor_needs_physical)
10238                 base = obj->phys_handle->busaddr;
10239         else
10240                 base = intel_plane_ggtt_offset(plane_state);
10241
10242         base += plane_state->color_plane[0].offset;
10243
10244         /* ILK+ do this automagically */
10245         if (HAS_GMCH(dev_priv) &&
10246             plane_state->base.rotation & DRM_MODE_ROTATE_180)
10247                 base += (plane_state->base.crtc_h *
10248                          plane_state->base.crtc_w - 1) * fb->format->cpp[0];
10249
10250         return base;
10251 }
10252
10253 static u32 intel_cursor_position(const struct intel_plane_state *plane_state)
10254 {
10255         int x = plane_state->base.crtc_x;
10256         int y = plane_state->base.crtc_y;
10257         u32 pos = 0;
10258
10259         if (x < 0) {
10260                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
10261                 x = -x;
10262         }
10263         pos |= x << CURSOR_X_SHIFT;
10264
10265         if (y < 0) {
10266                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
10267                 y = -y;
10268         }
10269         pos |= y << CURSOR_Y_SHIFT;
10270
10271         return pos;
10272 }
10273
10274 static bool intel_cursor_size_ok(const struct intel_plane_state *plane_state)
10275 {
10276         const struct drm_mode_config *config =
10277                 &plane_state->base.plane->dev->mode_config;
10278         int width = plane_state->base.crtc_w;
10279         int height = plane_state->base.crtc_h;
10280
10281         return width > 0 && width <= config->cursor_width &&
10282                 height > 0 && height <= config->cursor_height;
10283 }
10284
10285 static int intel_cursor_check_surface(struct intel_plane_state *plane_state)
10286 {
10287         int src_x, src_y;
10288         u32 offset;
10289         int ret;
10290
10291         ret = intel_plane_compute_gtt(plane_state);
10292         if (ret)
10293                 return ret;
10294
10295         if (!plane_state->base.visible)
10296                 return 0;
10297
10298         src_x = plane_state->base.src_x >> 16;
10299         src_y = plane_state->base.src_y >> 16;
10300
10301         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
10302         offset = intel_plane_compute_aligned_offset(&src_x, &src_y,
10303                                                     plane_state, 0);
10304
10305         if (src_x != 0 || src_y != 0) {
10306                 DRM_DEBUG_KMS("Arbitrary cursor panning not supported\n");
10307                 return -EINVAL;
10308         }
10309
10310         plane_state->color_plane[0].offset = offset;
10311
10312         return 0;
10313 }
10314
10315 static int intel_check_cursor(struct intel_crtc_state *crtc_state,
10316                               struct intel_plane_state *plane_state)
10317 {
10318         const struct drm_framebuffer *fb = plane_state->base.fb;
10319         int ret;
10320
10321         if (fb && fb->modifier != DRM_FORMAT_MOD_LINEAR) {
10322                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
10323                 return -EINVAL;
10324         }
10325
10326         ret = drm_atomic_helper_check_plane_state(&plane_state->base,
10327                                                   &crtc_state->base,
10328                                                   DRM_PLANE_HELPER_NO_SCALING,
10329                                                   DRM_PLANE_HELPER_NO_SCALING,
10330                                                   true, true);
10331         if (ret)
10332                 return ret;
10333
10334         ret = intel_cursor_check_surface(plane_state);
10335         if (ret)
10336                 return ret;
10337
10338         if (!plane_state->base.visible)
10339                 return 0;
10340
10341         ret = intel_plane_check_src_coordinates(plane_state);
10342         if (ret)
10343                 return ret;
10344
10345         return 0;
10346 }
10347
10348 static unsigned int
10349 i845_cursor_max_stride(struct intel_plane *plane,
10350                        u32 pixel_format, u64 modifier,
10351                        unsigned int rotation)
10352 {
10353         return 2048;
10354 }
10355
10356 static u32 i845_cursor_ctl_crtc(const struct intel_crtc_state *crtc_state)
10357 {
10358         u32 cntl = 0;
10359
10360         if (crtc_state->gamma_enable)
10361                 cntl |= CURSOR_GAMMA_ENABLE;
10362
10363         return cntl;
10364 }
10365
10366 static u32 i845_cursor_ctl(const struct intel_crtc_state *crtc_state,
10367                            const struct intel_plane_state *plane_state)
10368 {
10369         return CURSOR_ENABLE |
10370                 CURSOR_FORMAT_ARGB |
10371                 CURSOR_STRIDE(plane_state->color_plane[0].stride);
10372 }
10373
10374 static bool i845_cursor_size_ok(const struct intel_plane_state *plane_state)
10375 {
10376         int width = plane_state->base.crtc_w;
10377
10378         /*
10379          * 845g/865g are only limited by the width of their cursors,
10380          * the height is arbitrary up to the precision of the register.
10381          */
10382         return intel_cursor_size_ok(plane_state) && IS_ALIGNED(width, 64);
10383 }
10384
10385 static int i845_check_cursor(struct intel_crtc_state *crtc_state,
10386                              struct intel_plane_state *plane_state)
10387 {
10388         const struct drm_framebuffer *fb = plane_state->base.fb;
10389         int ret;
10390
10391         ret = intel_check_cursor(crtc_state, plane_state);
10392         if (ret)
10393                 return ret;
10394
10395         /* if we want to turn off the cursor ignore width and height */
10396         if (!fb)
10397                 return 0;
10398
10399         /* Check for which cursor types we support */
10400         if (!i845_cursor_size_ok(plane_state)) {
10401                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
10402                           plane_state->base.crtc_w,
10403                           plane_state->base.crtc_h);
10404                 return -EINVAL;
10405         }
10406
10407         WARN_ON(plane_state->base.visible &&
10408                 plane_state->color_plane[0].stride != fb->pitches[0]);
10409
10410         switch (fb->pitches[0]) {
10411         case 256:
10412         case 512:
10413         case 1024:
10414         case 2048:
10415                 break;
10416         default:
10417                 DRM_DEBUG_KMS("Invalid cursor stride (%u)\n",
10418                               fb->pitches[0]);
10419                 return -EINVAL;
10420         }
10421
10422         plane_state->ctl = i845_cursor_ctl(crtc_state, plane_state);
10423
10424         return 0;
10425 }
10426
10427 static void i845_update_cursor(struct intel_plane *plane,
10428                                const struct intel_crtc_state *crtc_state,
10429                                const struct intel_plane_state *plane_state)
10430 {
10431         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10432         u32 cntl = 0, base = 0, pos = 0, size = 0;
10433         unsigned long irqflags;
10434
10435         if (plane_state && plane_state->base.visible) {
10436                 unsigned int width = plane_state->base.crtc_w;
10437                 unsigned int height = plane_state->base.crtc_h;
10438
10439                 cntl = plane_state->ctl |
10440                         i845_cursor_ctl_crtc(crtc_state);
10441
10442                 size = (height << 12) | width;
10443
10444                 base = intel_cursor_base(plane_state);
10445                 pos = intel_cursor_position(plane_state);
10446         }
10447
10448         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
10449
10450         /* On these chipsets we can only modify the base/size/stride
10451          * whilst the cursor is disabled.
10452          */
10453         if (plane->cursor.base != base ||
10454             plane->cursor.size != size ||
10455             plane->cursor.cntl != cntl) {
10456                 I915_WRITE_FW(CURCNTR(PIPE_A), 0);
10457                 I915_WRITE_FW(CURBASE(PIPE_A), base);
10458                 I915_WRITE_FW(CURSIZE, size);
10459                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
10460                 I915_WRITE_FW(CURCNTR(PIPE_A), cntl);
10461
10462                 plane->cursor.base = base;
10463                 plane->cursor.size = size;
10464                 plane->cursor.cntl = cntl;
10465         } else {
10466                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
10467         }
10468
10469         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
10470 }
10471
10472 static void i845_disable_cursor(struct intel_plane *plane,
10473                                 const struct intel_crtc_state *crtc_state)
10474 {
10475         i845_update_cursor(plane, crtc_state, NULL);
10476 }
10477
10478 static bool i845_cursor_get_hw_state(struct intel_plane *plane,
10479                                      enum pipe *pipe)
10480 {
10481         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10482         enum intel_display_power_domain power_domain;
10483         intel_wakeref_t wakeref;
10484         bool ret;
10485
10486         power_domain = POWER_DOMAIN_PIPE(PIPE_A);
10487         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
10488         if (!wakeref)
10489                 return false;
10490
10491         ret = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
10492
10493         *pipe = PIPE_A;
10494
10495         intel_display_power_put(dev_priv, power_domain, wakeref);
10496
10497         return ret;
10498 }
10499
10500 static unsigned int
10501 i9xx_cursor_max_stride(struct intel_plane *plane,
10502                        u32 pixel_format, u64 modifier,
10503                        unsigned int rotation)
10504 {
10505         return plane->base.dev->mode_config.cursor_width * 4;
10506 }
10507
10508 static u32 i9xx_cursor_ctl_crtc(const struct intel_crtc_state *crtc_state)
10509 {
10510         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
10511         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10512         u32 cntl = 0;
10513
10514         if (INTEL_GEN(dev_priv) >= 11)
10515                 return cntl;
10516
10517         if (crtc_state->gamma_enable)
10518                 cntl = MCURSOR_GAMMA_ENABLE;
10519
10520         if (crtc_state->csc_enable)
10521                 cntl |= MCURSOR_PIPE_CSC_ENABLE;
10522
10523         if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10524                 cntl |= MCURSOR_PIPE_SELECT(crtc->pipe);
10525
10526         return cntl;
10527 }
10528
10529 static u32 i9xx_cursor_ctl(const struct intel_crtc_state *crtc_state,
10530                            const struct intel_plane_state *plane_state)
10531 {
10532         struct drm_i915_private *dev_priv =
10533                 to_i915(plane_state->base.plane->dev);
10534         u32 cntl = 0;
10535
10536         if (IS_GEN(dev_priv, 6) || IS_IVYBRIDGE(dev_priv))
10537                 cntl |= MCURSOR_TRICKLE_FEED_DISABLE;
10538
10539         switch (plane_state->base.crtc_w) {
10540         case 64:
10541                 cntl |= MCURSOR_MODE_64_ARGB_AX;
10542                 break;
10543         case 128:
10544                 cntl |= MCURSOR_MODE_128_ARGB_AX;
10545                 break;
10546         case 256:
10547                 cntl |= MCURSOR_MODE_256_ARGB_AX;
10548                 break;
10549         default:
10550                 MISSING_CASE(plane_state->base.crtc_w);
10551                 return 0;
10552         }
10553
10554         if (plane_state->base.rotation & DRM_MODE_ROTATE_180)
10555                 cntl |= MCURSOR_ROTATE_180;
10556
10557         return cntl;
10558 }
10559
10560 static bool i9xx_cursor_size_ok(const struct intel_plane_state *plane_state)
10561 {
10562         struct drm_i915_private *dev_priv =
10563                 to_i915(plane_state->base.plane->dev);
10564         int width = plane_state->base.crtc_w;
10565         int height = plane_state->base.crtc_h;
10566
10567         if (!intel_cursor_size_ok(plane_state))
10568                 return false;
10569
10570         /* Cursor width is limited to a few power-of-two sizes */
10571         switch (width) {
10572         case 256:
10573         case 128:
10574         case 64:
10575                 break;
10576         default:
10577                 return false;
10578         }
10579
10580         /*
10581          * IVB+ have CUR_FBC_CTL which allows an arbitrary cursor
10582          * height from 8 lines up to the cursor width, when the
10583          * cursor is not rotated. Everything else requires square
10584          * cursors.
10585          */
10586         if (HAS_CUR_FBC(dev_priv) &&
10587             plane_state->base.rotation & DRM_MODE_ROTATE_0) {
10588                 if (height < 8 || height > width)
10589                         return false;
10590         } else {
10591                 if (height != width)
10592                         return false;
10593         }
10594
10595         return true;
10596 }
10597
10598 static int i9xx_check_cursor(struct intel_crtc_state *crtc_state,
10599                              struct intel_plane_state *plane_state)
10600 {
10601         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
10602         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10603         const struct drm_framebuffer *fb = plane_state->base.fb;
10604         enum pipe pipe = plane->pipe;
10605         int ret;
10606
10607         ret = intel_check_cursor(crtc_state, plane_state);
10608         if (ret)
10609                 return ret;
10610
10611         /* if we want to turn off the cursor ignore width and height */
10612         if (!fb)
10613                 return 0;
10614
10615         /* Check for which cursor types we support */
10616         if (!i9xx_cursor_size_ok(plane_state)) {
10617                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
10618                           plane_state->base.crtc_w,
10619                           plane_state->base.crtc_h);
10620                 return -EINVAL;
10621         }
10622
10623         WARN_ON(plane_state->base.visible &&
10624                 plane_state->color_plane[0].stride != fb->pitches[0]);
10625
10626         if (fb->pitches[0] != plane_state->base.crtc_w * fb->format->cpp[0]) {
10627                 DRM_DEBUG_KMS("Invalid cursor stride (%u) (cursor width %d)\n",
10628                               fb->pitches[0], plane_state->base.crtc_w);
10629                 return -EINVAL;
10630         }
10631
10632         /*
10633          * There's something wrong with the cursor on CHV pipe C.
10634          * If it straddles the left edge of the screen then
10635          * moving it away from the edge or disabling it often
10636          * results in a pipe underrun, and often that can lead to
10637          * dead pipe (constant underrun reported, and it scans
10638          * out just a solid color). To recover from that, the
10639          * display power well must be turned off and on again.
10640          * Refuse the put the cursor into that compromised position.
10641          */
10642         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_C &&
10643             plane_state->base.visible && plane_state->base.crtc_x < 0) {
10644                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
10645                 return -EINVAL;
10646         }
10647
10648         plane_state->ctl = i9xx_cursor_ctl(crtc_state, plane_state);
10649
10650         return 0;
10651 }
10652
10653 static void i9xx_update_cursor(struct intel_plane *plane,
10654                                const struct intel_crtc_state *crtc_state,
10655                                const struct intel_plane_state *plane_state)
10656 {
10657         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10658         enum pipe pipe = plane->pipe;
10659         u32 cntl = 0, base = 0, pos = 0, fbc_ctl = 0;
10660         unsigned long irqflags;
10661
10662         if (plane_state && plane_state->base.visible) {
10663                 cntl = plane_state->ctl |
10664                         i9xx_cursor_ctl_crtc(crtc_state);
10665
10666                 if (plane_state->base.crtc_h != plane_state->base.crtc_w)
10667                         fbc_ctl = CUR_FBC_CTL_EN | (plane_state->base.crtc_h - 1);
10668
10669                 base = intel_cursor_base(plane_state);
10670                 pos = intel_cursor_position(plane_state);
10671         }
10672
10673         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
10674
10675         /*
10676          * On some platforms writing CURCNTR first will also
10677          * cause CURPOS to be armed by the CURBASE write.
10678          * Without the CURCNTR write the CURPOS write would
10679          * arm itself. Thus we always update CURCNTR before
10680          * CURPOS.
10681          *
10682          * On other platforms CURPOS always requires the
10683          * CURBASE write to arm the update. Additonally
10684          * a write to any of the cursor register will cancel
10685          * an already armed cursor update. Thus leaving out
10686          * the CURBASE write after CURPOS could lead to a
10687          * cursor that doesn't appear to move, or even change
10688          * shape. Thus we always write CURBASE.
10689          *
10690          * The other registers are armed by by the CURBASE write
10691          * except when the plane is getting enabled at which time
10692          * the CURCNTR write arms the update.
10693          */
10694
10695         if (INTEL_GEN(dev_priv) >= 9)
10696                 skl_write_cursor_wm(plane, crtc_state);
10697
10698         if (plane->cursor.base != base ||
10699             plane->cursor.size != fbc_ctl ||
10700             plane->cursor.cntl != cntl) {
10701                 if (HAS_CUR_FBC(dev_priv))
10702                         I915_WRITE_FW(CUR_FBC_CTL(pipe), fbc_ctl);
10703                 I915_WRITE_FW(CURCNTR(pipe), cntl);
10704                 I915_WRITE_FW(CURPOS(pipe), pos);
10705                 I915_WRITE_FW(CURBASE(pipe), base);
10706
10707                 plane->cursor.base = base;
10708                 plane->cursor.size = fbc_ctl;
10709                 plane->cursor.cntl = cntl;
10710         } else {
10711                 I915_WRITE_FW(CURPOS(pipe), pos);
10712                 I915_WRITE_FW(CURBASE(pipe), base);
10713         }
10714
10715         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
10716 }
10717
10718 static void i9xx_disable_cursor(struct intel_plane *plane,
10719                                 const struct intel_crtc_state *crtc_state)
10720 {
10721         i9xx_update_cursor(plane, crtc_state, NULL);
10722 }
10723
10724 static bool i9xx_cursor_get_hw_state(struct intel_plane *plane,
10725                                      enum pipe *pipe)
10726 {
10727         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10728         enum intel_display_power_domain power_domain;
10729         intel_wakeref_t wakeref;
10730         bool ret;
10731         u32 val;
10732
10733         /*
10734          * Not 100% correct for planes that can move between pipes,
10735          * but that's only the case for gen2-3 which don't have any
10736          * display power wells.
10737          */
10738         power_domain = POWER_DOMAIN_PIPE(plane->pipe);
10739         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
10740         if (!wakeref)
10741                 return false;
10742
10743         val = I915_READ(CURCNTR(plane->pipe));
10744
10745         ret = val & MCURSOR_MODE;
10746
10747         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
10748                 *pipe = plane->pipe;
10749         else
10750                 *pipe = (val & MCURSOR_PIPE_SELECT_MASK) >>
10751                         MCURSOR_PIPE_SELECT_SHIFT;
10752
10753         intel_display_power_put(dev_priv, power_domain, wakeref);
10754
10755         return ret;
10756 }
10757
10758 /* VESA 640x480x72Hz mode to set on the pipe */
10759 static const struct drm_display_mode load_detect_mode = {
10760         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10761                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10762 };
10763
10764 struct drm_framebuffer *
10765 intel_framebuffer_create(struct drm_i915_gem_object *obj,
10766                          struct drm_mode_fb_cmd2 *mode_cmd)
10767 {
10768         struct intel_framebuffer *intel_fb;
10769         int ret;
10770
10771         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10772         if (!intel_fb)
10773                 return ERR_PTR(-ENOMEM);
10774
10775         ret = intel_framebuffer_init(intel_fb, obj, mode_cmd);
10776         if (ret)
10777                 goto err;
10778
10779         return &intel_fb->base;
10780
10781 err:
10782         kfree(intel_fb);
10783         return ERR_PTR(ret);
10784 }
10785
10786 static int intel_modeset_disable_planes(struct drm_atomic_state *state,
10787                                         struct drm_crtc *crtc)
10788 {
10789         struct drm_plane *plane;
10790         struct drm_plane_state *plane_state;
10791         int ret, i;
10792
10793         ret = drm_atomic_add_affected_planes(state, crtc);
10794         if (ret)
10795                 return ret;
10796
10797         for_each_new_plane_in_state(state, plane, plane_state, i) {
10798                 if (plane_state->crtc != crtc)
10799                         continue;
10800
10801                 ret = drm_atomic_set_crtc_for_plane(plane_state, NULL);
10802                 if (ret)
10803                         return ret;
10804
10805                 drm_atomic_set_fb_for_plane(plane_state, NULL);
10806         }
10807
10808         return 0;
10809 }
10810
10811 int intel_get_load_detect_pipe(struct drm_connector *connector,
10812                                const struct drm_display_mode *mode,
10813                                struct intel_load_detect_pipe *old,
10814                                struct drm_modeset_acquire_ctx *ctx)
10815 {
10816         struct intel_crtc *intel_crtc;
10817         struct intel_encoder *intel_encoder =
10818                 intel_attached_encoder(connector);
10819         struct drm_crtc *possible_crtc;
10820         struct drm_encoder *encoder = &intel_encoder->base;
10821         struct drm_crtc *crtc = NULL;
10822         struct drm_device *dev = encoder->dev;
10823         struct drm_i915_private *dev_priv = to_i915(dev);
10824         struct drm_mode_config *config = &dev->mode_config;
10825         struct drm_atomic_state *state = NULL, *restore_state = NULL;
10826         struct drm_connector_state *connector_state;
10827         struct intel_crtc_state *crtc_state;
10828         int ret, i = -1;
10829
10830         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10831                       connector->base.id, connector->name,
10832                       encoder->base.id, encoder->name);
10833
10834         old->restore_state = NULL;
10835
10836         WARN_ON(!drm_modeset_is_locked(&config->connection_mutex));
10837
10838         /*
10839          * Algorithm gets a little messy:
10840          *
10841          *   - if the connector already has an assigned crtc, use it (but make
10842          *     sure it's on first)
10843          *
10844          *   - try to find the first unused crtc that can drive this connector,
10845          *     and use that if we find one
10846          */
10847
10848         /* See if we already have a CRTC for this connector */
10849         if (connector->state->crtc) {
10850                 crtc = connector->state->crtc;
10851
10852                 ret = drm_modeset_lock(&crtc->mutex, ctx);
10853                 if (ret)
10854                         goto fail;
10855
10856                 /* Make sure the crtc and connector are running */
10857                 goto found;
10858         }
10859
10860         /* Find an unused one (if possible) */
10861         for_each_crtc(dev, possible_crtc) {
10862                 i++;
10863                 if (!(encoder->possible_crtcs & (1 << i)))
10864                         continue;
10865
10866                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
10867                 if (ret)
10868                         goto fail;
10869
10870                 if (possible_crtc->state->enable) {
10871                         drm_modeset_unlock(&possible_crtc->mutex);
10872                         continue;
10873                 }
10874
10875                 crtc = possible_crtc;
10876                 break;
10877         }
10878
10879         /*
10880          * If we didn't find an unused CRTC, don't use any.
10881          */
10882         if (!crtc) {
10883                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
10884                 ret = -ENODEV;
10885                 goto fail;
10886         }
10887
10888 found:
10889         intel_crtc = to_intel_crtc(crtc);
10890
10891         state = drm_atomic_state_alloc(dev);
10892         restore_state = drm_atomic_state_alloc(dev);
10893         if (!state || !restore_state) {
10894                 ret = -ENOMEM;
10895                 goto fail;
10896         }
10897
10898         state->acquire_ctx = ctx;
10899         restore_state->acquire_ctx = ctx;
10900
10901         connector_state = drm_atomic_get_connector_state(state, connector);
10902         if (IS_ERR(connector_state)) {
10903                 ret = PTR_ERR(connector_state);
10904                 goto fail;
10905         }
10906
10907         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
10908         if (ret)
10909                 goto fail;
10910
10911         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10912         if (IS_ERR(crtc_state)) {
10913                 ret = PTR_ERR(crtc_state);
10914                 goto fail;
10915         }
10916
10917         crtc_state->base.active = crtc_state->base.enable = true;
10918
10919         if (!mode)
10920                 mode = &load_detect_mode;
10921
10922         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
10923         if (ret)
10924                 goto fail;
10925
10926         ret = intel_modeset_disable_planes(state, crtc);
10927         if (ret)
10928                 goto fail;
10929
10930         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
10931         if (!ret)
10932                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
10933         if (!ret)
10934                 ret = drm_atomic_add_affected_planes(restore_state, crtc);
10935         if (ret) {
10936                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
10937                 goto fail;
10938         }
10939
10940         ret = drm_atomic_commit(state);
10941         if (ret) {
10942                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
10943                 goto fail;
10944         }
10945
10946         old->restore_state = restore_state;
10947         drm_atomic_state_put(state);
10948
10949         /* let the connector get through one full cycle before testing */
10950         intel_wait_for_vblank(dev_priv, intel_crtc->pipe);
10951         return true;
10952
10953 fail:
10954         if (state) {
10955                 drm_atomic_state_put(state);
10956                 state = NULL;
10957         }
10958         if (restore_state) {
10959                 drm_atomic_state_put(restore_state);
10960                 restore_state = NULL;
10961         }
10962
10963         if (ret == -EDEADLK)
10964                 return ret;
10965
10966         return false;
10967 }
10968
10969 void intel_release_load_detect_pipe(struct drm_connector *connector,
10970                                     struct intel_load_detect_pipe *old,
10971                                     struct drm_modeset_acquire_ctx *ctx)
10972 {
10973         struct intel_encoder *intel_encoder =
10974                 intel_attached_encoder(connector);
10975         struct drm_encoder *encoder = &intel_encoder->base;
10976         struct drm_atomic_state *state = old->restore_state;
10977         int ret;
10978
10979         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10980                       connector->base.id, connector->name,
10981                       encoder->base.id, encoder->name);
10982
10983         if (!state)
10984                 return;
10985
10986         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
10987         if (ret)
10988                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
10989         drm_atomic_state_put(state);
10990 }
10991
10992 static int i9xx_pll_refclk(struct drm_device *dev,
10993                            const struct intel_crtc_state *pipe_config)
10994 {
10995         struct drm_i915_private *dev_priv = to_i915(dev);
10996         u32 dpll = pipe_config->dpll_hw_state.dpll;
10997
10998         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10999                 return dev_priv->vbt.lvds_ssc_freq;
11000         else if (HAS_PCH_SPLIT(dev_priv))
11001                 return 120000;
11002         else if (!IS_GEN(dev_priv, 2))
11003                 return 96000;
11004         else
11005                 return 48000;
11006 }
11007
11008 /* Returns the clock of the currently programmed mode of the given pipe. */
11009 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
11010                                 struct intel_crtc_state *pipe_config)
11011 {
11012         struct drm_device *dev = crtc->base.dev;
11013         struct drm_i915_private *dev_priv = to_i915(dev);
11014         int pipe = pipe_config->cpu_transcoder;
11015         u32 dpll = pipe_config->dpll_hw_state.dpll;
11016         u32 fp;
11017         struct dpll clock;
11018         int port_clock;
11019         int refclk = i9xx_pll_refclk(dev, pipe_config);
11020
11021         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
11022                 fp = pipe_config->dpll_hw_state.fp0;
11023         else
11024                 fp = pipe_config->dpll_hw_state.fp1;
11025
11026         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
11027         if (IS_PINEVIEW(dev_priv)) {
11028                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
11029                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
11030         } else {
11031                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
11032                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
11033         }
11034
11035         if (!IS_GEN(dev_priv, 2)) {
11036                 if (IS_PINEVIEW(dev_priv))
11037                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
11038                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
11039                 else
11040                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
11041                                DPLL_FPA01_P1_POST_DIV_SHIFT);
11042
11043                 switch (dpll & DPLL_MODE_MASK) {
11044                 case DPLLB_MODE_DAC_SERIAL:
11045                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
11046                                 5 : 10;
11047                         break;
11048                 case DPLLB_MODE_LVDS:
11049                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
11050                                 7 : 14;
11051                         break;
11052                 default:
11053                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
11054                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
11055                         return;
11056                 }
11057
11058                 if (IS_PINEVIEW(dev_priv))
11059                         port_clock = pnv_calc_dpll_params(refclk, &clock);
11060                 else
11061                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
11062         } else {
11063                 u32 lvds = IS_I830(dev_priv) ? 0 : I915_READ(LVDS);
11064                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
11065
11066                 if (is_lvds) {
11067                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
11068                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
11069
11070                         if (lvds & LVDS_CLKB_POWER_UP)
11071                                 clock.p2 = 7;
11072                         else
11073                                 clock.p2 = 14;
11074                 } else {
11075                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
11076                                 clock.p1 = 2;
11077                         else {
11078                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
11079                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
11080                         }
11081                         if (dpll & PLL_P2_DIVIDE_BY_4)
11082                                 clock.p2 = 4;
11083                         else
11084                                 clock.p2 = 2;
11085                 }
11086
11087                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
11088         }
11089
11090         /*
11091          * This value includes pixel_multiplier. We will use
11092          * port_clock to compute adjusted_mode.crtc_clock in the
11093          * encoder's get_config() function.
11094          */
11095         pipe_config->port_clock = port_clock;
11096 }
11097
11098 int intel_dotclock_calculate(int link_freq,
11099                              const struct intel_link_m_n *m_n)
11100 {
11101         /*
11102          * The calculation for the data clock is:
11103          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
11104          * But we want to avoid losing precison if possible, so:
11105          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
11106          *
11107          * and the link clock is simpler:
11108          * link_clock = (m * link_clock) / n
11109          */
11110
11111         if (!m_n->link_n)
11112                 return 0;
11113
11114         return div_u64(mul_u32_u32(m_n->link_m, link_freq), m_n->link_n);
11115 }
11116
11117 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
11118                                    struct intel_crtc_state *pipe_config)
11119 {
11120         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11121
11122         /* read out port_clock from the DPLL */
11123         i9xx_crtc_clock_get(crtc, pipe_config);
11124
11125         /*
11126          * In case there is an active pipe without active ports,
11127          * we may need some idea for the dotclock anyway.
11128          * Calculate one based on the FDI configuration.
11129          */
11130         pipe_config->base.adjusted_mode.crtc_clock =
11131                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
11132                                          &pipe_config->fdi_m_n);
11133 }
11134
11135 /* Returns the currently programmed mode of the given encoder. */
11136 struct drm_display_mode *
11137 intel_encoder_current_mode(struct intel_encoder *encoder)
11138 {
11139         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
11140         struct intel_crtc_state *crtc_state;
11141         struct drm_display_mode *mode;
11142         struct intel_crtc *crtc;
11143         enum pipe pipe;
11144
11145         if (!encoder->get_hw_state(encoder, &pipe))
11146                 return NULL;
11147
11148         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
11149
11150         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
11151         if (!mode)
11152                 return NULL;
11153
11154         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
11155         if (!crtc_state) {
11156                 kfree(mode);
11157                 return NULL;
11158         }
11159
11160         crtc_state->base.crtc = &crtc->base;
11161
11162         if (!dev_priv->display.get_pipe_config(crtc, crtc_state)) {
11163                 kfree(crtc_state);
11164                 kfree(mode);
11165                 return NULL;
11166         }
11167
11168         encoder->get_config(encoder, crtc_state);
11169
11170         intel_mode_from_pipe_config(mode, crtc_state);
11171
11172         kfree(crtc_state);
11173
11174         return mode;
11175 }
11176
11177 static void intel_crtc_destroy(struct drm_crtc *crtc)
11178 {
11179         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11180
11181         drm_crtc_cleanup(crtc);
11182         kfree(intel_crtc);
11183 }
11184
11185 /**
11186  * intel_wm_need_update - Check whether watermarks need updating
11187  * @cur: current plane state
11188  * @new: new plane state
11189  *
11190  * Check current plane state versus the new one to determine whether
11191  * watermarks need to be recalculated.
11192  *
11193  * Returns true or false.
11194  */
11195 static bool intel_wm_need_update(struct intel_plane_state *cur,
11196                                  struct intel_plane_state *new)
11197 {
11198         /* Update watermarks on tiling or size changes. */
11199         if (new->base.visible != cur->base.visible)
11200                 return true;
11201
11202         if (!cur->base.fb || !new->base.fb)
11203                 return false;
11204
11205         if (cur->base.fb->modifier != new->base.fb->modifier ||
11206             cur->base.rotation != new->base.rotation ||
11207             drm_rect_width(&new->base.src) != drm_rect_width(&cur->base.src) ||
11208             drm_rect_height(&new->base.src) != drm_rect_height(&cur->base.src) ||
11209             drm_rect_width(&new->base.dst) != drm_rect_width(&cur->base.dst) ||
11210             drm_rect_height(&new->base.dst) != drm_rect_height(&cur->base.dst))
11211                 return true;
11212
11213         return false;
11214 }
11215
11216 static bool needs_scaling(const struct intel_plane_state *state)
11217 {
11218         int src_w = drm_rect_width(&state->base.src) >> 16;
11219         int src_h = drm_rect_height(&state->base.src) >> 16;
11220         int dst_w = drm_rect_width(&state->base.dst);
11221         int dst_h = drm_rect_height(&state->base.dst);
11222
11223         return (src_w != dst_w || src_h != dst_h);
11224 }
11225
11226 int intel_plane_atomic_calc_changes(const struct intel_crtc_state *old_crtc_state,
11227                                     struct drm_crtc_state *crtc_state,
11228                                     const struct intel_plane_state *old_plane_state,
11229                                     struct drm_plane_state *plane_state)
11230 {
11231         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
11232         struct drm_crtc *crtc = crtc_state->crtc;
11233         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11234         struct intel_plane *plane = to_intel_plane(plane_state->plane);
11235         struct drm_device *dev = crtc->dev;
11236         struct drm_i915_private *dev_priv = to_i915(dev);
11237         bool mode_changed = needs_modeset(crtc_state);
11238         bool was_crtc_enabled = old_crtc_state->base.active;
11239         bool is_crtc_enabled = crtc_state->active;
11240         bool turn_off, turn_on, visible, was_visible;
11241         struct drm_framebuffer *fb = plane_state->fb;
11242         int ret;
11243
11244         if (INTEL_GEN(dev_priv) >= 9 && plane->id != PLANE_CURSOR) {
11245                 ret = skl_update_scaler_plane(
11246                         to_intel_crtc_state(crtc_state),
11247                         to_intel_plane_state(plane_state));
11248                 if (ret)
11249                         return ret;
11250         }
11251
11252         was_visible = old_plane_state->base.visible;
11253         visible = plane_state->visible;
11254
11255         if (!was_crtc_enabled && WARN_ON(was_visible))
11256                 was_visible = false;
11257
11258         /*
11259          * Visibility is calculated as if the crtc was on, but
11260          * after scaler setup everything depends on it being off
11261          * when the crtc isn't active.
11262          *
11263          * FIXME this is wrong for watermarks. Watermarks should also
11264          * be computed as if the pipe would be active. Perhaps move
11265          * per-plane wm computation to the .check_plane() hook, and
11266          * only combine the results from all planes in the current place?
11267          */
11268         if (!is_crtc_enabled) {
11269                 plane_state->visible = visible = false;
11270                 to_intel_crtc_state(crtc_state)->active_planes &= ~BIT(plane->id);
11271         }
11272
11273         if (!was_visible && !visible)
11274                 return 0;
11275
11276         if (fb != old_plane_state->base.fb)
11277                 pipe_config->fb_changed = true;
11278
11279         turn_off = was_visible && (!visible || mode_changed);
11280         turn_on = visible && (!was_visible || mode_changed);
11281
11282         DRM_DEBUG_ATOMIC("[CRTC:%d:%s] has [PLANE:%d:%s] with fb %i\n",
11283                          intel_crtc->base.base.id, intel_crtc->base.name,
11284                          plane->base.base.id, plane->base.name,
11285                          fb ? fb->base.id : -1);
11286
11287         DRM_DEBUG_ATOMIC("[PLANE:%d:%s] visible %i -> %i, off %i, on %i, ms %i\n",
11288                          plane->base.base.id, plane->base.name,
11289                          was_visible, visible,
11290                          turn_off, turn_on, mode_changed);
11291
11292         if (turn_on) {
11293                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
11294                         pipe_config->update_wm_pre = true;
11295
11296                 /* must disable cxsr around plane enable/disable */
11297                 if (plane->id != PLANE_CURSOR)
11298                         pipe_config->disable_cxsr = true;
11299         } else if (turn_off) {
11300                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
11301                         pipe_config->update_wm_post = true;
11302
11303                 /* must disable cxsr around plane enable/disable */
11304                 if (plane->id != PLANE_CURSOR)
11305                         pipe_config->disable_cxsr = true;
11306         } else if (intel_wm_need_update(to_intel_plane_state(plane->base.state),
11307                                         to_intel_plane_state(plane_state))) {
11308                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
11309                         /* FIXME bollocks */
11310                         pipe_config->update_wm_pre = true;
11311                         pipe_config->update_wm_post = true;
11312                 }
11313         }
11314
11315         if (visible || was_visible)
11316                 pipe_config->fb_bits |= plane->frontbuffer_bit;
11317
11318         /*
11319          * ILK/SNB DVSACNTR/Sprite Enable
11320          * IVB SPR_CTL/Sprite Enable
11321          * "When in Self Refresh Big FIFO mode, a write to enable the
11322          *  plane will be internally buffered and delayed while Big FIFO
11323          *  mode is exiting."
11324          *
11325          * Which means that enabling the sprite can take an extra frame
11326          * when we start in big FIFO mode (LP1+). Thus we need to drop
11327          * down to LP0 and wait for vblank in order to make sure the
11328          * sprite gets enabled on the next vblank after the register write.
11329          * Doing otherwise would risk enabling the sprite one frame after
11330          * we've already signalled flip completion. We can resume LP1+
11331          * once the sprite has been enabled.
11332          *
11333          *
11334          * WaCxSRDisabledForSpriteScaling:ivb
11335          * IVB SPR_SCALE/Scaling Enable
11336          * "Low Power watermarks must be disabled for at least one
11337          *  frame before enabling sprite scaling, and kept disabled
11338          *  until sprite scaling is disabled."
11339          *
11340          * ILK/SNB DVSASCALE/Scaling Enable
11341          * "When in Self Refresh Big FIFO mode, scaling enable will be
11342          *  masked off while Big FIFO mode is exiting."
11343          *
11344          * Despite the w/a only being listed for IVB we assume that
11345          * the ILK/SNB note has similar ramifications, hence we apply
11346          * the w/a on all three platforms.
11347          *
11348          * With experimental results seems this is needed also for primary
11349          * plane, not only sprite plane.
11350          */
11351         if (plane->id != PLANE_CURSOR &&
11352             (IS_GEN_RANGE(dev_priv, 5, 6) ||
11353              IS_IVYBRIDGE(dev_priv)) &&
11354             (turn_on || (!needs_scaling(old_plane_state) &&
11355                          needs_scaling(to_intel_plane_state(plane_state)))))
11356                 pipe_config->disable_lp_wm = true;
11357
11358         return 0;
11359 }
11360
11361 static bool encoders_cloneable(const struct intel_encoder *a,
11362                                const struct intel_encoder *b)
11363 {
11364         /* masks could be asymmetric, so check both ways */
11365         return a == b || (a->cloneable & (1 << b->type) &&
11366                           b->cloneable & (1 << a->type));
11367 }
11368
11369 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
11370                                          struct intel_crtc *crtc,
11371                                          struct intel_encoder *encoder)
11372 {
11373         struct intel_encoder *source_encoder;
11374         struct drm_connector *connector;
11375         struct drm_connector_state *connector_state;
11376         int i;
11377
11378         for_each_new_connector_in_state(state, connector, connector_state, i) {
11379                 if (connector_state->crtc != &crtc->base)
11380                         continue;
11381
11382                 source_encoder =
11383                         to_intel_encoder(connector_state->best_encoder);
11384                 if (!encoders_cloneable(encoder, source_encoder))
11385                         return false;
11386         }
11387
11388         return true;
11389 }
11390
11391 static int icl_add_linked_planes(struct intel_atomic_state *state)
11392 {
11393         struct intel_plane *plane, *linked;
11394         struct intel_plane_state *plane_state, *linked_plane_state;
11395         int i;
11396
11397         for_each_new_intel_plane_in_state(state, plane, plane_state, i) {
11398                 linked = plane_state->linked_plane;
11399
11400                 if (!linked)
11401                         continue;
11402
11403                 linked_plane_state = intel_atomic_get_plane_state(state, linked);
11404                 if (IS_ERR(linked_plane_state))
11405                         return PTR_ERR(linked_plane_state);
11406
11407                 WARN_ON(linked_plane_state->linked_plane != plane);
11408                 WARN_ON(linked_plane_state->slave == plane_state->slave);
11409         }
11410
11411         return 0;
11412 }
11413
11414 static int icl_check_nv12_planes(struct intel_crtc_state *crtc_state)
11415 {
11416         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
11417         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11418         struct intel_atomic_state *state = to_intel_atomic_state(crtc_state->base.state);
11419         struct intel_plane *plane, *linked;
11420         struct intel_plane_state *plane_state;
11421         int i;
11422
11423         if (INTEL_GEN(dev_priv) < 11)
11424                 return 0;
11425
11426         /*
11427          * Destroy all old plane links and make the slave plane invisible
11428          * in the crtc_state->active_planes mask.
11429          */
11430         for_each_new_intel_plane_in_state(state, plane, plane_state, i) {
11431                 if (plane->pipe != crtc->pipe || !plane_state->linked_plane)
11432                         continue;
11433
11434                 plane_state->linked_plane = NULL;
11435                 if (plane_state->slave && !plane_state->base.visible) {
11436                         crtc_state->active_planes &= ~BIT(plane->id);
11437                         crtc_state->update_planes |= BIT(plane->id);
11438                 }
11439
11440                 plane_state->slave = false;
11441         }
11442
11443         if (!crtc_state->nv12_planes)
11444                 return 0;
11445
11446         for_each_new_intel_plane_in_state(state, plane, plane_state, i) {
11447                 struct intel_plane_state *linked_state = NULL;
11448
11449                 if (plane->pipe != crtc->pipe ||
11450                     !(crtc_state->nv12_planes & BIT(plane->id)))
11451                         continue;
11452
11453                 for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, linked) {
11454                         if (!icl_is_nv12_y_plane(linked->id))
11455                                 continue;
11456
11457                         if (crtc_state->active_planes & BIT(linked->id))
11458                                 continue;
11459
11460                         linked_state = intel_atomic_get_plane_state(state, linked);
11461                         if (IS_ERR(linked_state))
11462                                 return PTR_ERR(linked_state);
11463
11464                         break;
11465                 }
11466
11467                 if (!linked_state) {
11468                         DRM_DEBUG_KMS("Need %d free Y planes for planar YUV\n",
11469                                       hweight8(crtc_state->nv12_planes));
11470
11471                         return -EINVAL;
11472                 }
11473
11474                 plane_state->linked_plane = linked;
11475
11476                 linked_state->slave = true;
11477                 linked_state->linked_plane = plane;
11478                 crtc_state->active_planes |= BIT(linked->id);
11479                 crtc_state->update_planes |= BIT(linked->id);
11480                 DRM_DEBUG_KMS("Using %s as Y plane for %s\n", linked->base.name, plane->base.name);
11481         }
11482
11483         return 0;
11484 }
11485
11486 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
11487                                    struct drm_crtc_state *crtc_state)
11488 {
11489         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
11490         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11491         struct intel_crtc_state *pipe_config =
11492                 to_intel_crtc_state(crtc_state);
11493         int ret;
11494         bool mode_changed = needs_modeset(crtc_state);
11495
11496         if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv) &&
11497             mode_changed && !crtc_state->active)
11498                 pipe_config->update_wm_post = true;
11499
11500         if (mode_changed && crtc_state->enable &&
11501             dev_priv->display.crtc_compute_clock &&
11502             !WARN_ON(pipe_config->shared_dpll)) {
11503                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
11504                                                            pipe_config);
11505                 if (ret)
11506                         return ret;
11507         }
11508
11509         if (mode_changed || pipe_config->update_pipe ||
11510             crtc_state->color_mgmt_changed) {
11511                 ret = intel_color_check(pipe_config);
11512                 if (ret)
11513                         return ret;
11514         }
11515
11516         ret = 0;
11517         if (dev_priv->display.compute_pipe_wm) {
11518                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
11519                 if (ret) {
11520                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
11521                         return ret;
11522                 }
11523         }
11524
11525         if (dev_priv->display.compute_intermediate_wm) {
11526                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
11527                         return 0;
11528
11529                 /*
11530                  * Calculate 'intermediate' watermarks that satisfy both the
11531                  * old state and the new state.  We can program these
11532                  * immediately.
11533                  */
11534                 ret = dev_priv->display.compute_intermediate_wm(pipe_config);
11535                 if (ret) {
11536                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
11537                         return ret;
11538                 }
11539         }
11540
11541         if (INTEL_GEN(dev_priv) >= 9) {
11542                 if (mode_changed || pipe_config->update_pipe)
11543                         ret = skl_update_scaler_crtc(pipe_config);
11544
11545                 if (!ret)
11546                         ret = icl_check_nv12_planes(pipe_config);
11547                 if (!ret)
11548                         ret = skl_check_pipe_max_pixel_rate(intel_crtc,
11549                                                             pipe_config);
11550                 if (!ret)
11551                         ret = intel_atomic_setup_scalers(dev_priv, intel_crtc,
11552                                                          pipe_config);
11553         }
11554
11555         if (HAS_IPS(dev_priv))
11556                 pipe_config->ips_enabled = hsw_compute_ips_config(pipe_config);
11557
11558         return ret;
11559 }
11560
11561 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
11562         .atomic_check = intel_crtc_atomic_check,
11563 };
11564
11565 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
11566 {
11567         struct intel_connector *connector;
11568         struct drm_connector_list_iter conn_iter;
11569
11570         drm_connector_list_iter_begin(dev, &conn_iter);
11571         for_each_intel_connector_iter(connector, &conn_iter) {
11572                 if (connector->base.state->crtc)
11573                         drm_connector_put(&connector->base);
11574
11575                 if (connector->base.encoder) {
11576                         connector->base.state->best_encoder =
11577                                 connector->base.encoder;
11578                         connector->base.state->crtc =
11579                                 connector->base.encoder->crtc;
11580
11581                         drm_connector_get(&connector->base);
11582                 } else {
11583                         connector->base.state->best_encoder = NULL;
11584                         connector->base.state->crtc = NULL;
11585                 }
11586         }
11587         drm_connector_list_iter_end(&conn_iter);
11588 }
11589
11590 static int
11591 compute_sink_pipe_bpp(const struct drm_connector_state *conn_state,
11592                       struct intel_crtc_state *pipe_config)
11593 {
11594         struct drm_connector *connector = conn_state->connector;
11595         const struct drm_display_info *info = &connector->display_info;
11596         int bpp;
11597
11598         switch (conn_state->max_bpc) {
11599         case 6 ... 7:
11600                 bpp = 6 * 3;
11601                 break;
11602         case 8 ... 9:
11603                 bpp = 8 * 3;
11604                 break;
11605         case 10 ... 11:
11606                 bpp = 10 * 3;
11607                 break;
11608         case 12:
11609                 bpp = 12 * 3;
11610                 break;
11611         default:
11612                 return -EINVAL;
11613         }
11614
11615         if (bpp < pipe_config->pipe_bpp) {
11616                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] Limiting display bpp to %d instead of "
11617                               "EDID bpp %d, requested bpp %d, max platform bpp %d\n",
11618                               connector->base.id, connector->name,
11619                               bpp, 3 * info->bpc, 3 * conn_state->max_requested_bpc,
11620                               pipe_config->pipe_bpp);
11621
11622                 pipe_config->pipe_bpp = bpp;
11623         }
11624
11625         return 0;
11626 }
11627
11628 static int
11629 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
11630                           struct intel_crtc_state *pipe_config)
11631 {
11632         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11633         struct drm_atomic_state *state = pipe_config->base.state;
11634         struct drm_connector *connector;
11635         struct drm_connector_state *connector_state;
11636         int bpp, i;
11637
11638         if ((IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
11639             IS_CHERRYVIEW(dev_priv)))
11640                 bpp = 10*3;
11641         else if (INTEL_GEN(dev_priv) >= 5)
11642                 bpp = 12*3;
11643         else
11644                 bpp = 8*3;
11645
11646         pipe_config->pipe_bpp = bpp;
11647
11648         /* Clamp display bpp to connector max bpp */
11649         for_each_new_connector_in_state(state, connector, connector_state, i) {
11650                 int ret;
11651
11652                 if (connector_state->crtc != &crtc->base)
11653                         continue;
11654
11655                 ret = compute_sink_pipe_bpp(connector_state, pipe_config);
11656                 if (ret)
11657                         return ret;
11658         }
11659
11660         return 0;
11661 }
11662
11663 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
11664 {
11665         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
11666                         "type: 0x%x flags: 0x%x\n",
11667                 mode->crtc_clock,
11668                 mode->crtc_hdisplay, mode->crtc_hsync_start,
11669                 mode->crtc_hsync_end, mode->crtc_htotal,
11670                 mode->crtc_vdisplay, mode->crtc_vsync_start,
11671                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
11672 }
11673
11674 static inline void
11675 intel_dump_m_n_config(struct intel_crtc_state *pipe_config, char *id,
11676                       unsigned int lane_count, struct intel_link_m_n *m_n)
11677 {
11678         DRM_DEBUG_KMS("%s: lanes: %i; gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
11679                       id, lane_count,
11680                       m_n->gmch_m, m_n->gmch_n,
11681                       m_n->link_m, m_n->link_n, m_n->tu);
11682 }
11683
11684 static void
11685 intel_dump_infoframe(struct drm_i915_private *dev_priv,
11686                      const union hdmi_infoframe *frame)
11687 {
11688         if ((drm_debug & DRM_UT_KMS) == 0)
11689                 return;
11690
11691         hdmi_infoframe_log(KERN_DEBUG, dev_priv->drm.dev, frame);
11692 }
11693
11694 #define OUTPUT_TYPE(x) [INTEL_OUTPUT_ ## x] = #x
11695
11696 static const char * const output_type_str[] = {
11697         OUTPUT_TYPE(UNUSED),
11698         OUTPUT_TYPE(ANALOG),
11699         OUTPUT_TYPE(DVO),
11700         OUTPUT_TYPE(SDVO),
11701         OUTPUT_TYPE(LVDS),
11702         OUTPUT_TYPE(TVOUT),
11703         OUTPUT_TYPE(HDMI),
11704         OUTPUT_TYPE(DP),
11705         OUTPUT_TYPE(EDP),
11706         OUTPUT_TYPE(DSI),
11707         OUTPUT_TYPE(DDI),
11708         OUTPUT_TYPE(DP_MST),
11709 };
11710
11711 #undef OUTPUT_TYPE
11712
11713 static void snprintf_output_types(char *buf, size_t len,
11714                                   unsigned int output_types)
11715 {
11716         char *str = buf;
11717         int i;
11718
11719         str[0] = '\0';
11720
11721         for (i = 0; i < ARRAY_SIZE(output_type_str); i++) {
11722                 int r;
11723
11724                 if ((output_types & BIT(i)) == 0)
11725                         continue;
11726
11727                 r = snprintf(str, len, "%s%s",
11728                              str != buf ? "," : "", output_type_str[i]);
11729                 if (r >= len)
11730                         break;
11731                 str += r;
11732                 len -= r;
11733
11734                 output_types &= ~BIT(i);
11735         }
11736
11737         WARN_ON_ONCE(output_types != 0);
11738 }
11739
11740 static const char * const output_format_str[] = {
11741         [INTEL_OUTPUT_FORMAT_INVALID] = "Invalid",
11742         [INTEL_OUTPUT_FORMAT_RGB] = "RGB",
11743         [INTEL_OUTPUT_FORMAT_YCBCR420] = "YCBCR4:2:0",
11744         [INTEL_OUTPUT_FORMAT_YCBCR444] = "YCBCR4:4:4",
11745 };
11746
11747 static const char *output_formats(enum intel_output_format format)
11748 {
11749         if (format >= ARRAY_SIZE(output_format_str))
11750                 format = INTEL_OUTPUT_FORMAT_INVALID;
11751         return output_format_str[format];
11752 }
11753
11754 static void intel_dump_pipe_config(struct intel_crtc *crtc,
11755                                    struct intel_crtc_state *pipe_config,
11756                                    const char *context)
11757 {
11758         struct drm_device *dev = crtc->base.dev;
11759         struct drm_i915_private *dev_priv = to_i915(dev);
11760         struct drm_plane *plane;
11761         struct intel_plane *intel_plane;
11762         struct intel_plane_state *state;
11763         struct drm_framebuffer *fb;
11764         char buf[64];
11765
11766         DRM_DEBUG_KMS("[CRTC:%d:%s]%s\n",
11767                       crtc->base.base.id, crtc->base.name, context);
11768
11769         snprintf_output_types(buf, sizeof(buf), pipe_config->output_types);
11770         DRM_DEBUG_KMS("output_types: %s (0x%x)\n",
11771                       buf, pipe_config->output_types);
11772
11773         DRM_DEBUG_KMS("output format: %s\n",
11774                       output_formats(pipe_config->output_format));
11775
11776         DRM_DEBUG_KMS("cpu_transcoder: %s, pipe bpp: %i, dithering: %i\n",
11777                       transcoder_name(pipe_config->cpu_transcoder),
11778                       pipe_config->pipe_bpp, pipe_config->dither);
11779
11780         if (pipe_config->has_pch_encoder)
11781                 intel_dump_m_n_config(pipe_config, "fdi",
11782                                       pipe_config->fdi_lanes,
11783                                       &pipe_config->fdi_m_n);
11784
11785         if (intel_crtc_has_dp_encoder(pipe_config)) {
11786                 intel_dump_m_n_config(pipe_config, "dp m_n",
11787                                 pipe_config->lane_count, &pipe_config->dp_m_n);
11788                 if (pipe_config->has_drrs)
11789                         intel_dump_m_n_config(pipe_config, "dp m2_n2",
11790                                               pipe_config->lane_count,
11791                                               &pipe_config->dp_m2_n2);
11792         }
11793
11794         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
11795                       pipe_config->has_audio, pipe_config->has_infoframe);
11796
11797         DRM_DEBUG_KMS("infoframes enabled: 0x%x\n",
11798                       pipe_config->infoframes.enable);
11799
11800         if (pipe_config->infoframes.enable &
11801             intel_hdmi_infoframe_enable(HDMI_PACKET_TYPE_GENERAL_CONTROL))
11802                 DRM_DEBUG_KMS("GCP: 0x%x\n", pipe_config->infoframes.gcp);
11803         if (pipe_config->infoframes.enable &
11804             intel_hdmi_infoframe_enable(HDMI_INFOFRAME_TYPE_AVI))
11805                 intel_dump_infoframe(dev_priv, &pipe_config->infoframes.avi);
11806         if (pipe_config->infoframes.enable &
11807             intel_hdmi_infoframe_enable(HDMI_INFOFRAME_TYPE_SPD))
11808                 intel_dump_infoframe(dev_priv, &pipe_config->infoframes.spd);
11809         if (pipe_config->infoframes.enable &
11810             intel_hdmi_infoframe_enable(HDMI_INFOFRAME_TYPE_VENDOR))
11811                 intel_dump_infoframe(dev_priv, &pipe_config->infoframes.hdmi);
11812
11813         DRM_DEBUG_KMS("requested mode:\n");
11814         drm_mode_debug_printmodeline(&pipe_config->base.mode);
11815         DRM_DEBUG_KMS("adjusted mode:\n");
11816         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
11817         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
11818         DRM_DEBUG_KMS("port clock: %d, pipe src size: %dx%d, pixel rate %d\n",
11819                       pipe_config->port_clock,
11820                       pipe_config->pipe_src_w, pipe_config->pipe_src_h,
11821                       pipe_config->pixel_rate);
11822
11823         if (INTEL_GEN(dev_priv) >= 9)
11824                 DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
11825                               crtc->num_scalers,
11826                               pipe_config->scaler_state.scaler_users,
11827                               pipe_config->scaler_state.scaler_id);
11828
11829         if (HAS_GMCH(dev_priv))
11830                 DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
11831                               pipe_config->gmch_pfit.control,
11832                               pipe_config->gmch_pfit.pgm_ratios,
11833                               pipe_config->gmch_pfit.lvds_border_bits);
11834         else
11835                 DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s, force thru: %s\n",
11836                               pipe_config->pch_pfit.pos,
11837                               pipe_config->pch_pfit.size,
11838                               enableddisabled(pipe_config->pch_pfit.enabled),
11839                               yesno(pipe_config->pch_pfit.force_thru));
11840
11841         DRM_DEBUG_KMS("ips: %i, double wide: %i\n",
11842                       pipe_config->ips_enabled, pipe_config->double_wide);
11843
11844         intel_dpll_dump_hw_state(dev_priv, &pipe_config->dpll_hw_state);
11845
11846         DRM_DEBUG_KMS("planes on this crtc\n");
11847         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
11848                 struct drm_format_name_buf format_name;
11849                 intel_plane = to_intel_plane(plane);
11850                 if (intel_plane->pipe != crtc->pipe)
11851                         continue;
11852
11853                 state = to_intel_plane_state(plane->state);
11854                 fb = state->base.fb;
11855                 if (!fb) {
11856                         DRM_DEBUG_KMS("[PLANE:%d:%s] disabled, scaler_id = %d\n",
11857                                       plane->base.id, plane->name, state->scaler_id);
11858                         continue;
11859                 }
11860
11861                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d, fb = %ux%u format = %s\n",
11862                               plane->base.id, plane->name,
11863                               fb->base.id, fb->width, fb->height,
11864                               drm_get_format_name(fb->format->format, &format_name));
11865                 if (INTEL_GEN(dev_priv) >= 9)
11866                         DRM_DEBUG_KMS("\tscaler:%d src %dx%d+%d+%d dst %dx%d+%d+%d\n",
11867                                       state->scaler_id,
11868                                       state->base.src.x1 >> 16,
11869                                       state->base.src.y1 >> 16,
11870                                       drm_rect_width(&state->base.src) >> 16,
11871                                       drm_rect_height(&state->base.src) >> 16,
11872                                       state->base.dst.x1, state->base.dst.y1,
11873                                       drm_rect_width(&state->base.dst),
11874                                       drm_rect_height(&state->base.dst));
11875         }
11876 }
11877
11878 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
11879 {
11880         struct drm_device *dev = state->dev;
11881         struct drm_connector *connector;
11882         struct drm_connector_list_iter conn_iter;
11883         unsigned int used_ports = 0;
11884         unsigned int used_mst_ports = 0;
11885         bool ret = true;
11886
11887         /*
11888          * Walk the connector list instead of the encoder
11889          * list to detect the problem on ddi platforms
11890          * where there's just one encoder per digital port.
11891          */
11892         drm_connector_list_iter_begin(dev, &conn_iter);
11893         drm_for_each_connector_iter(connector, &conn_iter) {
11894                 struct drm_connector_state *connector_state;
11895                 struct intel_encoder *encoder;
11896
11897                 connector_state = drm_atomic_get_new_connector_state(state, connector);
11898                 if (!connector_state)
11899                         connector_state = connector->state;
11900
11901                 if (!connector_state->best_encoder)
11902                         continue;
11903
11904                 encoder = to_intel_encoder(connector_state->best_encoder);
11905
11906                 WARN_ON(!connector_state->crtc);
11907
11908                 switch (encoder->type) {
11909                         unsigned int port_mask;
11910                 case INTEL_OUTPUT_DDI:
11911                         if (WARN_ON(!HAS_DDI(to_i915(dev))))
11912                                 break;
11913                         /* else: fall through */
11914                 case INTEL_OUTPUT_DP:
11915                 case INTEL_OUTPUT_HDMI:
11916                 case INTEL_OUTPUT_EDP:
11917                         port_mask = 1 << encoder->port;
11918
11919                         /* the same port mustn't appear more than once */
11920                         if (used_ports & port_mask)
11921                                 ret = false;
11922
11923                         used_ports |= port_mask;
11924                         break;
11925                 case INTEL_OUTPUT_DP_MST:
11926                         used_mst_ports |=
11927                                 1 << encoder->port;
11928                         break;
11929                 default:
11930                         break;
11931                 }
11932         }
11933         drm_connector_list_iter_end(&conn_iter);
11934
11935         /* can't mix MST and SST/HDMI on the same port */
11936         if (used_ports & used_mst_ports)
11937                 return false;
11938
11939         return ret;
11940 }
11941
11942 static int
11943 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
11944 {
11945         struct drm_i915_private *dev_priv =
11946                 to_i915(crtc_state->base.crtc->dev);
11947         struct intel_crtc_state *saved_state;
11948
11949         saved_state = kzalloc(sizeof(*saved_state), GFP_KERNEL);
11950         if (!saved_state)
11951                 return -ENOMEM;
11952
11953         /* FIXME: before the switch to atomic started, a new pipe_config was
11954          * kzalloc'd. Code that depends on any field being zero should be
11955          * fixed, so that the crtc_state can be safely duplicated. For now,
11956          * only fields that are know to not cause problems are preserved. */
11957
11958         saved_state->scaler_state = crtc_state->scaler_state;
11959         saved_state->shared_dpll = crtc_state->shared_dpll;
11960         saved_state->dpll_hw_state = crtc_state->dpll_hw_state;
11961         saved_state->crc_enabled = crtc_state->crc_enabled;
11962         if (IS_G4X(dev_priv) ||
11963             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11964                 saved_state->wm = crtc_state->wm;
11965
11966         /* Keep base drm_crtc_state intact, only clear our extended struct */
11967         BUILD_BUG_ON(offsetof(struct intel_crtc_state, base));
11968         memcpy(&crtc_state->base + 1, &saved_state->base + 1,
11969                sizeof(*crtc_state) - sizeof(crtc_state->base));
11970
11971         kfree(saved_state);
11972         return 0;
11973 }
11974
11975 static int
11976 intel_modeset_pipe_config(struct drm_crtc *crtc,
11977                           struct intel_crtc_state *pipe_config)
11978 {
11979         struct drm_atomic_state *state = pipe_config->base.state;
11980         struct intel_encoder *encoder;
11981         struct drm_connector *connector;
11982         struct drm_connector_state *connector_state;
11983         int base_bpp, ret;
11984         int i;
11985         bool retry = true;
11986
11987         ret = clear_intel_crtc_state(pipe_config);
11988         if (ret)
11989                 return ret;
11990
11991         pipe_config->cpu_transcoder =
11992                 (enum transcoder) to_intel_crtc(crtc)->pipe;
11993
11994         /*
11995          * Sanitize sync polarity flags based on requested ones. If neither
11996          * positive or negative polarity is requested, treat this as meaning
11997          * negative polarity.
11998          */
11999         if (!(pipe_config->base.adjusted_mode.flags &
12000               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
12001                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
12002
12003         if (!(pipe_config->base.adjusted_mode.flags &
12004               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
12005                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
12006
12007         ret = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
12008                                         pipe_config);
12009         if (ret)
12010                 return ret;
12011
12012         base_bpp = pipe_config->pipe_bpp;
12013
12014         /*
12015          * Determine the real pipe dimensions. Note that stereo modes can
12016          * increase the actual pipe size due to the frame doubling and
12017          * insertion of additional space for blanks between the frame. This
12018          * is stored in the crtc timings. We use the requested mode to do this
12019          * computation to clearly distinguish it from the adjusted mode, which
12020          * can be changed by the connectors in the below retry loop.
12021          */
12022         drm_mode_get_hv_timing(&pipe_config->base.mode,
12023                                &pipe_config->pipe_src_w,
12024                                &pipe_config->pipe_src_h);
12025
12026         for_each_new_connector_in_state(state, connector, connector_state, i) {
12027                 if (connector_state->crtc != crtc)
12028                         continue;
12029
12030                 encoder = to_intel_encoder(connector_state->best_encoder);
12031
12032                 if (!check_single_encoder_cloning(state, to_intel_crtc(crtc), encoder)) {
12033                         DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
12034                         return -EINVAL;
12035                 }
12036
12037                 /*
12038                  * Determine output_types before calling the .compute_config()
12039                  * hooks so that the hooks can use this information safely.
12040                  */
12041                 if (encoder->compute_output_type)
12042                         pipe_config->output_types |=
12043                                 BIT(encoder->compute_output_type(encoder, pipe_config,
12044                                                                  connector_state));
12045                 else
12046                         pipe_config->output_types |= BIT(encoder->type);
12047         }
12048
12049 encoder_retry:
12050         /* Ensure the port clock defaults are reset when retrying. */
12051         pipe_config->port_clock = 0;
12052         pipe_config->pixel_multiplier = 1;
12053
12054         /* Fill in default crtc timings, allow encoders to overwrite them. */
12055         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
12056                               CRTC_STEREO_DOUBLE);
12057
12058         /* Pass our mode to the connectors and the CRTC to give them a chance to
12059          * adjust it according to limitations or connector properties, and also
12060          * a chance to reject the mode entirely.
12061          */
12062         for_each_new_connector_in_state(state, connector, connector_state, i) {
12063                 if (connector_state->crtc != crtc)
12064                         continue;
12065
12066                 encoder = to_intel_encoder(connector_state->best_encoder);
12067                 ret = encoder->compute_config(encoder, pipe_config,
12068                                               connector_state);
12069                 if (ret < 0) {
12070                         if (ret != -EDEADLK)
12071                                 DRM_DEBUG_KMS("Encoder config failure: %d\n",
12072                                               ret);
12073                         return ret;
12074                 }
12075         }
12076
12077         /* Set default port clock if not overwritten by the encoder. Needs to be
12078          * done afterwards in case the encoder adjusts the mode. */
12079         if (!pipe_config->port_clock)
12080                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
12081                         * pipe_config->pixel_multiplier;
12082
12083         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
12084         if (ret == -EDEADLK)
12085                 return ret;
12086         if (ret < 0) {
12087                 DRM_DEBUG_KMS("CRTC fixup failed\n");
12088                 return ret;
12089         }
12090
12091         if (ret == RETRY) {
12092                 if (WARN(!retry, "loop in pipe configuration computation\n"))
12093                         return -EINVAL;
12094
12095                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
12096                 retry = false;
12097                 goto encoder_retry;
12098         }
12099
12100         /* Dithering seems to not pass-through bits correctly when it should, so
12101          * only enable it on 6bpc panels and when its not a compliance
12102          * test requesting 6bpc video pattern.
12103          */
12104         pipe_config->dither = (pipe_config->pipe_bpp == 6*3) &&
12105                 !pipe_config->dither_force_disable;
12106         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
12107                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
12108
12109         return 0;
12110 }
12111
12112 static bool intel_fuzzy_clock_check(int clock1, int clock2)
12113 {
12114         int diff;
12115
12116         if (clock1 == clock2)
12117                 return true;
12118
12119         if (!clock1 || !clock2)
12120                 return false;
12121
12122         diff = abs(clock1 - clock2);
12123
12124         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
12125                 return true;
12126
12127         return false;
12128 }
12129
12130 static bool
12131 intel_compare_m_n(unsigned int m, unsigned int n,
12132                   unsigned int m2, unsigned int n2,
12133                   bool exact)
12134 {
12135         if (m == m2 && n == n2)
12136                 return true;
12137
12138         if (exact || !m || !n || !m2 || !n2)
12139                 return false;
12140
12141         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
12142
12143         if (n > n2) {
12144                 while (n > n2) {
12145                         m2 <<= 1;
12146                         n2 <<= 1;
12147                 }
12148         } else if (n < n2) {
12149                 while (n < n2) {
12150                         m <<= 1;
12151                         n <<= 1;
12152                 }
12153         }
12154
12155         if (n != n2)
12156                 return false;
12157
12158         return intel_fuzzy_clock_check(m, m2);
12159 }
12160
12161 static bool
12162 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
12163                        struct intel_link_m_n *m2_n2,
12164                        bool adjust)
12165 {
12166         if (m_n->tu == m2_n2->tu &&
12167             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
12168                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
12169             intel_compare_m_n(m_n->link_m, m_n->link_n,
12170                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
12171                 if (adjust)
12172                         *m2_n2 = *m_n;
12173
12174                 return true;
12175         }
12176
12177         return false;
12178 }
12179
12180 static bool
12181 intel_compare_infoframe(const union hdmi_infoframe *a,
12182                         const union hdmi_infoframe *b)
12183 {
12184         return memcmp(a, b, sizeof(*a)) == 0;
12185 }
12186
12187 static void
12188 pipe_config_infoframe_err(struct drm_i915_private *dev_priv,
12189                           bool adjust, const char *name,
12190                           const union hdmi_infoframe *a,
12191                           const union hdmi_infoframe *b)
12192 {
12193         if (adjust) {
12194                 if ((drm_debug & DRM_UT_KMS) == 0)
12195                         return;
12196
12197                 drm_dbg(DRM_UT_KMS, "mismatch in %s infoframe", name);
12198                 drm_dbg(DRM_UT_KMS, "expected:");
12199                 hdmi_infoframe_log(KERN_DEBUG, dev_priv->drm.dev, a);
12200                 drm_dbg(DRM_UT_KMS, "found");
12201                 hdmi_infoframe_log(KERN_DEBUG, dev_priv->drm.dev, b);
12202         } else {
12203                 drm_err("mismatch in %s infoframe", name);
12204                 drm_err("expected:");
12205                 hdmi_infoframe_log(KERN_ERR, dev_priv->drm.dev, a);
12206                 drm_err("found");
12207                 hdmi_infoframe_log(KERN_ERR, dev_priv->drm.dev, b);
12208         }
12209 }
12210
12211 static void __printf(3, 4)
12212 pipe_config_err(bool adjust, const char *name, const char *format, ...)
12213 {
12214         struct va_format vaf;
12215         va_list args;
12216
12217         va_start(args, format);
12218         vaf.fmt = format;
12219         vaf.va = &args;
12220
12221         if (adjust)
12222                 drm_dbg(DRM_UT_KMS, "mismatch in %s %pV", name, &vaf);
12223         else
12224                 drm_err("mismatch in %s %pV", name, &vaf);
12225
12226         va_end(args);
12227 }
12228
12229 static bool fastboot_enabled(struct drm_i915_private *dev_priv)
12230 {
12231         if (i915_modparams.fastboot != -1)
12232                 return i915_modparams.fastboot;
12233
12234         /* Enable fastboot by default on Skylake and newer */
12235         if (INTEL_GEN(dev_priv) >= 9)
12236                 return true;
12237
12238         /* Enable fastboot by default on VLV and CHV */
12239         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
12240                 return true;
12241
12242         /* Disabled by default on all others */
12243         return false;
12244 }
12245
12246 static bool
12247 intel_pipe_config_compare(struct drm_i915_private *dev_priv,
12248                           struct intel_crtc_state *current_config,
12249                           struct intel_crtc_state *pipe_config,
12250                           bool adjust)
12251 {
12252         bool ret = true;
12253         bool fixup_inherited = adjust &&
12254                 (current_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED) &&
12255                 !(pipe_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED);
12256
12257         if (fixup_inherited && !fastboot_enabled(dev_priv)) {
12258                 DRM_DEBUG_KMS("initial modeset and fastboot not set\n");
12259                 ret = false;
12260         }
12261
12262 #define PIPE_CONF_CHECK_X(name) do { \
12263         if (current_config->name != pipe_config->name) { \
12264                 pipe_config_err(adjust, __stringify(name), \
12265                           "(expected 0x%08x, found 0x%08x)\n", \
12266                           current_config->name, \
12267                           pipe_config->name); \
12268                 ret = false; \
12269         } \
12270 } while (0)
12271
12272 #define PIPE_CONF_CHECK_I(name) do { \
12273         if (current_config->name != pipe_config->name) { \
12274                 pipe_config_err(adjust, __stringify(name), \
12275                           "(expected %i, found %i)\n", \
12276                           current_config->name, \
12277                           pipe_config->name); \
12278                 ret = false; \
12279         } \
12280 } while (0)
12281
12282 #define PIPE_CONF_CHECK_BOOL(name) do { \
12283         if (current_config->name != pipe_config->name) { \
12284                 pipe_config_err(adjust, __stringify(name), \
12285                           "(expected %s, found %s)\n", \
12286                           yesno(current_config->name), \
12287                           yesno(pipe_config->name)); \
12288                 ret = false; \
12289         } \
12290 } while (0)
12291
12292 /*
12293  * Checks state where we only read out the enabling, but not the entire
12294  * state itself (like full infoframes or ELD for audio). These states
12295  * require a full modeset on bootup to fix up.
12296  */
12297 #define PIPE_CONF_CHECK_BOOL_INCOMPLETE(name) do { \
12298         if (!fixup_inherited || (!current_config->name && !pipe_config->name)) { \
12299                 PIPE_CONF_CHECK_BOOL(name); \
12300         } else { \
12301                 pipe_config_err(adjust, __stringify(name), \
12302                           "unable to verify whether state matches exactly, forcing modeset (expected %s, found %s)\n", \
12303                           yesno(current_config->name), \
12304                           yesno(pipe_config->name)); \
12305                 ret = false; \
12306         } \
12307 } while (0)
12308
12309 #define PIPE_CONF_CHECK_P(name) do { \
12310         if (current_config->name != pipe_config->name) { \
12311                 pipe_config_err(adjust, __stringify(name), \
12312                           "(expected %p, found %p)\n", \
12313                           current_config->name, \
12314                           pipe_config->name); \
12315                 ret = false; \
12316         } \
12317 } while (0)
12318
12319 #define PIPE_CONF_CHECK_M_N(name) do { \
12320         if (!intel_compare_link_m_n(&current_config->name, \
12321                                     &pipe_config->name,\
12322                                     adjust)) { \
12323                 pipe_config_err(adjust, __stringify(name), \
12324                           "(expected tu %i gmch %i/%i link %i/%i, " \
12325                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12326                           current_config->name.tu, \
12327                           current_config->name.gmch_m, \
12328                           current_config->name.gmch_n, \
12329                           current_config->name.link_m, \
12330                           current_config->name.link_n, \
12331                           pipe_config->name.tu, \
12332                           pipe_config->name.gmch_m, \
12333                           pipe_config->name.gmch_n, \
12334                           pipe_config->name.link_m, \
12335                           pipe_config->name.link_n); \
12336                 ret = false; \
12337         } \
12338 } while (0)
12339
12340 /* This is required for BDW+ where there is only one set of registers for
12341  * switching between high and low RR.
12342  * This macro can be used whenever a comparison has to be made between one
12343  * hw state and multiple sw state variables.
12344  */
12345 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) do { \
12346         if (!intel_compare_link_m_n(&current_config->name, \
12347                                     &pipe_config->name, adjust) && \
12348             !intel_compare_link_m_n(&current_config->alt_name, \
12349                                     &pipe_config->name, adjust)) { \
12350                 pipe_config_err(adjust, __stringify(name), \
12351                           "(expected tu %i gmch %i/%i link %i/%i, " \
12352                           "or tu %i gmch %i/%i link %i/%i, " \
12353                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12354                           current_config->name.tu, \
12355                           current_config->name.gmch_m, \
12356                           current_config->name.gmch_n, \
12357                           current_config->name.link_m, \
12358                           current_config->name.link_n, \
12359                           current_config->alt_name.tu, \
12360                           current_config->alt_name.gmch_m, \
12361                           current_config->alt_name.gmch_n, \
12362                           current_config->alt_name.link_m, \
12363                           current_config->alt_name.link_n, \
12364                           pipe_config->name.tu, \
12365                           pipe_config->name.gmch_m, \
12366                           pipe_config->name.gmch_n, \
12367                           pipe_config->name.link_m, \
12368                           pipe_config->name.link_n); \
12369                 ret = false; \
12370         } \
12371 } while (0)
12372
12373 #define PIPE_CONF_CHECK_FLAGS(name, mask) do { \
12374         if ((current_config->name ^ pipe_config->name) & (mask)) { \
12375                 pipe_config_err(adjust, __stringify(name), \
12376                           "(%x) (expected %i, found %i)\n", \
12377                           (mask), \
12378                           current_config->name & (mask), \
12379                           pipe_config->name & (mask)); \
12380                 ret = false; \
12381         } \
12382 } while (0)
12383
12384 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) do { \
12385         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
12386                 pipe_config_err(adjust, __stringify(name), \
12387                           "(expected %i, found %i)\n", \
12388                           current_config->name, \
12389                           pipe_config->name); \
12390                 ret = false; \
12391         } \
12392 } while (0)
12393
12394 #define PIPE_CONF_CHECK_INFOFRAME(name) do { \
12395         if (!intel_compare_infoframe(&current_config->infoframes.name, \
12396                                      &pipe_config->infoframes.name)) { \
12397                 pipe_config_infoframe_err(dev_priv, adjust, __stringify(name), \
12398                                           &current_config->infoframes.name, \
12399                                           &pipe_config->infoframes.name); \
12400                 ret = false; \
12401         } \
12402 } while (0)
12403
12404 #define PIPE_CONF_QUIRK(quirk) \
12405         ((current_config->quirks | pipe_config->quirks) & (quirk))
12406
12407         PIPE_CONF_CHECK_I(cpu_transcoder);
12408
12409         PIPE_CONF_CHECK_BOOL(has_pch_encoder);
12410         PIPE_CONF_CHECK_I(fdi_lanes);
12411         PIPE_CONF_CHECK_M_N(fdi_m_n);
12412
12413         PIPE_CONF_CHECK_I(lane_count);
12414         PIPE_CONF_CHECK_X(lane_lat_optim_mask);
12415
12416         if (INTEL_GEN(dev_priv) < 8) {
12417                 PIPE_CONF_CHECK_M_N(dp_m_n);
12418
12419                 if (current_config->has_drrs)
12420                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
12421         } else
12422                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
12423
12424         PIPE_CONF_CHECK_X(output_types);
12425
12426         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
12427         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
12428         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
12429         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
12430         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
12431         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
12432
12433         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
12434         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
12435         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
12436         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
12437         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
12438         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
12439
12440         PIPE_CONF_CHECK_I(pixel_multiplier);
12441         PIPE_CONF_CHECK_I(output_format);
12442         PIPE_CONF_CHECK_BOOL(has_hdmi_sink);
12443         if ((INTEL_GEN(dev_priv) < 8 && !IS_HASWELL(dev_priv)) ||
12444             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
12445                 PIPE_CONF_CHECK_BOOL(limited_color_range);
12446
12447         PIPE_CONF_CHECK_BOOL(hdmi_scrambling);
12448         PIPE_CONF_CHECK_BOOL(hdmi_high_tmds_clock_ratio);
12449         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_infoframe);
12450
12451         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_audio);
12452
12453         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12454                               DRM_MODE_FLAG_INTERLACE);
12455
12456         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
12457                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12458                                       DRM_MODE_FLAG_PHSYNC);
12459                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12460                                       DRM_MODE_FLAG_NHSYNC);
12461                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12462                                       DRM_MODE_FLAG_PVSYNC);
12463                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12464                                       DRM_MODE_FLAG_NVSYNC);
12465         }
12466
12467         PIPE_CONF_CHECK_X(gmch_pfit.control);
12468         /* pfit ratios are autocomputed by the hw on gen4+ */
12469         if (INTEL_GEN(dev_priv) < 4)
12470                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
12471         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
12472
12473         /*
12474          * Changing the EDP transcoder input mux
12475          * (A_ONOFF vs. A_ON) requires a full modeset.
12476          */
12477         PIPE_CONF_CHECK_BOOL(pch_pfit.force_thru);
12478
12479         if (!adjust) {
12480                 PIPE_CONF_CHECK_I(pipe_src_w);
12481                 PIPE_CONF_CHECK_I(pipe_src_h);
12482
12483                 PIPE_CONF_CHECK_BOOL(pch_pfit.enabled);
12484                 if (current_config->pch_pfit.enabled) {
12485                         PIPE_CONF_CHECK_X(pch_pfit.pos);
12486                         PIPE_CONF_CHECK_X(pch_pfit.size);
12487                 }
12488
12489                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
12490                 PIPE_CONF_CHECK_CLOCK_FUZZY(pixel_rate);
12491
12492                 PIPE_CONF_CHECK_X(gamma_mode);
12493                 if (IS_CHERRYVIEW(dev_priv))
12494                         PIPE_CONF_CHECK_X(cgm_mode);
12495                 else
12496                         PIPE_CONF_CHECK_X(csc_mode);
12497                 PIPE_CONF_CHECK_BOOL(gamma_enable);
12498                 PIPE_CONF_CHECK_BOOL(csc_enable);
12499         }
12500
12501         PIPE_CONF_CHECK_BOOL(double_wide);
12502
12503         PIPE_CONF_CHECK_P(shared_dpll);
12504         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
12505         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
12506         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
12507         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
12508         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
12509         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
12510         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
12511         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
12512         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
12513         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr0);
12514         PIPE_CONF_CHECK_X(dpll_hw_state.ebb0);
12515         PIPE_CONF_CHECK_X(dpll_hw_state.ebb4);
12516         PIPE_CONF_CHECK_X(dpll_hw_state.pll0);
12517         PIPE_CONF_CHECK_X(dpll_hw_state.pll1);
12518         PIPE_CONF_CHECK_X(dpll_hw_state.pll2);
12519         PIPE_CONF_CHECK_X(dpll_hw_state.pll3);
12520         PIPE_CONF_CHECK_X(dpll_hw_state.pll6);
12521         PIPE_CONF_CHECK_X(dpll_hw_state.pll8);
12522         PIPE_CONF_CHECK_X(dpll_hw_state.pll9);
12523         PIPE_CONF_CHECK_X(dpll_hw_state.pll10);
12524         PIPE_CONF_CHECK_X(dpll_hw_state.pcsdw12);
12525         PIPE_CONF_CHECK_X(dpll_hw_state.mg_refclkin_ctl);
12526         PIPE_CONF_CHECK_X(dpll_hw_state.mg_clktop2_coreclkctl1);
12527         PIPE_CONF_CHECK_X(dpll_hw_state.mg_clktop2_hsclkctl);
12528         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_div0);
12529         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_div1);
12530         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_lf);
12531         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_frac_lock);
12532         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_ssc);
12533         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_bias);
12534         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_tdc_coldst_bias);
12535
12536         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
12537         PIPE_CONF_CHECK_X(dsi_pll.div);
12538
12539         if (IS_G4X(dev_priv) || INTEL_GEN(dev_priv) >= 5)
12540                 PIPE_CONF_CHECK_I(pipe_bpp);
12541
12542         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
12543         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
12544
12545         PIPE_CONF_CHECK_I(min_voltage_level);
12546
12547         PIPE_CONF_CHECK_X(infoframes.enable);
12548         PIPE_CONF_CHECK_X(infoframes.gcp);
12549         PIPE_CONF_CHECK_INFOFRAME(avi);
12550         PIPE_CONF_CHECK_INFOFRAME(spd);
12551         PIPE_CONF_CHECK_INFOFRAME(hdmi);
12552
12553 #undef PIPE_CONF_CHECK_X
12554 #undef PIPE_CONF_CHECK_I
12555 #undef PIPE_CONF_CHECK_BOOL
12556 #undef PIPE_CONF_CHECK_BOOL_INCOMPLETE
12557 #undef PIPE_CONF_CHECK_P
12558 #undef PIPE_CONF_CHECK_FLAGS
12559 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
12560 #undef PIPE_CONF_QUIRK
12561
12562         return ret;
12563 }
12564
12565 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
12566                                            const struct intel_crtc_state *pipe_config)
12567 {
12568         if (pipe_config->has_pch_encoder) {
12569                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
12570                                                             &pipe_config->fdi_m_n);
12571                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
12572
12573                 /*
12574                  * FDI already provided one idea for the dotclock.
12575                  * Yell if the encoder disagrees.
12576                  */
12577                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
12578                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
12579                      fdi_dotclock, dotclock);
12580         }
12581 }
12582
12583 static void verify_wm_state(struct drm_crtc *crtc,
12584                             struct drm_crtc_state *new_state)
12585 {
12586         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
12587         struct skl_hw_state {
12588                 struct skl_ddb_entry ddb_y[I915_MAX_PLANES];
12589                 struct skl_ddb_entry ddb_uv[I915_MAX_PLANES];
12590                 struct skl_ddb_allocation ddb;
12591                 struct skl_pipe_wm wm;
12592         } *hw;
12593         struct skl_ddb_allocation *sw_ddb;
12594         struct skl_pipe_wm *sw_wm;
12595         struct skl_ddb_entry *hw_ddb_entry, *sw_ddb_entry;
12596         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12597         const enum pipe pipe = intel_crtc->pipe;
12598         int plane, level, max_level = ilk_wm_max_level(dev_priv);
12599
12600         if (INTEL_GEN(dev_priv) < 9 || !new_state->active)
12601                 return;
12602
12603         hw = kzalloc(sizeof(*hw), GFP_KERNEL);
12604         if (!hw)
12605                 return;
12606
12607         skl_pipe_wm_get_hw_state(intel_crtc, &hw->wm);
12608         sw_wm = &to_intel_crtc_state(new_state)->wm.skl.optimal;
12609
12610         skl_pipe_ddb_get_hw_state(intel_crtc, hw->ddb_y, hw->ddb_uv);
12611
12612         skl_ddb_get_hw_state(dev_priv, &hw->ddb);
12613         sw_ddb = &dev_priv->wm.skl_hw.ddb;
12614
12615         if (INTEL_GEN(dev_priv) >= 11 &&
12616             hw->ddb.enabled_slices != sw_ddb->enabled_slices)
12617                 DRM_ERROR("mismatch in DBUF Slices (expected %u, got %u)\n",
12618                           sw_ddb->enabled_slices,
12619                           hw->ddb.enabled_slices);
12620
12621         /* planes */
12622         for_each_universal_plane(dev_priv, pipe, plane) {
12623                 struct skl_plane_wm *hw_plane_wm, *sw_plane_wm;
12624
12625                 hw_plane_wm = &hw->wm.planes[plane];
12626                 sw_plane_wm = &sw_wm->planes[plane];
12627
12628                 /* Watermarks */
12629                 for (level = 0; level <= max_level; level++) {
12630                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
12631                                                 &sw_plane_wm->wm[level]))
12632                                 continue;
12633
12634                         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",
12635                                   pipe_name(pipe), plane + 1, level,
12636                                   sw_plane_wm->wm[level].plane_en,
12637                                   sw_plane_wm->wm[level].plane_res_b,
12638                                   sw_plane_wm->wm[level].plane_res_l,
12639                                   hw_plane_wm->wm[level].plane_en,
12640                                   hw_plane_wm->wm[level].plane_res_b,
12641                                   hw_plane_wm->wm[level].plane_res_l);
12642                 }
12643
12644                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
12645                                          &sw_plane_wm->trans_wm)) {
12646                         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",
12647                                   pipe_name(pipe), plane + 1,
12648                                   sw_plane_wm->trans_wm.plane_en,
12649                                   sw_plane_wm->trans_wm.plane_res_b,
12650                                   sw_plane_wm->trans_wm.plane_res_l,
12651                                   hw_plane_wm->trans_wm.plane_en,
12652                                   hw_plane_wm->trans_wm.plane_res_b,
12653                                   hw_plane_wm->trans_wm.plane_res_l);
12654                 }
12655
12656                 /* DDB */
12657                 hw_ddb_entry = &hw->ddb_y[plane];
12658                 sw_ddb_entry = &to_intel_crtc_state(new_state)->wm.skl.plane_ddb_y[plane];
12659
12660                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
12661                         DRM_ERROR("mismatch in DDB state pipe %c plane %d (expected (%u,%u), found (%u,%u))\n",
12662                                   pipe_name(pipe), plane + 1,
12663                                   sw_ddb_entry->start, sw_ddb_entry->end,
12664                                   hw_ddb_entry->start, hw_ddb_entry->end);
12665                 }
12666         }
12667
12668         /*
12669          * cursor
12670          * If the cursor plane isn't active, we may not have updated it's ddb
12671          * allocation. In that case since the ddb allocation will be updated
12672          * once the plane becomes visible, we can skip this check
12673          */
12674         if (1) {
12675                 struct skl_plane_wm *hw_plane_wm, *sw_plane_wm;
12676
12677                 hw_plane_wm = &hw->wm.planes[PLANE_CURSOR];
12678                 sw_plane_wm = &sw_wm->planes[PLANE_CURSOR];
12679
12680                 /* Watermarks */
12681                 for (level = 0; level <= max_level; level++) {
12682                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
12683                                                 &sw_plane_wm->wm[level]))
12684                                 continue;
12685
12686                         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",
12687                                   pipe_name(pipe), level,
12688                                   sw_plane_wm->wm[level].plane_en,
12689                                   sw_plane_wm->wm[level].plane_res_b,
12690                                   sw_plane_wm->wm[level].plane_res_l,
12691                                   hw_plane_wm->wm[level].plane_en,
12692                                   hw_plane_wm->wm[level].plane_res_b,
12693                                   hw_plane_wm->wm[level].plane_res_l);
12694                 }
12695
12696                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
12697                                          &sw_plane_wm->trans_wm)) {
12698                         DRM_ERROR("mismatch in trans WM pipe %c cursor (expected e=%d b=%u l=%u, got e=%d b=%u l=%u)\n",
12699                                   pipe_name(pipe),
12700                                   sw_plane_wm->trans_wm.plane_en,
12701                                   sw_plane_wm->trans_wm.plane_res_b,
12702                                   sw_plane_wm->trans_wm.plane_res_l,
12703                                   hw_plane_wm->trans_wm.plane_en,
12704                                   hw_plane_wm->trans_wm.plane_res_b,
12705                                   hw_plane_wm->trans_wm.plane_res_l);
12706                 }
12707
12708                 /* DDB */
12709                 hw_ddb_entry = &hw->ddb_y[PLANE_CURSOR];
12710                 sw_ddb_entry = &to_intel_crtc_state(new_state)->wm.skl.plane_ddb_y[PLANE_CURSOR];
12711
12712                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
12713                         DRM_ERROR("mismatch in DDB state pipe %c cursor (expected (%u,%u), found (%u,%u))\n",
12714                                   pipe_name(pipe),
12715                                   sw_ddb_entry->start, sw_ddb_entry->end,
12716                                   hw_ddb_entry->start, hw_ddb_entry->end);
12717                 }
12718         }
12719
12720         kfree(hw);
12721 }
12722
12723 static void
12724 verify_connector_state(struct drm_device *dev,
12725                        struct drm_atomic_state *state,
12726                        struct drm_crtc *crtc)
12727 {
12728         struct drm_connector *connector;
12729         struct drm_connector_state *new_conn_state;
12730         int i;
12731
12732         for_each_new_connector_in_state(state, connector, new_conn_state, i) {
12733                 struct drm_encoder *encoder = connector->encoder;
12734                 struct drm_crtc_state *crtc_state = NULL;
12735
12736                 if (new_conn_state->crtc != crtc)
12737                         continue;
12738
12739                 if (crtc)
12740                         crtc_state = drm_atomic_get_new_crtc_state(state, new_conn_state->crtc);
12741
12742                 intel_connector_verify_state(crtc_state, new_conn_state);
12743
12744                 I915_STATE_WARN(new_conn_state->best_encoder != encoder,
12745                      "connector's atomic encoder doesn't match legacy encoder\n");
12746         }
12747 }
12748
12749 static void
12750 verify_encoder_state(struct drm_device *dev, struct drm_atomic_state *state)
12751 {
12752         struct intel_encoder *encoder;
12753         struct drm_connector *connector;
12754         struct drm_connector_state *old_conn_state, *new_conn_state;
12755         int i;
12756
12757         for_each_intel_encoder(dev, encoder) {
12758                 bool enabled = false, found = false;
12759                 enum pipe pipe;
12760
12761                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
12762                               encoder->base.base.id,
12763                               encoder->base.name);
12764
12765                 for_each_oldnew_connector_in_state(state, connector, old_conn_state,
12766                                                    new_conn_state, i) {
12767                         if (old_conn_state->best_encoder == &encoder->base)
12768                                 found = true;
12769
12770                         if (new_conn_state->best_encoder != &encoder->base)
12771                                 continue;
12772                         found = enabled = true;
12773
12774                         I915_STATE_WARN(new_conn_state->crtc !=
12775                                         encoder->base.crtc,
12776                              "connector's crtc doesn't match encoder crtc\n");
12777                 }
12778
12779                 if (!found)
12780                         continue;
12781
12782                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
12783                      "encoder's enabled state mismatch "
12784                      "(expected %i, found %i)\n",
12785                      !!encoder->base.crtc, enabled);
12786
12787                 if (!encoder->base.crtc) {
12788                         bool active;
12789
12790                         active = encoder->get_hw_state(encoder, &pipe);
12791                         I915_STATE_WARN(active,
12792                              "encoder detached but still enabled on pipe %c.\n",
12793                              pipe_name(pipe));
12794                 }
12795         }
12796 }
12797
12798 static void
12799 verify_crtc_state(struct drm_crtc *crtc,
12800                   struct drm_crtc_state *old_crtc_state,
12801                   struct drm_crtc_state *new_crtc_state)
12802 {
12803         struct drm_device *dev = crtc->dev;
12804         struct drm_i915_private *dev_priv = to_i915(dev);
12805         struct intel_encoder *encoder;
12806         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12807         struct intel_crtc_state *pipe_config, *sw_config;
12808         struct drm_atomic_state *old_state;
12809         bool active;
12810
12811         old_state = old_crtc_state->state;
12812         __drm_atomic_helper_crtc_destroy_state(old_crtc_state);
12813         pipe_config = to_intel_crtc_state(old_crtc_state);
12814         memset(pipe_config, 0, sizeof(*pipe_config));
12815         pipe_config->base.crtc = crtc;
12816         pipe_config->base.state = old_state;
12817
12818         DRM_DEBUG_KMS("[CRTC:%d:%s]\n", crtc->base.id, crtc->name);
12819
12820         active = dev_priv->display.get_pipe_config(intel_crtc, pipe_config);
12821
12822         /* we keep both pipes enabled on 830 */
12823         if (IS_I830(dev_priv))
12824                 active = new_crtc_state->active;
12825
12826         I915_STATE_WARN(new_crtc_state->active != active,
12827              "crtc active state doesn't match with hw state "
12828              "(expected %i, found %i)\n", new_crtc_state->active, active);
12829
12830         I915_STATE_WARN(intel_crtc->active != new_crtc_state->active,
12831              "transitional active state does not match atomic hw state "
12832              "(expected %i, found %i)\n", new_crtc_state->active, intel_crtc->active);
12833
12834         for_each_encoder_on_crtc(dev, crtc, encoder) {
12835                 enum pipe pipe;
12836
12837                 active = encoder->get_hw_state(encoder, &pipe);
12838                 I915_STATE_WARN(active != new_crtc_state->active,
12839                         "[ENCODER:%i] active %i with crtc active %i\n",
12840                         encoder->base.base.id, active, new_crtc_state->active);
12841
12842                 I915_STATE_WARN(active && intel_crtc->pipe != pipe,
12843                                 "Encoder connected to wrong pipe %c\n",
12844                                 pipe_name(pipe));
12845
12846                 if (active)
12847                         encoder->get_config(encoder, pipe_config);
12848         }
12849
12850         intel_crtc_compute_pixel_rate(pipe_config);
12851
12852         if (!new_crtc_state->active)
12853                 return;
12854
12855         intel_pipe_config_sanity_check(dev_priv, pipe_config);
12856
12857         sw_config = to_intel_crtc_state(new_crtc_state);
12858         if (!intel_pipe_config_compare(dev_priv, sw_config,
12859                                        pipe_config, false)) {
12860                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
12861                 intel_dump_pipe_config(intel_crtc, pipe_config,
12862                                        "[hw state]");
12863                 intel_dump_pipe_config(intel_crtc, sw_config,
12864                                        "[sw state]");
12865         }
12866 }
12867
12868 static void
12869 intel_verify_planes(struct intel_atomic_state *state)
12870 {
12871         struct intel_plane *plane;
12872         const struct intel_plane_state *plane_state;
12873         int i;
12874
12875         for_each_new_intel_plane_in_state(state, plane,
12876                                           plane_state, i)
12877                 assert_plane(plane, plane_state->slave ||
12878                              plane_state->base.visible);
12879 }
12880
12881 static void
12882 verify_single_dpll_state(struct drm_i915_private *dev_priv,
12883                          struct intel_shared_dpll *pll,
12884                          struct drm_crtc *crtc,
12885                          struct drm_crtc_state *new_state)
12886 {
12887         struct intel_dpll_hw_state dpll_hw_state;
12888         unsigned int crtc_mask;
12889         bool active;
12890
12891         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
12892
12893         DRM_DEBUG_KMS("%s\n", pll->info->name);
12894
12895         active = pll->info->funcs->get_hw_state(dev_priv, pll, &dpll_hw_state);
12896
12897         if (!(pll->info->flags & INTEL_DPLL_ALWAYS_ON)) {
12898                 I915_STATE_WARN(!pll->on && pll->active_mask,
12899                      "pll in active use but not on in sw tracking\n");
12900                 I915_STATE_WARN(pll->on && !pll->active_mask,
12901                      "pll is on but not used by any active crtc\n");
12902                 I915_STATE_WARN(pll->on != active,
12903                      "pll on state mismatch (expected %i, found %i)\n",
12904                      pll->on, active);
12905         }
12906
12907         if (!crtc) {
12908                 I915_STATE_WARN(pll->active_mask & ~pll->state.crtc_mask,
12909                                 "more active pll users than references: %x vs %x\n",
12910                                 pll->active_mask, pll->state.crtc_mask);
12911
12912                 return;
12913         }
12914
12915         crtc_mask = drm_crtc_mask(crtc);
12916
12917         if (new_state->active)
12918                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
12919                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
12920                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
12921         else
12922                 I915_STATE_WARN(pll->active_mask & crtc_mask,
12923                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
12924                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
12925
12926         I915_STATE_WARN(!(pll->state.crtc_mask & crtc_mask),
12927                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
12928                         crtc_mask, pll->state.crtc_mask);
12929
12930         I915_STATE_WARN(pll->on && memcmp(&pll->state.hw_state,
12931                                           &dpll_hw_state,
12932                                           sizeof(dpll_hw_state)),
12933                         "pll hw state mismatch\n");
12934 }
12935
12936 static void
12937 verify_shared_dpll_state(struct drm_device *dev, struct drm_crtc *crtc,
12938                          struct drm_crtc_state *old_crtc_state,
12939                          struct drm_crtc_state *new_crtc_state)
12940 {
12941         struct drm_i915_private *dev_priv = to_i915(dev);
12942         struct intel_crtc_state *old_state = to_intel_crtc_state(old_crtc_state);
12943         struct intel_crtc_state *new_state = to_intel_crtc_state(new_crtc_state);
12944
12945         if (new_state->shared_dpll)
12946                 verify_single_dpll_state(dev_priv, new_state->shared_dpll, crtc, new_crtc_state);
12947
12948         if (old_state->shared_dpll &&
12949             old_state->shared_dpll != new_state->shared_dpll) {
12950                 unsigned int crtc_mask = drm_crtc_mask(crtc);
12951                 struct intel_shared_dpll *pll = old_state->shared_dpll;
12952
12953                 I915_STATE_WARN(pll->active_mask & crtc_mask,
12954                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
12955                                 pipe_name(drm_crtc_index(crtc)));
12956                 I915_STATE_WARN(pll->state.crtc_mask & crtc_mask,
12957                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
12958                                 pipe_name(drm_crtc_index(crtc)));
12959         }
12960 }
12961
12962 static void
12963 intel_modeset_verify_crtc(struct drm_crtc *crtc,
12964                           struct drm_atomic_state *state,
12965                           struct drm_crtc_state *old_state,
12966                           struct drm_crtc_state *new_state)
12967 {
12968         if (!needs_modeset(new_state) &&
12969             !to_intel_crtc_state(new_state)->update_pipe)
12970                 return;
12971
12972         verify_wm_state(crtc, new_state);
12973         verify_connector_state(crtc->dev, state, crtc);
12974         verify_crtc_state(crtc, old_state, new_state);
12975         verify_shared_dpll_state(crtc->dev, crtc, old_state, new_state);
12976 }
12977
12978 static void
12979 verify_disabled_dpll_state(struct drm_device *dev)
12980 {
12981         struct drm_i915_private *dev_priv = to_i915(dev);
12982         int i;
12983
12984         for (i = 0; i < dev_priv->num_shared_dpll; i++)
12985                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
12986 }
12987
12988 static void
12989 intel_modeset_verify_disabled(struct drm_device *dev,
12990                               struct drm_atomic_state *state)
12991 {
12992         verify_encoder_state(dev, state);
12993         verify_connector_state(dev, state, NULL);
12994         verify_disabled_dpll_state(dev);
12995 }
12996
12997 static void update_scanline_offset(const struct intel_crtc_state *crtc_state)
12998 {
12999         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
13000         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13001
13002         /*
13003          * The scanline counter increments at the leading edge of hsync.
13004          *
13005          * On most platforms it starts counting from vtotal-1 on the
13006          * first active line. That means the scanline counter value is
13007          * always one less than what we would expect. Ie. just after
13008          * start of vblank, which also occurs at start of hsync (on the
13009          * last active line), the scanline counter will read vblank_start-1.
13010          *
13011          * On gen2 the scanline counter starts counting from 1 instead
13012          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
13013          * to keep the value positive), instead of adding one.
13014          *
13015          * On HSW+ the behaviour of the scanline counter depends on the output
13016          * type. For DP ports it behaves like most other platforms, but on HDMI
13017          * there's an extra 1 line difference. So we need to add two instead of
13018          * one to the value.
13019          *
13020          * On VLV/CHV DSI the scanline counter would appear to increment
13021          * approx. 1/3 of a scanline before start of vblank. Unfortunately
13022          * that means we can't tell whether we're in vblank or not while
13023          * we're on that particular line. We must still set scanline_offset
13024          * to 1 so that the vblank timestamps come out correct when we query
13025          * the scanline counter from within the vblank interrupt handler.
13026          * However if queried just before the start of vblank we'll get an
13027          * answer that's slightly in the future.
13028          */
13029         if (IS_GEN(dev_priv, 2)) {
13030                 const struct drm_display_mode *adjusted_mode = &crtc_state->base.adjusted_mode;
13031                 int vtotal;
13032
13033                 vtotal = adjusted_mode->crtc_vtotal;
13034                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
13035                         vtotal /= 2;
13036
13037                 crtc->scanline_offset = vtotal - 1;
13038         } else if (HAS_DDI(dev_priv) &&
13039                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI)) {
13040                 crtc->scanline_offset = 2;
13041         } else
13042                 crtc->scanline_offset = 1;
13043 }
13044
13045 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
13046 {
13047         struct drm_device *dev = state->dev;
13048         struct drm_i915_private *dev_priv = to_i915(dev);
13049         struct drm_crtc *crtc;
13050         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
13051         int i;
13052
13053         if (!dev_priv->display.crtc_compute_clock)
13054                 return;
13055
13056         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13057                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13058                 struct intel_shared_dpll *old_dpll =
13059                         to_intel_crtc_state(old_crtc_state)->shared_dpll;
13060
13061                 if (!needs_modeset(new_crtc_state))
13062                         continue;
13063
13064                 to_intel_crtc_state(new_crtc_state)->shared_dpll = NULL;
13065
13066                 if (!old_dpll)
13067                         continue;
13068
13069                 intel_release_shared_dpll(old_dpll, intel_crtc, state);
13070         }
13071 }
13072
13073 /*
13074  * This implements the workaround described in the "notes" section of the mode
13075  * set sequence documentation. When going from no pipes or single pipe to
13076  * multiple pipes, and planes are enabled after the pipe, we need to wait at
13077  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
13078  */
13079 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
13080 {
13081         struct drm_crtc_state *crtc_state;
13082         struct intel_crtc *intel_crtc;
13083         struct drm_crtc *crtc;
13084         struct intel_crtc_state *first_crtc_state = NULL;
13085         struct intel_crtc_state *other_crtc_state = NULL;
13086         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
13087         int i;
13088
13089         /* look at all crtc's that are going to be enabled in during modeset */
13090         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
13091                 intel_crtc = to_intel_crtc(crtc);
13092
13093                 if (!crtc_state->active || !needs_modeset(crtc_state))
13094                         continue;
13095
13096                 if (first_crtc_state) {
13097                         other_crtc_state = to_intel_crtc_state(crtc_state);
13098                         break;
13099                 } else {
13100                         first_crtc_state = to_intel_crtc_state(crtc_state);
13101                         first_pipe = intel_crtc->pipe;
13102                 }
13103         }
13104
13105         /* No workaround needed? */
13106         if (!first_crtc_state)
13107                 return 0;
13108
13109         /* w/a possibly needed, check how many crtc's are already enabled. */
13110         for_each_intel_crtc(state->dev, intel_crtc) {
13111                 struct intel_crtc_state *pipe_config;
13112
13113                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
13114                 if (IS_ERR(pipe_config))
13115                         return PTR_ERR(pipe_config);
13116
13117                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
13118
13119                 if (!pipe_config->base.active ||
13120                     needs_modeset(&pipe_config->base))
13121                         continue;
13122
13123                 /* 2 or more enabled crtcs means no need for w/a */
13124                 if (enabled_pipe != INVALID_PIPE)
13125                         return 0;
13126
13127                 enabled_pipe = intel_crtc->pipe;
13128         }
13129
13130         if (enabled_pipe != INVALID_PIPE)
13131                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
13132         else if (other_crtc_state)
13133                 other_crtc_state->hsw_workaround_pipe = first_pipe;
13134
13135         return 0;
13136 }
13137
13138 static int intel_lock_all_pipes(struct drm_atomic_state *state)
13139 {
13140         struct drm_crtc *crtc;
13141
13142         /* Add all pipes to the state */
13143         for_each_crtc(state->dev, crtc) {
13144                 struct drm_crtc_state *crtc_state;
13145
13146                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
13147                 if (IS_ERR(crtc_state))
13148                         return PTR_ERR(crtc_state);
13149         }
13150
13151         return 0;
13152 }
13153
13154 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
13155 {
13156         struct drm_crtc *crtc;
13157
13158         /*
13159          * Add all pipes to the state, and force
13160          * a modeset on all the active ones.
13161          */
13162         for_each_crtc(state->dev, crtc) {
13163                 struct drm_crtc_state *crtc_state;
13164                 int ret;
13165
13166                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
13167                 if (IS_ERR(crtc_state))
13168                         return PTR_ERR(crtc_state);
13169
13170                 if (!crtc_state->active || needs_modeset(crtc_state))
13171                         continue;
13172
13173                 crtc_state->mode_changed = true;
13174
13175                 ret = drm_atomic_add_affected_connectors(state, crtc);
13176                 if (ret)
13177                         return ret;
13178
13179                 ret = drm_atomic_add_affected_planes(state, crtc);
13180                 if (ret)
13181                         return ret;
13182         }
13183
13184         return 0;
13185 }
13186
13187 static int intel_modeset_checks(struct drm_atomic_state *state)
13188 {
13189         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13190         struct drm_i915_private *dev_priv = to_i915(state->dev);
13191         struct drm_crtc *crtc;
13192         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
13193         int ret = 0, i;
13194
13195         if (!check_digital_port_conflicts(state)) {
13196                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
13197                 return -EINVAL;
13198         }
13199
13200         /* keep the current setting */
13201         if (!intel_state->cdclk.force_min_cdclk_changed)
13202                 intel_state->cdclk.force_min_cdclk =
13203                         dev_priv->cdclk.force_min_cdclk;
13204
13205         intel_state->modeset = true;
13206         intel_state->active_crtcs = dev_priv->active_crtcs;
13207         intel_state->cdclk.logical = dev_priv->cdclk.logical;
13208         intel_state->cdclk.actual = dev_priv->cdclk.actual;
13209         intel_state->cdclk.pipe = INVALID_PIPE;
13210
13211         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13212                 if (new_crtc_state->active)
13213                         intel_state->active_crtcs |= 1 << i;
13214                 else
13215                         intel_state->active_crtcs &= ~(1 << i);
13216
13217                 if (old_crtc_state->active != new_crtc_state->active)
13218                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
13219         }
13220
13221         /*
13222          * See if the config requires any additional preparation, e.g.
13223          * to adjust global state with pipes off.  We need to do this
13224          * here so we can get the modeset_pipe updated config for the new
13225          * mode set on this crtc.  For other crtcs we need to use the
13226          * adjusted_mode bits in the crtc directly.
13227          */
13228         if (dev_priv->display.modeset_calc_cdclk) {
13229                 enum pipe pipe;
13230
13231                 ret = dev_priv->display.modeset_calc_cdclk(state);
13232                 if (ret < 0)
13233                         return ret;
13234
13235                 /*
13236                  * Writes to dev_priv->cdclk.logical must protected by
13237                  * holding all the crtc locks, even if we don't end up
13238                  * touching the hardware
13239                  */
13240                 if (intel_cdclk_changed(&dev_priv->cdclk.logical,
13241                                         &intel_state->cdclk.logical)) {
13242                         ret = intel_lock_all_pipes(state);
13243                         if (ret < 0)
13244                                 return ret;
13245                 }
13246
13247                 if (is_power_of_2(intel_state->active_crtcs)) {
13248                         struct drm_crtc *crtc;
13249                         struct drm_crtc_state *crtc_state;
13250
13251                         pipe = ilog2(intel_state->active_crtcs);
13252                         crtc = &intel_get_crtc_for_pipe(dev_priv, pipe)->base;
13253                         crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
13254                         if (crtc_state && needs_modeset(crtc_state))
13255                                 pipe = INVALID_PIPE;
13256                 } else {
13257                         pipe = INVALID_PIPE;
13258                 }
13259
13260                 /* All pipes must be switched off while we change the cdclk. */
13261                 if (pipe != INVALID_PIPE &&
13262                     intel_cdclk_needs_cd2x_update(dev_priv,
13263                                                   &dev_priv->cdclk.actual,
13264                                                   &intel_state->cdclk.actual)) {
13265                         ret = intel_lock_all_pipes(state);
13266                         if (ret < 0)
13267                                 return ret;
13268
13269                         intel_state->cdclk.pipe = pipe;
13270                 } else if (intel_cdclk_needs_modeset(&dev_priv->cdclk.actual,
13271                                                      &intel_state->cdclk.actual)) {
13272                         ret = intel_modeset_all_pipes(state);
13273                         if (ret < 0)
13274                                 return ret;
13275
13276                         intel_state->cdclk.pipe = INVALID_PIPE;
13277                 }
13278
13279                 DRM_DEBUG_KMS("New cdclk calculated to be logical %u kHz, actual %u kHz\n",
13280                               intel_state->cdclk.logical.cdclk,
13281                               intel_state->cdclk.actual.cdclk);
13282                 DRM_DEBUG_KMS("New voltage level calculated to be logical %u, actual %u\n",
13283                               intel_state->cdclk.logical.voltage_level,
13284                               intel_state->cdclk.actual.voltage_level);
13285         }
13286
13287         intel_modeset_clear_plls(state);
13288
13289         if (IS_HASWELL(dev_priv))
13290                 return haswell_mode_set_planes_workaround(state);
13291
13292         return 0;
13293 }
13294
13295 /*
13296  * Handle calculation of various watermark data at the end of the atomic check
13297  * phase.  The code here should be run after the per-crtc and per-plane 'check'
13298  * handlers to ensure that all derived state has been updated.
13299  */
13300 static int calc_watermark_data(struct intel_atomic_state *state)
13301 {
13302         struct drm_device *dev = state->base.dev;
13303         struct drm_i915_private *dev_priv = to_i915(dev);
13304
13305         /* Is there platform-specific watermark information to calculate? */
13306         if (dev_priv->display.compute_global_watermarks)
13307                 return dev_priv->display.compute_global_watermarks(state);
13308
13309         return 0;
13310 }
13311
13312 /**
13313  * intel_atomic_check - validate state object
13314  * @dev: drm device
13315  * @state: state to validate
13316  */
13317 static int intel_atomic_check(struct drm_device *dev,
13318                               struct drm_atomic_state *state)
13319 {
13320         struct drm_i915_private *dev_priv = to_i915(dev);
13321         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13322         struct drm_crtc *crtc;
13323         struct drm_crtc_state *old_crtc_state, *crtc_state;
13324         int ret, i;
13325         bool any_ms = intel_state->cdclk.force_min_cdclk_changed;
13326
13327         /* Catch I915_MODE_FLAG_INHERITED */
13328         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
13329                                       crtc_state, i) {
13330                 if (crtc_state->mode.private_flags !=
13331                     old_crtc_state->mode.private_flags)
13332                         crtc_state->mode_changed = true;
13333         }
13334
13335         ret = drm_atomic_helper_check_modeset(dev, state);
13336         if (ret)
13337                 return ret;
13338
13339         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, crtc_state, i) {
13340                 struct intel_crtc_state *pipe_config =
13341                         to_intel_crtc_state(crtc_state);
13342
13343                 if (!needs_modeset(crtc_state))
13344                         continue;
13345
13346                 if (!crtc_state->enable) {
13347                         any_ms = true;
13348                         continue;
13349                 }
13350
13351                 ret = intel_modeset_pipe_config(crtc, pipe_config);
13352                 if (ret == -EDEADLK)
13353                         return ret;
13354                 if (ret) {
13355                         intel_dump_pipe_config(to_intel_crtc(crtc),
13356                                                pipe_config, "[failed]");
13357                         return ret;
13358                 }
13359
13360                 if (intel_pipe_config_compare(dev_priv,
13361                                         to_intel_crtc_state(old_crtc_state),
13362                                         pipe_config, true)) {
13363                         crtc_state->mode_changed = false;
13364                         pipe_config->update_pipe = true;
13365                 }
13366
13367                 if (needs_modeset(crtc_state))
13368                         any_ms = true;
13369
13370                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
13371                                        needs_modeset(crtc_state) ?
13372                                        "[modeset]" : "[fastset]");
13373         }
13374
13375         ret = drm_dp_mst_atomic_check(state);
13376         if (ret)
13377                 return ret;
13378
13379         if (any_ms) {
13380                 ret = intel_modeset_checks(state);
13381
13382                 if (ret)
13383                         return ret;
13384         } else {
13385                 intel_state->cdclk.logical = dev_priv->cdclk.logical;
13386         }
13387
13388         ret = icl_add_linked_planes(intel_state);
13389         if (ret)
13390                 return ret;
13391
13392         ret = drm_atomic_helper_check_planes(dev, state);
13393         if (ret)
13394                 return ret;
13395
13396         intel_fbc_choose_crtc(dev_priv, intel_state);
13397         return calc_watermark_data(intel_state);
13398 }
13399
13400 static int intel_atomic_prepare_commit(struct drm_device *dev,
13401                                        struct drm_atomic_state *state)
13402 {
13403         return drm_atomic_helper_prepare_planes(dev, state);
13404 }
13405
13406 u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc)
13407 {
13408         struct drm_device *dev = crtc->base.dev;
13409         struct drm_vblank_crtc *vblank = &dev->vblank[drm_crtc_index(&crtc->base)];
13410
13411         if (!vblank->max_vblank_count)
13412                 return (u32)drm_crtc_accurate_vblank_count(&crtc->base);
13413
13414         return dev->driver->get_vblank_counter(dev, crtc->pipe);
13415 }
13416
13417 static void intel_update_crtc(struct drm_crtc *crtc,
13418                               struct drm_atomic_state *state,
13419                               struct drm_crtc_state *old_crtc_state,
13420                               struct drm_crtc_state *new_crtc_state)
13421 {
13422         struct drm_device *dev = crtc->dev;
13423         struct drm_i915_private *dev_priv = to_i915(dev);
13424         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13425         struct intel_crtc_state *pipe_config = to_intel_crtc_state(new_crtc_state);
13426         bool modeset = needs_modeset(new_crtc_state);
13427         struct intel_plane_state *new_plane_state =
13428                 intel_atomic_get_new_plane_state(to_intel_atomic_state(state),
13429                                                  to_intel_plane(crtc->primary));
13430
13431         if (modeset) {
13432                 update_scanline_offset(pipe_config);
13433                 dev_priv->display.crtc_enable(pipe_config, state);
13434
13435                 /* vblanks work again, re-enable pipe CRC. */
13436                 intel_crtc_enable_pipe_crc(intel_crtc);
13437         } else {
13438                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
13439                                        pipe_config);
13440
13441                 if (pipe_config->update_pipe)
13442                         intel_encoders_update_pipe(crtc, pipe_config, state);
13443         }
13444
13445         if (pipe_config->update_pipe && !pipe_config->enable_fbc)
13446                 intel_fbc_disable(intel_crtc);
13447         else if (new_plane_state)
13448                 intel_fbc_enable(intel_crtc, pipe_config, new_plane_state);
13449
13450         intel_begin_crtc_commit(to_intel_atomic_state(state), intel_crtc);
13451
13452         if (INTEL_GEN(dev_priv) >= 9)
13453                 skl_update_planes_on_crtc(to_intel_atomic_state(state), intel_crtc);
13454         else
13455                 i9xx_update_planes_on_crtc(to_intel_atomic_state(state), intel_crtc);
13456
13457         intel_finish_crtc_commit(to_intel_atomic_state(state), intel_crtc);
13458 }
13459
13460 static void intel_update_crtcs(struct drm_atomic_state *state)
13461 {
13462         struct drm_crtc *crtc;
13463         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
13464         int i;
13465
13466         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13467                 if (!new_crtc_state->active)
13468                         continue;
13469
13470                 intel_update_crtc(crtc, state, old_crtc_state,
13471                                   new_crtc_state);
13472         }
13473 }
13474
13475 static void skl_update_crtcs(struct drm_atomic_state *state)
13476 {
13477         struct drm_i915_private *dev_priv = to_i915(state->dev);
13478         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13479         struct drm_crtc *crtc;
13480         struct intel_crtc *intel_crtc;
13481         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
13482         struct intel_crtc_state *cstate;
13483         unsigned int updated = 0;
13484         bool progress;
13485         enum pipe pipe;
13486         int i;
13487         u8 hw_enabled_slices = dev_priv->wm.skl_hw.ddb.enabled_slices;
13488         u8 required_slices = intel_state->wm_results.ddb.enabled_slices;
13489         struct skl_ddb_entry entries[I915_MAX_PIPES] = {};
13490
13491         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i)
13492                 /* ignore allocations for crtc's that have been turned off. */
13493                 if (new_crtc_state->active)
13494                         entries[i] = to_intel_crtc_state(old_crtc_state)->wm.skl.ddb;
13495
13496         /* If 2nd DBuf slice required, enable it here */
13497         if (INTEL_GEN(dev_priv) >= 11 && required_slices > hw_enabled_slices)
13498                 icl_dbuf_slices_update(dev_priv, required_slices);
13499
13500         /*
13501          * Whenever the number of active pipes changes, we need to make sure we
13502          * update the pipes in the right order so that their ddb allocations
13503          * never overlap with eachother inbetween CRTC updates. Otherwise we'll
13504          * cause pipe underruns and other bad stuff.
13505          */
13506         do {
13507                 progress = false;
13508
13509                 for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13510                         bool vbl_wait = false;
13511                         unsigned int cmask = drm_crtc_mask(crtc);
13512
13513                         intel_crtc = to_intel_crtc(crtc);
13514                         cstate = to_intel_crtc_state(new_crtc_state);
13515                         pipe = intel_crtc->pipe;
13516
13517                         if (updated & cmask || !cstate->base.active)
13518                                 continue;
13519
13520                         if (skl_ddb_allocation_overlaps(&cstate->wm.skl.ddb,
13521                                                         entries,
13522                                                         INTEL_INFO(dev_priv)->num_pipes, i))
13523                                 continue;
13524
13525                         updated |= cmask;
13526                         entries[i] = cstate->wm.skl.ddb;
13527
13528                         /*
13529                          * If this is an already active pipe, it's DDB changed,
13530                          * and this isn't the last pipe that needs updating
13531                          * then we need to wait for a vblank to pass for the
13532                          * new ddb allocation to take effect.
13533                          */
13534                         if (!skl_ddb_entry_equal(&cstate->wm.skl.ddb,
13535                                                  &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb) &&
13536                             !new_crtc_state->active_changed &&
13537                             intel_state->wm_results.dirty_pipes != updated)
13538                                 vbl_wait = true;
13539
13540                         intel_update_crtc(crtc, state, old_crtc_state,
13541                                           new_crtc_state);
13542
13543                         if (vbl_wait)
13544                                 intel_wait_for_vblank(dev_priv, pipe);
13545
13546                         progress = true;
13547                 }
13548         } while (progress);
13549
13550         /* If 2nd DBuf slice is no more required disable it */
13551         if (INTEL_GEN(dev_priv) >= 11 && required_slices < hw_enabled_slices)
13552                 icl_dbuf_slices_update(dev_priv, required_slices);
13553 }
13554
13555 static void intel_atomic_helper_free_state(struct drm_i915_private *dev_priv)
13556 {
13557         struct intel_atomic_state *state, *next;
13558         struct llist_node *freed;
13559
13560         freed = llist_del_all(&dev_priv->atomic_helper.free_list);
13561         llist_for_each_entry_safe(state, next, freed, freed)
13562                 drm_atomic_state_put(&state->base);
13563 }
13564
13565 static void intel_atomic_helper_free_state_worker(struct work_struct *work)
13566 {
13567         struct drm_i915_private *dev_priv =
13568                 container_of(work, typeof(*dev_priv), atomic_helper.free_work);
13569
13570         intel_atomic_helper_free_state(dev_priv);
13571 }
13572
13573 static void intel_atomic_commit_fence_wait(struct intel_atomic_state *intel_state)
13574 {
13575         struct wait_queue_entry wait_fence, wait_reset;
13576         struct drm_i915_private *dev_priv = to_i915(intel_state->base.dev);
13577
13578         init_wait_entry(&wait_fence, 0);
13579         init_wait_entry(&wait_reset, 0);
13580         for (;;) {
13581                 prepare_to_wait(&intel_state->commit_ready.wait,
13582                                 &wait_fence, TASK_UNINTERRUPTIBLE);
13583                 prepare_to_wait(&dev_priv->gpu_error.wait_queue,
13584                                 &wait_reset, TASK_UNINTERRUPTIBLE);
13585
13586
13587                 if (i915_sw_fence_done(&intel_state->commit_ready)
13588                     || test_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags))
13589                         break;
13590
13591                 schedule();
13592         }
13593         finish_wait(&intel_state->commit_ready.wait, &wait_fence);
13594         finish_wait(&dev_priv->gpu_error.wait_queue, &wait_reset);
13595 }
13596
13597 static void intel_atomic_cleanup_work(struct work_struct *work)
13598 {
13599         struct drm_atomic_state *state =
13600                 container_of(work, struct drm_atomic_state, commit_work);
13601         struct drm_i915_private *i915 = to_i915(state->dev);
13602
13603         drm_atomic_helper_cleanup_planes(&i915->drm, state);
13604         drm_atomic_helper_commit_cleanup_done(state);
13605         drm_atomic_state_put(state);
13606
13607         intel_atomic_helper_free_state(i915);
13608 }
13609
13610 static void intel_atomic_commit_tail(struct drm_atomic_state *state)
13611 {
13612         struct drm_device *dev = state->dev;
13613         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13614         struct drm_i915_private *dev_priv = to_i915(dev);
13615         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
13616         struct intel_crtc_state *new_intel_crtc_state, *old_intel_crtc_state;
13617         struct drm_crtc *crtc;
13618         struct intel_crtc *intel_crtc;
13619         u64 put_domains[I915_MAX_PIPES] = {};
13620         intel_wakeref_t wakeref = 0;
13621         int i;
13622
13623         intel_atomic_commit_fence_wait(intel_state);
13624
13625         drm_atomic_helper_wait_for_dependencies(state);
13626
13627         if (intel_state->modeset)
13628                 wakeref = intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
13629
13630         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13631                 old_intel_crtc_state = to_intel_crtc_state(old_crtc_state);
13632                 new_intel_crtc_state = to_intel_crtc_state(new_crtc_state);
13633                 intel_crtc = to_intel_crtc(crtc);
13634
13635                 if (needs_modeset(new_crtc_state) ||
13636                     to_intel_crtc_state(new_crtc_state)->update_pipe) {
13637
13638                         put_domains[intel_crtc->pipe] =
13639                                 modeset_get_crtc_power_domains(crtc,
13640                                         new_intel_crtc_state);
13641                 }
13642
13643                 if (!needs_modeset(new_crtc_state))
13644                         continue;
13645
13646                 intel_pre_plane_update(old_intel_crtc_state, new_intel_crtc_state);
13647
13648                 if (old_crtc_state->active) {
13649                         intel_crtc_disable_planes(intel_state, intel_crtc);
13650
13651                         /*
13652                          * We need to disable pipe CRC before disabling the pipe,
13653                          * or we race against vblank off.
13654                          */
13655                         intel_crtc_disable_pipe_crc(intel_crtc);
13656
13657                         dev_priv->display.crtc_disable(old_intel_crtc_state, state);
13658                         intel_crtc->active = false;
13659                         intel_fbc_disable(intel_crtc);
13660                         intel_disable_shared_dpll(old_intel_crtc_state);
13661
13662                         /*
13663                          * Underruns don't always raise
13664                          * interrupts, so check manually.
13665                          */
13666                         intel_check_cpu_fifo_underruns(dev_priv);
13667                         intel_check_pch_fifo_underruns(dev_priv);
13668
13669                         /* FIXME unify this for all platforms */
13670                         if (!new_crtc_state->active &&
13671                             !HAS_GMCH(dev_priv) &&
13672                             dev_priv->display.initial_watermarks)
13673                                 dev_priv->display.initial_watermarks(intel_state,
13674                                                                      new_intel_crtc_state);
13675                 }
13676         }
13677
13678         /* FIXME: Eventually get rid of our intel_crtc->config pointer */
13679         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i)
13680                 to_intel_crtc(crtc)->config = to_intel_crtc_state(new_crtc_state);
13681
13682         if (intel_state->modeset) {
13683                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
13684
13685                 intel_set_cdclk_pre_plane_update(dev_priv,
13686                                                  &intel_state->cdclk.actual,
13687                                                  &dev_priv->cdclk.actual,
13688                                                  intel_state->cdclk.pipe);
13689
13690                 /*
13691                  * SKL workaround: bspec recommends we disable the SAGV when we
13692                  * have more then one pipe enabled
13693                  */
13694                 if (!intel_can_enable_sagv(state))
13695                         intel_disable_sagv(dev_priv);
13696
13697                 intel_modeset_verify_disabled(dev, state);
13698         }
13699
13700         /* Complete the events for pipes that have now been disabled */
13701         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13702                 bool modeset = needs_modeset(new_crtc_state);
13703
13704                 /* Complete events for now disable pipes here. */
13705                 if (modeset && !new_crtc_state->active && new_crtc_state->event) {
13706                         spin_lock_irq(&dev->event_lock);
13707                         drm_crtc_send_vblank_event(crtc, new_crtc_state->event);
13708                         spin_unlock_irq(&dev->event_lock);
13709
13710                         new_crtc_state->event = NULL;
13711                 }
13712         }
13713
13714         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
13715         dev_priv->display.update_crtcs(state);
13716
13717         if (intel_state->modeset)
13718                 intel_set_cdclk_post_plane_update(dev_priv,
13719                                                   &intel_state->cdclk.actual,
13720                                                   &dev_priv->cdclk.actual,
13721                                                   intel_state->cdclk.pipe);
13722
13723         /* FIXME: We should call drm_atomic_helper_commit_hw_done() here
13724          * already, but still need the state for the delayed optimization. To
13725          * fix this:
13726          * - wrap the optimization/post_plane_update stuff into a per-crtc work.
13727          * - schedule that vblank worker _before_ calling hw_done
13728          * - at the start of commit_tail, cancel it _synchrously
13729          * - switch over to the vblank wait helper in the core after that since
13730          *   we don't need out special handling any more.
13731          */
13732         drm_atomic_helper_wait_for_flip_done(dev, state);
13733
13734         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13735                 new_intel_crtc_state = to_intel_crtc_state(new_crtc_state);
13736
13737                 if (new_crtc_state->active &&
13738                     !needs_modeset(new_crtc_state) &&
13739                     (new_intel_crtc_state->base.color_mgmt_changed ||
13740                      new_intel_crtc_state->update_pipe))
13741                         intel_color_load_luts(new_intel_crtc_state);
13742         }
13743
13744         /*
13745          * Now that the vblank has passed, we can go ahead and program the
13746          * optimal watermarks on platforms that need two-step watermark
13747          * programming.
13748          *
13749          * TODO: Move this (and other cleanup) to an async worker eventually.
13750          */
13751         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13752                 new_intel_crtc_state = to_intel_crtc_state(new_crtc_state);
13753
13754                 if (dev_priv->display.optimize_watermarks)
13755                         dev_priv->display.optimize_watermarks(intel_state,
13756                                                               new_intel_crtc_state);
13757         }
13758
13759         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13760                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
13761
13762                 if (put_domains[i])
13763                         modeset_put_power_domains(dev_priv, put_domains[i]);
13764
13765                 intel_modeset_verify_crtc(crtc, state, old_crtc_state, new_crtc_state);
13766         }
13767
13768         if (intel_state->modeset)
13769                 intel_verify_planes(intel_state);
13770
13771         if (intel_state->modeset && intel_can_enable_sagv(state))
13772                 intel_enable_sagv(dev_priv);
13773
13774         drm_atomic_helper_commit_hw_done(state);
13775
13776         if (intel_state->modeset) {
13777                 /* As one of the primary mmio accessors, KMS has a high
13778                  * likelihood of triggering bugs in unclaimed access. After we
13779                  * finish modesetting, see if an error has been flagged, and if
13780                  * so enable debugging for the next modeset - and hope we catch
13781                  * the culprit.
13782                  */
13783                 intel_uncore_arm_unclaimed_mmio_detection(&dev_priv->uncore);
13784                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET, wakeref);
13785         }
13786
13787         /*
13788          * Defer the cleanup of the old state to a separate worker to not
13789          * impede the current task (userspace for blocking modesets) that
13790          * are executed inline. For out-of-line asynchronous modesets/flips,
13791          * deferring to a new worker seems overkill, but we would place a
13792          * schedule point (cond_resched()) here anyway to keep latencies
13793          * down.
13794          */
13795         INIT_WORK(&state->commit_work, intel_atomic_cleanup_work);
13796         queue_work(system_highpri_wq, &state->commit_work);
13797 }
13798
13799 static void intel_atomic_commit_work(struct work_struct *work)
13800 {
13801         struct drm_atomic_state *state =
13802                 container_of(work, struct drm_atomic_state, commit_work);
13803
13804         intel_atomic_commit_tail(state);
13805 }
13806
13807 static int __i915_sw_fence_call
13808 intel_atomic_commit_ready(struct i915_sw_fence *fence,
13809                           enum i915_sw_fence_notify notify)
13810 {
13811         struct intel_atomic_state *state =
13812                 container_of(fence, struct intel_atomic_state, commit_ready);
13813
13814         switch (notify) {
13815         case FENCE_COMPLETE:
13816                 /* we do blocking waits in the worker, nothing to do here */
13817                 break;
13818         case FENCE_FREE:
13819                 {
13820                         struct intel_atomic_helper *helper =
13821                                 &to_i915(state->base.dev)->atomic_helper;
13822
13823                         if (llist_add(&state->freed, &helper->free_list))
13824                                 schedule_work(&helper->free_work);
13825                         break;
13826                 }
13827         }
13828
13829         return NOTIFY_DONE;
13830 }
13831
13832 static void intel_atomic_track_fbs(struct drm_atomic_state *state)
13833 {
13834         struct drm_plane_state *old_plane_state, *new_plane_state;
13835         struct drm_plane *plane;
13836         int i;
13837
13838         for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i)
13839                 i915_gem_track_fb(intel_fb_obj(old_plane_state->fb),
13840                                   intel_fb_obj(new_plane_state->fb),
13841                                   to_intel_plane(plane)->frontbuffer_bit);
13842 }
13843
13844 /**
13845  * intel_atomic_commit - commit validated state object
13846  * @dev: DRM device
13847  * @state: the top-level driver state object
13848  * @nonblock: nonblocking commit
13849  *
13850  * This function commits a top-level state object that has been validated
13851  * with drm_atomic_helper_check().
13852  *
13853  * RETURNS
13854  * Zero for success or -errno.
13855  */
13856 static int intel_atomic_commit(struct drm_device *dev,
13857                                struct drm_atomic_state *state,
13858                                bool nonblock)
13859 {
13860         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13861         struct drm_i915_private *dev_priv = to_i915(dev);
13862         int ret = 0;
13863
13864         drm_atomic_state_get(state);
13865         i915_sw_fence_init(&intel_state->commit_ready,
13866                            intel_atomic_commit_ready);
13867
13868         /*
13869          * The intel_legacy_cursor_update() fast path takes care
13870          * of avoiding the vblank waits for simple cursor
13871          * movement and flips. For cursor on/off and size changes,
13872          * we want to perform the vblank waits so that watermark
13873          * updates happen during the correct frames. Gen9+ have
13874          * double buffered watermarks and so shouldn't need this.
13875          *
13876          * Unset state->legacy_cursor_update before the call to
13877          * drm_atomic_helper_setup_commit() because otherwise
13878          * drm_atomic_helper_wait_for_flip_done() is a noop and
13879          * we get FIFO underruns because we didn't wait
13880          * for vblank.
13881          *
13882          * FIXME doing watermarks and fb cleanup from a vblank worker
13883          * (assuming we had any) would solve these problems.
13884          */
13885         if (INTEL_GEN(dev_priv) < 9 && state->legacy_cursor_update) {
13886                 struct intel_crtc_state *new_crtc_state;
13887                 struct intel_crtc *crtc;
13888                 int i;
13889
13890                 for_each_new_intel_crtc_in_state(intel_state, crtc, new_crtc_state, i)
13891                         if (new_crtc_state->wm.need_postvbl_update ||
13892                             new_crtc_state->update_wm_post)
13893                                 state->legacy_cursor_update = false;
13894         }
13895
13896         ret = intel_atomic_prepare_commit(dev, state);
13897         if (ret) {
13898                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
13899                 i915_sw_fence_commit(&intel_state->commit_ready);
13900                 return ret;
13901         }
13902
13903         ret = drm_atomic_helper_setup_commit(state, nonblock);
13904         if (!ret)
13905                 ret = drm_atomic_helper_swap_state(state, true);
13906
13907         if (ret) {
13908                 i915_sw_fence_commit(&intel_state->commit_ready);
13909
13910                 drm_atomic_helper_cleanup_planes(dev, state);
13911                 return ret;
13912         }
13913         dev_priv->wm.distrust_bios_wm = false;
13914         intel_shared_dpll_swap_state(state);
13915         intel_atomic_track_fbs(state);
13916
13917         if (intel_state->modeset) {
13918                 memcpy(dev_priv->min_cdclk, intel_state->min_cdclk,
13919                        sizeof(intel_state->min_cdclk));
13920                 memcpy(dev_priv->min_voltage_level,
13921                        intel_state->min_voltage_level,
13922                        sizeof(intel_state->min_voltage_level));
13923                 dev_priv->active_crtcs = intel_state->active_crtcs;
13924                 dev_priv->cdclk.force_min_cdclk =
13925                         intel_state->cdclk.force_min_cdclk;
13926
13927                 intel_cdclk_swap_state(intel_state);
13928         }
13929
13930         drm_atomic_state_get(state);
13931         INIT_WORK(&state->commit_work, intel_atomic_commit_work);
13932
13933         i915_sw_fence_commit(&intel_state->commit_ready);
13934         if (nonblock && intel_state->modeset) {
13935                 queue_work(dev_priv->modeset_wq, &state->commit_work);
13936         } else if (nonblock) {
13937                 queue_work(system_unbound_wq, &state->commit_work);
13938         } else {
13939                 if (intel_state->modeset)
13940                         flush_workqueue(dev_priv->modeset_wq);
13941                 intel_atomic_commit_tail(state);
13942         }
13943
13944         return 0;
13945 }
13946
13947 static const struct drm_crtc_funcs intel_crtc_funcs = {
13948         .gamma_set = drm_atomic_helper_legacy_gamma_set,
13949         .set_config = drm_atomic_helper_set_config,
13950         .destroy = intel_crtc_destroy,
13951         .page_flip = drm_atomic_helper_page_flip,
13952         .atomic_duplicate_state = intel_crtc_duplicate_state,
13953         .atomic_destroy_state = intel_crtc_destroy_state,
13954         .set_crc_source = intel_crtc_set_crc_source,
13955         .verify_crc_source = intel_crtc_verify_crc_source,
13956         .get_crc_sources = intel_crtc_get_crc_sources,
13957 };
13958
13959 struct wait_rps_boost {
13960         struct wait_queue_entry wait;
13961
13962         struct drm_crtc *crtc;
13963         struct i915_request *request;
13964 };
13965
13966 static int do_rps_boost(struct wait_queue_entry *_wait,
13967                         unsigned mode, int sync, void *key)
13968 {
13969         struct wait_rps_boost *wait = container_of(_wait, typeof(*wait), wait);
13970         struct i915_request *rq = wait->request;
13971
13972         /*
13973          * If we missed the vblank, but the request is already running it
13974          * is reasonable to assume that it will complete before the next
13975          * vblank without our intervention, so leave RPS alone.
13976          */
13977         if (!i915_request_started(rq))
13978                 gen6_rps_boost(rq);
13979         i915_request_put(rq);
13980
13981         drm_crtc_vblank_put(wait->crtc);
13982
13983         list_del(&wait->wait.entry);
13984         kfree(wait);
13985         return 1;
13986 }
13987
13988 static void add_rps_boost_after_vblank(struct drm_crtc *crtc,
13989                                        struct dma_fence *fence)
13990 {
13991         struct wait_rps_boost *wait;
13992
13993         if (!dma_fence_is_i915(fence))
13994                 return;
13995
13996         if (INTEL_GEN(to_i915(crtc->dev)) < 6)
13997                 return;
13998
13999         if (drm_crtc_vblank_get(crtc))
14000                 return;
14001
14002         wait = kmalloc(sizeof(*wait), GFP_KERNEL);
14003         if (!wait) {
14004                 drm_crtc_vblank_put(crtc);
14005                 return;
14006         }
14007
14008         wait->request = to_request(dma_fence_get(fence));
14009         wait->crtc = crtc;
14010
14011         wait->wait.func = do_rps_boost;
14012         wait->wait.flags = 0;
14013
14014         add_wait_queue(drm_crtc_vblank_waitqueue(crtc), &wait->wait);
14015 }
14016
14017 static int intel_plane_pin_fb(struct intel_plane_state *plane_state)
14018 {
14019         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
14020         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
14021         struct drm_framebuffer *fb = plane_state->base.fb;
14022         struct i915_vma *vma;
14023
14024         if (plane->id == PLANE_CURSOR &&
14025             INTEL_INFO(dev_priv)->display.cursor_needs_physical) {
14026                 struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14027                 const int align = intel_cursor_alignment(dev_priv);
14028                 int err;
14029
14030                 err = i915_gem_object_attach_phys(obj, align);
14031                 if (err)
14032                         return err;
14033         }
14034
14035         vma = intel_pin_and_fence_fb_obj(fb,
14036                                          &plane_state->view,
14037                                          intel_plane_uses_fence(plane_state),
14038                                          &plane_state->flags);
14039         if (IS_ERR(vma))
14040                 return PTR_ERR(vma);
14041
14042         plane_state->vma = vma;
14043
14044         return 0;
14045 }
14046
14047 static void intel_plane_unpin_fb(struct intel_plane_state *old_plane_state)
14048 {
14049         struct i915_vma *vma;
14050
14051         vma = fetch_and_zero(&old_plane_state->vma);
14052         if (vma)
14053                 intel_unpin_fb_vma(vma, old_plane_state->flags);
14054 }
14055
14056 static void fb_obj_bump_render_priority(struct drm_i915_gem_object *obj)
14057 {
14058         struct i915_sched_attr attr = {
14059                 .priority = I915_PRIORITY_DISPLAY,
14060         };
14061
14062         i915_gem_object_wait_priority(obj, 0, &attr);
14063 }
14064
14065 /**
14066  * intel_prepare_plane_fb - Prepare fb for usage on plane
14067  * @plane: drm plane to prepare for
14068  * @new_state: the plane state being prepared
14069  *
14070  * Prepares a framebuffer for usage on a display plane.  Generally this
14071  * involves pinning the underlying object and updating the frontbuffer tracking
14072  * bits.  Some older platforms need special physical address handling for
14073  * cursor planes.
14074  *
14075  * Must be called with struct_mutex held.
14076  *
14077  * Returns 0 on success, negative error code on failure.
14078  */
14079 int
14080 intel_prepare_plane_fb(struct drm_plane *plane,
14081                        struct drm_plane_state *new_state)
14082 {
14083         struct intel_atomic_state *intel_state =
14084                 to_intel_atomic_state(new_state->state);
14085         struct drm_i915_private *dev_priv = to_i915(plane->dev);
14086         struct drm_framebuffer *fb = new_state->fb;
14087         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14088         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
14089         int ret;
14090
14091         if (old_obj) {
14092                 struct drm_crtc_state *crtc_state =
14093                         drm_atomic_get_new_crtc_state(new_state->state,
14094                                                       plane->state->crtc);
14095
14096                 /* Big Hammer, we also need to ensure that any pending
14097                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
14098                  * current scanout is retired before unpinning the old
14099                  * framebuffer. Note that we rely on userspace rendering
14100                  * into the buffer attached to the pipe they are waiting
14101                  * on. If not, userspace generates a GPU hang with IPEHR
14102                  * point to the MI_WAIT_FOR_EVENT.
14103                  *
14104                  * This should only fail upon a hung GPU, in which case we
14105                  * can safely continue.
14106                  */
14107                 if (needs_modeset(crtc_state)) {
14108                         ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
14109                                                               old_obj->resv, NULL,
14110                                                               false, 0,
14111                                                               GFP_KERNEL);
14112                         if (ret < 0)
14113                                 return ret;
14114                 }
14115         }
14116
14117         if (new_state->fence) { /* explicit fencing */
14118                 ret = i915_sw_fence_await_dma_fence(&intel_state->commit_ready,
14119                                                     new_state->fence,
14120                                                     I915_FENCE_TIMEOUT,
14121                                                     GFP_KERNEL);
14122                 if (ret < 0)
14123                         return ret;
14124         }
14125
14126         if (!obj)
14127                 return 0;
14128
14129         ret = i915_gem_object_pin_pages(obj);
14130         if (ret)
14131                 return ret;
14132
14133         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
14134         if (ret) {
14135                 i915_gem_object_unpin_pages(obj);
14136                 return ret;
14137         }
14138
14139         ret = intel_plane_pin_fb(to_intel_plane_state(new_state));
14140
14141         mutex_unlock(&dev_priv->drm.struct_mutex);
14142         i915_gem_object_unpin_pages(obj);
14143         if (ret)
14144                 return ret;
14145
14146         fb_obj_bump_render_priority(obj);
14147         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
14148
14149         if (!new_state->fence) { /* implicit fencing */
14150                 struct dma_fence *fence;
14151
14152                 ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
14153                                                       obj->resv, NULL,
14154                                                       false, I915_FENCE_TIMEOUT,
14155                                                       GFP_KERNEL);
14156                 if (ret < 0)
14157                         return ret;
14158
14159                 fence = reservation_object_get_excl_rcu(obj->resv);
14160                 if (fence) {
14161                         add_rps_boost_after_vblank(new_state->crtc, fence);
14162                         dma_fence_put(fence);
14163                 }
14164         } else {
14165                 add_rps_boost_after_vblank(new_state->crtc, new_state->fence);
14166         }
14167
14168         /*
14169          * We declare pageflips to be interactive and so merit a small bias
14170          * towards upclocking to deliver the frame on time. By only changing
14171          * the RPS thresholds to sample more regularly and aim for higher
14172          * clocks we can hopefully deliver low power workloads (like kodi)
14173          * that are not quite steady state without resorting to forcing
14174          * maximum clocks following a vblank miss (see do_rps_boost()).
14175          */
14176         if (!intel_state->rps_interactive) {
14177                 intel_rps_mark_interactive(dev_priv, true);
14178                 intel_state->rps_interactive = true;
14179         }
14180
14181         return 0;
14182 }
14183
14184 /**
14185  * intel_cleanup_plane_fb - Cleans up an fb after plane use
14186  * @plane: drm plane to clean up for
14187  * @old_state: the state from the previous modeset
14188  *
14189  * Cleans up a framebuffer that has just been removed from a plane.
14190  *
14191  * Must be called with struct_mutex held.
14192  */
14193 void
14194 intel_cleanup_plane_fb(struct drm_plane *plane,
14195                        struct drm_plane_state *old_state)
14196 {
14197         struct intel_atomic_state *intel_state =
14198                 to_intel_atomic_state(old_state->state);
14199         struct drm_i915_private *dev_priv = to_i915(plane->dev);
14200
14201         if (intel_state->rps_interactive) {
14202                 intel_rps_mark_interactive(dev_priv, false);
14203                 intel_state->rps_interactive = false;
14204         }
14205
14206         /* Should only be called after a successful intel_prepare_plane_fb()! */
14207         mutex_lock(&dev_priv->drm.struct_mutex);
14208         intel_plane_unpin_fb(to_intel_plane_state(old_state));
14209         mutex_unlock(&dev_priv->drm.struct_mutex);
14210 }
14211
14212 int
14213 skl_max_scale(const struct intel_crtc_state *crtc_state,
14214               u32 pixel_format)
14215 {
14216         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
14217         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
14218         int max_scale, mult;
14219         int crtc_clock, max_dotclk, tmpclk1, tmpclk2;
14220
14221         if (!crtc_state->base.enable)
14222                 return DRM_PLANE_HELPER_NO_SCALING;
14223
14224         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
14225         max_dotclk = to_intel_atomic_state(crtc_state->base.state)->cdclk.logical.cdclk;
14226
14227         if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) >= 10)
14228                 max_dotclk *= 2;
14229
14230         if (WARN_ON_ONCE(!crtc_clock || max_dotclk < crtc_clock))
14231                 return DRM_PLANE_HELPER_NO_SCALING;
14232
14233         /*
14234          * skl max scale is lower of:
14235          *    close to 3 but not 3, -1 is for that purpose
14236          *            or
14237          *    cdclk/crtc_clock
14238          */
14239         mult = is_planar_yuv_format(pixel_format) ? 2 : 3;
14240         tmpclk1 = (1 << 16) * mult - 1;
14241         tmpclk2 = (1 << 8) * ((max_dotclk << 8) / crtc_clock);
14242         max_scale = min(tmpclk1, tmpclk2);
14243
14244         return max_scale;
14245 }
14246
14247 static void intel_begin_crtc_commit(struct intel_atomic_state *state,
14248                                     struct intel_crtc *crtc)
14249 {
14250         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
14251         struct intel_crtc_state *old_crtc_state =
14252                 intel_atomic_get_old_crtc_state(state, crtc);
14253         struct intel_crtc_state *new_crtc_state =
14254                 intel_atomic_get_new_crtc_state(state, crtc);
14255         bool modeset = needs_modeset(&new_crtc_state->base);
14256
14257         /* Perform vblank evasion around commit operation */
14258         intel_pipe_update_start(new_crtc_state);
14259
14260         if (modeset)
14261                 goto out;
14262
14263         if (new_crtc_state->base.color_mgmt_changed ||
14264             new_crtc_state->update_pipe)
14265                 intel_color_commit(new_crtc_state);
14266
14267         if (new_crtc_state->update_pipe)
14268                 intel_update_pipe_config(old_crtc_state, new_crtc_state);
14269         else if (INTEL_GEN(dev_priv) >= 9)
14270                 skl_detach_scalers(new_crtc_state);
14271
14272         if (INTEL_GEN(dev_priv) >= 9 || IS_BROADWELL(dev_priv))
14273                 bdw_set_pipemisc(new_crtc_state);
14274
14275 out:
14276         if (dev_priv->display.atomic_update_watermarks)
14277                 dev_priv->display.atomic_update_watermarks(state,
14278                                                            new_crtc_state);
14279 }
14280
14281 void intel_crtc_arm_fifo_underrun(struct intel_crtc *crtc,
14282                                   struct intel_crtc_state *crtc_state)
14283 {
14284         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
14285
14286         if (!IS_GEN(dev_priv, 2))
14287                 intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, true);
14288
14289         if (crtc_state->has_pch_encoder) {
14290                 enum pipe pch_transcoder =
14291                         intel_crtc_pch_transcoder(crtc);
14292
14293                 intel_set_pch_fifo_underrun_reporting(dev_priv, pch_transcoder, true);
14294         }
14295 }
14296
14297 static void intel_finish_crtc_commit(struct intel_atomic_state *state,
14298                                      struct intel_crtc *crtc)
14299 {
14300         struct intel_crtc_state *old_crtc_state =
14301                 intel_atomic_get_old_crtc_state(state, crtc);
14302         struct intel_crtc_state *new_crtc_state =
14303                 intel_atomic_get_new_crtc_state(state, crtc);
14304
14305         intel_pipe_update_end(new_crtc_state);
14306
14307         if (new_crtc_state->update_pipe &&
14308             !needs_modeset(&new_crtc_state->base) &&
14309             old_crtc_state->base.mode.private_flags & I915_MODE_FLAG_INHERITED)
14310                 intel_crtc_arm_fifo_underrun(crtc, new_crtc_state);
14311 }
14312
14313 /**
14314  * intel_plane_destroy - destroy a plane
14315  * @plane: plane to destroy
14316  *
14317  * Common destruction function for all types of planes (primary, cursor,
14318  * sprite).
14319  */
14320 void intel_plane_destroy(struct drm_plane *plane)
14321 {
14322         drm_plane_cleanup(plane);
14323         kfree(to_intel_plane(plane));
14324 }
14325
14326 static bool i8xx_plane_format_mod_supported(struct drm_plane *_plane,
14327                                             u32 format, u64 modifier)
14328 {
14329         switch (modifier) {
14330         case DRM_FORMAT_MOD_LINEAR:
14331         case I915_FORMAT_MOD_X_TILED:
14332                 break;
14333         default:
14334                 return false;
14335         }
14336
14337         switch (format) {
14338         case DRM_FORMAT_C8:
14339         case DRM_FORMAT_RGB565:
14340         case DRM_FORMAT_XRGB1555:
14341         case DRM_FORMAT_XRGB8888:
14342                 return modifier == DRM_FORMAT_MOD_LINEAR ||
14343                         modifier == I915_FORMAT_MOD_X_TILED;
14344         default:
14345                 return false;
14346         }
14347 }
14348
14349 static bool i965_plane_format_mod_supported(struct drm_plane *_plane,
14350                                             u32 format, u64 modifier)
14351 {
14352         switch (modifier) {
14353         case DRM_FORMAT_MOD_LINEAR:
14354         case I915_FORMAT_MOD_X_TILED:
14355                 break;
14356         default:
14357                 return false;
14358         }
14359
14360         switch (format) {
14361         case DRM_FORMAT_C8:
14362         case DRM_FORMAT_RGB565:
14363         case DRM_FORMAT_XRGB8888:
14364         case DRM_FORMAT_XBGR8888:
14365         case DRM_FORMAT_XRGB2101010:
14366         case DRM_FORMAT_XBGR2101010:
14367                 return modifier == DRM_FORMAT_MOD_LINEAR ||
14368                         modifier == I915_FORMAT_MOD_X_TILED;
14369         default:
14370                 return false;
14371         }
14372 }
14373
14374 static bool intel_cursor_format_mod_supported(struct drm_plane *_plane,
14375                                               u32 format, u64 modifier)
14376 {
14377         return modifier == DRM_FORMAT_MOD_LINEAR &&
14378                 format == DRM_FORMAT_ARGB8888;
14379 }
14380
14381 static const struct drm_plane_funcs i965_plane_funcs = {
14382         .update_plane = drm_atomic_helper_update_plane,
14383         .disable_plane = drm_atomic_helper_disable_plane,
14384         .destroy = intel_plane_destroy,
14385         .atomic_get_property = intel_plane_atomic_get_property,
14386         .atomic_set_property = intel_plane_atomic_set_property,
14387         .atomic_duplicate_state = intel_plane_duplicate_state,
14388         .atomic_destroy_state = intel_plane_destroy_state,
14389         .format_mod_supported = i965_plane_format_mod_supported,
14390 };
14391
14392 static const struct drm_plane_funcs i8xx_plane_funcs = {
14393         .update_plane = drm_atomic_helper_update_plane,
14394         .disable_plane = drm_atomic_helper_disable_plane,
14395         .destroy = intel_plane_destroy,
14396         .atomic_get_property = intel_plane_atomic_get_property,
14397         .atomic_set_property = intel_plane_atomic_set_property,
14398         .atomic_duplicate_state = intel_plane_duplicate_state,
14399         .atomic_destroy_state = intel_plane_destroy_state,
14400         .format_mod_supported = i8xx_plane_format_mod_supported,
14401 };
14402
14403 static int
14404 intel_legacy_cursor_update(struct drm_plane *plane,
14405                            struct drm_crtc *crtc,
14406                            struct drm_framebuffer *fb,
14407                            int crtc_x, int crtc_y,
14408                            unsigned int crtc_w, unsigned int crtc_h,
14409                            u32 src_x, u32 src_y,
14410                            u32 src_w, u32 src_h,
14411                            struct drm_modeset_acquire_ctx *ctx)
14412 {
14413         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
14414         int ret;
14415         struct drm_plane_state *old_plane_state, *new_plane_state;
14416         struct intel_plane *intel_plane = to_intel_plane(plane);
14417         struct drm_framebuffer *old_fb;
14418         struct intel_crtc_state *crtc_state =
14419                 to_intel_crtc_state(crtc->state);
14420         struct intel_crtc_state *new_crtc_state;
14421
14422         /*
14423          * When crtc is inactive or there is a modeset pending,
14424          * wait for it to complete in the slowpath
14425          */
14426         if (!crtc_state->base.active || needs_modeset(&crtc_state->base) ||
14427             crtc_state->update_pipe)
14428                 goto slow;
14429
14430         old_plane_state = plane->state;
14431         /*
14432          * Don't do an async update if there is an outstanding commit modifying
14433          * the plane.  This prevents our async update's changes from getting
14434          * overridden by a previous synchronous update's state.
14435          */
14436         if (old_plane_state->commit &&
14437             !try_wait_for_completion(&old_plane_state->commit->hw_done))
14438                 goto slow;
14439
14440         /*
14441          * If any parameters change that may affect watermarks,
14442          * take the slowpath. Only changing fb or position should be
14443          * in the fastpath.
14444          */
14445         if (old_plane_state->crtc != crtc ||
14446             old_plane_state->src_w != src_w ||
14447             old_plane_state->src_h != src_h ||
14448             old_plane_state->crtc_w != crtc_w ||
14449             old_plane_state->crtc_h != crtc_h ||
14450             !old_plane_state->fb != !fb)
14451                 goto slow;
14452
14453         new_plane_state = intel_plane_duplicate_state(plane);
14454         if (!new_plane_state)
14455                 return -ENOMEM;
14456
14457         new_crtc_state = to_intel_crtc_state(intel_crtc_duplicate_state(crtc));
14458         if (!new_crtc_state) {
14459                 ret = -ENOMEM;
14460                 goto out_free;
14461         }
14462
14463         drm_atomic_set_fb_for_plane(new_plane_state, fb);
14464
14465         new_plane_state->src_x = src_x;
14466         new_plane_state->src_y = src_y;
14467         new_plane_state->src_w = src_w;
14468         new_plane_state->src_h = src_h;
14469         new_plane_state->crtc_x = crtc_x;
14470         new_plane_state->crtc_y = crtc_y;
14471         new_plane_state->crtc_w = crtc_w;
14472         new_plane_state->crtc_h = crtc_h;
14473
14474         ret = intel_plane_atomic_check_with_state(crtc_state, new_crtc_state,
14475                                                   to_intel_plane_state(old_plane_state),
14476                                                   to_intel_plane_state(new_plane_state));
14477         if (ret)
14478                 goto out_free;
14479
14480         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
14481         if (ret)
14482                 goto out_free;
14483
14484         ret = intel_plane_pin_fb(to_intel_plane_state(new_plane_state));
14485         if (ret)
14486                 goto out_unlock;
14487
14488         intel_fb_obj_flush(intel_fb_obj(fb), ORIGIN_FLIP);
14489
14490         old_fb = old_plane_state->fb;
14491         i915_gem_track_fb(intel_fb_obj(old_fb), intel_fb_obj(fb),
14492                           intel_plane->frontbuffer_bit);
14493
14494         /* Swap plane state */
14495         plane->state = new_plane_state;
14496
14497         /*
14498          * We cannot swap crtc_state as it may be in use by an atomic commit or
14499          * page flip that's running simultaneously. If we swap crtc_state and
14500          * destroy the old state, we will cause a use-after-free there.
14501          *
14502          * Only update active_planes, which is needed for our internal
14503          * bookkeeping. Either value will do the right thing when updating
14504          * planes atomically. If the cursor was part of the atomic update then
14505          * we would have taken the slowpath.
14506          */
14507         crtc_state->active_planes = new_crtc_state->active_planes;
14508
14509         if (plane->state->visible)
14510                 intel_update_plane(intel_plane, crtc_state,
14511                                    to_intel_plane_state(plane->state));
14512         else
14513                 intel_disable_plane(intel_plane, crtc_state);
14514
14515         intel_plane_unpin_fb(to_intel_plane_state(old_plane_state));
14516
14517 out_unlock:
14518         mutex_unlock(&dev_priv->drm.struct_mutex);
14519 out_free:
14520         if (new_crtc_state)
14521                 intel_crtc_destroy_state(crtc, &new_crtc_state->base);
14522         if (ret)
14523                 intel_plane_destroy_state(plane, new_plane_state);
14524         else
14525                 intel_plane_destroy_state(plane, old_plane_state);
14526         return ret;
14527
14528 slow:
14529         return drm_atomic_helper_update_plane(plane, crtc, fb,
14530                                               crtc_x, crtc_y, crtc_w, crtc_h,
14531                                               src_x, src_y, src_w, src_h, ctx);
14532 }
14533
14534 static const struct drm_plane_funcs intel_cursor_plane_funcs = {
14535         .update_plane = intel_legacy_cursor_update,
14536         .disable_plane = drm_atomic_helper_disable_plane,
14537         .destroy = intel_plane_destroy,
14538         .atomic_get_property = intel_plane_atomic_get_property,
14539         .atomic_set_property = intel_plane_atomic_set_property,
14540         .atomic_duplicate_state = intel_plane_duplicate_state,
14541         .atomic_destroy_state = intel_plane_destroy_state,
14542         .format_mod_supported = intel_cursor_format_mod_supported,
14543 };
14544
14545 static bool i9xx_plane_has_fbc(struct drm_i915_private *dev_priv,
14546                                enum i9xx_plane_id i9xx_plane)
14547 {
14548         if (!HAS_FBC(dev_priv))
14549                 return false;
14550
14551         if (IS_BROADWELL(dev_priv) || IS_HASWELL(dev_priv))
14552                 return i9xx_plane == PLANE_A; /* tied to pipe A */
14553         else if (IS_IVYBRIDGE(dev_priv))
14554                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B ||
14555                         i9xx_plane == PLANE_C;
14556         else if (INTEL_GEN(dev_priv) >= 4)
14557                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B;
14558         else
14559                 return i9xx_plane == PLANE_A;
14560 }
14561
14562 static struct intel_plane *
14563 intel_primary_plane_create(struct drm_i915_private *dev_priv, enum pipe pipe)
14564 {
14565         struct intel_plane *plane;
14566         const struct drm_plane_funcs *plane_funcs;
14567         unsigned int supported_rotations;
14568         unsigned int possible_crtcs;
14569         const u64 *modifiers;
14570         const u32 *formats;
14571         int num_formats;
14572         int ret;
14573
14574         if (INTEL_GEN(dev_priv) >= 9)
14575                 return skl_universal_plane_create(dev_priv, pipe,
14576                                                   PLANE_PRIMARY);
14577
14578         plane = intel_plane_alloc();
14579         if (IS_ERR(plane))
14580                 return plane;
14581
14582         plane->pipe = pipe;
14583         /*
14584          * On gen2/3 only plane A can do FBC, but the panel fitter and LVDS
14585          * port is hooked to pipe B. Hence we want plane A feeding pipe B.
14586          */
14587         if (HAS_FBC(dev_priv) && INTEL_GEN(dev_priv) < 4)
14588                 plane->i9xx_plane = (enum i9xx_plane_id) !pipe;
14589         else
14590                 plane->i9xx_plane = (enum i9xx_plane_id) pipe;
14591         plane->id = PLANE_PRIMARY;
14592         plane->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, plane->id);
14593
14594         plane->has_fbc = i9xx_plane_has_fbc(dev_priv, plane->i9xx_plane);
14595         if (plane->has_fbc) {
14596                 struct intel_fbc *fbc = &dev_priv->fbc;
14597
14598                 fbc->possible_framebuffer_bits |= plane->frontbuffer_bit;
14599         }
14600
14601         if (INTEL_GEN(dev_priv) >= 4) {
14602                 formats = i965_primary_formats;
14603                 num_formats = ARRAY_SIZE(i965_primary_formats);
14604                 modifiers = i9xx_format_modifiers;
14605
14606                 plane->max_stride = i9xx_plane_max_stride;
14607                 plane->update_plane = i9xx_update_plane;
14608                 plane->disable_plane = i9xx_disable_plane;
14609                 plane->get_hw_state = i9xx_plane_get_hw_state;
14610                 plane->check_plane = i9xx_plane_check;
14611
14612                 plane_funcs = &i965_plane_funcs;
14613         } else {
14614                 formats = i8xx_primary_formats;
14615                 num_formats = ARRAY_SIZE(i8xx_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 = &i8xx_plane_funcs;
14625         }
14626
14627         possible_crtcs = BIT(pipe);
14628
14629         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
14630                 ret = drm_universal_plane_init(&dev_priv->drm, &plane->base,
14631                                                possible_crtcs, plane_funcs,
14632                                                formats, num_formats, modifiers,
14633                                                DRM_PLANE_TYPE_PRIMARY,
14634                                                "primary %c", pipe_name(pipe));
14635         else
14636                 ret = drm_universal_plane_init(&dev_priv->drm, &plane->base,
14637                                                possible_crtcs, plane_funcs,
14638                                                formats, num_formats, modifiers,
14639                                                DRM_PLANE_TYPE_PRIMARY,
14640                                                "plane %c",
14641                                                plane_name(plane->i9xx_plane));
14642         if (ret)
14643                 goto fail;
14644
14645         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
14646                 supported_rotations =
14647                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180 |
14648                         DRM_MODE_REFLECT_X;
14649         } else if (INTEL_GEN(dev_priv) >= 4) {
14650                 supported_rotations =
14651                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180;
14652         } else {
14653                 supported_rotations = DRM_MODE_ROTATE_0;
14654         }
14655
14656         if (INTEL_GEN(dev_priv) >= 4)
14657                 drm_plane_create_rotation_property(&plane->base,
14658                                                    DRM_MODE_ROTATE_0,
14659                                                    supported_rotations);
14660
14661         drm_plane_helper_add(&plane->base, &intel_plane_helper_funcs);
14662
14663         return plane;
14664
14665 fail:
14666         intel_plane_free(plane);
14667
14668         return ERR_PTR(ret);
14669 }
14670
14671 static struct intel_plane *
14672 intel_cursor_plane_create(struct drm_i915_private *dev_priv,
14673                           enum pipe pipe)
14674 {
14675         unsigned int possible_crtcs;
14676         struct intel_plane *cursor;
14677         int ret;
14678
14679         cursor = intel_plane_alloc();
14680         if (IS_ERR(cursor))
14681                 return cursor;
14682
14683         cursor->pipe = pipe;
14684         cursor->i9xx_plane = (enum i9xx_plane_id) pipe;
14685         cursor->id = PLANE_CURSOR;
14686         cursor->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, cursor->id);
14687
14688         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
14689                 cursor->max_stride = i845_cursor_max_stride;
14690                 cursor->update_plane = i845_update_cursor;
14691                 cursor->disable_plane = i845_disable_cursor;
14692                 cursor->get_hw_state = i845_cursor_get_hw_state;
14693                 cursor->check_plane = i845_check_cursor;
14694         } else {
14695                 cursor->max_stride = i9xx_cursor_max_stride;
14696                 cursor->update_plane = i9xx_update_cursor;
14697                 cursor->disable_plane = i9xx_disable_cursor;
14698                 cursor->get_hw_state = i9xx_cursor_get_hw_state;
14699                 cursor->check_plane = i9xx_check_cursor;
14700         }
14701
14702         cursor->cursor.base = ~0;
14703         cursor->cursor.cntl = ~0;
14704
14705         if (IS_I845G(dev_priv) || IS_I865G(dev_priv) || HAS_CUR_FBC(dev_priv))
14706                 cursor->cursor.size = ~0;
14707
14708         possible_crtcs = BIT(pipe);
14709
14710         ret = drm_universal_plane_init(&dev_priv->drm, &cursor->base,
14711                                        possible_crtcs, &intel_cursor_plane_funcs,
14712                                        intel_cursor_formats,
14713                                        ARRAY_SIZE(intel_cursor_formats),
14714                                        cursor_format_modifiers,
14715                                        DRM_PLANE_TYPE_CURSOR,
14716                                        "cursor %c", pipe_name(pipe));
14717         if (ret)
14718                 goto fail;
14719
14720         if (INTEL_GEN(dev_priv) >= 4)
14721                 drm_plane_create_rotation_property(&cursor->base,
14722                                                    DRM_MODE_ROTATE_0,
14723                                                    DRM_MODE_ROTATE_0 |
14724                                                    DRM_MODE_ROTATE_180);
14725
14726         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
14727
14728         return cursor;
14729
14730 fail:
14731         intel_plane_free(cursor);
14732
14733         return ERR_PTR(ret);
14734 }
14735
14736 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
14737                                     struct intel_crtc_state *crtc_state)
14738 {
14739         struct intel_crtc_scaler_state *scaler_state =
14740                 &crtc_state->scaler_state;
14741         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
14742         int i;
14743
14744         crtc->num_scalers = RUNTIME_INFO(dev_priv)->num_scalers[crtc->pipe];
14745         if (!crtc->num_scalers)
14746                 return;
14747
14748         for (i = 0; i < crtc->num_scalers; i++) {
14749                 struct intel_scaler *scaler = &scaler_state->scalers[i];
14750
14751                 scaler->in_use = 0;
14752                 scaler->mode = 0;
14753         }
14754
14755         scaler_state->scaler_id = -1;
14756 }
14757
14758 static int intel_crtc_init(struct drm_i915_private *dev_priv, enum pipe pipe)
14759 {
14760         struct intel_crtc *intel_crtc;
14761         struct intel_crtc_state *crtc_state = NULL;
14762         struct intel_plane *primary = NULL;
14763         struct intel_plane *cursor = NULL;
14764         int sprite, ret;
14765
14766         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
14767         if (!intel_crtc)
14768                 return -ENOMEM;
14769
14770         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
14771         if (!crtc_state) {
14772                 ret = -ENOMEM;
14773                 goto fail;
14774         }
14775         intel_crtc->config = crtc_state;
14776         intel_crtc->base.state = &crtc_state->base;
14777         crtc_state->base.crtc = &intel_crtc->base;
14778
14779         primary = intel_primary_plane_create(dev_priv, pipe);
14780         if (IS_ERR(primary)) {
14781                 ret = PTR_ERR(primary);
14782                 goto fail;
14783         }
14784         intel_crtc->plane_ids_mask |= BIT(primary->id);
14785
14786         for_each_sprite(dev_priv, pipe, sprite) {
14787                 struct intel_plane *plane;
14788
14789                 plane = intel_sprite_plane_create(dev_priv, pipe, sprite);
14790                 if (IS_ERR(plane)) {
14791                         ret = PTR_ERR(plane);
14792                         goto fail;
14793                 }
14794                 intel_crtc->plane_ids_mask |= BIT(plane->id);
14795         }
14796
14797         cursor = intel_cursor_plane_create(dev_priv, pipe);
14798         if (IS_ERR(cursor)) {
14799                 ret = PTR_ERR(cursor);
14800                 goto fail;
14801         }
14802         intel_crtc->plane_ids_mask |= BIT(cursor->id);
14803
14804         ret = drm_crtc_init_with_planes(&dev_priv->drm, &intel_crtc->base,
14805                                         &primary->base, &cursor->base,
14806                                         &intel_crtc_funcs,
14807                                         "pipe %c", pipe_name(pipe));
14808         if (ret)
14809                 goto fail;
14810
14811         intel_crtc->pipe = pipe;
14812
14813         /* initialize shared scalers */
14814         intel_crtc_init_scalers(intel_crtc, crtc_state);
14815
14816         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->pipe_to_crtc_mapping) ||
14817                dev_priv->pipe_to_crtc_mapping[pipe] != NULL);
14818         dev_priv->pipe_to_crtc_mapping[pipe] = intel_crtc;
14819
14820         if (INTEL_GEN(dev_priv) < 9) {
14821                 enum i9xx_plane_id i9xx_plane = primary->i9xx_plane;
14822
14823                 BUG_ON(i9xx_plane >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
14824                        dev_priv->plane_to_crtc_mapping[i9xx_plane] != NULL);
14825                 dev_priv->plane_to_crtc_mapping[i9xx_plane] = intel_crtc;
14826         }
14827
14828         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
14829
14830         intel_color_init(intel_crtc);
14831
14832         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
14833
14834         return 0;
14835
14836 fail:
14837         /*
14838          * drm_mode_config_cleanup() will free up any
14839          * crtcs/planes already initialized.
14840          */
14841         kfree(crtc_state);
14842         kfree(intel_crtc);
14843
14844         return ret;
14845 }
14846
14847 int intel_get_pipe_from_crtc_id_ioctl(struct drm_device *dev, void *data,
14848                                       struct drm_file *file)
14849 {
14850         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
14851         struct drm_crtc *drmmode_crtc;
14852         struct intel_crtc *crtc;
14853
14854         drmmode_crtc = drm_crtc_find(dev, file, pipe_from_crtc_id->crtc_id);
14855         if (!drmmode_crtc)
14856                 return -ENOENT;
14857
14858         crtc = to_intel_crtc(drmmode_crtc);
14859         pipe_from_crtc_id->pipe = crtc->pipe;
14860
14861         return 0;
14862 }
14863
14864 static int intel_encoder_clones(struct intel_encoder *encoder)
14865 {
14866         struct drm_device *dev = encoder->base.dev;
14867         struct intel_encoder *source_encoder;
14868         int index_mask = 0;
14869         int entry = 0;
14870
14871         for_each_intel_encoder(dev, source_encoder) {
14872                 if (encoders_cloneable(encoder, source_encoder))
14873                         index_mask |= (1 << entry);
14874
14875                 entry++;
14876         }
14877
14878         return index_mask;
14879 }
14880
14881 static bool ilk_has_edp_a(struct drm_i915_private *dev_priv)
14882 {
14883         if (!IS_MOBILE(dev_priv))
14884                 return false;
14885
14886         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
14887                 return false;
14888
14889         if (IS_GEN(dev_priv, 5) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
14890                 return false;
14891
14892         return true;
14893 }
14894
14895 static bool intel_ddi_crt_present(struct drm_i915_private *dev_priv)
14896 {
14897         if (INTEL_GEN(dev_priv) >= 9)
14898                 return false;
14899
14900         if (IS_HSW_ULT(dev_priv) || IS_BDW_ULT(dev_priv))
14901                 return false;
14902
14903         if (HAS_PCH_LPT_H(dev_priv) &&
14904             I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
14905                 return false;
14906
14907         /* DDI E can't be used if DDI A requires 4 lanes */
14908         if (I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
14909                 return false;
14910
14911         if (!dev_priv->vbt.int_crt_support)
14912                 return false;
14913
14914         return true;
14915 }
14916
14917 void intel_pps_unlock_regs_wa(struct drm_i915_private *dev_priv)
14918 {
14919         int pps_num;
14920         int pps_idx;
14921
14922         if (HAS_DDI(dev_priv))
14923                 return;
14924         /*
14925          * This w/a is needed at least on CPT/PPT, but to be sure apply it
14926          * everywhere where registers can be write protected.
14927          */
14928         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
14929                 pps_num = 2;
14930         else
14931                 pps_num = 1;
14932
14933         for (pps_idx = 0; pps_idx < pps_num; pps_idx++) {
14934                 u32 val = I915_READ(PP_CONTROL(pps_idx));
14935
14936                 val = (val & ~PANEL_UNLOCK_MASK) | PANEL_UNLOCK_REGS;
14937                 I915_WRITE(PP_CONTROL(pps_idx), val);
14938         }
14939 }
14940
14941 static void intel_pps_init(struct drm_i915_private *dev_priv)
14942 {
14943         if (HAS_PCH_SPLIT(dev_priv) || IS_GEN9_LP(dev_priv))
14944                 dev_priv->pps_mmio_base = PCH_PPS_BASE;
14945         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
14946                 dev_priv->pps_mmio_base = VLV_PPS_BASE;
14947         else
14948                 dev_priv->pps_mmio_base = PPS_BASE;
14949
14950         intel_pps_unlock_regs_wa(dev_priv);
14951 }
14952
14953 static void intel_setup_outputs(struct drm_i915_private *dev_priv)
14954 {
14955         struct intel_encoder *encoder;
14956         bool dpd_is_edp = false;
14957
14958         intel_pps_init(dev_priv);
14959
14960         if (!HAS_DISPLAY(dev_priv))
14961                 return;
14962
14963         if (IS_ELKHARTLAKE(dev_priv)) {
14964                 intel_ddi_init(dev_priv, PORT_A);
14965                 intel_ddi_init(dev_priv, PORT_B);
14966                 intel_ddi_init(dev_priv, PORT_C);
14967                 icl_dsi_init(dev_priv);
14968         } else if (INTEL_GEN(dev_priv) >= 11) {
14969                 intel_ddi_init(dev_priv, PORT_A);
14970                 intel_ddi_init(dev_priv, PORT_B);
14971                 intel_ddi_init(dev_priv, PORT_C);
14972                 intel_ddi_init(dev_priv, PORT_D);
14973                 intel_ddi_init(dev_priv, PORT_E);
14974                 /*
14975                  * On some ICL SKUs port F is not present. No strap bits for
14976                  * this, so rely on VBT.
14977                  * Work around broken VBTs on SKUs known to have no port F.
14978                  */
14979                 if (IS_ICL_WITH_PORT_F(dev_priv) &&
14980                     intel_bios_is_port_present(dev_priv, PORT_F))
14981                         intel_ddi_init(dev_priv, PORT_F);
14982
14983                 icl_dsi_init(dev_priv);
14984         } else if (IS_GEN9_LP(dev_priv)) {
14985                 /*
14986                  * FIXME: Broxton doesn't support port detection via the
14987                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
14988                  * detect the ports.
14989                  */
14990                 intel_ddi_init(dev_priv, PORT_A);
14991                 intel_ddi_init(dev_priv, PORT_B);
14992                 intel_ddi_init(dev_priv, PORT_C);
14993
14994                 vlv_dsi_init(dev_priv);
14995         } else if (HAS_DDI(dev_priv)) {
14996                 int found;
14997
14998                 if (intel_ddi_crt_present(dev_priv))
14999                         intel_crt_init(dev_priv);
15000
15001                 /*
15002                  * Haswell uses DDI functions to detect digital outputs.
15003                  * On SKL pre-D0 the strap isn't connected, so we assume
15004                  * it's there.
15005                  */
15006                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
15007                 /* WaIgnoreDDIAStrap: skl */
15008                 if (found || IS_GEN9_BC(dev_priv))
15009                         intel_ddi_init(dev_priv, PORT_A);
15010
15011                 /* DDI B, C, D, and F detection is indicated by the SFUSE_STRAP
15012                  * register */
15013                 found = I915_READ(SFUSE_STRAP);
15014
15015                 if (found & SFUSE_STRAP_DDIB_DETECTED)
15016                         intel_ddi_init(dev_priv, PORT_B);
15017                 if (found & SFUSE_STRAP_DDIC_DETECTED)
15018                         intel_ddi_init(dev_priv, PORT_C);
15019                 if (found & SFUSE_STRAP_DDID_DETECTED)
15020                         intel_ddi_init(dev_priv, PORT_D);
15021                 if (found & SFUSE_STRAP_DDIF_DETECTED)
15022                         intel_ddi_init(dev_priv, PORT_F);
15023                 /*
15024                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
15025                  */
15026                 if (IS_GEN9_BC(dev_priv) &&
15027                     intel_bios_is_port_present(dev_priv, PORT_E))
15028                         intel_ddi_init(dev_priv, PORT_E);
15029
15030         } else if (HAS_PCH_SPLIT(dev_priv)) {
15031                 int found;
15032
15033                 /*
15034                  * intel_edp_init_connector() depends on this completing first,
15035                  * to prevent the registration of both eDP and LVDS and the
15036                  * incorrect sharing of the PPS.
15037                  */
15038                 intel_lvds_init(dev_priv);
15039                 intel_crt_init(dev_priv);
15040
15041                 dpd_is_edp = intel_dp_is_port_edp(dev_priv, PORT_D);
15042
15043                 if (ilk_has_edp_a(dev_priv))
15044                         intel_dp_init(dev_priv, DP_A, PORT_A);
15045
15046                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
15047                         /* PCH SDVOB multiplex with HDMIB */
15048                         found = intel_sdvo_init(dev_priv, PCH_SDVOB, PORT_B);
15049                         if (!found)
15050                                 intel_hdmi_init(dev_priv, PCH_HDMIB, PORT_B);
15051                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
15052                                 intel_dp_init(dev_priv, PCH_DP_B, PORT_B);
15053                 }
15054
15055                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
15056                         intel_hdmi_init(dev_priv, PCH_HDMIC, PORT_C);
15057
15058                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
15059                         intel_hdmi_init(dev_priv, PCH_HDMID, PORT_D);
15060
15061                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
15062                         intel_dp_init(dev_priv, PCH_DP_C, PORT_C);
15063
15064                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
15065                         intel_dp_init(dev_priv, PCH_DP_D, PORT_D);
15066         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
15067                 bool has_edp, has_port;
15068
15069                 if (IS_VALLEYVIEW(dev_priv) && dev_priv->vbt.int_crt_support)
15070                         intel_crt_init(dev_priv);
15071
15072                 /*
15073                  * The DP_DETECTED bit is the latched state of the DDC
15074                  * SDA pin at boot. However since eDP doesn't require DDC
15075                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
15076                  * eDP ports may have been muxed to an alternate function.
15077                  * Thus we can't rely on the DP_DETECTED bit alone to detect
15078                  * eDP ports. Consult the VBT as well as DP_DETECTED to
15079                  * detect eDP ports.
15080                  *
15081                  * Sadly the straps seem to be missing sometimes even for HDMI
15082                  * ports (eg. on Voyo V3 - CHT x7-Z8700), so check both strap
15083                  * and VBT for the presence of the port. Additionally we can't
15084                  * trust the port type the VBT declares as we've seen at least
15085                  * HDMI ports that the VBT claim are DP or eDP.
15086                  */
15087                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_B);
15088                 has_port = intel_bios_is_port_present(dev_priv, PORT_B);
15089                 if (I915_READ(VLV_DP_B) & DP_DETECTED || has_port)
15090                         has_edp &= intel_dp_init(dev_priv, VLV_DP_B, PORT_B);
15091                 if ((I915_READ(VLV_HDMIB) & SDVO_DETECTED || has_port) && !has_edp)
15092                         intel_hdmi_init(dev_priv, VLV_HDMIB, PORT_B);
15093
15094                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_C);
15095                 has_port = intel_bios_is_port_present(dev_priv, PORT_C);
15096                 if (I915_READ(VLV_DP_C) & DP_DETECTED || has_port)
15097                         has_edp &= intel_dp_init(dev_priv, VLV_DP_C, PORT_C);
15098                 if ((I915_READ(VLV_HDMIC) & SDVO_DETECTED || has_port) && !has_edp)
15099                         intel_hdmi_init(dev_priv, VLV_HDMIC, PORT_C);
15100
15101                 if (IS_CHERRYVIEW(dev_priv)) {
15102                         /*
15103                          * eDP not supported on port D,
15104                          * so no need to worry about it
15105                          */
15106                         has_port = intel_bios_is_port_present(dev_priv, PORT_D);
15107                         if (I915_READ(CHV_DP_D) & DP_DETECTED || has_port)
15108                                 intel_dp_init(dev_priv, CHV_DP_D, PORT_D);
15109                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED || has_port)
15110                                 intel_hdmi_init(dev_priv, CHV_HDMID, PORT_D);
15111                 }
15112
15113                 vlv_dsi_init(dev_priv);
15114         } else if (IS_PINEVIEW(dev_priv)) {
15115                 intel_lvds_init(dev_priv);
15116                 intel_crt_init(dev_priv);
15117         } else if (IS_GEN_RANGE(dev_priv, 3, 4)) {
15118                 bool found = false;
15119
15120                 if (IS_MOBILE(dev_priv))
15121                         intel_lvds_init(dev_priv);
15122
15123                 intel_crt_init(dev_priv);
15124
15125                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
15126                         DRM_DEBUG_KMS("probing SDVOB\n");
15127                         found = intel_sdvo_init(dev_priv, GEN3_SDVOB, PORT_B);
15128                         if (!found && IS_G4X(dev_priv)) {
15129                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
15130                                 intel_hdmi_init(dev_priv, GEN4_HDMIB, PORT_B);
15131                         }
15132
15133                         if (!found && IS_G4X(dev_priv))
15134                                 intel_dp_init(dev_priv, DP_B, PORT_B);
15135                 }
15136
15137                 /* Before G4X SDVOC doesn't have its own detect register */
15138
15139                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
15140                         DRM_DEBUG_KMS("probing SDVOC\n");
15141                         found = intel_sdvo_init(dev_priv, GEN3_SDVOC, PORT_C);
15142                 }
15143
15144                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
15145
15146                         if (IS_G4X(dev_priv)) {
15147                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
15148                                 intel_hdmi_init(dev_priv, GEN4_HDMIC, PORT_C);
15149                         }
15150                         if (IS_G4X(dev_priv))
15151                                 intel_dp_init(dev_priv, DP_C, PORT_C);
15152                 }
15153
15154                 if (IS_G4X(dev_priv) && (I915_READ(DP_D) & DP_DETECTED))
15155                         intel_dp_init(dev_priv, DP_D, PORT_D);
15156
15157                 if (SUPPORTS_TV(dev_priv))
15158                         intel_tv_init(dev_priv);
15159         } else if (IS_GEN(dev_priv, 2)) {
15160                 if (IS_I85X(dev_priv))
15161                         intel_lvds_init(dev_priv);
15162
15163                 intel_crt_init(dev_priv);
15164                 intel_dvo_init(dev_priv);
15165         }
15166
15167         intel_psr_init(dev_priv);
15168
15169         for_each_intel_encoder(&dev_priv->drm, encoder) {
15170                 encoder->base.possible_crtcs = encoder->crtc_mask;
15171                 encoder->base.possible_clones =
15172                         intel_encoder_clones(encoder);
15173         }
15174
15175         intel_init_pch_refclk(dev_priv);
15176
15177         drm_helper_move_panel_connectors_to_head(&dev_priv->drm);
15178 }
15179
15180 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
15181 {
15182         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
15183         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
15184
15185         drm_framebuffer_cleanup(fb);
15186
15187         i915_gem_object_lock(obj);
15188         WARN_ON(!obj->framebuffer_references--);
15189         i915_gem_object_unlock(obj);
15190
15191         i915_gem_object_put(obj);
15192
15193         kfree(intel_fb);
15194 }
15195
15196 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
15197                                                 struct drm_file *file,
15198                                                 unsigned int *handle)
15199 {
15200         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
15201
15202         if (obj->userptr.mm) {
15203                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
15204                 return -EINVAL;
15205         }
15206
15207         return drm_gem_handle_create(file, &obj->base, handle);
15208 }
15209
15210 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
15211                                         struct drm_file *file,
15212                                         unsigned flags, unsigned color,
15213                                         struct drm_clip_rect *clips,
15214                                         unsigned num_clips)
15215 {
15216         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
15217
15218         i915_gem_object_flush_if_display(obj);
15219         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
15220
15221         return 0;
15222 }
15223
15224 static const struct drm_framebuffer_funcs intel_fb_funcs = {
15225         .destroy = intel_user_framebuffer_destroy,
15226         .create_handle = intel_user_framebuffer_create_handle,
15227         .dirty = intel_user_framebuffer_dirty,
15228 };
15229
15230 static int intel_framebuffer_init(struct intel_framebuffer *intel_fb,
15231                                   struct drm_i915_gem_object *obj,
15232                                   struct drm_mode_fb_cmd2 *mode_cmd)
15233 {
15234         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
15235         struct drm_framebuffer *fb = &intel_fb->base;
15236         u32 max_stride;
15237         unsigned int tiling, stride;
15238         int ret = -EINVAL;
15239         int i;
15240
15241         i915_gem_object_lock(obj);
15242         obj->framebuffer_references++;
15243         tiling = i915_gem_object_get_tiling(obj);
15244         stride = i915_gem_object_get_stride(obj);
15245         i915_gem_object_unlock(obj);
15246
15247         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
15248                 /*
15249                  * If there's a fence, enforce that
15250                  * the fb modifier and tiling mode match.
15251                  */
15252                 if (tiling != I915_TILING_NONE &&
15253                     tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
15254                         DRM_DEBUG_KMS("tiling_mode doesn't match fb modifier\n");
15255                         goto err;
15256                 }
15257         } else {
15258                 if (tiling == I915_TILING_X) {
15259                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
15260                 } else if (tiling == I915_TILING_Y) {
15261                         DRM_DEBUG_KMS("No Y tiling for legacy addfb\n");
15262                         goto err;
15263                 }
15264         }
15265
15266         if (!drm_any_plane_has_format(&dev_priv->drm,
15267                                       mode_cmd->pixel_format,
15268                                       mode_cmd->modifier[0])) {
15269                 struct drm_format_name_buf format_name;
15270
15271                 DRM_DEBUG_KMS("unsupported pixel format %s / modifier 0x%llx\n",
15272                               drm_get_format_name(mode_cmd->pixel_format,
15273                                                   &format_name),
15274                               mode_cmd->modifier[0]);
15275                 goto err;
15276         }
15277
15278         /*
15279          * gen2/3 display engine uses the fence if present,
15280          * so the tiling mode must match the fb modifier exactly.
15281          */
15282         if (INTEL_GEN(dev_priv) < 4 &&
15283             tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
15284                 DRM_DEBUG_KMS("tiling_mode must match fb modifier exactly on gen2/3\n");
15285                 goto err;
15286         }
15287
15288         max_stride = intel_fb_max_stride(dev_priv, mode_cmd->pixel_format,
15289                                          mode_cmd->modifier[0]);
15290         if (mode_cmd->pitches[0] > max_stride) {
15291                 DRM_DEBUG_KMS("%s pitch (%u) must be at most %d\n",
15292                               mode_cmd->modifier[0] != DRM_FORMAT_MOD_LINEAR ?
15293                               "tiled" : "linear",
15294                               mode_cmd->pitches[0], max_stride);
15295                 goto err;
15296         }
15297
15298         /*
15299          * If there's a fence, enforce that
15300          * the fb pitch and fence stride match.
15301          */
15302         if (tiling != I915_TILING_NONE && mode_cmd->pitches[0] != stride) {
15303                 DRM_DEBUG_KMS("pitch (%d) must match tiling stride (%d)\n",
15304                               mode_cmd->pitches[0], stride);
15305                 goto err;
15306         }
15307
15308         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
15309         if (mode_cmd->offsets[0] != 0)
15310                 goto err;
15311
15312         drm_helper_mode_fill_fb_struct(&dev_priv->drm, fb, mode_cmd);
15313
15314         for (i = 0; i < fb->format->num_planes; i++) {
15315                 u32 stride_alignment;
15316
15317                 if (mode_cmd->handles[i] != mode_cmd->handles[0]) {
15318                         DRM_DEBUG_KMS("bad plane %d handle\n", i);
15319                         goto err;
15320                 }
15321
15322                 stride_alignment = intel_fb_stride_alignment(fb, i);
15323
15324                 /*
15325                  * Display WA #0531: skl,bxt,kbl,glk
15326                  *
15327                  * Render decompression and plane width > 3840
15328                  * combined with horizontal panning requires the
15329                  * plane stride to be a multiple of 4. We'll just
15330                  * require the entire fb to accommodate that to avoid
15331                  * potential runtime errors at plane configuration time.
15332                  */
15333                 if (IS_GEN(dev_priv, 9) && i == 0 && fb->width > 3840 &&
15334                     is_ccs_modifier(fb->modifier))
15335                         stride_alignment *= 4;
15336
15337                 if (fb->pitches[i] & (stride_alignment - 1)) {
15338                         DRM_DEBUG_KMS("plane %d pitch (%d) must be at least %u byte aligned\n",
15339                                       i, fb->pitches[i], stride_alignment);
15340                         goto err;
15341                 }
15342
15343                 fb->obj[i] = &obj->base;
15344         }
15345
15346         ret = intel_fill_fb_info(dev_priv, fb);
15347         if (ret)
15348                 goto err;
15349
15350         ret = drm_framebuffer_init(&dev_priv->drm, fb, &intel_fb_funcs);
15351         if (ret) {
15352                 DRM_ERROR("framebuffer init failed %d\n", ret);
15353                 goto err;
15354         }
15355
15356         return 0;
15357
15358 err:
15359         i915_gem_object_lock(obj);
15360         obj->framebuffer_references--;
15361         i915_gem_object_unlock(obj);
15362         return ret;
15363 }
15364
15365 static struct drm_framebuffer *
15366 intel_user_framebuffer_create(struct drm_device *dev,
15367                               struct drm_file *filp,
15368                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
15369 {
15370         struct drm_framebuffer *fb;
15371         struct drm_i915_gem_object *obj;
15372         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
15373
15374         obj = i915_gem_object_lookup(filp, mode_cmd.handles[0]);
15375         if (!obj)
15376                 return ERR_PTR(-ENOENT);
15377
15378         fb = intel_framebuffer_create(obj, &mode_cmd);
15379         if (IS_ERR(fb))
15380                 i915_gem_object_put(obj);
15381
15382         return fb;
15383 }
15384
15385 static void intel_atomic_state_free(struct drm_atomic_state *state)
15386 {
15387         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
15388
15389         drm_atomic_state_default_release(state);
15390
15391         i915_sw_fence_fini(&intel_state->commit_ready);
15392
15393         kfree(state);
15394 }
15395
15396 static enum drm_mode_status
15397 intel_mode_valid(struct drm_device *dev,
15398                  const struct drm_display_mode *mode)
15399 {
15400         struct drm_i915_private *dev_priv = to_i915(dev);
15401         int hdisplay_max, htotal_max;
15402         int vdisplay_max, vtotal_max;
15403
15404         /*
15405          * Can't reject DBLSCAN here because Xorg ddxen can add piles
15406          * of DBLSCAN modes to the output's mode list when they detect
15407          * the scaling mode property on the connector. And they don't
15408          * ask the kernel to validate those modes in any way until
15409          * modeset time at which point the client gets a protocol error.
15410          * So in order to not upset those clients we silently ignore the
15411          * DBLSCAN flag on such connectors. For other connectors we will
15412          * reject modes with the DBLSCAN flag in encoder->compute_config().
15413          * And we always reject DBLSCAN modes in connector->mode_valid()
15414          * as we never want such modes on the connector's mode list.
15415          */
15416
15417         if (mode->vscan > 1)
15418                 return MODE_NO_VSCAN;
15419
15420         if (mode->flags & DRM_MODE_FLAG_HSKEW)
15421                 return MODE_H_ILLEGAL;
15422
15423         if (mode->flags & (DRM_MODE_FLAG_CSYNC |
15424                            DRM_MODE_FLAG_NCSYNC |
15425                            DRM_MODE_FLAG_PCSYNC))
15426                 return MODE_HSYNC;
15427
15428         if (mode->flags & (DRM_MODE_FLAG_BCAST |
15429                            DRM_MODE_FLAG_PIXMUX |
15430                            DRM_MODE_FLAG_CLKDIV2))
15431                 return MODE_BAD;
15432
15433         if (INTEL_GEN(dev_priv) >= 9 ||
15434             IS_BROADWELL(dev_priv) || IS_HASWELL(dev_priv)) {
15435                 hdisplay_max = 8192; /* FDI max 4096 handled elsewhere */
15436                 vdisplay_max = 4096;
15437                 htotal_max = 8192;
15438                 vtotal_max = 8192;
15439         } else if (INTEL_GEN(dev_priv) >= 3) {
15440                 hdisplay_max = 4096;
15441                 vdisplay_max = 4096;
15442                 htotal_max = 8192;
15443                 vtotal_max = 8192;
15444         } else {
15445                 hdisplay_max = 2048;
15446                 vdisplay_max = 2048;
15447                 htotal_max = 4096;
15448                 vtotal_max = 4096;
15449         }
15450
15451         if (mode->hdisplay > hdisplay_max ||
15452             mode->hsync_start > htotal_max ||
15453             mode->hsync_end > htotal_max ||
15454             mode->htotal > htotal_max)
15455                 return MODE_H_ILLEGAL;
15456
15457         if (mode->vdisplay > vdisplay_max ||
15458             mode->vsync_start > vtotal_max ||
15459             mode->vsync_end > vtotal_max ||
15460             mode->vtotal > vtotal_max)
15461                 return MODE_V_ILLEGAL;
15462
15463         return MODE_OK;
15464 }
15465
15466 static const struct drm_mode_config_funcs intel_mode_funcs = {
15467         .fb_create = intel_user_framebuffer_create,
15468         .get_format_info = intel_get_format_info,
15469         .output_poll_changed = intel_fbdev_output_poll_changed,
15470         .mode_valid = intel_mode_valid,
15471         .atomic_check = intel_atomic_check,
15472         .atomic_commit = intel_atomic_commit,
15473         .atomic_state_alloc = intel_atomic_state_alloc,
15474         .atomic_state_clear = intel_atomic_state_clear,
15475         .atomic_state_free = intel_atomic_state_free,
15476 };
15477
15478 /**
15479  * intel_init_display_hooks - initialize the display modesetting hooks
15480  * @dev_priv: device private
15481  */
15482 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
15483 {
15484         intel_init_cdclk_hooks(dev_priv);
15485
15486         if (INTEL_GEN(dev_priv) >= 9) {
15487                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
15488                 dev_priv->display.get_initial_plane_config =
15489                         skylake_get_initial_plane_config;
15490                 dev_priv->display.crtc_compute_clock =
15491                         haswell_crtc_compute_clock;
15492                 dev_priv->display.crtc_enable = haswell_crtc_enable;
15493                 dev_priv->display.crtc_disable = haswell_crtc_disable;
15494         } else if (HAS_DDI(dev_priv)) {
15495                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
15496                 dev_priv->display.get_initial_plane_config =
15497                         i9xx_get_initial_plane_config;
15498                 dev_priv->display.crtc_compute_clock =
15499                         haswell_crtc_compute_clock;
15500                 dev_priv->display.crtc_enable = haswell_crtc_enable;
15501                 dev_priv->display.crtc_disable = haswell_crtc_disable;
15502         } else if (HAS_PCH_SPLIT(dev_priv)) {
15503                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
15504                 dev_priv->display.get_initial_plane_config =
15505                         i9xx_get_initial_plane_config;
15506                 dev_priv->display.crtc_compute_clock =
15507                         ironlake_crtc_compute_clock;
15508                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
15509                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
15510         } else if (IS_CHERRYVIEW(dev_priv)) {
15511                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15512                 dev_priv->display.get_initial_plane_config =
15513                         i9xx_get_initial_plane_config;
15514                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
15515                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
15516                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15517         } else if (IS_VALLEYVIEW(dev_priv)) {
15518                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15519                 dev_priv->display.get_initial_plane_config =
15520                         i9xx_get_initial_plane_config;
15521                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
15522                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
15523                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15524         } else if (IS_G4X(dev_priv)) {
15525                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15526                 dev_priv->display.get_initial_plane_config =
15527                         i9xx_get_initial_plane_config;
15528                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
15529                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15530                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15531         } else if (IS_PINEVIEW(dev_priv)) {
15532                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15533                 dev_priv->display.get_initial_plane_config =
15534                         i9xx_get_initial_plane_config;
15535                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
15536                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15537                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15538         } else if (!IS_GEN(dev_priv, 2)) {
15539                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15540                 dev_priv->display.get_initial_plane_config =
15541                         i9xx_get_initial_plane_config;
15542                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
15543                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15544                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15545         } else {
15546                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15547                 dev_priv->display.get_initial_plane_config =
15548                         i9xx_get_initial_plane_config;
15549                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
15550                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15551                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15552         }
15553
15554         if (IS_GEN(dev_priv, 5)) {
15555                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
15556         } else if (IS_GEN(dev_priv, 6)) {
15557                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
15558         } else if (IS_IVYBRIDGE(dev_priv)) {
15559                 /* FIXME: detect B0+ stepping and use auto training */
15560                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
15561         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
15562                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
15563         }
15564
15565         if (INTEL_GEN(dev_priv) >= 9)
15566                 dev_priv->display.update_crtcs = skl_update_crtcs;
15567         else
15568                 dev_priv->display.update_crtcs = intel_update_crtcs;
15569 }
15570
15571 static i915_reg_t i915_vgacntrl_reg(struct drm_i915_private *dev_priv)
15572 {
15573         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
15574                 return VLV_VGACNTRL;
15575         else if (INTEL_GEN(dev_priv) >= 5)
15576                 return CPU_VGACNTRL;
15577         else
15578                 return VGACNTRL;
15579 }
15580
15581 /* Disable the VGA plane that we never use */
15582 static void i915_disable_vga(struct drm_i915_private *dev_priv)
15583 {
15584         struct pci_dev *pdev = dev_priv->drm.pdev;
15585         u8 sr1;
15586         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
15587
15588         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
15589         vga_get_uninterruptible(pdev, VGA_RSRC_LEGACY_IO);
15590         outb(SR01, VGA_SR_INDEX);
15591         sr1 = inb(VGA_SR_DATA);
15592         outb(sr1 | 1<<5, VGA_SR_DATA);
15593         vga_put(pdev, VGA_RSRC_LEGACY_IO);
15594         udelay(300);
15595
15596         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
15597         POSTING_READ(vga_reg);
15598 }
15599
15600 void intel_modeset_init_hw(struct drm_device *dev)
15601 {
15602         struct drm_i915_private *dev_priv = to_i915(dev);
15603
15604         intel_update_cdclk(dev_priv);
15605         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
15606         dev_priv->cdclk.logical = dev_priv->cdclk.actual = dev_priv->cdclk.hw;
15607 }
15608
15609 /*
15610  * Calculate what we think the watermarks should be for the state we've read
15611  * out of the hardware and then immediately program those watermarks so that
15612  * we ensure the hardware settings match our internal state.
15613  *
15614  * We can calculate what we think WM's should be by creating a duplicate of the
15615  * current state (which was constructed during hardware readout) and running it
15616  * through the atomic check code to calculate new watermark values in the
15617  * state object.
15618  */
15619 static void sanitize_watermarks(struct drm_device *dev)
15620 {
15621         struct drm_i915_private *dev_priv = to_i915(dev);
15622         struct drm_atomic_state *state;
15623         struct intel_atomic_state *intel_state;
15624         struct drm_crtc *crtc;
15625         struct drm_crtc_state *cstate;
15626         struct drm_modeset_acquire_ctx ctx;
15627         int ret;
15628         int i;
15629
15630         /* Only supported on platforms that use atomic watermark design */
15631         if (!dev_priv->display.optimize_watermarks)
15632                 return;
15633
15634         /*
15635          * We need to hold connection_mutex before calling duplicate_state so
15636          * that the connector loop is protected.
15637          */
15638         drm_modeset_acquire_init(&ctx, 0);
15639 retry:
15640         ret = drm_modeset_lock_all_ctx(dev, &ctx);
15641         if (ret == -EDEADLK) {
15642                 drm_modeset_backoff(&ctx);
15643                 goto retry;
15644         } else if (WARN_ON(ret)) {
15645                 goto fail;
15646         }
15647
15648         state = drm_atomic_helper_duplicate_state(dev, &ctx);
15649         if (WARN_ON(IS_ERR(state)))
15650                 goto fail;
15651
15652         intel_state = to_intel_atomic_state(state);
15653
15654         /*
15655          * Hardware readout is the only time we don't want to calculate
15656          * intermediate watermarks (since we don't trust the current
15657          * watermarks).
15658          */
15659         if (!HAS_GMCH(dev_priv))
15660                 intel_state->skip_intermediate_wm = true;
15661
15662         ret = intel_atomic_check(dev, state);
15663         if (ret) {
15664                 /*
15665                  * If we fail here, it means that the hardware appears to be
15666                  * programmed in a way that shouldn't be possible, given our
15667                  * understanding of watermark requirements.  This might mean a
15668                  * mistake in the hardware readout code or a mistake in the
15669                  * watermark calculations for a given platform.  Raise a WARN
15670                  * so that this is noticeable.
15671                  *
15672                  * If this actually happens, we'll have to just leave the
15673                  * BIOS-programmed watermarks untouched and hope for the best.
15674                  */
15675                 WARN(true, "Could not determine valid watermarks for inherited state\n");
15676                 goto put_state;
15677         }
15678
15679         /* Write calculated watermark values back */
15680         for_each_new_crtc_in_state(state, crtc, cstate, i) {
15681                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
15682
15683                 cs->wm.need_postvbl_update = true;
15684                 dev_priv->display.optimize_watermarks(intel_state, cs);
15685
15686                 to_intel_crtc_state(crtc->state)->wm = cs->wm;
15687         }
15688
15689 put_state:
15690         drm_atomic_state_put(state);
15691 fail:
15692         drm_modeset_drop_locks(&ctx);
15693         drm_modeset_acquire_fini(&ctx);
15694 }
15695
15696 static void intel_update_fdi_pll_freq(struct drm_i915_private *dev_priv)
15697 {
15698         if (IS_GEN(dev_priv, 5)) {
15699                 u32 fdi_pll_clk =
15700                         I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK;
15701
15702                 dev_priv->fdi_pll_freq = (fdi_pll_clk + 2) * 10000;
15703         } else if (IS_GEN(dev_priv, 6) || IS_IVYBRIDGE(dev_priv)) {
15704                 dev_priv->fdi_pll_freq = 270000;
15705         } else {
15706                 return;
15707         }
15708
15709         DRM_DEBUG_DRIVER("FDI PLL freq=%d\n", dev_priv->fdi_pll_freq);
15710 }
15711
15712 static int intel_initial_commit(struct drm_device *dev)
15713 {
15714         struct drm_atomic_state *state = NULL;
15715         struct drm_modeset_acquire_ctx ctx;
15716         struct drm_crtc *crtc;
15717         struct drm_crtc_state *crtc_state;
15718         int ret = 0;
15719
15720         state = drm_atomic_state_alloc(dev);
15721         if (!state)
15722                 return -ENOMEM;
15723
15724         drm_modeset_acquire_init(&ctx, 0);
15725
15726 retry:
15727         state->acquire_ctx = &ctx;
15728
15729         drm_for_each_crtc(crtc, dev) {
15730                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
15731                 if (IS_ERR(crtc_state)) {
15732                         ret = PTR_ERR(crtc_state);
15733                         goto out;
15734                 }
15735
15736                 if (crtc_state->active) {
15737                         ret = drm_atomic_add_affected_planes(state, crtc);
15738                         if (ret)
15739                                 goto out;
15740
15741                         /*
15742                          * FIXME hack to force a LUT update to avoid the
15743                          * plane update forcing the pipe gamma on without
15744                          * having a proper LUT loaded. Remove once we
15745                          * have readout for pipe gamma enable.
15746                          */
15747                         crtc_state->color_mgmt_changed = true;
15748                 }
15749         }
15750
15751         ret = drm_atomic_commit(state);
15752
15753 out:
15754         if (ret == -EDEADLK) {
15755                 drm_atomic_state_clear(state);
15756                 drm_modeset_backoff(&ctx);
15757                 goto retry;
15758         }
15759
15760         drm_atomic_state_put(state);
15761
15762         drm_modeset_drop_locks(&ctx);
15763         drm_modeset_acquire_fini(&ctx);
15764
15765         return ret;
15766 }
15767
15768 int intel_modeset_init(struct drm_device *dev)
15769 {
15770         struct drm_i915_private *dev_priv = to_i915(dev);
15771         struct i915_ggtt *ggtt = &dev_priv->ggtt;
15772         enum pipe pipe;
15773         struct intel_crtc *crtc;
15774         int ret;
15775
15776         dev_priv->modeset_wq = alloc_ordered_workqueue("i915_modeset", 0);
15777
15778         drm_mode_config_init(dev);
15779
15780         dev->mode_config.min_width = 0;
15781         dev->mode_config.min_height = 0;
15782
15783         dev->mode_config.preferred_depth = 24;
15784         dev->mode_config.prefer_shadow = 1;
15785
15786         dev->mode_config.allow_fb_modifiers = true;
15787
15788         dev->mode_config.funcs = &intel_mode_funcs;
15789
15790         init_llist_head(&dev_priv->atomic_helper.free_list);
15791         INIT_WORK(&dev_priv->atomic_helper.free_work,
15792                   intel_atomic_helper_free_state_worker);
15793
15794         intel_init_quirks(dev_priv);
15795
15796         intel_fbc_init(dev_priv);
15797
15798         intel_init_pm(dev_priv);
15799
15800         /*
15801          * There may be no VBT; and if the BIOS enabled SSC we can
15802          * just keep using it to avoid unnecessary flicker.  Whereas if the
15803          * BIOS isn't using it, don't assume it will work even if the VBT
15804          * indicates as much.
15805          */
15806         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv)) {
15807                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
15808                                             DREF_SSC1_ENABLE);
15809
15810                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
15811                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
15812                                      bios_lvds_use_ssc ? "en" : "dis",
15813                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
15814                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
15815                 }
15816         }
15817
15818         /* maximum framebuffer dimensions */
15819         if (IS_GEN(dev_priv, 2)) {
15820                 dev->mode_config.max_width = 2048;
15821                 dev->mode_config.max_height = 2048;
15822         } else if (IS_GEN(dev_priv, 3)) {
15823                 dev->mode_config.max_width = 4096;
15824                 dev->mode_config.max_height = 4096;
15825         } else {
15826                 dev->mode_config.max_width = 8192;
15827                 dev->mode_config.max_height = 8192;
15828         }
15829
15830         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
15831                 dev->mode_config.cursor_width = IS_I845G(dev_priv) ? 64 : 512;
15832                 dev->mode_config.cursor_height = 1023;
15833         } else if (IS_GEN(dev_priv, 2)) {
15834                 dev->mode_config.cursor_width = 64;
15835                 dev->mode_config.cursor_height = 64;
15836         } else {
15837                 dev->mode_config.cursor_width = 256;
15838                 dev->mode_config.cursor_height = 256;
15839         }
15840
15841         dev->mode_config.fb_base = ggtt->gmadr.start;
15842
15843         DRM_DEBUG_KMS("%d display pipe%s available.\n",
15844                       INTEL_INFO(dev_priv)->num_pipes,
15845                       INTEL_INFO(dev_priv)->num_pipes > 1 ? "s" : "");
15846
15847         for_each_pipe(dev_priv, pipe) {
15848                 ret = intel_crtc_init(dev_priv, pipe);
15849                 if (ret) {
15850                         drm_mode_config_cleanup(dev);
15851                         return ret;
15852                 }
15853         }
15854
15855         intel_shared_dpll_init(dev);
15856         intel_update_fdi_pll_freq(dev_priv);
15857
15858         intel_update_czclk(dev_priv);
15859         intel_modeset_init_hw(dev);
15860
15861         intel_hdcp_component_init(dev_priv);
15862
15863         if (dev_priv->max_cdclk_freq == 0)
15864                 intel_update_max_cdclk(dev_priv);
15865
15866         /* Just disable it once at startup */
15867         i915_disable_vga(dev_priv);
15868         intel_setup_outputs(dev_priv);
15869
15870         drm_modeset_lock_all(dev);
15871         intel_modeset_setup_hw_state(dev, dev->mode_config.acquire_ctx);
15872         drm_modeset_unlock_all(dev);
15873
15874         for_each_intel_crtc(dev, crtc) {
15875                 struct intel_initial_plane_config plane_config = {};
15876
15877                 if (!crtc->active)
15878                         continue;
15879
15880                 /*
15881                  * Note that reserving the BIOS fb up front prevents us
15882                  * from stuffing other stolen allocations like the ring
15883                  * on top.  This prevents some ugliness at boot time, and
15884                  * can even allow for smooth boot transitions if the BIOS
15885                  * fb is large enough for the active pipe configuration.
15886                  */
15887                 dev_priv->display.get_initial_plane_config(crtc,
15888                                                            &plane_config);
15889
15890                 /*
15891                  * If the fb is shared between multiple heads, we'll
15892                  * just get the first one.
15893                  */
15894                 intel_find_initial_plane_obj(crtc, &plane_config);
15895         }
15896
15897         /*
15898          * Make sure hardware watermarks really match the state we read out.
15899          * Note that we need to do this after reconstructing the BIOS fb's
15900          * since the watermark calculation done here will use pstate->fb.
15901          */
15902         if (!HAS_GMCH(dev_priv))
15903                 sanitize_watermarks(dev);
15904
15905         /*
15906          * Force all active planes to recompute their states. So that on
15907          * mode_setcrtc after probe, all the intel_plane_state variables
15908          * are already calculated and there is no assert_plane warnings
15909          * during bootup.
15910          */
15911         ret = intel_initial_commit(dev);
15912         if (ret)
15913                 DRM_DEBUG_KMS("Initial commit in probe failed.\n");
15914
15915         return 0;
15916 }
15917
15918 void i830_enable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
15919 {
15920         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15921         /* 640x480@60Hz, ~25175 kHz */
15922         struct dpll clock = {
15923                 .m1 = 18,
15924                 .m2 = 7,
15925                 .p1 = 13,
15926                 .p2 = 4,
15927                 .n = 2,
15928         };
15929         u32 dpll, fp;
15930         int i;
15931
15932         WARN_ON(i9xx_calc_dpll_params(48000, &clock) != 25154);
15933
15934         DRM_DEBUG_KMS("enabling pipe %c due to force quirk (vco=%d dot=%d)\n",
15935                       pipe_name(pipe), clock.vco, clock.dot);
15936
15937         fp = i9xx_dpll_compute_fp(&clock);
15938         dpll = DPLL_DVO_2X_MODE |
15939                 DPLL_VGA_MODE_DIS |
15940                 ((clock.p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT) |
15941                 PLL_P2_DIVIDE_BY_4 |
15942                 PLL_REF_INPUT_DREFCLK |
15943                 DPLL_VCO_ENABLE;
15944
15945         I915_WRITE(FP0(pipe), fp);
15946         I915_WRITE(FP1(pipe), fp);
15947
15948         I915_WRITE(HTOTAL(pipe), (640 - 1) | ((800 - 1) << 16));
15949         I915_WRITE(HBLANK(pipe), (640 - 1) | ((800 - 1) << 16));
15950         I915_WRITE(HSYNC(pipe), (656 - 1) | ((752 - 1) << 16));
15951         I915_WRITE(VTOTAL(pipe), (480 - 1) | ((525 - 1) << 16));
15952         I915_WRITE(VBLANK(pipe), (480 - 1) | ((525 - 1) << 16));
15953         I915_WRITE(VSYNC(pipe), (490 - 1) | ((492 - 1) << 16));
15954         I915_WRITE(PIPESRC(pipe), ((640 - 1) << 16) | (480 - 1));
15955
15956         /*
15957          * Apparently we need to have VGA mode enabled prior to changing
15958          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
15959          * dividers, even though the register value does change.
15960          */
15961         I915_WRITE(DPLL(pipe), dpll & ~DPLL_VGA_MODE_DIS);
15962         I915_WRITE(DPLL(pipe), dpll);
15963
15964         /* Wait for the clocks to stabilize. */
15965         POSTING_READ(DPLL(pipe));
15966         udelay(150);
15967
15968         /* The pixel multiplier can only be updated once the
15969          * DPLL is enabled and the clocks are stable.
15970          *
15971          * So write it again.
15972          */
15973         I915_WRITE(DPLL(pipe), dpll);
15974
15975         /* We do this three times for luck */
15976         for (i = 0; i < 3 ; i++) {
15977                 I915_WRITE(DPLL(pipe), dpll);
15978                 POSTING_READ(DPLL(pipe));
15979                 udelay(150); /* wait for warmup */
15980         }
15981
15982         I915_WRITE(PIPECONF(pipe), PIPECONF_ENABLE | PIPECONF_PROGRESSIVE);
15983         POSTING_READ(PIPECONF(pipe));
15984
15985         intel_wait_for_pipe_scanline_moving(crtc);
15986 }
15987
15988 void i830_disable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
15989 {
15990         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15991
15992         DRM_DEBUG_KMS("disabling pipe %c due to force quirk\n",
15993                       pipe_name(pipe));
15994
15995         WARN_ON(I915_READ(DSPCNTR(PLANE_A)) & DISPLAY_PLANE_ENABLE);
15996         WARN_ON(I915_READ(DSPCNTR(PLANE_B)) & DISPLAY_PLANE_ENABLE);
15997         WARN_ON(I915_READ(DSPCNTR(PLANE_C)) & DISPLAY_PLANE_ENABLE);
15998         WARN_ON(I915_READ(CURCNTR(PIPE_A)) & MCURSOR_MODE);
15999         WARN_ON(I915_READ(CURCNTR(PIPE_B)) & MCURSOR_MODE);
16000
16001         I915_WRITE(PIPECONF(pipe), 0);
16002         POSTING_READ(PIPECONF(pipe));
16003
16004         intel_wait_for_pipe_scanline_stopped(crtc);
16005
16006         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
16007         POSTING_READ(DPLL(pipe));
16008 }
16009
16010 static void
16011 intel_sanitize_plane_mapping(struct drm_i915_private *dev_priv)
16012 {
16013         struct intel_crtc *crtc;
16014
16015         if (INTEL_GEN(dev_priv) >= 4)
16016                 return;
16017
16018         for_each_intel_crtc(&dev_priv->drm, crtc) {
16019                 struct intel_plane *plane =
16020                         to_intel_plane(crtc->base.primary);
16021                 struct intel_crtc *plane_crtc;
16022                 enum pipe pipe;
16023
16024                 if (!plane->get_hw_state(plane, &pipe))
16025                         continue;
16026
16027                 if (pipe == crtc->pipe)
16028                         continue;
16029
16030                 DRM_DEBUG_KMS("[PLANE:%d:%s] attached to the wrong pipe, disabling plane\n",
16031                               plane->base.base.id, plane->base.name);
16032
16033                 plane_crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
16034                 intel_plane_disable_noatomic(plane_crtc, plane);
16035         }
16036 }
16037
16038 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
16039 {
16040         struct drm_device *dev = crtc->base.dev;
16041         struct intel_encoder *encoder;
16042
16043         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
16044                 return true;
16045
16046         return false;
16047 }
16048
16049 static struct intel_connector *intel_encoder_find_connector(struct intel_encoder *encoder)
16050 {
16051         struct drm_device *dev = encoder->base.dev;
16052         struct intel_connector *connector;
16053
16054         for_each_connector_on_encoder(dev, &encoder->base, connector)
16055                 return connector;
16056
16057         return NULL;
16058 }
16059
16060 static bool has_pch_trancoder(struct drm_i915_private *dev_priv,
16061                               enum pipe pch_transcoder)
16062 {
16063         return HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv) ||
16064                 (HAS_PCH_LPT_H(dev_priv) && pch_transcoder == PIPE_A);
16065 }
16066
16067 static void intel_sanitize_crtc(struct intel_crtc *crtc,
16068                                 struct drm_modeset_acquire_ctx *ctx)
16069 {
16070         struct drm_device *dev = crtc->base.dev;
16071         struct drm_i915_private *dev_priv = to_i915(dev);
16072         struct intel_crtc_state *crtc_state = to_intel_crtc_state(crtc->base.state);
16073         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
16074
16075         /* Clear any frame start delays used for debugging left by the BIOS */
16076         if (crtc->active && !transcoder_is_dsi(cpu_transcoder)) {
16077                 i915_reg_t reg = PIPECONF(cpu_transcoder);
16078
16079                 I915_WRITE(reg,
16080                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
16081         }
16082
16083         if (crtc_state->base.active) {
16084                 struct intel_plane *plane;
16085
16086                 /* Disable everything but the primary plane */
16087                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
16088                         const struct intel_plane_state *plane_state =
16089                                 to_intel_plane_state(plane->base.state);
16090
16091                         if (plane_state->base.visible &&
16092                             plane->base.type != DRM_PLANE_TYPE_PRIMARY)
16093                                 intel_plane_disable_noatomic(crtc, plane);
16094                 }
16095
16096                 /*
16097                  * Disable any background color set by the BIOS, but enable the
16098                  * gamma and CSC to match how we program our planes.
16099                  */
16100                 if (INTEL_GEN(dev_priv) >= 9)
16101                         I915_WRITE(SKL_BOTTOM_COLOR(crtc->pipe),
16102                                    SKL_BOTTOM_COLOR_GAMMA_ENABLE |
16103                                    SKL_BOTTOM_COLOR_CSC_ENABLE);
16104         }
16105
16106         /* Adjust the state of the output pipe according to whether we
16107          * have active connectors/encoders. */
16108         if (crtc_state->base.active && !intel_crtc_has_encoders(crtc))
16109                 intel_crtc_disable_noatomic(&crtc->base, ctx);
16110
16111         if (crtc_state->base.active || HAS_GMCH(dev_priv)) {
16112                 /*
16113                  * We start out with underrun reporting disabled to avoid races.
16114                  * For correct bookkeeping mark this on active crtcs.
16115                  *
16116                  * Also on gmch platforms we dont have any hardware bits to
16117                  * disable the underrun reporting. Which means we need to start
16118                  * out with underrun reporting disabled also on inactive pipes,
16119                  * since otherwise we'll complain about the garbage we read when
16120                  * e.g. coming up after runtime pm.
16121                  *
16122                  * No protection against concurrent access is required - at
16123                  * worst a fifo underrun happens which also sets this to false.
16124                  */
16125                 crtc->cpu_fifo_underrun_disabled = true;
16126                 /*
16127                  * We track the PCH trancoder underrun reporting state
16128                  * within the crtc. With crtc for pipe A housing the underrun
16129                  * reporting state for PCH transcoder A, crtc for pipe B housing
16130                  * it for PCH transcoder B, etc. LPT-H has only PCH transcoder A,
16131                  * and marking underrun reporting as disabled for the non-existing
16132                  * PCH transcoders B and C would prevent enabling the south
16133                  * error interrupt (see cpt_can_enable_serr_int()).
16134                  */
16135                 if (has_pch_trancoder(dev_priv, crtc->pipe))
16136                         crtc->pch_fifo_underrun_disabled = true;
16137         }
16138 }
16139
16140 static bool has_bogus_dpll_config(const struct intel_crtc_state *crtc_state)
16141 {
16142         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
16143
16144         /*
16145          * Some SNB BIOSen (eg. ASUS K53SV) are known to misprogram
16146          * the hardware when a high res displays plugged in. DPLL P
16147          * divider is zero, and the pipe timings are bonkers. We'll
16148          * try to disable everything in that case.
16149          *
16150          * FIXME would be nice to be able to sanitize this state
16151          * without several WARNs, but for now let's take the easy
16152          * road.
16153          */
16154         return IS_GEN(dev_priv, 6) &&
16155                 crtc_state->base.active &&
16156                 crtc_state->shared_dpll &&
16157                 crtc_state->port_clock == 0;
16158 }
16159
16160 static void intel_sanitize_encoder(struct intel_encoder *encoder)
16161 {
16162         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
16163         struct intel_connector *connector;
16164         struct intel_crtc *crtc = to_intel_crtc(encoder->base.crtc);
16165         struct intel_crtc_state *crtc_state = crtc ?
16166                 to_intel_crtc_state(crtc->base.state) : NULL;
16167
16168         /* We need to check both for a crtc link (meaning that the
16169          * encoder is active and trying to read from a pipe) and the
16170          * pipe itself being active. */
16171         bool has_active_crtc = crtc_state &&
16172                 crtc_state->base.active;
16173
16174         if (crtc_state && has_bogus_dpll_config(crtc_state)) {
16175                 DRM_DEBUG_KMS("BIOS has misprogrammed the hardware. Disabling pipe %c\n",
16176                               pipe_name(crtc->pipe));
16177                 has_active_crtc = false;
16178         }
16179
16180         connector = intel_encoder_find_connector(encoder);
16181         if (connector && !has_active_crtc) {
16182                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
16183                               encoder->base.base.id,
16184                               encoder->base.name);
16185
16186                 /* Connector is active, but has no active pipe. This is
16187                  * fallout from our resume register restoring. Disable
16188                  * the encoder manually again. */
16189                 if (crtc_state) {
16190                         struct drm_encoder *best_encoder;
16191
16192                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
16193                                       encoder->base.base.id,
16194                                       encoder->base.name);
16195
16196                         /* avoid oopsing in case the hooks consult best_encoder */
16197                         best_encoder = connector->base.state->best_encoder;
16198                         connector->base.state->best_encoder = &encoder->base;
16199
16200                         if (encoder->disable)
16201                                 encoder->disable(encoder, crtc_state,
16202                                                  connector->base.state);
16203                         if (encoder->post_disable)
16204                                 encoder->post_disable(encoder, crtc_state,
16205                                                       connector->base.state);
16206
16207                         connector->base.state->best_encoder = best_encoder;
16208                 }
16209                 encoder->base.crtc = NULL;
16210
16211                 /* Inconsistent output/port/pipe state happens presumably due to
16212                  * a bug in one of the get_hw_state functions. Or someplace else
16213                  * in our code, like the register restore mess on resume. Clamp
16214                  * things to off as a safer default. */
16215
16216                 connector->base.dpms = DRM_MODE_DPMS_OFF;
16217                 connector->base.encoder = NULL;
16218         }
16219
16220         /* notify opregion of the sanitized encoder state */
16221         intel_opregion_notify_encoder(encoder, connector && has_active_crtc);
16222
16223         if (INTEL_GEN(dev_priv) >= 11)
16224                 icl_sanitize_encoder_pll_mapping(encoder);
16225 }
16226
16227 void i915_redisable_vga_power_on(struct drm_i915_private *dev_priv)
16228 {
16229         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
16230
16231         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
16232                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
16233                 i915_disable_vga(dev_priv);
16234         }
16235 }
16236
16237 void i915_redisable_vga(struct drm_i915_private *dev_priv)
16238 {
16239         intel_wakeref_t wakeref;
16240
16241         /*
16242          * This function can be called both from intel_modeset_setup_hw_state or
16243          * at a very early point in our resume sequence, where the power well
16244          * structures are not yet restored. Since this function is at a very
16245          * paranoid "someone might have enabled VGA while we were not looking"
16246          * level, just check if the power well is enabled instead of trying to
16247          * follow the "don't touch the power well if we don't need it" policy
16248          * the rest of the driver uses.
16249          */
16250         wakeref = intel_display_power_get_if_enabled(dev_priv,
16251                                                      POWER_DOMAIN_VGA);
16252         if (!wakeref)
16253                 return;
16254
16255         i915_redisable_vga_power_on(dev_priv);
16256
16257         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA, wakeref);
16258 }
16259
16260 /* FIXME read out full plane state for all planes */
16261 static void readout_plane_state(struct drm_i915_private *dev_priv)
16262 {
16263         struct intel_plane *plane;
16264         struct intel_crtc *crtc;
16265
16266         for_each_intel_plane(&dev_priv->drm, plane) {
16267                 struct intel_plane_state *plane_state =
16268                         to_intel_plane_state(plane->base.state);
16269                 struct intel_crtc_state *crtc_state;
16270                 enum pipe pipe = PIPE_A;
16271                 bool visible;
16272
16273                 visible = plane->get_hw_state(plane, &pipe);
16274
16275                 crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
16276                 crtc_state = to_intel_crtc_state(crtc->base.state);
16277
16278                 intel_set_plane_visible(crtc_state, plane_state, visible);
16279
16280                 DRM_DEBUG_KMS("[PLANE:%d:%s] hw state readout: %s, pipe %c\n",
16281                               plane->base.base.id, plane->base.name,
16282                               enableddisabled(visible), pipe_name(pipe));
16283         }
16284
16285         for_each_intel_crtc(&dev_priv->drm, crtc) {
16286                 struct intel_crtc_state *crtc_state =
16287                         to_intel_crtc_state(crtc->base.state);
16288
16289                 fixup_active_planes(crtc_state);
16290         }
16291 }
16292
16293 static void intel_modeset_readout_hw_state(struct drm_device *dev)
16294 {
16295         struct drm_i915_private *dev_priv = to_i915(dev);
16296         enum pipe pipe;
16297         struct intel_crtc *crtc;
16298         struct intel_encoder *encoder;
16299         struct intel_connector *connector;
16300         struct drm_connector_list_iter conn_iter;
16301         int i;
16302
16303         dev_priv->active_crtcs = 0;
16304
16305         for_each_intel_crtc(dev, crtc) {
16306                 struct intel_crtc_state *crtc_state =
16307                         to_intel_crtc_state(crtc->base.state);
16308
16309                 __drm_atomic_helper_crtc_destroy_state(&crtc_state->base);
16310                 memset(crtc_state, 0, sizeof(*crtc_state));
16311                 crtc_state->base.crtc = &crtc->base;
16312
16313                 crtc_state->base.active = crtc_state->base.enable =
16314                         dev_priv->display.get_pipe_config(crtc, crtc_state);
16315
16316                 crtc->base.enabled = crtc_state->base.enable;
16317                 crtc->active = crtc_state->base.active;
16318
16319                 if (crtc_state->base.active)
16320                         dev_priv->active_crtcs |= 1 << crtc->pipe;
16321
16322                 DRM_DEBUG_KMS("[CRTC:%d:%s] hw state readout: %s\n",
16323                               crtc->base.base.id, crtc->base.name,
16324                               enableddisabled(crtc_state->base.active));
16325         }
16326
16327         readout_plane_state(dev_priv);
16328
16329         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
16330                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
16331
16332                 pll->on = pll->info->funcs->get_hw_state(dev_priv, pll,
16333                                                         &pll->state.hw_state);
16334                 pll->state.crtc_mask = 0;
16335                 for_each_intel_crtc(dev, crtc) {
16336                         struct intel_crtc_state *crtc_state =
16337                                 to_intel_crtc_state(crtc->base.state);
16338
16339                         if (crtc_state->base.active &&
16340                             crtc_state->shared_dpll == pll)
16341                                 pll->state.crtc_mask |= 1 << crtc->pipe;
16342                 }
16343                 pll->active_mask = pll->state.crtc_mask;
16344
16345                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
16346                               pll->info->name, pll->state.crtc_mask, pll->on);
16347         }
16348
16349         for_each_intel_encoder(dev, encoder) {
16350                 pipe = 0;
16351
16352                 if (encoder->get_hw_state(encoder, &pipe)) {
16353                         struct intel_crtc_state *crtc_state;
16354
16355                         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
16356                         crtc_state = to_intel_crtc_state(crtc->base.state);
16357
16358                         encoder->base.crtc = &crtc->base;
16359                         encoder->get_config(encoder, crtc_state);
16360                 } else {
16361                         encoder->base.crtc = NULL;
16362                 }
16363
16364                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
16365                               encoder->base.base.id, encoder->base.name,
16366                               enableddisabled(encoder->base.crtc),
16367                               pipe_name(pipe));
16368         }
16369
16370         drm_connector_list_iter_begin(dev, &conn_iter);
16371         for_each_intel_connector_iter(connector, &conn_iter) {
16372                 if (connector->get_hw_state(connector)) {
16373                         connector->base.dpms = DRM_MODE_DPMS_ON;
16374
16375                         encoder = connector->encoder;
16376                         connector->base.encoder = &encoder->base;
16377
16378                         if (encoder->base.crtc &&
16379                             encoder->base.crtc->state->active) {
16380                                 /*
16381                                  * This has to be done during hardware readout
16382                                  * because anything calling .crtc_disable may
16383                                  * rely on the connector_mask being accurate.
16384                                  */
16385                                 encoder->base.crtc->state->connector_mask |=
16386                                         drm_connector_mask(&connector->base);
16387                                 encoder->base.crtc->state->encoder_mask |=
16388                                         drm_encoder_mask(&encoder->base);
16389                         }
16390
16391                 } else {
16392                         connector->base.dpms = DRM_MODE_DPMS_OFF;
16393                         connector->base.encoder = NULL;
16394                 }
16395                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
16396                               connector->base.base.id, connector->base.name,
16397                               enableddisabled(connector->base.encoder));
16398         }
16399         drm_connector_list_iter_end(&conn_iter);
16400
16401         for_each_intel_crtc(dev, crtc) {
16402                 struct intel_crtc_state *crtc_state =
16403                         to_intel_crtc_state(crtc->base.state);
16404                 int min_cdclk = 0;
16405
16406                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
16407                 if (crtc_state->base.active) {
16408                         intel_mode_from_pipe_config(&crtc->base.mode, crtc_state);
16409                         crtc->base.mode.hdisplay = crtc_state->pipe_src_w;
16410                         crtc->base.mode.vdisplay = crtc_state->pipe_src_h;
16411                         intel_mode_from_pipe_config(&crtc_state->base.adjusted_mode, crtc_state);
16412                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
16413
16414                         /*
16415                          * The initial mode needs to be set in order to keep
16416                          * the atomic core happy. It wants a valid mode if the
16417                          * crtc's enabled, so we do the above call.
16418                          *
16419                          * But we don't set all the derived state fully, hence
16420                          * set a flag to indicate that a full recalculation is
16421                          * needed on the next commit.
16422                          */
16423                         crtc_state->base.mode.private_flags = I915_MODE_FLAG_INHERITED;
16424
16425                         intel_crtc_compute_pixel_rate(crtc_state);
16426
16427                         if (dev_priv->display.modeset_calc_cdclk) {
16428                                 min_cdclk = intel_crtc_compute_min_cdclk(crtc_state);
16429                                 if (WARN_ON(min_cdclk < 0))
16430                                         min_cdclk = 0;
16431                         }
16432
16433                         drm_calc_timestamping_constants(&crtc->base,
16434                                                         &crtc_state->base.adjusted_mode);
16435                         update_scanline_offset(crtc_state);
16436                 }
16437
16438                 dev_priv->min_cdclk[crtc->pipe] = min_cdclk;
16439                 dev_priv->min_voltage_level[crtc->pipe] =
16440                         crtc_state->min_voltage_level;
16441
16442                 intel_pipe_config_sanity_check(dev_priv, crtc_state);
16443         }
16444 }
16445
16446 static void
16447 get_encoder_power_domains(struct drm_i915_private *dev_priv)
16448 {
16449         struct intel_encoder *encoder;
16450
16451         for_each_intel_encoder(&dev_priv->drm, encoder) {
16452                 struct intel_crtc_state *crtc_state;
16453
16454                 if (!encoder->get_power_domains)
16455                         continue;
16456
16457                 /*
16458                  * MST-primary and inactive encoders don't have a crtc state
16459                  * and neither of these require any power domain references.
16460                  */
16461                 if (!encoder->base.crtc)
16462                         continue;
16463
16464                 crtc_state = to_intel_crtc_state(encoder->base.crtc->state);
16465                 encoder->get_power_domains(encoder, crtc_state);
16466         }
16467 }
16468
16469 static void intel_early_display_was(struct drm_i915_private *dev_priv)
16470 {
16471         /* Display WA #1185 WaDisableDARBFClkGating:cnl,glk */
16472         if (IS_CANNONLAKE(dev_priv) || IS_GEMINILAKE(dev_priv))
16473                 I915_WRITE(GEN9_CLKGATE_DIS_0, I915_READ(GEN9_CLKGATE_DIS_0) |
16474                            DARBF_GATING_DIS);
16475
16476         if (IS_HASWELL(dev_priv)) {
16477                 /*
16478                  * WaRsPkgCStateDisplayPMReq:hsw
16479                  * System hang if this isn't done before disabling all planes!
16480                  */
16481                 I915_WRITE(CHICKEN_PAR1_1,
16482                            I915_READ(CHICKEN_PAR1_1) | FORCE_ARB_IDLE_PLANES);
16483         }
16484 }
16485
16486 static void ibx_sanitize_pch_hdmi_port(struct drm_i915_private *dev_priv,
16487                                        enum port port, i915_reg_t hdmi_reg)
16488 {
16489         u32 val = I915_READ(hdmi_reg);
16490
16491         if (val & SDVO_ENABLE ||
16492             (val & SDVO_PIPE_SEL_MASK) == SDVO_PIPE_SEL(PIPE_A))
16493                 return;
16494
16495         DRM_DEBUG_KMS("Sanitizing transcoder select for HDMI %c\n",
16496                       port_name(port));
16497
16498         val &= ~SDVO_PIPE_SEL_MASK;
16499         val |= SDVO_PIPE_SEL(PIPE_A);
16500
16501         I915_WRITE(hdmi_reg, val);
16502 }
16503
16504 static void ibx_sanitize_pch_dp_port(struct drm_i915_private *dev_priv,
16505                                      enum port port, i915_reg_t dp_reg)
16506 {
16507         u32 val = I915_READ(dp_reg);
16508
16509         if (val & DP_PORT_EN ||
16510             (val & DP_PIPE_SEL_MASK) == DP_PIPE_SEL(PIPE_A))
16511                 return;
16512
16513         DRM_DEBUG_KMS("Sanitizing transcoder select for DP %c\n",
16514                       port_name(port));
16515
16516         val &= ~DP_PIPE_SEL_MASK;
16517         val |= DP_PIPE_SEL(PIPE_A);
16518
16519         I915_WRITE(dp_reg, val);
16520 }
16521
16522 static void ibx_sanitize_pch_ports(struct drm_i915_private *dev_priv)
16523 {
16524         /*
16525          * The BIOS may select transcoder B on some of the PCH
16526          * ports even it doesn't enable the port. This would trip
16527          * assert_pch_dp_disabled() and assert_pch_hdmi_disabled().
16528          * Sanitize the transcoder select bits to prevent that. We
16529          * assume that the BIOS never actually enabled the port,
16530          * because if it did we'd actually have to toggle the port
16531          * on and back off to make the transcoder A select stick
16532          * (see. intel_dp_link_down(), intel_disable_hdmi(),
16533          * intel_disable_sdvo()).
16534          */
16535         ibx_sanitize_pch_dp_port(dev_priv, PORT_B, PCH_DP_B);
16536         ibx_sanitize_pch_dp_port(dev_priv, PORT_C, PCH_DP_C);
16537         ibx_sanitize_pch_dp_port(dev_priv, PORT_D, PCH_DP_D);
16538
16539         /* PCH SDVOB multiplex with HDMIB */
16540         ibx_sanitize_pch_hdmi_port(dev_priv, PORT_B, PCH_HDMIB);
16541         ibx_sanitize_pch_hdmi_port(dev_priv, PORT_C, PCH_HDMIC);
16542         ibx_sanitize_pch_hdmi_port(dev_priv, PORT_D, PCH_HDMID);
16543 }
16544
16545 /* Scan out the current hw modeset state,
16546  * and sanitizes it to the current state
16547  */
16548 static void
16549 intel_modeset_setup_hw_state(struct drm_device *dev,
16550                              struct drm_modeset_acquire_ctx *ctx)
16551 {
16552         struct drm_i915_private *dev_priv = to_i915(dev);
16553         struct intel_crtc_state *crtc_state;
16554         struct intel_encoder *encoder;
16555         struct intel_crtc *crtc;
16556         intel_wakeref_t wakeref;
16557         int i;
16558
16559         wakeref = intel_display_power_get(dev_priv, POWER_DOMAIN_INIT);
16560
16561         intel_early_display_was(dev_priv);
16562         intel_modeset_readout_hw_state(dev);
16563
16564         /* HW state is read out, now we need to sanitize this mess. */
16565         get_encoder_power_domains(dev_priv);
16566
16567         if (HAS_PCH_IBX(dev_priv))
16568                 ibx_sanitize_pch_ports(dev_priv);
16569
16570         /*
16571          * intel_sanitize_plane_mapping() may need to do vblank
16572          * waits, so we need vblank interrupts restored beforehand.
16573          */
16574         for_each_intel_crtc(&dev_priv->drm, crtc) {
16575                 crtc_state = to_intel_crtc_state(crtc->base.state);
16576
16577                 drm_crtc_vblank_reset(&crtc->base);
16578
16579                 if (crtc_state->base.active)
16580                         intel_crtc_vblank_on(crtc_state);
16581         }
16582
16583         intel_sanitize_plane_mapping(dev_priv);
16584
16585         for_each_intel_encoder(dev, encoder)
16586                 intel_sanitize_encoder(encoder);
16587
16588         for_each_intel_crtc(&dev_priv->drm, crtc) {
16589                 crtc_state = to_intel_crtc_state(crtc->base.state);
16590                 intel_sanitize_crtc(crtc, ctx);
16591                 intel_dump_pipe_config(crtc, crtc_state,
16592                                        "[setup_hw_state]");
16593         }
16594
16595         intel_modeset_update_connector_atomic_state(dev);
16596
16597         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
16598                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
16599
16600                 if (!pll->on || pll->active_mask)
16601                         continue;
16602
16603                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n",
16604                               pll->info->name);
16605
16606                 pll->info->funcs->disable(dev_priv, pll);
16607                 pll->on = false;
16608         }
16609
16610         if (IS_G4X(dev_priv)) {
16611                 g4x_wm_get_hw_state(dev_priv);
16612                 g4x_wm_sanitize(dev_priv);
16613         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
16614                 vlv_wm_get_hw_state(dev_priv);
16615                 vlv_wm_sanitize(dev_priv);
16616         } else if (INTEL_GEN(dev_priv) >= 9) {
16617                 skl_wm_get_hw_state(dev_priv);
16618         } else if (HAS_PCH_SPLIT(dev_priv)) {
16619                 ilk_wm_get_hw_state(dev_priv);
16620         }
16621
16622         for_each_intel_crtc(dev, crtc) {
16623                 u64 put_domains;
16624
16625                 crtc_state = to_intel_crtc_state(crtc->base.state);
16626                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc_state);
16627                 if (WARN_ON(put_domains))
16628                         modeset_put_power_domains(dev_priv, put_domains);
16629         }
16630
16631         intel_display_power_put(dev_priv, POWER_DOMAIN_INIT, wakeref);
16632
16633         intel_fbc_init_pipe_state(dev_priv);
16634 }
16635
16636 void intel_display_resume(struct drm_device *dev)
16637 {
16638         struct drm_i915_private *dev_priv = to_i915(dev);
16639         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
16640         struct drm_modeset_acquire_ctx ctx;
16641         int ret;
16642
16643         dev_priv->modeset_restore_state = NULL;
16644         if (state)
16645                 state->acquire_ctx = &ctx;
16646
16647         drm_modeset_acquire_init(&ctx, 0);
16648
16649         while (1) {
16650                 ret = drm_modeset_lock_all_ctx(dev, &ctx);
16651                 if (ret != -EDEADLK)
16652                         break;
16653
16654                 drm_modeset_backoff(&ctx);
16655         }
16656
16657         if (!ret)
16658                 ret = __intel_display_resume(dev, state, &ctx);
16659
16660         intel_enable_ipc(dev_priv);
16661         drm_modeset_drop_locks(&ctx);
16662         drm_modeset_acquire_fini(&ctx);
16663
16664         if (ret)
16665                 DRM_ERROR("Restoring old state failed with %i\n", ret);
16666         if (state)
16667                 drm_atomic_state_put(state);
16668 }
16669
16670 static void intel_hpd_poll_fini(struct drm_device *dev)
16671 {
16672         struct intel_connector *connector;
16673         struct drm_connector_list_iter conn_iter;
16674
16675         /* Kill all the work that may have been queued by hpd. */
16676         drm_connector_list_iter_begin(dev, &conn_iter);
16677         for_each_intel_connector_iter(connector, &conn_iter) {
16678                 if (connector->modeset_retry_work.func)
16679                         cancel_work_sync(&connector->modeset_retry_work);
16680                 if (connector->hdcp.shim) {
16681                         cancel_delayed_work_sync(&connector->hdcp.check_work);
16682                         cancel_work_sync(&connector->hdcp.prop_work);
16683                 }
16684         }
16685         drm_connector_list_iter_end(&conn_iter);
16686 }
16687
16688 void intel_modeset_cleanup(struct drm_device *dev)
16689 {
16690         struct drm_i915_private *dev_priv = to_i915(dev);
16691
16692         flush_workqueue(dev_priv->modeset_wq);
16693
16694         flush_work(&dev_priv->atomic_helper.free_work);
16695         WARN_ON(!llist_empty(&dev_priv->atomic_helper.free_list));
16696
16697         /*
16698          * Interrupts and polling as the first thing to avoid creating havoc.
16699          * Too much stuff here (turning of connectors, ...) would
16700          * experience fancy races otherwise.
16701          */
16702         intel_irq_uninstall(dev_priv);
16703
16704         /*
16705          * Due to the hpd irq storm handling the hotplug work can re-arm the
16706          * poll handlers. Hence disable polling after hpd handling is shut down.
16707          */
16708         intel_hpd_poll_fini(dev);
16709
16710         /* poll work can call into fbdev, hence clean that up afterwards */
16711         intel_fbdev_fini(dev_priv);
16712
16713         intel_unregister_dsm_handler();
16714
16715         intel_fbc_global_disable(dev_priv);
16716
16717         /* flush any delayed tasks or pending work */
16718         flush_scheduled_work();
16719
16720         intel_hdcp_component_fini(dev_priv);
16721
16722         drm_mode_config_cleanup(dev);
16723
16724         intel_overlay_cleanup(dev_priv);
16725
16726         intel_gmbus_teardown(dev_priv);
16727
16728         destroy_workqueue(dev_priv->modeset_wq);
16729
16730         intel_fbc_cleanup_cfb(dev_priv);
16731 }
16732
16733 /*
16734  * set vga decode state - true == enable VGA decode
16735  */
16736 int intel_modeset_vga_set_state(struct drm_i915_private *dev_priv, bool state)
16737 {
16738         unsigned reg = INTEL_GEN(dev_priv) >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
16739         u16 gmch_ctrl;
16740
16741         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
16742                 DRM_ERROR("failed to read control word\n");
16743                 return -EIO;
16744         }
16745
16746         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
16747                 return 0;
16748
16749         if (state)
16750                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
16751         else
16752                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
16753
16754         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
16755                 DRM_ERROR("failed to write control word\n");
16756                 return -EIO;
16757         }
16758
16759         return 0;
16760 }
16761
16762 #if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
16763
16764 struct intel_display_error_state {
16765
16766         u32 power_well_driver;
16767
16768         struct intel_cursor_error_state {
16769                 u32 control;
16770                 u32 position;
16771                 u32 base;
16772                 u32 size;
16773         } cursor[I915_MAX_PIPES];
16774
16775         struct intel_pipe_error_state {
16776                 bool power_domain_on;
16777                 u32 source;
16778                 u32 stat;
16779         } pipe[I915_MAX_PIPES];
16780
16781         struct intel_plane_error_state {
16782                 u32 control;
16783                 u32 stride;
16784                 u32 size;
16785                 u32 pos;
16786                 u32 addr;
16787                 u32 surface;
16788                 u32 tile_offset;
16789         } plane[I915_MAX_PIPES];
16790
16791         struct intel_transcoder_error_state {
16792                 bool available;
16793                 bool power_domain_on;
16794                 enum transcoder cpu_transcoder;
16795
16796                 u32 conf;
16797
16798                 u32 htotal;
16799                 u32 hblank;
16800                 u32 hsync;
16801                 u32 vtotal;
16802                 u32 vblank;
16803                 u32 vsync;
16804         } transcoder[4];
16805 };
16806
16807 struct intel_display_error_state *
16808 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
16809 {
16810         struct intel_display_error_state *error;
16811         int transcoders[] = {
16812                 TRANSCODER_A,
16813                 TRANSCODER_B,
16814                 TRANSCODER_C,
16815                 TRANSCODER_EDP,
16816         };
16817         int i;
16818
16819         BUILD_BUG_ON(ARRAY_SIZE(transcoders) != ARRAY_SIZE(error->transcoder));
16820
16821         if (!HAS_DISPLAY(dev_priv))
16822                 return NULL;
16823
16824         error = kzalloc(sizeof(*error), GFP_ATOMIC);
16825         if (error == NULL)
16826                 return NULL;
16827
16828         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
16829                 error->power_well_driver = I915_READ(HSW_PWR_WELL_CTL2);
16830
16831         for_each_pipe(dev_priv, i) {
16832                 error->pipe[i].power_domain_on =
16833                         __intel_display_power_is_enabled(dev_priv,
16834                                                          POWER_DOMAIN_PIPE(i));
16835                 if (!error->pipe[i].power_domain_on)
16836                         continue;
16837
16838                 error->cursor[i].control = I915_READ(CURCNTR(i));
16839                 error->cursor[i].position = I915_READ(CURPOS(i));
16840                 error->cursor[i].base = I915_READ(CURBASE(i));
16841
16842                 error->plane[i].control = I915_READ(DSPCNTR(i));
16843                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
16844                 if (INTEL_GEN(dev_priv) <= 3) {
16845                         error->plane[i].size = I915_READ(DSPSIZE(i));
16846                         error->plane[i].pos = I915_READ(DSPPOS(i));
16847                 }
16848                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
16849                         error->plane[i].addr = I915_READ(DSPADDR(i));
16850                 if (INTEL_GEN(dev_priv) >= 4) {
16851                         error->plane[i].surface = I915_READ(DSPSURF(i));
16852                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
16853                 }
16854
16855                 error->pipe[i].source = I915_READ(PIPESRC(i));
16856
16857                 if (HAS_GMCH(dev_priv))
16858                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
16859         }
16860
16861         for (i = 0; i < ARRAY_SIZE(error->transcoder); i++) {
16862                 enum transcoder cpu_transcoder = transcoders[i];
16863
16864                 if (!INTEL_INFO(dev_priv)->trans_offsets[cpu_transcoder])
16865                         continue;
16866
16867                 error->transcoder[i].available = true;
16868                 error->transcoder[i].power_domain_on =
16869                         __intel_display_power_is_enabled(dev_priv,
16870                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
16871                 if (!error->transcoder[i].power_domain_on)
16872                         continue;
16873
16874                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
16875
16876                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
16877                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
16878                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
16879                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
16880                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
16881                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
16882                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
16883         }
16884
16885         return error;
16886 }
16887
16888 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
16889
16890 void
16891 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
16892                                 struct intel_display_error_state *error)
16893 {
16894         struct drm_i915_private *dev_priv = m->i915;
16895         int i;
16896
16897         if (!error)
16898                 return;
16899
16900         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev_priv)->num_pipes);
16901         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
16902                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
16903                            error->power_well_driver);
16904         for_each_pipe(dev_priv, i) {
16905                 err_printf(m, "Pipe [%d]:\n", i);
16906                 err_printf(m, "  Power: %s\n",
16907                            onoff(error->pipe[i].power_domain_on));
16908                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
16909                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
16910
16911                 err_printf(m, "Plane [%d]:\n", i);
16912                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
16913                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
16914                 if (INTEL_GEN(dev_priv) <= 3) {
16915                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
16916                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
16917                 }
16918                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
16919                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
16920                 if (INTEL_GEN(dev_priv) >= 4) {
16921                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
16922                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
16923                 }
16924
16925                 err_printf(m, "Cursor [%d]:\n", i);
16926                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
16927                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
16928                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
16929         }
16930
16931         for (i = 0; i < ARRAY_SIZE(error->transcoder); i++) {
16932                 if (!error->transcoder[i].available)
16933                         continue;
16934
16935                 err_printf(m, "CPU transcoder: %s\n",
16936                            transcoder_name(error->transcoder[i].cpu_transcoder));
16937                 err_printf(m, "  Power: %s\n",
16938                            onoff(error->transcoder[i].power_domain_on));
16939                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
16940                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
16941                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
16942                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
16943                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
16944                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
16945                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
16946         }
16947 }
16948
16949 #endif