drm/i915: Use the atomic state in intel_update_primary_planes.
[cascardo/linux.git] / drivers / gpu / drm / i915 / intel_display.c
1 /*
2  * Copyright © 2006-2007 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *      Eric Anholt <eric@anholt.net>
25  */
26
27 #include <linux/dmi.h>
28 #include <linux/module.h>
29 #include <linux/input.h>
30 #include <linux/i2c.h>
31 #include <linux/kernel.h>
32 #include <linux/slab.h>
33 #include <linux/vgaarb.h>
34 #include <drm/drm_edid.h>
35 #include <drm/drmP.h>
36 #include "intel_drv.h"
37 #include <drm/i915_drm.h>
38 #include "i915_drv.h"
39 #include "i915_trace.h"
40 #include <drm/drm_atomic.h>
41 #include <drm/drm_atomic_helper.h>
42 #include <drm/drm_dp_helper.h>
43 #include <drm/drm_crtc_helper.h>
44 #include <drm/drm_plane_helper.h>
45 #include <drm/drm_rect.h>
46 #include <linux/dma_remapping.h>
47
48 /* Primary plane formats for gen <= 3 */
49 static const uint32_t i8xx_primary_formats[] = {
50         DRM_FORMAT_C8,
51         DRM_FORMAT_RGB565,
52         DRM_FORMAT_XRGB1555,
53         DRM_FORMAT_XRGB8888,
54 };
55
56 /* Primary plane formats for gen >= 4 */
57 static const uint32_t i965_primary_formats[] = {
58         DRM_FORMAT_C8,
59         DRM_FORMAT_RGB565,
60         DRM_FORMAT_XRGB8888,
61         DRM_FORMAT_XBGR8888,
62         DRM_FORMAT_XRGB2101010,
63         DRM_FORMAT_XBGR2101010,
64 };
65
66 static const uint32_t skl_primary_formats[] = {
67         DRM_FORMAT_C8,
68         DRM_FORMAT_RGB565,
69         DRM_FORMAT_XRGB8888,
70         DRM_FORMAT_XBGR8888,
71         DRM_FORMAT_ARGB8888,
72         DRM_FORMAT_ABGR8888,
73         DRM_FORMAT_XRGB2101010,
74         DRM_FORMAT_XBGR2101010,
75         DRM_FORMAT_YUYV,
76         DRM_FORMAT_YVYU,
77         DRM_FORMAT_UYVY,
78         DRM_FORMAT_VYUY,
79 };
80
81 /* Cursor formats */
82 static const uint32_t intel_cursor_formats[] = {
83         DRM_FORMAT_ARGB8888,
84 };
85
86 static void intel_crtc_update_cursor(struct drm_crtc *crtc, bool on);
87
88 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
89                                 struct intel_crtc_state *pipe_config);
90 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
91                                    struct intel_crtc_state *pipe_config);
92
93 static int intel_framebuffer_init(struct drm_device *dev,
94                                   struct intel_framebuffer *ifb,
95                                   struct drm_mode_fb_cmd2 *mode_cmd,
96                                   struct drm_i915_gem_object *obj);
97 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc);
98 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc);
99 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
100                                          struct intel_link_m_n *m_n,
101                                          struct intel_link_m_n *m2_n2);
102 static void ironlake_set_pipeconf(struct drm_crtc *crtc);
103 static void haswell_set_pipeconf(struct drm_crtc *crtc);
104 static void intel_set_pipe_csc(struct drm_crtc *crtc);
105 static void vlv_prepare_pll(struct intel_crtc *crtc,
106                             const struct intel_crtc_state *pipe_config);
107 static void chv_prepare_pll(struct intel_crtc *crtc,
108                             const struct intel_crtc_state *pipe_config);
109 static void intel_begin_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
110 static void intel_finish_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
111 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
112         struct intel_crtc_state *crtc_state);
113 static int i9xx_get_refclk(const struct intel_crtc_state *crtc_state,
114                            int num_connectors);
115 static void intel_modeset_setup_hw_state(struct drm_device *dev);
116
117 typedef struct {
118         int     min, max;
119 } intel_range_t;
120
121 typedef struct {
122         int     dot_limit;
123         int     p2_slow, p2_fast;
124 } intel_p2_t;
125
126 typedef struct intel_limit intel_limit_t;
127 struct intel_limit {
128         intel_range_t   dot, vco, n, m, m1, m2, p, p1;
129         intel_p2_t          p2;
130 };
131
132 int
133 intel_pch_rawclk(struct drm_device *dev)
134 {
135         struct drm_i915_private *dev_priv = dev->dev_private;
136
137         WARN_ON(!HAS_PCH_SPLIT(dev));
138
139         return I915_READ(PCH_RAWCLK_FREQ) & RAWCLK_FREQ_MASK;
140 }
141
142 /* hrawclock is 1/4 the FSB frequency */
143 int intel_hrawclk(struct drm_device *dev)
144 {
145         struct drm_i915_private *dev_priv = dev->dev_private;
146         uint32_t clkcfg;
147
148         /* There is no CLKCFG reg in Valleyview. VLV hrawclk is 200 MHz */
149         if (IS_VALLEYVIEW(dev))
150                 return 200;
151
152         clkcfg = I915_READ(CLKCFG);
153         switch (clkcfg & CLKCFG_FSB_MASK) {
154         case CLKCFG_FSB_400:
155                 return 100;
156         case CLKCFG_FSB_533:
157                 return 133;
158         case CLKCFG_FSB_667:
159                 return 166;
160         case CLKCFG_FSB_800:
161                 return 200;
162         case CLKCFG_FSB_1067:
163                 return 266;
164         case CLKCFG_FSB_1333:
165                 return 333;
166         /* these two are just a guess; one of them might be right */
167         case CLKCFG_FSB_1600:
168         case CLKCFG_FSB_1600_ALT:
169                 return 400;
170         default:
171                 return 133;
172         }
173 }
174
175 static inline u32 /* units of 100MHz */
176 intel_fdi_link_freq(struct drm_device *dev)
177 {
178         if (IS_GEN5(dev)) {
179                 struct drm_i915_private *dev_priv = dev->dev_private;
180                 return (I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK) + 2;
181         } else
182                 return 27;
183 }
184
185 static const intel_limit_t intel_limits_i8xx_dac = {
186         .dot = { .min = 25000, .max = 350000 },
187         .vco = { .min = 908000, .max = 1512000 },
188         .n = { .min = 2, .max = 16 },
189         .m = { .min = 96, .max = 140 },
190         .m1 = { .min = 18, .max = 26 },
191         .m2 = { .min = 6, .max = 16 },
192         .p = { .min = 4, .max = 128 },
193         .p1 = { .min = 2, .max = 33 },
194         .p2 = { .dot_limit = 165000,
195                 .p2_slow = 4, .p2_fast = 2 },
196 };
197
198 static const intel_limit_t intel_limits_i8xx_dvo = {
199         .dot = { .min = 25000, .max = 350000 },
200         .vco = { .min = 908000, .max = 1512000 },
201         .n = { .min = 2, .max = 16 },
202         .m = { .min = 96, .max = 140 },
203         .m1 = { .min = 18, .max = 26 },
204         .m2 = { .min = 6, .max = 16 },
205         .p = { .min = 4, .max = 128 },
206         .p1 = { .min = 2, .max = 33 },
207         .p2 = { .dot_limit = 165000,
208                 .p2_slow = 4, .p2_fast = 4 },
209 };
210
211 static const intel_limit_t intel_limits_i8xx_lvds = {
212         .dot = { .min = 25000, .max = 350000 },
213         .vco = { .min = 908000, .max = 1512000 },
214         .n = { .min = 2, .max = 16 },
215         .m = { .min = 96, .max = 140 },
216         .m1 = { .min = 18, .max = 26 },
217         .m2 = { .min = 6, .max = 16 },
218         .p = { .min = 4, .max = 128 },
219         .p1 = { .min = 1, .max = 6 },
220         .p2 = { .dot_limit = 165000,
221                 .p2_slow = 14, .p2_fast = 7 },
222 };
223
224 static const intel_limit_t intel_limits_i9xx_sdvo = {
225         .dot = { .min = 20000, .max = 400000 },
226         .vco = { .min = 1400000, .max = 2800000 },
227         .n = { .min = 1, .max = 6 },
228         .m = { .min = 70, .max = 120 },
229         .m1 = { .min = 8, .max = 18 },
230         .m2 = { .min = 3, .max = 7 },
231         .p = { .min = 5, .max = 80 },
232         .p1 = { .min = 1, .max = 8 },
233         .p2 = { .dot_limit = 200000,
234                 .p2_slow = 10, .p2_fast = 5 },
235 };
236
237 static const intel_limit_t intel_limits_i9xx_lvds = {
238         .dot = { .min = 20000, .max = 400000 },
239         .vco = { .min = 1400000, .max = 2800000 },
240         .n = { .min = 1, .max = 6 },
241         .m = { .min = 70, .max = 120 },
242         .m1 = { .min = 8, .max = 18 },
243         .m2 = { .min = 3, .max = 7 },
244         .p = { .min = 7, .max = 98 },
245         .p1 = { .min = 1, .max = 8 },
246         .p2 = { .dot_limit = 112000,
247                 .p2_slow = 14, .p2_fast = 7 },
248 };
249
250
251 static const intel_limit_t intel_limits_g4x_sdvo = {
252         .dot = { .min = 25000, .max = 270000 },
253         .vco = { .min = 1750000, .max = 3500000},
254         .n = { .min = 1, .max = 4 },
255         .m = { .min = 104, .max = 138 },
256         .m1 = { .min = 17, .max = 23 },
257         .m2 = { .min = 5, .max = 11 },
258         .p = { .min = 10, .max = 30 },
259         .p1 = { .min = 1, .max = 3},
260         .p2 = { .dot_limit = 270000,
261                 .p2_slow = 10,
262                 .p2_fast = 10
263         },
264 };
265
266 static const intel_limit_t intel_limits_g4x_hdmi = {
267         .dot = { .min = 22000, .max = 400000 },
268         .vco = { .min = 1750000, .max = 3500000},
269         .n = { .min = 1, .max = 4 },
270         .m = { .min = 104, .max = 138 },
271         .m1 = { .min = 16, .max = 23 },
272         .m2 = { .min = 5, .max = 11 },
273         .p = { .min = 5, .max = 80 },
274         .p1 = { .min = 1, .max = 8},
275         .p2 = { .dot_limit = 165000,
276                 .p2_slow = 10, .p2_fast = 5 },
277 };
278
279 static const intel_limit_t intel_limits_g4x_single_channel_lvds = {
280         .dot = { .min = 20000, .max = 115000 },
281         .vco = { .min = 1750000, .max = 3500000 },
282         .n = { .min = 1, .max = 3 },
283         .m = { .min = 104, .max = 138 },
284         .m1 = { .min = 17, .max = 23 },
285         .m2 = { .min = 5, .max = 11 },
286         .p = { .min = 28, .max = 112 },
287         .p1 = { .min = 2, .max = 8 },
288         .p2 = { .dot_limit = 0,
289                 .p2_slow = 14, .p2_fast = 14
290         },
291 };
292
293 static const intel_limit_t intel_limits_g4x_dual_channel_lvds = {
294         .dot = { .min = 80000, .max = 224000 },
295         .vco = { .min = 1750000, .max = 3500000 },
296         .n = { .min = 1, .max = 3 },
297         .m = { .min = 104, .max = 138 },
298         .m1 = { .min = 17, .max = 23 },
299         .m2 = { .min = 5, .max = 11 },
300         .p = { .min = 14, .max = 42 },
301         .p1 = { .min = 2, .max = 6 },
302         .p2 = { .dot_limit = 0,
303                 .p2_slow = 7, .p2_fast = 7
304         },
305 };
306
307 static const intel_limit_t intel_limits_pineview_sdvo = {
308         .dot = { .min = 20000, .max = 400000},
309         .vco = { .min = 1700000, .max = 3500000 },
310         /* Pineview's Ncounter is a ring counter */
311         .n = { .min = 3, .max = 6 },
312         .m = { .min = 2, .max = 256 },
313         /* Pineview only has one combined m divider, which we treat as m2. */
314         .m1 = { .min = 0, .max = 0 },
315         .m2 = { .min = 0, .max = 254 },
316         .p = { .min = 5, .max = 80 },
317         .p1 = { .min = 1, .max = 8 },
318         .p2 = { .dot_limit = 200000,
319                 .p2_slow = 10, .p2_fast = 5 },
320 };
321
322 static const intel_limit_t intel_limits_pineview_lvds = {
323         .dot = { .min = 20000, .max = 400000 },
324         .vco = { .min = 1700000, .max = 3500000 },
325         .n = { .min = 3, .max = 6 },
326         .m = { .min = 2, .max = 256 },
327         .m1 = { .min = 0, .max = 0 },
328         .m2 = { .min = 0, .max = 254 },
329         .p = { .min = 7, .max = 112 },
330         .p1 = { .min = 1, .max = 8 },
331         .p2 = { .dot_limit = 112000,
332                 .p2_slow = 14, .p2_fast = 14 },
333 };
334
335 /* Ironlake / Sandybridge
336  *
337  * We calculate clock using (register_value + 2) for N/M1/M2, so here
338  * the range value for them is (actual_value - 2).
339  */
340 static const intel_limit_t intel_limits_ironlake_dac = {
341         .dot = { .min = 25000, .max = 350000 },
342         .vco = { .min = 1760000, .max = 3510000 },
343         .n = { .min = 1, .max = 5 },
344         .m = { .min = 79, .max = 127 },
345         .m1 = { .min = 12, .max = 22 },
346         .m2 = { .min = 5, .max = 9 },
347         .p = { .min = 5, .max = 80 },
348         .p1 = { .min = 1, .max = 8 },
349         .p2 = { .dot_limit = 225000,
350                 .p2_slow = 10, .p2_fast = 5 },
351 };
352
353 static const intel_limit_t intel_limits_ironlake_single_lvds = {
354         .dot = { .min = 25000, .max = 350000 },
355         .vco = { .min = 1760000, .max = 3510000 },
356         .n = { .min = 1, .max = 3 },
357         .m = { .min = 79, .max = 118 },
358         .m1 = { .min = 12, .max = 22 },
359         .m2 = { .min = 5, .max = 9 },
360         .p = { .min = 28, .max = 112 },
361         .p1 = { .min = 2, .max = 8 },
362         .p2 = { .dot_limit = 225000,
363                 .p2_slow = 14, .p2_fast = 14 },
364 };
365
366 static const intel_limit_t intel_limits_ironlake_dual_lvds = {
367         .dot = { .min = 25000, .max = 350000 },
368         .vco = { .min = 1760000, .max = 3510000 },
369         .n = { .min = 1, .max = 3 },
370         .m = { .min = 79, .max = 127 },
371         .m1 = { .min = 12, .max = 22 },
372         .m2 = { .min = 5, .max = 9 },
373         .p = { .min = 14, .max = 56 },
374         .p1 = { .min = 2, .max = 8 },
375         .p2 = { .dot_limit = 225000,
376                 .p2_slow = 7, .p2_fast = 7 },
377 };
378
379 /* LVDS 100mhz refclk limits. */
380 static const intel_limit_t intel_limits_ironlake_single_lvds_100m = {
381         .dot = { .min = 25000, .max = 350000 },
382         .vco = { .min = 1760000, .max = 3510000 },
383         .n = { .min = 1, .max = 2 },
384         .m = { .min = 79, .max = 126 },
385         .m1 = { .min = 12, .max = 22 },
386         .m2 = { .min = 5, .max = 9 },
387         .p = { .min = 28, .max = 112 },
388         .p1 = { .min = 2, .max = 8 },
389         .p2 = { .dot_limit = 225000,
390                 .p2_slow = 14, .p2_fast = 14 },
391 };
392
393 static const intel_limit_t intel_limits_ironlake_dual_lvds_100m = {
394         .dot = { .min = 25000, .max = 350000 },
395         .vco = { .min = 1760000, .max = 3510000 },
396         .n = { .min = 1, .max = 3 },
397         .m = { .min = 79, .max = 126 },
398         .m1 = { .min = 12, .max = 22 },
399         .m2 = { .min = 5, .max = 9 },
400         .p = { .min = 14, .max = 42 },
401         .p1 = { .min = 2, .max = 6 },
402         .p2 = { .dot_limit = 225000,
403                 .p2_slow = 7, .p2_fast = 7 },
404 };
405
406 static const intel_limit_t intel_limits_vlv = {
407          /*
408           * These are the data rate limits (measured in fast clocks)
409           * since those are the strictest limits we have. The fast
410           * clock and actual rate limits are more relaxed, so checking
411           * them would make no difference.
412           */
413         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
414         .vco = { .min = 4000000, .max = 6000000 },
415         .n = { .min = 1, .max = 7 },
416         .m1 = { .min = 2, .max = 3 },
417         .m2 = { .min = 11, .max = 156 },
418         .p1 = { .min = 2, .max = 3 },
419         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
420 };
421
422 static const intel_limit_t intel_limits_chv = {
423         /*
424          * These are the data rate limits (measured in fast clocks)
425          * since those are the strictest limits we have.  The fast
426          * clock and actual rate limits are more relaxed, so checking
427          * them would make no difference.
428          */
429         .dot = { .min = 25000 * 5, .max = 540000 * 5},
430         .vco = { .min = 4800000, .max = 6480000 },
431         .n = { .min = 1, .max = 1 },
432         .m1 = { .min = 2, .max = 2 },
433         .m2 = { .min = 24 << 22, .max = 175 << 22 },
434         .p1 = { .min = 2, .max = 4 },
435         .p2 = { .p2_slow = 1, .p2_fast = 14 },
436 };
437
438 static const intel_limit_t intel_limits_bxt = {
439         /* FIXME: find real dot limits */
440         .dot = { .min = 0, .max = INT_MAX },
441         .vco = { .min = 4800000, .max = 6700000 },
442         .n = { .min = 1, .max = 1 },
443         .m1 = { .min = 2, .max = 2 },
444         /* FIXME: find real m2 limits */
445         .m2 = { .min = 2 << 22, .max = 255 << 22 },
446         .p1 = { .min = 2, .max = 4 },
447         .p2 = { .p2_slow = 1, .p2_fast = 20 },
448 };
449
450 static bool
451 needs_modeset(struct drm_crtc_state *state)
452 {
453         return drm_atomic_crtc_needs_modeset(state);
454 }
455
456 /**
457  * Returns whether any output on the specified pipe is of the specified type
458  */
459 bool intel_pipe_has_type(struct intel_crtc *crtc, enum intel_output_type type)
460 {
461         struct drm_device *dev = crtc->base.dev;
462         struct intel_encoder *encoder;
463
464         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
465                 if (encoder->type == type)
466                         return true;
467
468         return false;
469 }
470
471 /**
472  * Returns whether any output on the specified pipe will have the specified
473  * type after a staged modeset is complete, i.e., the same as
474  * intel_pipe_has_type() but looking at encoder->new_crtc instead of
475  * encoder->crtc.
476  */
477 static bool intel_pipe_will_have_type(const struct intel_crtc_state *crtc_state,
478                                       int type)
479 {
480         struct drm_atomic_state *state = crtc_state->base.state;
481         struct drm_connector *connector;
482         struct drm_connector_state *connector_state;
483         struct intel_encoder *encoder;
484         int i, num_connectors = 0;
485
486         for_each_connector_in_state(state, connector, connector_state, i) {
487                 if (connector_state->crtc != crtc_state->base.crtc)
488                         continue;
489
490                 num_connectors++;
491
492                 encoder = to_intel_encoder(connector_state->best_encoder);
493                 if (encoder->type == type)
494                         return true;
495         }
496
497         WARN_ON(num_connectors == 0);
498
499         return false;
500 }
501
502 static const intel_limit_t *
503 intel_ironlake_limit(struct intel_crtc_state *crtc_state, int refclk)
504 {
505         struct drm_device *dev = crtc_state->base.crtc->dev;
506         const intel_limit_t *limit;
507
508         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
509                 if (intel_is_dual_link_lvds(dev)) {
510                         if (refclk == 100000)
511                                 limit = &intel_limits_ironlake_dual_lvds_100m;
512                         else
513                                 limit = &intel_limits_ironlake_dual_lvds;
514                 } else {
515                         if (refclk == 100000)
516                                 limit = &intel_limits_ironlake_single_lvds_100m;
517                         else
518                                 limit = &intel_limits_ironlake_single_lvds;
519                 }
520         } else
521                 limit = &intel_limits_ironlake_dac;
522
523         return limit;
524 }
525
526 static const intel_limit_t *
527 intel_g4x_limit(struct intel_crtc_state *crtc_state)
528 {
529         struct drm_device *dev = crtc_state->base.crtc->dev;
530         const intel_limit_t *limit;
531
532         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
533                 if (intel_is_dual_link_lvds(dev))
534                         limit = &intel_limits_g4x_dual_channel_lvds;
535                 else
536                         limit = &intel_limits_g4x_single_channel_lvds;
537         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_HDMI) ||
538                    intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
539                 limit = &intel_limits_g4x_hdmi;
540         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_SDVO)) {
541                 limit = &intel_limits_g4x_sdvo;
542         } else /* The option is for other outputs */
543                 limit = &intel_limits_i9xx_sdvo;
544
545         return limit;
546 }
547
548 static const intel_limit_t *
549 intel_limit(struct intel_crtc_state *crtc_state, int refclk)
550 {
551         struct drm_device *dev = crtc_state->base.crtc->dev;
552         const intel_limit_t *limit;
553
554         if (IS_BROXTON(dev))
555                 limit = &intel_limits_bxt;
556         else if (HAS_PCH_SPLIT(dev))
557                 limit = intel_ironlake_limit(crtc_state, refclk);
558         else if (IS_G4X(dev)) {
559                 limit = intel_g4x_limit(crtc_state);
560         } else if (IS_PINEVIEW(dev)) {
561                 if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
562                         limit = &intel_limits_pineview_lvds;
563                 else
564                         limit = &intel_limits_pineview_sdvo;
565         } else if (IS_CHERRYVIEW(dev)) {
566                 limit = &intel_limits_chv;
567         } else if (IS_VALLEYVIEW(dev)) {
568                 limit = &intel_limits_vlv;
569         } else if (!IS_GEN2(dev)) {
570                 if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
571                         limit = &intel_limits_i9xx_lvds;
572                 else
573                         limit = &intel_limits_i9xx_sdvo;
574         } else {
575                 if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
576                         limit = &intel_limits_i8xx_lvds;
577                 else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_DVO))
578                         limit = &intel_limits_i8xx_dvo;
579                 else
580                         limit = &intel_limits_i8xx_dac;
581         }
582         return limit;
583 }
584
585 /*
586  * Platform specific helpers to calculate the port PLL loopback- (clock.m),
587  * and post-divider (clock.p) values, pre- (clock.vco) and post-divided fast
588  * (clock.dot) clock rates. This fast dot clock is fed to the port's IO logic.
589  * The helpers' return value is the rate of the clock that is fed to the
590  * display engine's pipe which can be the above fast dot clock rate or a
591  * divided-down version of it.
592  */
593 /* m1 is reserved as 0 in Pineview, n is a ring counter */
594 static int pnv_calc_dpll_params(int refclk, intel_clock_t *clock)
595 {
596         clock->m = clock->m2 + 2;
597         clock->p = clock->p1 * clock->p2;
598         if (WARN_ON(clock->n == 0 || clock->p == 0))
599                 return 0;
600         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
601         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
602
603         return clock->dot;
604 }
605
606 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
607 {
608         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
609 }
610
611 static int i9xx_calc_dpll_params(int refclk, intel_clock_t *clock)
612 {
613         clock->m = i9xx_dpll_compute_m(clock);
614         clock->p = clock->p1 * clock->p2;
615         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
616                 return 0;
617         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
618         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
619
620         return clock->dot;
621 }
622
623 static int vlv_calc_dpll_params(int refclk, intel_clock_t *clock)
624 {
625         clock->m = clock->m1 * clock->m2;
626         clock->p = clock->p1 * clock->p2;
627         if (WARN_ON(clock->n == 0 || clock->p == 0))
628                 return 0;
629         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
630         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
631
632         return clock->dot / 5;
633 }
634
635 int chv_calc_dpll_params(int refclk, intel_clock_t *clock)
636 {
637         clock->m = clock->m1 * clock->m2;
638         clock->p = clock->p1 * clock->p2;
639         if (WARN_ON(clock->n == 0 || clock->p == 0))
640                 return 0;
641         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
642                         clock->n << 22);
643         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
644
645         return clock->dot / 5;
646 }
647
648 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
649 /**
650  * Returns whether the given set of divisors are valid for a given refclk with
651  * the given connectors.
652  */
653
654 static bool intel_PLL_is_valid(struct drm_device *dev,
655                                const intel_limit_t *limit,
656                                const intel_clock_t *clock)
657 {
658         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
659                 INTELPllInvalid("n out of range\n");
660         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
661                 INTELPllInvalid("p1 out of range\n");
662         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
663                 INTELPllInvalid("m2 out of range\n");
664         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
665                 INTELPllInvalid("m1 out of range\n");
666
667         if (!IS_PINEVIEW(dev) && !IS_VALLEYVIEW(dev) && !IS_BROXTON(dev))
668                 if (clock->m1 <= clock->m2)
669                         INTELPllInvalid("m1 <= m2\n");
670
671         if (!IS_VALLEYVIEW(dev) && !IS_BROXTON(dev)) {
672                 if (clock->p < limit->p.min || limit->p.max < clock->p)
673                         INTELPllInvalid("p out of range\n");
674                 if (clock->m < limit->m.min || limit->m.max < clock->m)
675                         INTELPllInvalid("m out of range\n");
676         }
677
678         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
679                 INTELPllInvalid("vco out of range\n");
680         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
681          * connector, etc., rather than just a single range.
682          */
683         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
684                 INTELPllInvalid("dot out of range\n");
685
686         return true;
687 }
688
689 static int
690 i9xx_select_p2_div(const intel_limit_t *limit,
691                    const struct intel_crtc_state *crtc_state,
692                    int target)
693 {
694         struct drm_device *dev = crtc_state->base.crtc->dev;
695
696         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
697                 /*
698                  * For LVDS just rely on its current settings for dual-channel.
699                  * We haven't figured out how to reliably set up different
700                  * single/dual channel state, if we even can.
701                  */
702                 if (intel_is_dual_link_lvds(dev))
703                         return limit->p2.p2_fast;
704                 else
705                         return limit->p2.p2_slow;
706         } else {
707                 if (target < limit->p2.dot_limit)
708                         return limit->p2.p2_slow;
709                 else
710                         return limit->p2.p2_fast;
711         }
712 }
713
714 static bool
715 i9xx_find_best_dpll(const intel_limit_t *limit,
716                     struct intel_crtc_state *crtc_state,
717                     int target, int refclk, intel_clock_t *match_clock,
718                     intel_clock_t *best_clock)
719 {
720         struct drm_device *dev = crtc_state->base.crtc->dev;
721         intel_clock_t clock;
722         int err = target;
723
724         memset(best_clock, 0, sizeof(*best_clock));
725
726         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
727
728         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
729              clock.m1++) {
730                 for (clock.m2 = limit->m2.min;
731                      clock.m2 <= limit->m2.max; clock.m2++) {
732                         if (clock.m2 >= clock.m1)
733                                 break;
734                         for (clock.n = limit->n.min;
735                              clock.n <= limit->n.max; clock.n++) {
736                                 for (clock.p1 = limit->p1.min;
737                                         clock.p1 <= limit->p1.max; clock.p1++) {
738                                         int this_err;
739
740                                         i9xx_calc_dpll_params(refclk, &clock);
741                                         if (!intel_PLL_is_valid(dev, limit,
742                                                                 &clock))
743                                                 continue;
744                                         if (match_clock &&
745                                             clock.p != match_clock->p)
746                                                 continue;
747
748                                         this_err = abs(clock.dot - target);
749                                         if (this_err < err) {
750                                                 *best_clock = clock;
751                                                 err = this_err;
752                                         }
753                                 }
754                         }
755                 }
756         }
757
758         return (err != target);
759 }
760
761 static bool
762 pnv_find_best_dpll(const intel_limit_t *limit,
763                    struct intel_crtc_state *crtc_state,
764                    int target, int refclk, intel_clock_t *match_clock,
765                    intel_clock_t *best_clock)
766 {
767         struct drm_device *dev = crtc_state->base.crtc->dev;
768         intel_clock_t clock;
769         int err = target;
770
771         memset(best_clock, 0, sizeof(*best_clock));
772
773         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
774
775         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
776              clock.m1++) {
777                 for (clock.m2 = limit->m2.min;
778                      clock.m2 <= limit->m2.max; clock.m2++) {
779                         for (clock.n = limit->n.min;
780                              clock.n <= limit->n.max; clock.n++) {
781                                 for (clock.p1 = limit->p1.min;
782                                         clock.p1 <= limit->p1.max; clock.p1++) {
783                                         int this_err;
784
785                                         pnv_calc_dpll_params(refclk, &clock);
786                                         if (!intel_PLL_is_valid(dev, limit,
787                                                                 &clock))
788                                                 continue;
789                                         if (match_clock &&
790                                             clock.p != match_clock->p)
791                                                 continue;
792
793                                         this_err = abs(clock.dot - target);
794                                         if (this_err < err) {
795                                                 *best_clock = clock;
796                                                 err = this_err;
797                                         }
798                                 }
799                         }
800                 }
801         }
802
803         return (err != target);
804 }
805
806 static bool
807 g4x_find_best_dpll(const intel_limit_t *limit,
808                    struct intel_crtc_state *crtc_state,
809                    int target, int refclk, intel_clock_t *match_clock,
810                    intel_clock_t *best_clock)
811 {
812         struct drm_device *dev = crtc_state->base.crtc->dev;
813         intel_clock_t clock;
814         int max_n;
815         bool found = false;
816         /* approximately equals target * 0.00585 */
817         int err_most = (target >> 8) + (target >> 9);
818
819         memset(best_clock, 0, sizeof(*best_clock));
820
821         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
822
823         max_n = limit->n.max;
824         /* based on hardware requirement, prefer smaller n to precision */
825         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
826                 /* based on hardware requirement, prefere larger m1,m2 */
827                 for (clock.m1 = limit->m1.max;
828                      clock.m1 >= limit->m1.min; clock.m1--) {
829                         for (clock.m2 = limit->m2.max;
830                              clock.m2 >= limit->m2.min; clock.m2--) {
831                                 for (clock.p1 = limit->p1.max;
832                                      clock.p1 >= limit->p1.min; clock.p1--) {
833                                         int this_err;
834
835                                         i9xx_calc_dpll_params(refclk, &clock);
836                                         if (!intel_PLL_is_valid(dev, limit,
837                                                                 &clock))
838                                                 continue;
839
840                                         this_err = abs(clock.dot - target);
841                                         if (this_err < err_most) {
842                                                 *best_clock = clock;
843                                                 err_most = this_err;
844                                                 max_n = clock.n;
845                                                 found = true;
846                                         }
847                                 }
848                         }
849                 }
850         }
851         return found;
852 }
853
854 /*
855  * Check if the calculated PLL configuration is more optimal compared to the
856  * best configuration and error found so far. Return the calculated error.
857  */
858 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
859                                const intel_clock_t *calculated_clock,
860                                const intel_clock_t *best_clock,
861                                unsigned int best_error_ppm,
862                                unsigned int *error_ppm)
863 {
864         /*
865          * For CHV ignore the error and consider only the P value.
866          * Prefer a bigger P value based on HW requirements.
867          */
868         if (IS_CHERRYVIEW(dev)) {
869                 *error_ppm = 0;
870
871                 return calculated_clock->p > best_clock->p;
872         }
873
874         if (WARN_ON_ONCE(!target_freq))
875                 return false;
876
877         *error_ppm = div_u64(1000000ULL *
878                                 abs(target_freq - calculated_clock->dot),
879                              target_freq);
880         /*
881          * Prefer a better P value over a better (smaller) error if the error
882          * is small. Ensure this preference for future configurations too by
883          * setting the error to 0.
884          */
885         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
886                 *error_ppm = 0;
887
888                 return true;
889         }
890
891         return *error_ppm + 10 < best_error_ppm;
892 }
893
894 static bool
895 vlv_find_best_dpll(const intel_limit_t *limit,
896                    struct intel_crtc_state *crtc_state,
897                    int target, int refclk, intel_clock_t *match_clock,
898                    intel_clock_t *best_clock)
899 {
900         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
901         struct drm_device *dev = crtc->base.dev;
902         intel_clock_t clock;
903         unsigned int bestppm = 1000000;
904         /* min update 19.2 MHz */
905         int max_n = min(limit->n.max, refclk / 19200);
906         bool found = false;
907
908         target *= 5; /* fast clock */
909
910         memset(best_clock, 0, sizeof(*best_clock));
911
912         /* based on hardware requirement, prefer smaller n to precision */
913         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
914                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
915                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
916                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
917                                 clock.p = clock.p1 * clock.p2;
918                                 /* based on hardware requirement, prefer bigger m1,m2 values */
919                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
920                                         unsigned int ppm;
921
922                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
923                                                                      refclk * clock.m1);
924
925                                         vlv_calc_dpll_params(refclk, &clock);
926
927                                         if (!intel_PLL_is_valid(dev, limit,
928                                                                 &clock))
929                                                 continue;
930
931                                         if (!vlv_PLL_is_optimal(dev, target,
932                                                                 &clock,
933                                                                 best_clock,
934                                                                 bestppm, &ppm))
935                                                 continue;
936
937                                         *best_clock = clock;
938                                         bestppm = ppm;
939                                         found = true;
940                                 }
941                         }
942                 }
943         }
944
945         return found;
946 }
947
948 static bool
949 chv_find_best_dpll(const intel_limit_t *limit,
950                    struct intel_crtc_state *crtc_state,
951                    int target, int refclk, intel_clock_t *match_clock,
952                    intel_clock_t *best_clock)
953 {
954         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
955         struct drm_device *dev = crtc->base.dev;
956         unsigned int best_error_ppm;
957         intel_clock_t clock;
958         uint64_t m2;
959         int found = false;
960
961         memset(best_clock, 0, sizeof(*best_clock));
962         best_error_ppm = 1000000;
963
964         /*
965          * Based on hardware doc, the n always set to 1, and m1 always
966          * set to 2.  If requires to support 200Mhz refclk, we need to
967          * revisit this because n may not 1 anymore.
968          */
969         clock.n = 1, clock.m1 = 2;
970         target *= 5;    /* fast clock */
971
972         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
973                 for (clock.p2 = limit->p2.p2_fast;
974                                 clock.p2 >= limit->p2.p2_slow;
975                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
976                         unsigned int error_ppm;
977
978                         clock.p = clock.p1 * clock.p2;
979
980                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
981                                         clock.n) << 22, refclk * clock.m1);
982
983                         if (m2 > INT_MAX/clock.m1)
984                                 continue;
985
986                         clock.m2 = m2;
987
988                         chv_calc_dpll_params(refclk, &clock);
989
990                         if (!intel_PLL_is_valid(dev, limit, &clock))
991                                 continue;
992
993                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
994                                                 best_error_ppm, &error_ppm))
995                                 continue;
996
997                         *best_clock = clock;
998                         best_error_ppm = error_ppm;
999                         found = true;
1000                 }
1001         }
1002
1003         return found;
1004 }
1005
1006 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state, int target_clock,
1007                         intel_clock_t *best_clock)
1008 {
1009         int refclk = i9xx_get_refclk(crtc_state, 0);
1010
1011         return chv_find_best_dpll(intel_limit(crtc_state, refclk), crtc_state,
1012                                   target_clock, refclk, NULL, best_clock);
1013 }
1014
1015 bool intel_crtc_active(struct drm_crtc *crtc)
1016 {
1017         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1018
1019         /* Be paranoid as we can arrive here with only partial
1020          * state retrieved from the hardware during setup.
1021          *
1022          * We can ditch the adjusted_mode.crtc_clock check as soon
1023          * as Haswell has gained clock readout/fastboot support.
1024          *
1025          * We can ditch the crtc->primary->fb check as soon as we can
1026          * properly reconstruct framebuffers.
1027          *
1028          * FIXME: The intel_crtc->active here should be switched to
1029          * crtc->state->active once we have proper CRTC states wired up
1030          * for atomic.
1031          */
1032         return intel_crtc->active && crtc->primary->state->fb &&
1033                 intel_crtc->config->base.adjusted_mode.crtc_clock;
1034 }
1035
1036 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
1037                                              enum pipe pipe)
1038 {
1039         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1040         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1041
1042         return intel_crtc->config->cpu_transcoder;
1043 }
1044
1045 static bool pipe_dsl_stopped(struct drm_device *dev, enum pipe pipe)
1046 {
1047         struct drm_i915_private *dev_priv = dev->dev_private;
1048         u32 reg = PIPEDSL(pipe);
1049         u32 line1, line2;
1050         u32 line_mask;
1051
1052         if (IS_GEN2(dev))
1053                 line_mask = DSL_LINEMASK_GEN2;
1054         else
1055                 line_mask = DSL_LINEMASK_GEN3;
1056
1057         line1 = I915_READ(reg) & line_mask;
1058         msleep(5);
1059         line2 = I915_READ(reg) & line_mask;
1060
1061         return line1 == line2;
1062 }
1063
1064 /*
1065  * intel_wait_for_pipe_off - wait for pipe to turn off
1066  * @crtc: crtc whose pipe to wait for
1067  *
1068  * After disabling a pipe, we can't wait for vblank in the usual way,
1069  * spinning on the vblank interrupt status bit, since we won't actually
1070  * see an interrupt when the pipe is disabled.
1071  *
1072  * On Gen4 and above:
1073  *   wait for the pipe register state bit to turn off
1074  *
1075  * Otherwise:
1076  *   wait for the display line value to settle (it usually
1077  *   ends up stopping at the start of the next frame).
1078  *
1079  */
1080 static void intel_wait_for_pipe_off(struct intel_crtc *crtc)
1081 {
1082         struct drm_device *dev = crtc->base.dev;
1083         struct drm_i915_private *dev_priv = dev->dev_private;
1084         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1085         enum pipe pipe = crtc->pipe;
1086
1087         if (INTEL_INFO(dev)->gen >= 4) {
1088                 int reg = PIPECONF(cpu_transcoder);
1089
1090                 /* Wait for the Pipe State to go off */
1091                 if (wait_for((I915_READ(reg) & I965_PIPECONF_ACTIVE) == 0,
1092                              100))
1093                         WARN(1, "pipe_off wait timed out\n");
1094         } else {
1095                 /* Wait for the display line to settle */
1096                 if (wait_for(pipe_dsl_stopped(dev, pipe), 100))
1097                         WARN(1, "pipe_off wait timed out\n");
1098         }
1099 }
1100
1101 static const char *state_string(bool enabled)
1102 {
1103         return enabled ? "on" : "off";
1104 }
1105
1106 /* Only for pre-ILK configs */
1107 void assert_pll(struct drm_i915_private *dev_priv,
1108                 enum pipe pipe, bool state)
1109 {
1110         int reg;
1111         u32 val;
1112         bool cur_state;
1113
1114         reg = DPLL(pipe);
1115         val = I915_READ(reg);
1116         cur_state = !!(val & DPLL_VCO_ENABLE);
1117         I915_STATE_WARN(cur_state != state,
1118              "PLL state assertion failure (expected %s, current %s)\n",
1119              state_string(state), state_string(cur_state));
1120 }
1121
1122 /* XXX: the dsi pll is shared between MIPI DSI ports */
1123 static void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1124 {
1125         u32 val;
1126         bool cur_state;
1127
1128         mutex_lock(&dev_priv->sb_lock);
1129         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1130         mutex_unlock(&dev_priv->sb_lock);
1131
1132         cur_state = val & DSI_PLL_VCO_EN;
1133         I915_STATE_WARN(cur_state != state,
1134              "DSI PLL state assertion failure (expected %s, current %s)\n",
1135              state_string(state), state_string(cur_state));
1136 }
1137 #define assert_dsi_pll_enabled(d) assert_dsi_pll(d, true)
1138 #define assert_dsi_pll_disabled(d) assert_dsi_pll(d, false)
1139
1140 struct intel_shared_dpll *
1141 intel_crtc_to_shared_dpll(struct intel_crtc *crtc)
1142 {
1143         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
1144
1145         if (crtc->config->shared_dpll < 0)
1146                 return NULL;
1147
1148         return &dev_priv->shared_dplls[crtc->config->shared_dpll];
1149 }
1150
1151 /* For ILK+ */
1152 void assert_shared_dpll(struct drm_i915_private *dev_priv,
1153                         struct intel_shared_dpll *pll,
1154                         bool state)
1155 {
1156         bool cur_state;
1157         struct intel_dpll_hw_state hw_state;
1158
1159         if (WARN (!pll,
1160                   "asserting DPLL %s with no DPLL\n", state_string(state)))
1161                 return;
1162
1163         cur_state = pll->get_hw_state(dev_priv, pll, &hw_state);
1164         I915_STATE_WARN(cur_state != state,
1165              "%s assertion failure (expected %s, current %s)\n",
1166              pll->name, state_string(state), state_string(cur_state));
1167 }
1168
1169 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1170                           enum pipe pipe, bool state)
1171 {
1172         int reg;
1173         u32 val;
1174         bool cur_state;
1175         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1176                                                                       pipe);
1177
1178         if (HAS_DDI(dev_priv->dev)) {
1179                 /* DDI does not have a specific FDI_TX register */
1180                 reg = TRANS_DDI_FUNC_CTL(cpu_transcoder);
1181                 val = I915_READ(reg);
1182                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1183         } else {
1184                 reg = FDI_TX_CTL(pipe);
1185                 val = I915_READ(reg);
1186                 cur_state = !!(val & FDI_TX_ENABLE);
1187         }
1188         I915_STATE_WARN(cur_state != state,
1189              "FDI TX state assertion failure (expected %s, current %s)\n",
1190              state_string(state), state_string(cur_state));
1191 }
1192 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1193 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1194
1195 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1196                           enum pipe pipe, bool state)
1197 {
1198         int reg;
1199         u32 val;
1200         bool cur_state;
1201
1202         reg = FDI_RX_CTL(pipe);
1203         val = I915_READ(reg);
1204         cur_state = !!(val & FDI_RX_ENABLE);
1205         I915_STATE_WARN(cur_state != state,
1206              "FDI RX state assertion failure (expected %s, current %s)\n",
1207              state_string(state), state_string(cur_state));
1208 }
1209 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1210 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1211
1212 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1213                                       enum pipe pipe)
1214 {
1215         int reg;
1216         u32 val;
1217
1218         /* ILK FDI PLL is always enabled */
1219         if (INTEL_INFO(dev_priv->dev)->gen == 5)
1220                 return;
1221
1222         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1223         if (HAS_DDI(dev_priv->dev))
1224                 return;
1225
1226         reg = FDI_TX_CTL(pipe);
1227         val = I915_READ(reg);
1228         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1229 }
1230
1231 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1232                        enum pipe pipe, bool state)
1233 {
1234         int reg;
1235         u32 val;
1236         bool cur_state;
1237
1238         reg = FDI_RX_CTL(pipe);
1239         val = I915_READ(reg);
1240         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1241         I915_STATE_WARN(cur_state != state,
1242              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1243              state_string(state), state_string(cur_state));
1244 }
1245
1246 void assert_panel_unlocked(struct drm_i915_private *dev_priv,
1247                            enum pipe pipe)
1248 {
1249         struct drm_device *dev = dev_priv->dev;
1250         int pp_reg;
1251         u32 val;
1252         enum pipe panel_pipe = PIPE_A;
1253         bool locked = true;
1254
1255         if (WARN_ON(HAS_DDI(dev)))
1256                 return;
1257
1258         if (HAS_PCH_SPLIT(dev)) {
1259                 u32 port_sel;
1260
1261                 pp_reg = PCH_PP_CONTROL;
1262                 port_sel = I915_READ(PCH_PP_ON_DELAYS) & PANEL_PORT_SELECT_MASK;
1263
1264                 if (port_sel == PANEL_PORT_SELECT_LVDS &&
1265                     I915_READ(PCH_LVDS) & LVDS_PIPEB_SELECT)
1266                         panel_pipe = PIPE_B;
1267                 /* XXX: else fix for eDP */
1268         } else if (IS_VALLEYVIEW(dev)) {
1269                 /* presumably write lock depends on pipe, not port select */
1270                 pp_reg = VLV_PIPE_PP_CONTROL(pipe);
1271                 panel_pipe = pipe;
1272         } else {
1273                 pp_reg = PP_CONTROL;
1274                 if (I915_READ(LVDS) & LVDS_PIPEB_SELECT)
1275                         panel_pipe = PIPE_B;
1276         }
1277
1278         val = I915_READ(pp_reg);
1279         if (!(val & PANEL_POWER_ON) ||
1280             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1281                 locked = false;
1282
1283         I915_STATE_WARN(panel_pipe == pipe && locked,
1284              "panel assertion failure, pipe %c regs locked\n",
1285              pipe_name(pipe));
1286 }
1287
1288 static void assert_cursor(struct drm_i915_private *dev_priv,
1289                           enum pipe pipe, bool state)
1290 {
1291         struct drm_device *dev = dev_priv->dev;
1292         bool cur_state;
1293
1294         if (IS_845G(dev) || IS_I865G(dev))
1295                 cur_state = I915_READ(_CURACNTR) & CURSOR_ENABLE;
1296         else
1297                 cur_state = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
1298
1299         I915_STATE_WARN(cur_state != state,
1300              "cursor on pipe %c assertion failure (expected %s, current %s)\n",
1301              pipe_name(pipe), state_string(state), state_string(cur_state));
1302 }
1303 #define assert_cursor_enabled(d, p) assert_cursor(d, p, true)
1304 #define assert_cursor_disabled(d, p) assert_cursor(d, p, false)
1305
1306 void assert_pipe(struct drm_i915_private *dev_priv,
1307                  enum pipe pipe, bool state)
1308 {
1309         int reg;
1310         u32 val;
1311         bool cur_state;
1312         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1313                                                                       pipe);
1314
1315         /* if we need the pipe quirk it must be always on */
1316         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1317             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1318                 state = true;
1319
1320         if (!intel_display_power_is_enabled(dev_priv,
1321                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder))) {
1322                 cur_state = false;
1323         } else {
1324                 reg = PIPECONF(cpu_transcoder);
1325                 val = I915_READ(reg);
1326                 cur_state = !!(val & PIPECONF_ENABLE);
1327         }
1328
1329         I915_STATE_WARN(cur_state != state,
1330              "pipe %c assertion failure (expected %s, current %s)\n",
1331              pipe_name(pipe), state_string(state), state_string(cur_state));
1332 }
1333
1334 static void assert_plane(struct drm_i915_private *dev_priv,
1335                          enum plane plane, bool state)
1336 {
1337         int reg;
1338         u32 val;
1339         bool cur_state;
1340
1341         reg = DSPCNTR(plane);
1342         val = I915_READ(reg);
1343         cur_state = !!(val & DISPLAY_PLANE_ENABLE);
1344         I915_STATE_WARN(cur_state != state,
1345              "plane %c assertion failure (expected %s, current %s)\n",
1346              plane_name(plane), state_string(state), state_string(cur_state));
1347 }
1348
1349 #define assert_plane_enabled(d, p) assert_plane(d, p, true)
1350 #define assert_plane_disabled(d, p) assert_plane(d, p, false)
1351
1352 static void assert_planes_disabled(struct drm_i915_private *dev_priv,
1353                                    enum pipe pipe)
1354 {
1355         struct drm_device *dev = dev_priv->dev;
1356         int reg, i;
1357         u32 val;
1358         int cur_pipe;
1359
1360         /* Primary planes are fixed to pipes on gen4+ */
1361         if (INTEL_INFO(dev)->gen >= 4) {
1362                 reg = DSPCNTR(pipe);
1363                 val = I915_READ(reg);
1364                 I915_STATE_WARN(val & DISPLAY_PLANE_ENABLE,
1365                      "plane %c assertion failure, should be disabled but not\n",
1366                      plane_name(pipe));
1367                 return;
1368         }
1369
1370         /* Need to check both planes against the pipe */
1371         for_each_pipe(dev_priv, i) {
1372                 reg = DSPCNTR(i);
1373                 val = I915_READ(reg);
1374                 cur_pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
1375                         DISPPLANE_SEL_PIPE_SHIFT;
1376                 I915_STATE_WARN((val & DISPLAY_PLANE_ENABLE) && pipe == cur_pipe,
1377                      "plane %c assertion failure, should be off on pipe %c but is still active\n",
1378                      plane_name(i), pipe_name(pipe));
1379         }
1380 }
1381
1382 static void assert_sprites_disabled(struct drm_i915_private *dev_priv,
1383                                     enum pipe pipe)
1384 {
1385         struct drm_device *dev = dev_priv->dev;
1386         int reg, sprite;
1387         u32 val;
1388
1389         if (INTEL_INFO(dev)->gen >= 9) {
1390                 for_each_sprite(dev_priv, pipe, sprite) {
1391                         val = I915_READ(PLANE_CTL(pipe, sprite));
1392                         I915_STATE_WARN(val & PLANE_CTL_ENABLE,
1393                              "plane %d assertion failure, should be off on pipe %c but is still active\n",
1394                              sprite, pipe_name(pipe));
1395                 }
1396         } else if (IS_VALLEYVIEW(dev)) {
1397                 for_each_sprite(dev_priv, pipe, sprite) {
1398                         reg = SPCNTR(pipe, sprite);
1399                         val = I915_READ(reg);
1400                         I915_STATE_WARN(val & SP_ENABLE,
1401                              "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1402                              sprite_name(pipe, sprite), pipe_name(pipe));
1403                 }
1404         } else if (INTEL_INFO(dev)->gen >= 7) {
1405                 reg = SPRCTL(pipe);
1406                 val = I915_READ(reg);
1407                 I915_STATE_WARN(val & SPRITE_ENABLE,
1408                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1409                      plane_name(pipe), pipe_name(pipe));
1410         } else if (INTEL_INFO(dev)->gen >= 5) {
1411                 reg = DVSCNTR(pipe);
1412                 val = I915_READ(reg);
1413                 I915_STATE_WARN(val & DVS_ENABLE,
1414                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1415                      plane_name(pipe), pipe_name(pipe));
1416         }
1417 }
1418
1419 static void assert_vblank_disabled(struct drm_crtc *crtc)
1420 {
1421         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1422                 drm_crtc_vblank_put(crtc);
1423 }
1424
1425 static void ibx_assert_pch_refclk_enabled(struct drm_i915_private *dev_priv)
1426 {
1427         u32 val;
1428         bool enabled;
1429
1430         I915_STATE_WARN_ON(!(HAS_PCH_IBX(dev_priv->dev) || HAS_PCH_CPT(dev_priv->dev)));
1431
1432         val = I915_READ(PCH_DREF_CONTROL);
1433         enabled = !!(val & (DREF_SSC_SOURCE_MASK | DREF_NONSPREAD_SOURCE_MASK |
1434                             DREF_SUPERSPREAD_SOURCE_MASK));
1435         I915_STATE_WARN(!enabled, "PCH refclk assertion failure, should be active but is disabled\n");
1436 }
1437
1438 static void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1439                                            enum pipe pipe)
1440 {
1441         int reg;
1442         u32 val;
1443         bool enabled;
1444
1445         reg = PCH_TRANSCONF(pipe);
1446         val = I915_READ(reg);
1447         enabled = !!(val & TRANS_ENABLE);
1448         I915_STATE_WARN(enabled,
1449              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1450              pipe_name(pipe));
1451 }
1452
1453 static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1454                             enum pipe pipe, u32 port_sel, u32 val)
1455 {
1456         if ((val & DP_PORT_EN) == 0)
1457                 return false;
1458
1459         if (HAS_PCH_CPT(dev_priv->dev)) {
1460                 u32     trans_dp_ctl_reg = TRANS_DP_CTL(pipe);
1461                 u32     trans_dp_ctl = I915_READ(trans_dp_ctl_reg);
1462                 if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1463                         return false;
1464         } else if (IS_CHERRYVIEW(dev_priv->dev)) {
1465                 if ((val & DP_PIPE_MASK_CHV) != DP_PIPE_SELECT_CHV(pipe))
1466                         return false;
1467         } else {
1468                 if ((val & DP_PIPE_MASK) != (pipe << 30))
1469                         return false;
1470         }
1471         return true;
1472 }
1473
1474 static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1475                               enum pipe pipe, u32 val)
1476 {
1477         if ((val & SDVO_ENABLE) == 0)
1478                 return false;
1479
1480         if (HAS_PCH_CPT(dev_priv->dev)) {
1481                 if ((val & SDVO_PIPE_SEL_MASK_CPT) != SDVO_PIPE_SEL_CPT(pipe))
1482                         return false;
1483         } else if (IS_CHERRYVIEW(dev_priv->dev)) {
1484                 if ((val & SDVO_PIPE_SEL_MASK_CHV) != SDVO_PIPE_SEL_CHV(pipe))
1485                         return false;
1486         } else {
1487                 if ((val & SDVO_PIPE_SEL_MASK) != SDVO_PIPE_SEL(pipe))
1488                         return false;
1489         }
1490         return true;
1491 }
1492
1493 static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1494                               enum pipe pipe, u32 val)
1495 {
1496         if ((val & LVDS_PORT_EN) == 0)
1497                 return false;
1498
1499         if (HAS_PCH_CPT(dev_priv->dev)) {
1500                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1501                         return false;
1502         } else {
1503                 if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1504                         return false;
1505         }
1506         return true;
1507 }
1508
1509 static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1510                               enum pipe pipe, u32 val)
1511 {
1512         if ((val & ADPA_DAC_ENABLE) == 0)
1513                 return false;
1514         if (HAS_PCH_CPT(dev_priv->dev)) {
1515                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1516                         return false;
1517         } else {
1518                 if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1519                         return false;
1520         }
1521         return true;
1522 }
1523
1524 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1525                                    enum pipe pipe, int reg, u32 port_sel)
1526 {
1527         u32 val = I915_READ(reg);
1528         I915_STATE_WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1529              "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1530              reg, pipe_name(pipe));
1531
1532         I915_STATE_WARN(HAS_PCH_IBX(dev_priv->dev) && (val & DP_PORT_EN) == 0
1533              && (val & DP_PIPEB_SELECT),
1534              "IBX PCH dp port still using transcoder B\n");
1535 }
1536
1537 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1538                                      enum pipe pipe, int reg)
1539 {
1540         u32 val = I915_READ(reg);
1541         I915_STATE_WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1542              "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1543              reg, pipe_name(pipe));
1544
1545         I915_STATE_WARN(HAS_PCH_IBX(dev_priv->dev) && (val & SDVO_ENABLE) == 0
1546              && (val & SDVO_PIPE_B_SELECT),
1547              "IBX PCH hdmi port still using transcoder B\n");
1548 }
1549
1550 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1551                                       enum pipe pipe)
1552 {
1553         int reg;
1554         u32 val;
1555
1556         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1557         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1558         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1559
1560         reg = PCH_ADPA;
1561         val = I915_READ(reg);
1562         I915_STATE_WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1563              "PCH VGA enabled on transcoder %c, should be disabled\n",
1564              pipe_name(pipe));
1565
1566         reg = PCH_LVDS;
1567         val = I915_READ(reg);
1568         I915_STATE_WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1569              "PCH LVDS enabled on transcoder %c, should be disabled\n",
1570              pipe_name(pipe));
1571
1572         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIB);
1573         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIC);
1574         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMID);
1575 }
1576
1577 static void vlv_enable_pll(struct intel_crtc *crtc,
1578                            const struct intel_crtc_state *pipe_config)
1579 {
1580         struct drm_device *dev = crtc->base.dev;
1581         struct drm_i915_private *dev_priv = dev->dev_private;
1582         int reg = DPLL(crtc->pipe);
1583         u32 dpll = pipe_config->dpll_hw_state.dpll;
1584
1585         assert_pipe_disabled(dev_priv, crtc->pipe);
1586
1587         /* No really, not for ILK+ */
1588         BUG_ON(!IS_VALLEYVIEW(dev_priv->dev));
1589
1590         /* PLL is protected by panel, make sure we can write it */
1591         if (IS_MOBILE(dev_priv->dev))
1592                 assert_panel_unlocked(dev_priv, crtc->pipe);
1593
1594         I915_WRITE(reg, dpll);
1595         POSTING_READ(reg);
1596         udelay(150);
1597
1598         if (wait_for(((I915_READ(reg) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1599                 DRM_ERROR("DPLL %d failed to lock\n", crtc->pipe);
1600
1601         I915_WRITE(DPLL_MD(crtc->pipe), pipe_config->dpll_hw_state.dpll_md);
1602         POSTING_READ(DPLL_MD(crtc->pipe));
1603
1604         /* We do this three times for luck */
1605         I915_WRITE(reg, dpll);
1606         POSTING_READ(reg);
1607         udelay(150); /* wait for warmup */
1608         I915_WRITE(reg, dpll);
1609         POSTING_READ(reg);
1610         udelay(150); /* wait for warmup */
1611         I915_WRITE(reg, dpll);
1612         POSTING_READ(reg);
1613         udelay(150); /* wait for warmup */
1614 }
1615
1616 static void chv_enable_pll(struct intel_crtc *crtc,
1617                            const struct intel_crtc_state *pipe_config)
1618 {
1619         struct drm_device *dev = crtc->base.dev;
1620         struct drm_i915_private *dev_priv = dev->dev_private;
1621         int pipe = crtc->pipe;
1622         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1623         u32 tmp;
1624
1625         assert_pipe_disabled(dev_priv, crtc->pipe);
1626
1627         BUG_ON(!IS_CHERRYVIEW(dev_priv->dev));
1628
1629         mutex_lock(&dev_priv->sb_lock);
1630
1631         /* Enable back the 10bit clock to display controller */
1632         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1633         tmp |= DPIO_DCLKP_EN;
1634         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1635
1636         mutex_unlock(&dev_priv->sb_lock);
1637
1638         /*
1639          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1640          */
1641         udelay(1);
1642
1643         /* Enable PLL */
1644         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1645
1646         /* Check PLL is locked */
1647         if (wait_for(((I915_READ(DPLL(pipe)) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1648                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1649
1650         /* not sure when this should be written */
1651         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1652         POSTING_READ(DPLL_MD(pipe));
1653 }
1654
1655 static int intel_num_dvo_pipes(struct drm_device *dev)
1656 {
1657         struct intel_crtc *crtc;
1658         int count = 0;
1659
1660         for_each_intel_crtc(dev, crtc)
1661                 count += crtc->base.state->active &&
1662                         intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO);
1663
1664         return count;
1665 }
1666
1667 static void i9xx_enable_pll(struct intel_crtc *crtc)
1668 {
1669         struct drm_device *dev = crtc->base.dev;
1670         struct drm_i915_private *dev_priv = dev->dev_private;
1671         int reg = DPLL(crtc->pipe);
1672         u32 dpll = crtc->config->dpll_hw_state.dpll;
1673
1674         assert_pipe_disabled(dev_priv, crtc->pipe);
1675
1676         /* No really, not for ILK+ */
1677         BUG_ON(INTEL_INFO(dev)->gen >= 5);
1678
1679         /* PLL is protected by panel, make sure we can write it */
1680         if (IS_MOBILE(dev) && !IS_I830(dev))
1681                 assert_panel_unlocked(dev_priv, crtc->pipe);
1682
1683         /* Enable DVO 2x clock on both PLLs if necessary */
1684         if (IS_I830(dev) && intel_num_dvo_pipes(dev) > 0) {
1685                 /*
1686                  * It appears to be important that we don't enable this
1687                  * for the current pipe before otherwise configuring the
1688                  * PLL. No idea how this should be handled if multiple
1689                  * DVO outputs are enabled simultaneosly.
1690                  */
1691                 dpll |= DPLL_DVO_2X_MODE;
1692                 I915_WRITE(DPLL(!crtc->pipe),
1693                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1694         }
1695
1696         /* Wait for the clocks to stabilize. */
1697         POSTING_READ(reg);
1698         udelay(150);
1699
1700         if (INTEL_INFO(dev)->gen >= 4) {
1701                 I915_WRITE(DPLL_MD(crtc->pipe),
1702                            crtc->config->dpll_hw_state.dpll_md);
1703         } else {
1704                 /* The pixel multiplier can only be updated once the
1705                  * DPLL is enabled and the clocks are stable.
1706                  *
1707                  * So write it again.
1708                  */
1709                 I915_WRITE(reg, dpll);
1710         }
1711
1712         /* We do this three times for luck */
1713         I915_WRITE(reg, dpll);
1714         POSTING_READ(reg);
1715         udelay(150); /* wait for warmup */
1716         I915_WRITE(reg, dpll);
1717         POSTING_READ(reg);
1718         udelay(150); /* wait for warmup */
1719         I915_WRITE(reg, dpll);
1720         POSTING_READ(reg);
1721         udelay(150); /* wait for warmup */
1722 }
1723
1724 /**
1725  * i9xx_disable_pll - disable a PLL
1726  * @dev_priv: i915 private structure
1727  * @pipe: pipe PLL to disable
1728  *
1729  * Disable the PLL for @pipe, making sure the pipe is off first.
1730  *
1731  * Note!  This is for pre-ILK only.
1732  */
1733 static void i9xx_disable_pll(struct intel_crtc *crtc)
1734 {
1735         struct drm_device *dev = crtc->base.dev;
1736         struct drm_i915_private *dev_priv = dev->dev_private;
1737         enum pipe pipe = crtc->pipe;
1738
1739         /* Disable DVO 2x clock on both PLLs if necessary */
1740         if (IS_I830(dev) &&
1741             intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO) &&
1742             !intel_num_dvo_pipes(dev)) {
1743                 I915_WRITE(DPLL(PIPE_B),
1744                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1745                 I915_WRITE(DPLL(PIPE_A),
1746                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1747         }
1748
1749         /* Don't disable pipe or pipe PLLs if needed */
1750         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1751             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1752                 return;
1753
1754         /* Make sure the pipe isn't still relying on us */
1755         assert_pipe_disabled(dev_priv, pipe);
1756
1757         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1758         POSTING_READ(DPLL(pipe));
1759 }
1760
1761 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1762 {
1763         u32 val;
1764
1765         /* Make sure the pipe isn't still relying on us */
1766         assert_pipe_disabled(dev_priv, pipe);
1767
1768         /*
1769          * Leave integrated clock source and reference clock enabled for pipe B.
1770          * The latter is needed for VGA hotplug / manual detection.
1771          */
1772         val = DPLL_VGA_MODE_DIS;
1773         if (pipe == PIPE_B)
1774                 val = DPLL_INTEGRATED_CRI_CLK_VLV | DPLL_REF_CLK_ENABLE_VLV;
1775         I915_WRITE(DPLL(pipe), val);
1776         POSTING_READ(DPLL(pipe));
1777
1778 }
1779
1780 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1781 {
1782         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1783         u32 val;
1784
1785         /* Make sure the pipe isn't still relying on us */
1786         assert_pipe_disabled(dev_priv, pipe);
1787
1788         /* Set PLL en = 0 */
1789         val = DPLL_SSC_REF_CLK_CHV |
1790                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1791         if (pipe != PIPE_A)
1792                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1793         I915_WRITE(DPLL(pipe), val);
1794         POSTING_READ(DPLL(pipe));
1795
1796         mutex_lock(&dev_priv->sb_lock);
1797
1798         /* Disable 10bit clock to display controller */
1799         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1800         val &= ~DPIO_DCLKP_EN;
1801         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1802
1803         mutex_unlock(&dev_priv->sb_lock);
1804 }
1805
1806 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1807                          struct intel_digital_port *dport,
1808                          unsigned int expected_mask)
1809 {
1810         u32 port_mask;
1811         int dpll_reg;
1812
1813         switch (dport->port) {
1814         case PORT_B:
1815                 port_mask = DPLL_PORTB_READY_MASK;
1816                 dpll_reg = DPLL(0);
1817                 break;
1818         case PORT_C:
1819                 port_mask = DPLL_PORTC_READY_MASK;
1820                 dpll_reg = DPLL(0);
1821                 expected_mask <<= 4;
1822                 break;
1823         case PORT_D:
1824                 port_mask = DPLL_PORTD_READY_MASK;
1825                 dpll_reg = DPIO_PHY_STATUS;
1826                 break;
1827         default:
1828                 BUG();
1829         }
1830
1831         if (wait_for((I915_READ(dpll_reg) & port_mask) == expected_mask, 1000))
1832                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1833                      port_name(dport->port), I915_READ(dpll_reg) & port_mask, expected_mask);
1834 }
1835
1836 static void intel_prepare_shared_dpll(struct intel_crtc *crtc)
1837 {
1838         struct drm_device *dev = crtc->base.dev;
1839         struct drm_i915_private *dev_priv = dev->dev_private;
1840         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1841
1842         if (WARN_ON(pll == NULL))
1843                 return;
1844
1845         WARN_ON(!pll->config.crtc_mask);
1846         if (pll->active == 0) {
1847                 DRM_DEBUG_DRIVER("setting up %s\n", pll->name);
1848                 WARN_ON(pll->on);
1849                 assert_shared_dpll_disabled(dev_priv, pll);
1850
1851                 pll->mode_set(dev_priv, pll);
1852         }
1853 }
1854
1855 /**
1856  * intel_enable_shared_dpll - enable PCH PLL
1857  * @dev_priv: i915 private structure
1858  * @pipe: pipe PLL to enable
1859  *
1860  * The PCH PLL needs to be enabled before the PCH transcoder, since it
1861  * drives the transcoder clock.
1862  */
1863 static void intel_enable_shared_dpll(struct intel_crtc *crtc)
1864 {
1865         struct drm_device *dev = crtc->base.dev;
1866         struct drm_i915_private *dev_priv = dev->dev_private;
1867         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1868
1869         if (WARN_ON(pll == NULL))
1870                 return;
1871
1872         if (WARN_ON(pll->config.crtc_mask == 0))
1873                 return;
1874
1875         DRM_DEBUG_KMS("enable %s (active %d, on? %d) for crtc %d\n",
1876                       pll->name, pll->active, pll->on,
1877                       crtc->base.base.id);
1878
1879         if (pll->active++) {
1880                 WARN_ON(!pll->on);
1881                 assert_shared_dpll_enabled(dev_priv, pll);
1882                 return;
1883         }
1884         WARN_ON(pll->on);
1885
1886         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
1887
1888         DRM_DEBUG_KMS("enabling %s\n", pll->name);
1889         pll->enable(dev_priv, pll);
1890         pll->on = true;
1891 }
1892
1893 static void intel_disable_shared_dpll(struct intel_crtc *crtc)
1894 {
1895         struct drm_device *dev = crtc->base.dev;
1896         struct drm_i915_private *dev_priv = dev->dev_private;
1897         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1898
1899         /* PCH only available on ILK+ */
1900         if (INTEL_INFO(dev)->gen < 5)
1901                 return;
1902
1903         if (pll == NULL)
1904                 return;
1905
1906         if (WARN_ON(!(pll->config.crtc_mask & (1 << drm_crtc_index(&crtc->base)))))
1907                 return;
1908
1909         DRM_DEBUG_KMS("disable %s (active %d, on? %d) for crtc %d\n",
1910                       pll->name, pll->active, pll->on,
1911                       crtc->base.base.id);
1912
1913         if (WARN_ON(pll->active == 0)) {
1914                 assert_shared_dpll_disabled(dev_priv, pll);
1915                 return;
1916         }
1917
1918         assert_shared_dpll_enabled(dev_priv, pll);
1919         WARN_ON(!pll->on);
1920         if (--pll->active)
1921                 return;
1922
1923         DRM_DEBUG_KMS("disabling %s\n", pll->name);
1924         pll->disable(dev_priv, pll);
1925         pll->on = false;
1926
1927         intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS);
1928 }
1929
1930 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1931                                            enum pipe pipe)
1932 {
1933         struct drm_device *dev = dev_priv->dev;
1934         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1935         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1936         uint32_t reg, val, pipeconf_val;
1937
1938         /* PCH only available on ILK+ */
1939         BUG_ON(!HAS_PCH_SPLIT(dev));
1940
1941         /* Make sure PCH DPLL is enabled */
1942         assert_shared_dpll_enabled(dev_priv,
1943                                    intel_crtc_to_shared_dpll(intel_crtc));
1944
1945         /* FDI must be feeding us bits for PCH ports */
1946         assert_fdi_tx_enabled(dev_priv, pipe);
1947         assert_fdi_rx_enabled(dev_priv, pipe);
1948
1949         if (HAS_PCH_CPT(dev)) {
1950                 /* Workaround: Set the timing override bit before enabling the
1951                  * pch transcoder. */
1952                 reg = TRANS_CHICKEN2(pipe);
1953                 val = I915_READ(reg);
1954                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1955                 I915_WRITE(reg, val);
1956         }
1957
1958         reg = PCH_TRANSCONF(pipe);
1959         val = I915_READ(reg);
1960         pipeconf_val = I915_READ(PIPECONF(pipe));
1961
1962         if (HAS_PCH_IBX(dev_priv->dev)) {
1963                 /*
1964                  * Make the BPC in transcoder be consistent with
1965                  * that in pipeconf reg. For HDMI we must use 8bpc
1966                  * here for both 8bpc and 12bpc.
1967                  */
1968                 val &= ~PIPECONF_BPC_MASK;
1969                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_HDMI))
1970                         val |= PIPECONF_8BPC;
1971                 else
1972                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1973         }
1974
1975         val &= ~TRANS_INTERLACE_MASK;
1976         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1977                 if (HAS_PCH_IBX(dev_priv->dev) &&
1978                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
1979                         val |= TRANS_LEGACY_INTERLACED_ILK;
1980                 else
1981                         val |= TRANS_INTERLACED;
1982         else
1983                 val |= TRANS_PROGRESSIVE;
1984
1985         I915_WRITE(reg, val | TRANS_ENABLE);
1986         if (wait_for(I915_READ(reg) & TRANS_STATE_ENABLE, 100))
1987                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1988 }
1989
1990 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1991                                       enum transcoder cpu_transcoder)
1992 {
1993         u32 val, pipeconf_val;
1994
1995         /* PCH only available on ILK+ */
1996         BUG_ON(!HAS_PCH_SPLIT(dev_priv->dev));
1997
1998         /* FDI must be feeding us bits for PCH ports */
1999         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
2000         assert_fdi_rx_enabled(dev_priv, TRANSCODER_A);
2001
2002         /* Workaround: set timing override bit. */
2003         val = I915_READ(_TRANSA_CHICKEN2);
2004         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
2005         I915_WRITE(_TRANSA_CHICKEN2, val);
2006
2007         val = TRANS_ENABLE;
2008         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
2009
2010         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
2011             PIPECONF_INTERLACED_ILK)
2012                 val |= TRANS_INTERLACED;
2013         else
2014                 val |= TRANS_PROGRESSIVE;
2015
2016         I915_WRITE(LPT_TRANSCONF, val);
2017         if (wait_for(I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE, 100))
2018                 DRM_ERROR("Failed to enable PCH transcoder\n");
2019 }
2020
2021 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
2022                                             enum pipe pipe)
2023 {
2024         struct drm_device *dev = dev_priv->dev;
2025         uint32_t reg, val;
2026
2027         /* FDI relies on the transcoder */
2028         assert_fdi_tx_disabled(dev_priv, pipe);
2029         assert_fdi_rx_disabled(dev_priv, pipe);
2030
2031         /* Ports must be off as well */
2032         assert_pch_ports_disabled(dev_priv, pipe);
2033
2034         reg = PCH_TRANSCONF(pipe);
2035         val = I915_READ(reg);
2036         val &= ~TRANS_ENABLE;
2037         I915_WRITE(reg, val);
2038         /* wait for PCH transcoder off, transcoder state */
2039         if (wait_for((I915_READ(reg) & TRANS_STATE_ENABLE) == 0, 50))
2040                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
2041
2042         if (!HAS_PCH_IBX(dev)) {
2043                 /* Workaround: Clear the timing override chicken bit again. */
2044                 reg = TRANS_CHICKEN2(pipe);
2045                 val = I915_READ(reg);
2046                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
2047                 I915_WRITE(reg, val);
2048         }
2049 }
2050
2051 static void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
2052 {
2053         u32 val;
2054
2055         val = I915_READ(LPT_TRANSCONF);
2056         val &= ~TRANS_ENABLE;
2057         I915_WRITE(LPT_TRANSCONF, val);
2058         /* wait for PCH transcoder off, transcoder state */
2059         if (wait_for((I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE) == 0, 50))
2060                 DRM_ERROR("Failed to disable PCH transcoder\n");
2061
2062         /* Workaround: clear timing override bit. */
2063         val = I915_READ(_TRANSA_CHICKEN2);
2064         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
2065         I915_WRITE(_TRANSA_CHICKEN2, val);
2066 }
2067
2068 /**
2069  * intel_enable_pipe - enable a pipe, asserting requirements
2070  * @crtc: crtc responsible for the pipe
2071  *
2072  * Enable @crtc's pipe, making sure that various hardware specific requirements
2073  * are met, if applicable, e.g. PLL enabled, LVDS pairs enabled, etc.
2074  */
2075 static void intel_enable_pipe(struct intel_crtc *crtc)
2076 {
2077         struct drm_device *dev = crtc->base.dev;
2078         struct drm_i915_private *dev_priv = dev->dev_private;
2079         enum pipe pipe = crtc->pipe;
2080         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
2081                                                                       pipe);
2082         enum pipe pch_transcoder;
2083         int reg;
2084         u32 val;
2085
2086         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
2087
2088         assert_planes_disabled(dev_priv, pipe);
2089         assert_cursor_disabled(dev_priv, pipe);
2090         assert_sprites_disabled(dev_priv, pipe);
2091
2092         if (HAS_PCH_LPT(dev_priv->dev))
2093                 pch_transcoder = TRANSCODER_A;
2094         else
2095                 pch_transcoder = pipe;
2096
2097         /*
2098          * A pipe without a PLL won't actually be able to drive bits from
2099          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
2100          * need the check.
2101          */
2102         if (HAS_GMCH_DISPLAY(dev_priv->dev))
2103                 if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DSI))
2104                         assert_dsi_pll_enabled(dev_priv);
2105                 else
2106                         assert_pll_enabled(dev_priv, pipe);
2107         else {
2108                 if (crtc->config->has_pch_encoder) {
2109                         /* if driving the PCH, we need FDI enabled */
2110                         assert_fdi_rx_pll_enabled(dev_priv, pch_transcoder);
2111                         assert_fdi_tx_pll_enabled(dev_priv,
2112                                                   (enum pipe) cpu_transcoder);
2113                 }
2114                 /* FIXME: assert CPU port conditions for SNB+ */
2115         }
2116
2117         reg = PIPECONF(cpu_transcoder);
2118         val = I915_READ(reg);
2119         if (val & PIPECONF_ENABLE) {
2120                 WARN_ON(!((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
2121                           (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE)));
2122                 return;
2123         }
2124
2125         I915_WRITE(reg, val | PIPECONF_ENABLE);
2126         POSTING_READ(reg);
2127 }
2128
2129 /**
2130  * intel_disable_pipe - disable a pipe, asserting requirements
2131  * @crtc: crtc whose pipes is to be disabled
2132  *
2133  * Disable the pipe of @crtc, making sure that various hardware
2134  * specific requirements are met, if applicable, e.g. plane
2135  * disabled, panel fitter off, etc.
2136  *
2137  * Will wait until the pipe has shut down before returning.
2138  */
2139 static void intel_disable_pipe(struct intel_crtc *crtc)
2140 {
2141         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
2142         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
2143         enum pipe pipe = crtc->pipe;
2144         int reg;
2145         u32 val;
2146
2147         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
2148
2149         /*
2150          * Make sure planes won't keep trying to pump pixels to us,
2151          * or we might hang the display.
2152          */
2153         assert_planes_disabled(dev_priv, pipe);
2154         assert_cursor_disabled(dev_priv, pipe);
2155         assert_sprites_disabled(dev_priv, pipe);
2156
2157         reg = PIPECONF(cpu_transcoder);
2158         val = I915_READ(reg);
2159         if ((val & PIPECONF_ENABLE) == 0)
2160                 return;
2161
2162         /*
2163          * Double wide has implications for planes
2164          * so best keep it disabled when not needed.
2165          */
2166         if (crtc->config->double_wide)
2167                 val &= ~PIPECONF_DOUBLE_WIDE;
2168
2169         /* Don't disable pipe or pipe PLLs if needed */
2170         if (!(pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) &&
2171             !(pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
2172                 val &= ~PIPECONF_ENABLE;
2173
2174         I915_WRITE(reg, val);
2175         if ((val & PIPECONF_ENABLE) == 0)
2176                 intel_wait_for_pipe_off(crtc);
2177 }
2178
2179 static bool need_vtd_wa(struct drm_device *dev)
2180 {
2181 #ifdef CONFIG_INTEL_IOMMU
2182         if (INTEL_INFO(dev)->gen >= 6 && intel_iommu_gfx_mapped)
2183                 return true;
2184 #endif
2185         return false;
2186 }
2187
2188 unsigned int
2189 intel_tile_height(struct drm_device *dev, uint32_t pixel_format,
2190                   uint64_t fb_format_modifier)
2191 {
2192         unsigned int tile_height;
2193         uint32_t pixel_bytes;
2194
2195         switch (fb_format_modifier) {
2196         case DRM_FORMAT_MOD_NONE:
2197                 tile_height = 1;
2198                 break;
2199         case I915_FORMAT_MOD_X_TILED:
2200                 tile_height = IS_GEN2(dev) ? 16 : 8;
2201                 break;
2202         case I915_FORMAT_MOD_Y_TILED:
2203                 tile_height = 32;
2204                 break;
2205         case I915_FORMAT_MOD_Yf_TILED:
2206                 pixel_bytes = drm_format_plane_cpp(pixel_format, 0);
2207                 switch (pixel_bytes) {
2208                 default:
2209                 case 1:
2210                         tile_height = 64;
2211                         break;
2212                 case 2:
2213                 case 4:
2214                         tile_height = 32;
2215                         break;
2216                 case 8:
2217                         tile_height = 16;
2218                         break;
2219                 case 16:
2220                         WARN_ONCE(1,
2221                                   "128-bit pixels are not supported for display!");
2222                         tile_height = 16;
2223                         break;
2224                 }
2225                 break;
2226         default:
2227                 MISSING_CASE(fb_format_modifier);
2228                 tile_height = 1;
2229                 break;
2230         }
2231
2232         return tile_height;
2233 }
2234
2235 unsigned int
2236 intel_fb_align_height(struct drm_device *dev, unsigned int height,
2237                       uint32_t pixel_format, uint64_t fb_format_modifier)
2238 {
2239         return ALIGN(height, intel_tile_height(dev, pixel_format,
2240                                                fb_format_modifier));
2241 }
2242
2243 static int
2244 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view, struct drm_framebuffer *fb,
2245                         const struct drm_plane_state *plane_state)
2246 {
2247         struct intel_rotation_info *info = &view->rotation_info;
2248         unsigned int tile_height, tile_pitch;
2249
2250         *view = i915_ggtt_view_normal;
2251
2252         if (!plane_state)
2253                 return 0;
2254
2255         if (!intel_rotation_90_or_270(plane_state->rotation))
2256                 return 0;
2257
2258         *view = i915_ggtt_view_rotated;
2259
2260         info->height = fb->height;
2261         info->pixel_format = fb->pixel_format;
2262         info->pitch = fb->pitches[0];
2263         info->fb_modifier = fb->modifier[0];
2264
2265         tile_height = intel_tile_height(fb->dev, fb->pixel_format,
2266                                         fb->modifier[0]);
2267         tile_pitch = PAGE_SIZE / tile_height;
2268         info->width_pages = DIV_ROUND_UP(fb->pitches[0], tile_pitch);
2269         info->height_pages = DIV_ROUND_UP(fb->height, tile_height);
2270         info->size = info->width_pages * info->height_pages * PAGE_SIZE;
2271
2272         return 0;
2273 }
2274
2275 static unsigned int intel_linear_alignment(struct drm_i915_private *dev_priv)
2276 {
2277         if (INTEL_INFO(dev_priv)->gen >= 9)
2278                 return 256 * 1024;
2279         else if (IS_BROADWATER(dev_priv) || IS_CRESTLINE(dev_priv) ||
2280                  IS_VALLEYVIEW(dev_priv))
2281                 return 128 * 1024;
2282         else if (INTEL_INFO(dev_priv)->gen >= 4)
2283                 return 4 * 1024;
2284         else
2285                 return 0;
2286 }
2287
2288 int
2289 intel_pin_and_fence_fb_obj(struct drm_plane *plane,
2290                            struct drm_framebuffer *fb,
2291                            const struct drm_plane_state *plane_state,
2292                            struct intel_engine_cs *pipelined,
2293                            struct drm_i915_gem_request **pipelined_request)
2294 {
2295         struct drm_device *dev = fb->dev;
2296         struct drm_i915_private *dev_priv = dev->dev_private;
2297         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2298         struct i915_ggtt_view view;
2299         u32 alignment;
2300         int ret;
2301
2302         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2303
2304         switch (fb->modifier[0]) {
2305         case DRM_FORMAT_MOD_NONE:
2306                 alignment = intel_linear_alignment(dev_priv);
2307                 break;
2308         case I915_FORMAT_MOD_X_TILED:
2309                 if (INTEL_INFO(dev)->gen >= 9)
2310                         alignment = 256 * 1024;
2311                 else {
2312                         /* pin() will align the object as required by fence */
2313                         alignment = 0;
2314                 }
2315                 break;
2316         case I915_FORMAT_MOD_Y_TILED:
2317         case I915_FORMAT_MOD_Yf_TILED:
2318                 if (WARN_ONCE(INTEL_INFO(dev)->gen < 9,
2319                           "Y tiling bo slipped through, driver bug!\n"))
2320                         return -EINVAL;
2321                 alignment = 1 * 1024 * 1024;
2322                 break;
2323         default:
2324                 MISSING_CASE(fb->modifier[0]);
2325                 return -EINVAL;
2326         }
2327
2328         ret = intel_fill_fb_ggtt_view(&view, fb, plane_state);
2329         if (ret)
2330                 return ret;
2331
2332         /* Note that the w/a also requires 64 PTE of padding following the
2333          * bo. We currently fill all unused PTE with the shadow page and so
2334          * we should always have valid PTE following the scanout preventing
2335          * the VT-d warning.
2336          */
2337         if (need_vtd_wa(dev) && alignment < 256 * 1024)
2338                 alignment = 256 * 1024;
2339
2340         /*
2341          * Global gtt pte registers are special registers which actually forward
2342          * writes to a chunk of system memory. Which means that there is no risk
2343          * that the register values disappear as soon as we call
2344          * intel_runtime_pm_put(), so it is correct to wrap only the
2345          * pin/unpin/fence and not more.
2346          */
2347         intel_runtime_pm_get(dev_priv);
2348
2349         dev_priv->mm.interruptible = false;
2350         ret = i915_gem_object_pin_to_display_plane(obj, alignment, pipelined,
2351                                                    pipelined_request, &view);
2352         if (ret)
2353                 goto err_interruptible;
2354
2355         /* Install a fence for tiled scan-out. Pre-i965 always needs a
2356          * fence, whereas 965+ only requires a fence if using
2357          * framebuffer compression.  For simplicity, we always install
2358          * a fence as the cost is not that onerous.
2359          */
2360         ret = i915_gem_object_get_fence(obj);
2361         if (ret == -EDEADLK) {
2362                 /*
2363                  * -EDEADLK means there are no free fences
2364                  * no pending flips.
2365                  *
2366                  * This is propagated to atomic, but it uses
2367                  * -EDEADLK to force a locking recovery, so
2368                  * change the returned error to -EBUSY.
2369                  */
2370                 ret = -EBUSY;
2371                 goto err_unpin;
2372         } else if (ret)
2373                 goto err_unpin;
2374
2375         i915_gem_object_pin_fence(obj);
2376
2377         dev_priv->mm.interruptible = true;
2378         intel_runtime_pm_put(dev_priv);
2379         return 0;
2380
2381 err_unpin:
2382         i915_gem_object_unpin_from_display_plane(obj, &view);
2383 err_interruptible:
2384         dev_priv->mm.interruptible = true;
2385         intel_runtime_pm_put(dev_priv);
2386         return ret;
2387 }
2388
2389 static void intel_unpin_fb_obj(struct drm_framebuffer *fb,
2390                                const struct drm_plane_state *plane_state)
2391 {
2392         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2393         struct i915_ggtt_view view;
2394         int ret;
2395
2396         WARN_ON(!mutex_is_locked(&obj->base.dev->struct_mutex));
2397
2398         ret = intel_fill_fb_ggtt_view(&view, fb, plane_state);
2399         WARN_ONCE(ret, "Couldn't get view from plane state!");
2400
2401         i915_gem_object_unpin_fence(obj);
2402         i915_gem_object_unpin_from_display_plane(obj, &view);
2403 }
2404
2405 /* Computes the linear offset to the base tile and adjusts x, y. bytes per pixel
2406  * is assumed to be a power-of-two. */
2407 unsigned long intel_gen4_compute_page_offset(struct drm_i915_private *dev_priv,
2408                                              int *x, int *y,
2409                                              unsigned int tiling_mode,
2410                                              unsigned int cpp,
2411                                              unsigned int pitch)
2412 {
2413         if (tiling_mode != I915_TILING_NONE) {
2414                 unsigned int tile_rows, tiles;
2415
2416                 tile_rows = *y / 8;
2417                 *y %= 8;
2418
2419                 tiles = *x / (512/cpp);
2420                 *x %= 512/cpp;
2421
2422                 return tile_rows * pitch * 8 + tiles * 4096;
2423         } else {
2424                 unsigned int alignment = intel_linear_alignment(dev_priv) - 1;
2425                 unsigned int offset;
2426
2427                 offset = *y * pitch + *x * cpp;
2428                 *y = (offset & alignment) / pitch;
2429                 *x = ((offset & alignment) - *y * pitch) / cpp;
2430                 return offset & ~alignment;
2431         }
2432 }
2433
2434 static int i9xx_format_to_fourcc(int format)
2435 {
2436         switch (format) {
2437         case DISPPLANE_8BPP:
2438                 return DRM_FORMAT_C8;
2439         case DISPPLANE_BGRX555:
2440                 return DRM_FORMAT_XRGB1555;
2441         case DISPPLANE_BGRX565:
2442                 return DRM_FORMAT_RGB565;
2443         default:
2444         case DISPPLANE_BGRX888:
2445                 return DRM_FORMAT_XRGB8888;
2446         case DISPPLANE_RGBX888:
2447                 return DRM_FORMAT_XBGR8888;
2448         case DISPPLANE_BGRX101010:
2449                 return DRM_FORMAT_XRGB2101010;
2450         case DISPPLANE_RGBX101010:
2451                 return DRM_FORMAT_XBGR2101010;
2452         }
2453 }
2454
2455 static int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2456 {
2457         switch (format) {
2458         case PLANE_CTL_FORMAT_RGB_565:
2459                 return DRM_FORMAT_RGB565;
2460         default:
2461         case PLANE_CTL_FORMAT_XRGB_8888:
2462                 if (rgb_order) {
2463                         if (alpha)
2464                                 return DRM_FORMAT_ABGR8888;
2465                         else
2466                                 return DRM_FORMAT_XBGR8888;
2467                 } else {
2468                         if (alpha)
2469                                 return DRM_FORMAT_ARGB8888;
2470                         else
2471                                 return DRM_FORMAT_XRGB8888;
2472                 }
2473         case PLANE_CTL_FORMAT_XRGB_2101010:
2474                 if (rgb_order)
2475                         return DRM_FORMAT_XBGR2101010;
2476                 else
2477                         return DRM_FORMAT_XRGB2101010;
2478         }
2479 }
2480
2481 static bool
2482 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2483                               struct intel_initial_plane_config *plane_config)
2484 {
2485         struct drm_device *dev = crtc->base.dev;
2486         struct drm_i915_gem_object *obj = NULL;
2487         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2488         struct drm_framebuffer *fb = &plane_config->fb->base;
2489         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2490         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2491                                     PAGE_SIZE);
2492
2493         size_aligned -= base_aligned;
2494
2495         if (plane_config->size == 0)
2496                 return false;
2497
2498         obj = i915_gem_object_create_stolen_for_preallocated(dev,
2499                                                              base_aligned,
2500                                                              base_aligned,
2501                                                              size_aligned);
2502         if (!obj)
2503                 return false;
2504
2505         obj->tiling_mode = plane_config->tiling;
2506         if (obj->tiling_mode == I915_TILING_X)
2507                 obj->stride = fb->pitches[0];
2508
2509         mode_cmd.pixel_format = fb->pixel_format;
2510         mode_cmd.width = fb->width;
2511         mode_cmd.height = fb->height;
2512         mode_cmd.pitches[0] = fb->pitches[0];
2513         mode_cmd.modifier[0] = fb->modifier[0];
2514         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2515
2516         mutex_lock(&dev->struct_mutex);
2517         if (intel_framebuffer_init(dev, to_intel_framebuffer(fb),
2518                                    &mode_cmd, obj)) {
2519                 DRM_DEBUG_KMS("intel fb init failed\n");
2520                 goto out_unref_obj;
2521         }
2522         mutex_unlock(&dev->struct_mutex);
2523
2524         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2525         return true;
2526
2527 out_unref_obj:
2528         drm_gem_object_unreference(&obj->base);
2529         mutex_unlock(&dev->struct_mutex);
2530         return false;
2531 }
2532
2533 /* Update plane->state->fb to match plane->fb after driver-internal updates */
2534 static void
2535 update_state_fb(struct drm_plane *plane)
2536 {
2537         if (plane->fb == plane->state->fb)
2538                 return;
2539
2540         if (plane->state->fb)
2541                 drm_framebuffer_unreference(plane->state->fb);
2542         plane->state->fb = plane->fb;
2543         if (plane->state->fb)
2544                 drm_framebuffer_reference(plane->state->fb);
2545 }
2546
2547 static void
2548 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2549                              struct intel_initial_plane_config *plane_config)
2550 {
2551         struct drm_device *dev = intel_crtc->base.dev;
2552         struct drm_i915_private *dev_priv = dev->dev_private;
2553         struct drm_crtc *c;
2554         struct intel_crtc *i;
2555         struct drm_i915_gem_object *obj;
2556         struct drm_plane *primary = intel_crtc->base.primary;
2557         struct drm_plane_state *plane_state = primary->state;
2558         struct drm_framebuffer *fb;
2559
2560         if (!plane_config->fb)
2561                 return;
2562
2563         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2564                 fb = &plane_config->fb->base;
2565                 goto valid_fb;
2566         }
2567
2568         kfree(plane_config->fb);
2569
2570         /*
2571          * Failed to alloc the obj, check to see if we should share
2572          * an fb with another CRTC instead
2573          */
2574         for_each_crtc(dev, c) {
2575                 i = to_intel_crtc(c);
2576
2577                 if (c == &intel_crtc->base)
2578                         continue;
2579
2580                 if (!i->active)
2581                         continue;
2582
2583                 fb = c->primary->fb;
2584                 if (!fb)
2585                         continue;
2586
2587                 obj = intel_fb_obj(fb);
2588                 if (i915_gem_obj_ggtt_offset(obj) == plane_config->base) {
2589                         drm_framebuffer_reference(fb);
2590                         goto valid_fb;
2591                 }
2592         }
2593
2594         return;
2595
2596 valid_fb:
2597         plane_state->src_x = plane_state->src_y = 0;
2598         plane_state->src_w = fb->width << 16;
2599         plane_state->src_h = fb->height << 16;
2600
2601         plane_state->crtc_x = plane_state->src_y = 0;
2602         plane_state->crtc_w = fb->width;
2603         plane_state->crtc_h = fb->height;
2604
2605         obj = intel_fb_obj(fb);
2606         if (obj->tiling_mode != I915_TILING_NONE)
2607                 dev_priv->preserve_bios_swizzle = true;
2608
2609         drm_framebuffer_reference(fb);
2610         primary->fb = primary->state->fb = fb;
2611         primary->crtc = primary->state->crtc = &intel_crtc->base;
2612         intel_crtc->base.state->plane_mask |= (1 << drm_plane_index(primary));
2613         obj->frontbuffer_bits |= to_intel_plane(primary)->frontbuffer_bit;
2614 }
2615
2616 static void i9xx_update_primary_plane(struct drm_crtc *crtc,
2617                                       struct drm_framebuffer *fb,
2618                                       int x, int y)
2619 {
2620         struct drm_device *dev = crtc->dev;
2621         struct drm_i915_private *dev_priv = dev->dev_private;
2622         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2623         struct drm_plane *primary = crtc->primary;
2624         bool visible = to_intel_plane_state(primary->state)->visible;
2625         struct drm_i915_gem_object *obj;
2626         int plane = intel_crtc->plane;
2627         unsigned long linear_offset;
2628         u32 dspcntr;
2629         u32 reg = DSPCNTR(plane);
2630         int pixel_size;
2631
2632         if (!visible || !fb) {
2633                 I915_WRITE(reg, 0);
2634                 if (INTEL_INFO(dev)->gen >= 4)
2635                         I915_WRITE(DSPSURF(plane), 0);
2636                 else
2637                         I915_WRITE(DSPADDR(plane), 0);
2638                 POSTING_READ(reg);
2639                 return;
2640         }
2641
2642         obj = intel_fb_obj(fb);
2643         if (WARN_ON(obj == NULL))
2644                 return;
2645
2646         pixel_size = drm_format_plane_cpp(fb->pixel_format, 0);
2647
2648         dspcntr = DISPPLANE_GAMMA_ENABLE;
2649
2650         dspcntr |= DISPLAY_PLANE_ENABLE;
2651
2652         if (INTEL_INFO(dev)->gen < 4) {
2653                 if (intel_crtc->pipe == PIPE_B)
2654                         dspcntr |= DISPPLANE_SEL_PIPE_B;
2655
2656                 /* pipesrc and dspsize control the size that is scaled from,
2657                  * which should always be the user's requested size.
2658                  */
2659                 I915_WRITE(DSPSIZE(plane),
2660                            ((intel_crtc->config->pipe_src_h - 1) << 16) |
2661                            (intel_crtc->config->pipe_src_w - 1));
2662                 I915_WRITE(DSPPOS(plane), 0);
2663         } else if (IS_CHERRYVIEW(dev) && plane == PLANE_B) {
2664                 I915_WRITE(PRIMSIZE(plane),
2665                            ((intel_crtc->config->pipe_src_h - 1) << 16) |
2666                            (intel_crtc->config->pipe_src_w - 1));
2667                 I915_WRITE(PRIMPOS(plane), 0);
2668                 I915_WRITE(PRIMCNSTALPHA(plane), 0);
2669         }
2670
2671         switch (fb->pixel_format) {
2672         case DRM_FORMAT_C8:
2673                 dspcntr |= DISPPLANE_8BPP;
2674                 break;
2675         case DRM_FORMAT_XRGB1555:
2676                 dspcntr |= DISPPLANE_BGRX555;
2677                 break;
2678         case DRM_FORMAT_RGB565:
2679                 dspcntr |= DISPPLANE_BGRX565;
2680                 break;
2681         case DRM_FORMAT_XRGB8888:
2682                 dspcntr |= DISPPLANE_BGRX888;
2683                 break;
2684         case DRM_FORMAT_XBGR8888:
2685                 dspcntr |= DISPPLANE_RGBX888;
2686                 break;
2687         case DRM_FORMAT_XRGB2101010:
2688                 dspcntr |= DISPPLANE_BGRX101010;
2689                 break;
2690         case DRM_FORMAT_XBGR2101010:
2691                 dspcntr |= DISPPLANE_RGBX101010;
2692                 break;
2693         default:
2694                 BUG();
2695         }
2696
2697         if (INTEL_INFO(dev)->gen >= 4 &&
2698             obj->tiling_mode != I915_TILING_NONE)
2699                 dspcntr |= DISPPLANE_TILED;
2700
2701         if (IS_G4X(dev))
2702                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2703
2704         linear_offset = y * fb->pitches[0] + x * pixel_size;
2705
2706         if (INTEL_INFO(dev)->gen >= 4) {
2707                 intel_crtc->dspaddr_offset =
2708                         intel_gen4_compute_page_offset(dev_priv,
2709                                                        &x, &y, obj->tiling_mode,
2710                                                        pixel_size,
2711                                                        fb->pitches[0]);
2712                 linear_offset -= intel_crtc->dspaddr_offset;
2713         } else {
2714                 intel_crtc->dspaddr_offset = linear_offset;
2715         }
2716
2717         if (crtc->primary->state->rotation == BIT(DRM_ROTATE_180)) {
2718                 dspcntr |= DISPPLANE_ROTATE_180;
2719
2720                 x += (intel_crtc->config->pipe_src_w - 1);
2721                 y += (intel_crtc->config->pipe_src_h - 1);
2722
2723                 /* Finding the last pixel of the last line of the display
2724                 data and adding to linear_offset*/
2725                 linear_offset +=
2726                         (intel_crtc->config->pipe_src_h - 1) * fb->pitches[0] +
2727                         (intel_crtc->config->pipe_src_w - 1) * pixel_size;
2728         }
2729
2730         I915_WRITE(reg, dspcntr);
2731
2732         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2733         if (INTEL_INFO(dev)->gen >= 4) {
2734                 I915_WRITE(DSPSURF(plane),
2735                            i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2736                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2737                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2738         } else
2739                 I915_WRITE(DSPADDR(plane), i915_gem_obj_ggtt_offset(obj) + linear_offset);
2740         POSTING_READ(reg);
2741 }
2742
2743 static void ironlake_update_primary_plane(struct drm_crtc *crtc,
2744                                           struct drm_framebuffer *fb,
2745                                           int x, int y)
2746 {
2747         struct drm_device *dev = crtc->dev;
2748         struct drm_i915_private *dev_priv = dev->dev_private;
2749         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2750         struct drm_plane *primary = crtc->primary;
2751         bool visible = to_intel_plane_state(primary->state)->visible;
2752         struct drm_i915_gem_object *obj;
2753         int plane = intel_crtc->plane;
2754         unsigned long linear_offset;
2755         u32 dspcntr;
2756         u32 reg = DSPCNTR(plane);
2757         int pixel_size;
2758
2759         if (!visible || !fb) {
2760                 I915_WRITE(reg, 0);
2761                 I915_WRITE(DSPSURF(plane), 0);
2762                 POSTING_READ(reg);
2763                 return;
2764         }
2765
2766         obj = intel_fb_obj(fb);
2767         if (WARN_ON(obj == NULL))
2768                 return;
2769
2770         pixel_size = drm_format_plane_cpp(fb->pixel_format, 0);
2771
2772         dspcntr = DISPPLANE_GAMMA_ENABLE;
2773
2774         dspcntr |= DISPLAY_PLANE_ENABLE;
2775
2776         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
2777                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
2778
2779         switch (fb->pixel_format) {
2780         case DRM_FORMAT_C8:
2781                 dspcntr |= DISPPLANE_8BPP;
2782                 break;
2783         case DRM_FORMAT_RGB565:
2784                 dspcntr |= DISPPLANE_BGRX565;
2785                 break;
2786         case DRM_FORMAT_XRGB8888:
2787                 dspcntr |= DISPPLANE_BGRX888;
2788                 break;
2789         case DRM_FORMAT_XBGR8888:
2790                 dspcntr |= DISPPLANE_RGBX888;
2791                 break;
2792         case DRM_FORMAT_XRGB2101010:
2793                 dspcntr |= DISPPLANE_BGRX101010;
2794                 break;
2795         case DRM_FORMAT_XBGR2101010:
2796                 dspcntr |= DISPPLANE_RGBX101010;
2797                 break;
2798         default:
2799                 BUG();
2800         }
2801
2802         if (obj->tiling_mode != I915_TILING_NONE)
2803                 dspcntr |= DISPPLANE_TILED;
2804
2805         if (!IS_HASWELL(dev) && !IS_BROADWELL(dev))
2806                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2807
2808         linear_offset = y * fb->pitches[0] + x * pixel_size;
2809         intel_crtc->dspaddr_offset =
2810                 intel_gen4_compute_page_offset(dev_priv,
2811                                                &x, &y, obj->tiling_mode,
2812                                                pixel_size,
2813                                                fb->pitches[0]);
2814         linear_offset -= intel_crtc->dspaddr_offset;
2815         if (crtc->primary->state->rotation == BIT(DRM_ROTATE_180)) {
2816                 dspcntr |= DISPPLANE_ROTATE_180;
2817
2818                 if (!IS_HASWELL(dev) && !IS_BROADWELL(dev)) {
2819                         x += (intel_crtc->config->pipe_src_w - 1);
2820                         y += (intel_crtc->config->pipe_src_h - 1);
2821
2822                         /* Finding the last pixel of the last line of the display
2823                         data and adding to linear_offset*/
2824                         linear_offset +=
2825                                 (intel_crtc->config->pipe_src_h - 1) * fb->pitches[0] +
2826                                 (intel_crtc->config->pipe_src_w - 1) * pixel_size;
2827                 }
2828         }
2829
2830         I915_WRITE(reg, dspcntr);
2831
2832         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2833         I915_WRITE(DSPSURF(plane),
2834                    i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2835         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
2836                 I915_WRITE(DSPOFFSET(plane), (y << 16) | x);
2837         } else {
2838                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2839                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2840         }
2841         POSTING_READ(reg);
2842 }
2843
2844 u32 intel_fb_stride_alignment(struct drm_device *dev, uint64_t fb_modifier,
2845                               uint32_t pixel_format)
2846 {
2847         u32 bits_per_pixel = drm_format_plane_cpp(pixel_format, 0) * 8;
2848
2849         /*
2850          * The stride is either expressed as a multiple of 64 bytes
2851          * chunks for linear buffers or in number of tiles for tiled
2852          * buffers.
2853          */
2854         switch (fb_modifier) {
2855         case DRM_FORMAT_MOD_NONE:
2856                 return 64;
2857         case I915_FORMAT_MOD_X_TILED:
2858                 if (INTEL_INFO(dev)->gen == 2)
2859                         return 128;
2860                 return 512;
2861         case I915_FORMAT_MOD_Y_TILED:
2862                 /* No need to check for old gens and Y tiling since this is
2863                  * about the display engine and those will be blocked before
2864                  * we get here.
2865                  */
2866                 return 128;
2867         case I915_FORMAT_MOD_Yf_TILED:
2868                 if (bits_per_pixel == 8)
2869                         return 64;
2870                 else
2871                         return 128;
2872         default:
2873                 MISSING_CASE(fb_modifier);
2874                 return 64;
2875         }
2876 }
2877
2878 unsigned long intel_plane_obj_offset(struct intel_plane *intel_plane,
2879                                      struct drm_i915_gem_object *obj)
2880 {
2881         const struct i915_ggtt_view *view = &i915_ggtt_view_normal;
2882
2883         if (intel_rotation_90_or_270(intel_plane->base.state->rotation))
2884                 view = &i915_ggtt_view_rotated;
2885
2886         return i915_gem_obj_ggtt_offset_view(obj, view);
2887 }
2888
2889 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
2890 {
2891         struct drm_device *dev = intel_crtc->base.dev;
2892         struct drm_i915_private *dev_priv = dev->dev_private;
2893
2894         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
2895         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
2896         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
2897 }
2898
2899 /*
2900  * This function detaches (aka. unbinds) unused scalers in hardware
2901  */
2902 static void skl_detach_scalers(struct intel_crtc *intel_crtc)
2903 {
2904         struct intel_crtc_scaler_state *scaler_state;
2905         int i;
2906
2907         scaler_state = &intel_crtc->config->scaler_state;
2908
2909         /* loop through and disable scalers that aren't in use */
2910         for (i = 0; i < intel_crtc->num_scalers; i++) {
2911                 if (!scaler_state->scalers[i].in_use)
2912                         skl_detach_scaler(intel_crtc, i);
2913         }
2914 }
2915
2916 u32 skl_plane_ctl_format(uint32_t pixel_format)
2917 {
2918         switch (pixel_format) {
2919         case DRM_FORMAT_C8:
2920                 return PLANE_CTL_FORMAT_INDEXED;
2921         case DRM_FORMAT_RGB565:
2922                 return PLANE_CTL_FORMAT_RGB_565;
2923         case DRM_FORMAT_XBGR8888:
2924                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
2925         case DRM_FORMAT_XRGB8888:
2926                 return PLANE_CTL_FORMAT_XRGB_8888;
2927         /*
2928          * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
2929          * to be already pre-multiplied. We need to add a knob (or a different
2930          * DRM_FORMAT) for user-space to configure that.
2931          */
2932         case DRM_FORMAT_ABGR8888:
2933                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX |
2934                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
2935         case DRM_FORMAT_ARGB8888:
2936                 return PLANE_CTL_FORMAT_XRGB_8888 |
2937                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
2938         case DRM_FORMAT_XRGB2101010:
2939                 return PLANE_CTL_FORMAT_XRGB_2101010;
2940         case DRM_FORMAT_XBGR2101010:
2941                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
2942         case DRM_FORMAT_YUYV:
2943                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
2944         case DRM_FORMAT_YVYU:
2945                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
2946         case DRM_FORMAT_UYVY:
2947                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
2948         case DRM_FORMAT_VYUY:
2949                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
2950         default:
2951                 MISSING_CASE(pixel_format);
2952         }
2953
2954         return 0;
2955 }
2956
2957 u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
2958 {
2959         switch (fb_modifier) {
2960         case DRM_FORMAT_MOD_NONE:
2961                 break;
2962         case I915_FORMAT_MOD_X_TILED:
2963                 return PLANE_CTL_TILED_X;
2964         case I915_FORMAT_MOD_Y_TILED:
2965                 return PLANE_CTL_TILED_Y;
2966         case I915_FORMAT_MOD_Yf_TILED:
2967                 return PLANE_CTL_TILED_YF;
2968         default:
2969                 MISSING_CASE(fb_modifier);
2970         }
2971
2972         return 0;
2973 }
2974
2975 u32 skl_plane_ctl_rotation(unsigned int rotation)
2976 {
2977         switch (rotation) {
2978         case BIT(DRM_ROTATE_0):
2979                 break;
2980         /*
2981          * DRM_ROTATE_ is counter clockwise to stay compatible with Xrandr
2982          * while i915 HW rotation is clockwise, thats why this swapping.
2983          */
2984         case BIT(DRM_ROTATE_90):
2985                 return PLANE_CTL_ROTATE_270;
2986         case BIT(DRM_ROTATE_180):
2987                 return PLANE_CTL_ROTATE_180;
2988         case BIT(DRM_ROTATE_270):
2989                 return PLANE_CTL_ROTATE_90;
2990         default:
2991                 MISSING_CASE(rotation);
2992         }
2993
2994         return 0;
2995 }
2996
2997 static void skylake_update_primary_plane(struct drm_crtc *crtc,
2998                                          struct drm_framebuffer *fb,
2999                                          int x, int y)
3000 {
3001         struct drm_device *dev = crtc->dev;
3002         struct drm_i915_private *dev_priv = dev->dev_private;
3003         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3004         struct drm_plane *plane = crtc->primary;
3005         bool visible = to_intel_plane_state(plane->state)->visible;
3006         struct drm_i915_gem_object *obj;
3007         int pipe = intel_crtc->pipe;
3008         u32 plane_ctl, stride_div, stride;
3009         u32 tile_height, plane_offset, plane_size;
3010         unsigned int rotation;
3011         int x_offset, y_offset;
3012         unsigned long surf_addr;
3013         struct intel_crtc_state *crtc_state = intel_crtc->config;
3014         struct intel_plane_state *plane_state;
3015         int src_x = 0, src_y = 0, src_w = 0, src_h = 0;
3016         int dst_x = 0, dst_y = 0, dst_w = 0, dst_h = 0;
3017         int scaler_id = -1;
3018
3019         plane_state = to_intel_plane_state(plane->state);
3020
3021         if (!visible || !fb) {
3022                 I915_WRITE(PLANE_CTL(pipe, 0), 0);
3023                 I915_WRITE(PLANE_SURF(pipe, 0), 0);
3024                 POSTING_READ(PLANE_CTL(pipe, 0));
3025                 return;
3026         }
3027
3028         plane_ctl = PLANE_CTL_ENABLE |
3029                     PLANE_CTL_PIPE_GAMMA_ENABLE |
3030                     PLANE_CTL_PIPE_CSC_ENABLE;
3031
3032         plane_ctl |= skl_plane_ctl_format(fb->pixel_format);
3033         plane_ctl |= skl_plane_ctl_tiling(fb->modifier[0]);
3034         plane_ctl |= PLANE_CTL_PLANE_GAMMA_DISABLE;
3035
3036         rotation = plane->state->rotation;
3037         plane_ctl |= skl_plane_ctl_rotation(rotation);
3038
3039         obj = intel_fb_obj(fb);
3040         stride_div = intel_fb_stride_alignment(dev, fb->modifier[0],
3041                                                fb->pixel_format);
3042         surf_addr = intel_plane_obj_offset(to_intel_plane(plane), obj);
3043
3044         /*
3045          * FIXME: intel_plane_state->src, dst aren't set when transitional
3046          * update_plane helpers are called from legacy paths.
3047          * Once full atomic crtc is available, below check can be avoided.
3048          */
3049         if (drm_rect_width(&plane_state->src)) {
3050                 scaler_id = plane_state->scaler_id;
3051                 src_x = plane_state->src.x1 >> 16;
3052                 src_y = plane_state->src.y1 >> 16;
3053                 src_w = drm_rect_width(&plane_state->src) >> 16;
3054                 src_h = drm_rect_height(&plane_state->src) >> 16;
3055                 dst_x = plane_state->dst.x1;
3056                 dst_y = plane_state->dst.y1;
3057                 dst_w = drm_rect_width(&plane_state->dst);
3058                 dst_h = drm_rect_height(&plane_state->dst);
3059
3060                 WARN_ON(x != src_x || y != src_y);
3061         } else {
3062                 src_w = intel_crtc->config->pipe_src_w;
3063                 src_h = intel_crtc->config->pipe_src_h;
3064         }
3065
3066         if (intel_rotation_90_or_270(rotation)) {
3067                 /* stride = Surface height in tiles */
3068                 tile_height = intel_tile_height(dev, fb->pixel_format,
3069                                                 fb->modifier[0]);
3070                 stride = DIV_ROUND_UP(fb->height, tile_height);
3071                 x_offset = stride * tile_height - y - src_h;
3072                 y_offset = x;
3073                 plane_size = (src_w - 1) << 16 | (src_h - 1);
3074         } else {
3075                 stride = fb->pitches[0] / stride_div;
3076                 x_offset = x;
3077                 y_offset = y;
3078                 plane_size = (src_h - 1) << 16 | (src_w - 1);
3079         }
3080         plane_offset = y_offset << 16 | x_offset;
3081
3082         I915_WRITE(PLANE_CTL(pipe, 0), plane_ctl);
3083         I915_WRITE(PLANE_OFFSET(pipe, 0), plane_offset);
3084         I915_WRITE(PLANE_SIZE(pipe, 0), plane_size);
3085         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
3086
3087         if (scaler_id >= 0) {
3088                 uint32_t ps_ctrl = 0;
3089
3090                 WARN_ON(!dst_w || !dst_h);
3091                 ps_ctrl = PS_SCALER_EN | PS_PLANE_SEL(0) |
3092                         crtc_state->scaler_state.scalers[scaler_id].mode;
3093                 I915_WRITE(SKL_PS_CTRL(pipe, scaler_id), ps_ctrl);
3094                 I915_WRITE(SKL_PS_PWR_GATE(pipe, scaler_id), 0);
3095                 I915_WRITE(SKL_PS_WIN_POS(pipe, scaler_id), (dst_x << 16) | dst_y);
3096                 I915_WRITE(SKL_PS_WIN_SZ(pipe, scaler_id), (dst_w << 16) | dst_h);
3097                 I915_WRITE(PLANE_POS(pipe, 0), 0);
3098         } else {
3099                 I915_WRITE(PLANE_POS(pipe, 0), (dst_y << 16) | dst_x);
3100         }
3101
3102         I915_WRITE(PLANE_SURF(pipe, 0), surf_addr);
3103
3104         POSTING_READ(PLANE_SURF(pipe, 0));
3105 }
3106
3107 /* Assume fb object is pinned & idle & fenced and just update base pointers */
3108 static int
3109 intel_pipe_set_base_atomic(struct drm_crtc *crtc, struct drm_framebuffer *fb,
3110                            int x, int y, enum mode_set_atomic state)
3111 {
3112         struct drm_device *dev = crtc->dev;
3113         struct drm_i915_private *dev_priv = dev->dev_private;
3114
3115         if (dev_priv->fbc.disable_fbc)
3116                 dev_priv->fbc.disable_fbc(dev_priv);
3117
3118         dev_priv->display.update_primary_plane(crtc, fb, x, y);
3119
3120         return 0;
3121 }
3122
3123 static void intel_complete_page_flips(struct drm_device *dev)
3124 {
3125         struct drm_crtc *crtc;
3126
3127         for_each_crtc(dev, crtc) {
3128                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3129                 enum plane plane = intel_crtc->plane;
3130
3131                 intel_prepare_page_flip(dev, plane);
3132                 intel_finish_page_flip_plane(dev, plane);
3133         }
3134 }
3135
3136 static void intel_update_primary_planes(struct drm_device *dev)
3137 {
3138         struct drm_crtc *crtc;
3139
3140         for_each_crtc(dev, crtc) {
3141                 struct intel_plane *plane = to_intel_plane(crtc->primary);
3142                 struct intel_plane_state *plane_state;
3143
3144                 drm_modeset_lock_crtc(crtc, &plane->base);
3145
3146                 plane_state = to_intel_plane_state(plane->base.state);
3147
3148                 if (plane_state->base.fb)
3149                         plane->commit_plane(&plane->base, plane_state);
3150
3151                 drm_modeset_unlock_crtc(crtc);
3152         }
3153 }
3154
3155 void intel_prepare_reset(struct drm_device *dev)
3156 {
3157         /* no reset support for gen2 */
3158         if (IS_GEN2(dev))
3159                 return;
3160
3161         /* reset doesn't touch the display */
3162         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
3163                 return;
3164
3165         drm_modeset_lock_all(dev);
3166         /*
3167          * Disabling the crtcs gracefully seems nicer. Also the
3168          * g33 docs say we should at least disable all the planes.
3169          */
3170         intel_display_suspend(dev);
3171 }
3172
3173 void intel_finish_reset(struct drm_device *dev)
3174 {
3175         struct drm_i915_private *dev_priv = to_i915(dev);
3176
3177         /*
3178          * Flips in the rings will be nuked by the reset,
3179          * so complete all pending flips so that user space
3180          * will get its events and not get stuck.
3181          */
3182         intel_complete_page_flips(dev);
3183
3184         /* no reset support for gen2 */
3185         if (IS_GEN2(dev))
3186                 return;
3187
3188         /* reset doesn't touch the display */
3189         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev)) {
3190                 /*
3191                  * Flips in the rings have been nuked by the reset,
3192                  * so update the base address of all primary
3193                  * planes to the the last fb to make sure we're
3194                  * showing the correct fb after a reset.
3195                  *
3196                  * FIXME: Atomic will make this obsolete since we won't schedule
3197                  * CS-based flips (which might get lost in gpu resets) any more.
3198                  */
3199                 intel_update_primary_planes(dev);
3200                 return;
3201         }
3202
3203         /*
3204          * The display has been reset as well,
3205          * so need a full re-initialization.
3206          */
3207         intel_runtime_pm_disable_interrupts(dev_priv);
3208         intel_runtime_pm_enable_interrupts(dev_priv);
3209
3210         intel_modeset_init_hw(dev);
3211
3212         spin_lock_irq(&dev_priv->irq_lock);
3213         if (dev_priv->display.hpd_irq_setup)
3214                 dev_priv->display.hpd_irq_setup(dev);
3215         spin_unlock_irq(&dev_priv->irq_lock);
3216
3217         intel_display_resume(dev);
3218
3219         intel_hpd_init(dev_priv);
3220
3221         drm_modeset_unlock_all(dev);
3222 }
3223
3224 static void
3225 intel_finish_fb(struct drm_framebuffer *old_fb)
3226 {
3227         struct drm_i915_gem_object *obj = intel_fb_obj(old_fb);
3228         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
3229         bool was_interruptible = dev_priv->mm.interruptible;
3230         int ret;
3231
3232         /* Big Hammer, we also need to ensure that any pending
3233          * MI_WAIT_FOR_EVENT inside a user batch buffer on the
3234          * current scanout is retired before unpinning the old
3235          * framebuffer. Note that we rely on userspace rendering
3236          * into the buffer attached to the pipe they are waiting
3237          * on. If not, userspace generates a GPU hang with IPEHR
3238          * point to the MI_WAIT_FOR_EVENT.
3239          *
3240          * This should only fail upon a hung GPU, in which case we
3241          * can safely continue.
3242          */
3243         dev_priv->mm.interruptible = false;
3244         ret = i915_gem_object_wait_rendering(obj, true);
3245         dev_priv->mm.interruptible = was_interruptible;
3246
3247         WARN_ON(ret);
3248 }
3249
3250 static bool intel_crtc_has_pending_flip(struct drm_crtc *crtc)
3251 {
3252         struct drm_device *dev = crtc->dev;
3253         struct drm_i915_private *dev_priv = dev->dev_private;
3254         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3255         bool pending;
3256
3257         if (i915_reset_in_progress(&dev_priv->gpu_error) ||
3258             intel_crtc->reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
3259                 return false;
3260
3261         spin_lock_irq(&dev->event_lock);
3262         pending = to_intel_crtc(crtc)->unpin_work != NULL;
3263         spin_unlock_irq(&dev->event_lock);
3264
3265         return pending;
3266 }
3267
3268 static void intel_update_pipe_size(struct intel_crtc *crtc)
3269 {
3270         struct drm_device *dev = crtc->base.dev;
3271         struct drm_i915_private *dev_priv = dev->dev_private;
3272         const struct drm_display_mode *adjusted_mode;
3273
3274         if (!i915.fastboot)
3275                 return;
3276
3277         /*
3278          * Update pipe size and adjust fitter if needed: the reason for this is
3279          * that in compute_mode_changes we check the native mode (not the pfit
3280          * mode) to see if we can flip rather than do a full mode set. In the
3281          * fastboot case, we'll flip, but if we don't update the pipesrc and
3282          * pfit state, we'll end up with a big fb scanned out into the wrong
3283          * sized surface.
3284          *
3285          * To fix this properly, we need to hoist the checks up into
3286          * compute_mode_changes (or above), check the actual pfit state and
3287          * whether the platform allows pfit disable with pipe active, and only
3288          * then update the pipesrc and pfit state, even on the flip path.
3289          */
3290
3291         adjusted_mode = &crtc->config->base.adjusted_mode;
3292
3293         I915_WRITE(PIPESRC(crtc->pipe),
3294                    ((adjusted_mode->crtc_hdisplay - 1) << 16) |
3295                    (adjusted_mode->crtc_vdisplay - 1));
3296         if (!crtc->config->pch_pfit.enabled &&
3297             (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS) ||
3298              intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP))) {
3299                 I915_WRITE(PF_CTL(crtc->pipe), 0);
3300                 I915_WRITE(PF_WIN_POS(crtc->pipe), 0);
3301                 I915_WRITE(PF_WIN_SZ(crtc->pipe), 0);
3302         }
3303         crtc->config->pipe_src_w = adjusted_mode->crtc_hdisplay;
3304         crtc->config->pipe_src_h = adjusted_mode->crtc_vdisplay;
3305 }
3306
3307 static void intel_fdi_normal_train(struct drm_crtc *crtc)
3308 {
3309         struct drm_device *dev = crtc->dev;
3310         struct drm_i915_private *dev_priv = dev->dev_private;
3311         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3312         int pipe = intel_crtc->pipe;
3313         u32 reg, temp;
3314
3315         /* enable normal train */
3316         reg = FDI_TX_CTL(pipe);
3317         temp = I915_READ(reg);
3318         if (IS_IVYBRIDGE(dev)) {
3319                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3320                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3321         } else {
3322                 temp &= ~FDI_LINK_TRAIN_NONE;
3323                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3324         }
3325         I915_WRITE(reg, temp);
3326
3327         reg = FDI_RX_CTL(pipe);
3328         temp = I915_READ(reg);
3329         if (HAS_PCH_CPT(dev)) {
3330                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3331                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3332         } else {
3333                 temp &= ~FDI_LINK_TRAIN_NONE;
3334                 temp |= FDI_LINK_TRAIN_NONE;
3335         }
3336         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3337
3338         /* wait one idle pattern time */
3339         POSTING_READ(reg);
3340         udelay(1000);
3341
3342         /* IVB wants error correction enabled */
3343         if (IS_IVYBRIDGE(dev))
3344                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3345                            FDI_FE_ERRC_ENABLE);
3346 }
3347
3348 /* The FDI link training functions for ILK/Ibexpeak. */
3349 static void ironlake_fdi_link_train(struct drm_crtc *crtc)
3350 {
3351         struct drm_device *dev = crtc->dev;
3352         struct drm_i915_private *dev_priv = dev->dev_private;
3353         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3354         int pipe = intel_crtc->pipe;
3355         u32 reg, temp, tries;
3356
3357         /* FDI needs bits from pipe first */
3358         assert_pipe_enabled(dev_priv, pipe);
3359
3360         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3361            for train result */
3362         reg = FDI_RX_IMR(pipe);
3363         temp = I915_READ(reg);
3364         temp &= ~FDI_RX_SYMBOL_LOCK;
3365         temp &= ~FDI_RX_BIT_LOCK;
3366         I915_WRITE(reg, temp);
3367         I915_READ(reg);
3368         udelay(150);
3369
3370         /* enable CPU FDI TX and PCH FDI RX */
3371         reg = FDI_TX_CTL(pipe);
3372         temp = I915_READ(reg);
3373         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3374         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3375         temp &= ~FDI_LINK_TRAIN_NONE;
3376         temp |= FDI_LINK_TRAIN_PATTERN_1;
3377         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3378
3379         reg = FDI_RX_CTL(pipe);
3380         temp = I915_READ(reg);
3381         temp &= ~FDI_LINK_TRAIN_NONE;
3382         temp |= FDI_LINK_TRAIN_PATTERN_1;
3383         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3384
3385         POSTING_READ(reg);
3386         udelay(150);
3387
3388         /* Ironlake workaround, enable clock pointer after FDI enable*/
3389         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3390         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3391                    FDI_RX_PHASE_SYNC_POINTER_EN);
3392
3393         reg = FDI_RX_IIR(pipe);
3394         for (tries = 0; tries < 5; tries++) {
3395                 temp = I915_READ(reg);
3396                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3397
3398                 if ((temp & FDI_RX_BIT_LOCK)) {
3399                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3400                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3401                         break;
3402                 }
3403         }
3404         if (tries == 5)
3405                 DRM_ERROR("FDI train 1 fail!\n");
3406
3407         /* Train 2 */
3408         reg = FDI_TX_CTL(pipe);
3409         temp = I915_READ(reg);
3410         temp &= ~FDI_LINK_TRAIN_NONE;
3411         temp |= FDI_LINK_TRAIN_PATTERN_2;
3412         I915_WRITE(reg, temp);
3413
3414         reg = FDI_RX_CTL(pipe);
3415         temp = I915_READ(reg);
3416         temp &= ~FDI_LINK_TRAIN_NONE;
3417         temp |= FDI_LINK_TRAIN_PATTERN_2;
3418         I915_WRITE(reg, temp);
3419
3420         POSTING_READ(reg);
3421         udelay(150);
3422
3423         reg = FDI_RX_IIR(pipe);
3424         for (tries = 0; tries < 5; tries++) {
3425                 temp = I915_READ(reg);
3426                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3427
3428                 if (temp & FDI_RX_SYMBOL_LOCK) {
3429                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3430                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3431                         break;
3432                 }
3433         }
3434         if (tries == 5)
3435                 DRM_ERROR("FDI train 2 fail!\n");
3436
3437         DRM_DEBUG_KMS("FDI train done\n");
3438
3439 }
3440
3441 static const int snb_b_fdi_train_param[] = {
3442         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3443         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3444         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3445         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3446 };
3447
3448 /* The FDI link training functions for SNB/Cougarpoint. */
3449 static void gen6_fdi_link_train(struct drm_crtc *crtc)
3450 {
3451         struct drm_device *dev = crtc->dev;
3452         struct drm_i915_private *dev_priv = dev->dev_private;
3453         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3454         int pipe = intel_crtc->pipe;
3455         u32 reg, temp, i, retry;
3456
3457         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3458            for train result */
3459         reg = FDI_RX_IMR(pipe);
3460         temp = I915_READ(reg);
3461         temp &= ~FDI_RX_SYMBOL_LOCK;
3462         temp &= ~FDI_RX_BIT_LOCK;
3463         I915_WRITE(reg, temp);
3464
3465         POSTING_READ(reg);
3466         udelay(150);
3467
3468         /* enable CPU FDI TX and PCH FDI RX */
3469         reg = FDI_TX_CTL(pipe);
3470         temp = I915_READ(reg);
3471         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3472         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3473         temp &= ~FDI_LINK_TRAIN_NONE;
3474         temp |= FDI_LINK_TRAIN_PATTERN_1;
3475         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3476         /* SNB-B */
3477         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3478         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3479
3480         I915_WRITE(FDI_RX_MISC(pipe),
3481                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3482
3483         reg = FDI_RX_CTL(pipe);
3484         temp = I915_READ(reg);
3485         if (HAS_PCH_CPT(dev)) {
3486                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3487                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3488         } else {
3489                 temp &= ~FDI_LINK_TRAIN_NONE;
3490                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3491         }
3492         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3493
3494         POSTING_READ(reg);
3495         udelay(150);
3496
3497         for (i = 0; i < 4; i++) {
3498                 reg = FDI_TX_CTL(pipe);
3499                 temp = I915_READ(reg);
3500                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3501                 temp |= snb_b_fdi_train_param[i];
3502                 I915_WRITE(reg, temp);
3503
3504                 POSTING_READ(reg);
3505                 udelay(500);
3506
3507                 for (retry = 0; retry < 5; retry++) {
3508                         reg = FDI_RX_IIR(pipe);
3509                         temp = I915_READ(reg);
3510                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3511                         if (temp & FDI_RX_BIT_LOCK) {
3512                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3513                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
3514                                 break;
3515                         }
3516                         udelay(50);
3517                 }
3518                 if (retry < 5)
3519                         break;
3520         }
3521         if (i == 4)
3522                 DRM_ERROR("FDI train 1 fail!\n");
3523
3524         /* Train 2 */
3525         reg = FDI_TX_CTL(pipe);
3526         temp = I915_READ(reg);
3527         temp &= ~FDI_LINK_TRAIN_NONE;
3528         temp |= FDI_LINK_TRAIN_PATTERN_2;
3529         if (IS_GEN6(dev)) {
3530                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3531                 /* SNB-B */
3532                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3533         }
3534         I915_WRITE(reg, temp);
3535
3536         reg = FDI_RX_CTL(pipe);
3537         temp = I915_READ(reg);
3538         if (HAS_PCH_CPT(dev)) {
3539                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3540                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3541         } else {
3542                 temp &= ~FDI_LINK_TRAIN_NONE;
3543                 temp |= FDI_LINK_TRAIN_PATTERN_2;
3544         }
3545         I915_WRITE(reg, temp);
3546
3547         POSTING_READ(reg);
3548         udelay(150);
3549
3550         for (i = 0; i < 4; i++) {
3551                 reg = FDI_TX_CTL(pipe);
3552                 temp = I915_READ(reg);
3553                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3554                 temp |= snb_b_fdi_train_param[i];
3555                 I915_WRITE(reg, temp);
3556
3557                 POSTING_READ(reg);
3558                 udelay(500);
3559
3560                 for (retry = 0; retry < 5; retry++) {
3561                         reg = FDI_RX_IIR(pipe);
3562                         temp = I915_READ(reg);
3563                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3564                         if (temp & FDI_RX_SYMBOL_LOCK) {
3565                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3566                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
3567                                 break;
3568                         }
3569                         udelay(50);
3570                 }
3571                 if (retry < 5)
3572                         break;
3573         }
3574         if (i == 4)
3575                 DRM_ERROR("FDI train 2 fail!\n");
3576
3577         DRM_DEBUG_KMS("FDI train done.\n");
3578 }
3579
3580 /* Manual link training for Ivy Bridge A0 parts */
3581 static void ivb_manual_fdi_link_train(struct drm_crtc *crtc)
3582 {
3583         struct drm_device *dev = crtc->dev;
3584         struct drm_i915_private *dev_priv = dev->dev_private;
3585         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3586         int pipe = intel_crtc->pipe;
3587         u32 reg, temp, i, j;
3588
3589         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3590            for train result */
3591         reg = FDI_RX_IMR(pipe);
3592         temp = I915_READ(reg);
3593         temp &= ~FDI_RX_SYMBOL_LOCK;
3594         temp &= ~FDI_RX_BIT_LOCK;
3595         I915_WRITE(reg, temp);
3596
3597         POSTING_READ(reg);
3598         udelay(150);
3599
3600         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
3601                       I915_READ(FDI_RX_IIR(pipe)));
3602
3603         /* Try each vswing and preemphasis setting twice before moving on */
3604         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
3605                 /* disable first in case we need to retry */
3606                 reg = FDI_TX_CTL(pipe);
3607                 temp = I915_READ(reg);
3608                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
3609                 temp &= ~FDI_TX_ENABLE;
3610                 I915_WRITE(reg, temp);
3611
3612                 reg = FDI_RX_CTL(pipe);
3613                 temp = I915_READ(reg);
3614                 temp &= ~FDI_LINK_TRAIN_AUTO;
3615                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3616                 temp &= ~FDI_RX_ENABLE;
3617                 I915_WRITE(reg, temp);
3618
3619                 /* enable CPU FDI TX and PCH FDI RX */
3620                 reg = FDI_TX_CTL(pipe);
3621                 temp = I915_READ(reg);
3622                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
3623                 temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3624                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
3625                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3626                 temp |= snb_b_fdi_train_param[j/2];
3627                 temp |= FDI_COMPOSITE_SYNC;
3628                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
3629
3630                 I915_WRITE(FDI_RX_MISC(pipe),
3631                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3632
3633                 reg = FDI_RX_CTL(pipe);
3634                 temp = I915_READ(reg);
3635                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3636                 temp |= FDI_COMPOSITE_SYNC;
3637                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
3638
3639                 POSTING_READ(reg);
3640                 udelay(1); /* should be 0.5us */
3641
3642                 for (i = 0; i < 4; i++) {
3643                         reg = FDI_RX_IIR(pipe);
3644                         temp = I915_READ(reg);
3645                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3646
3647                         if (temp & FDI_RX_BIT_LOCK ||
3648                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
3649                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3650                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
3651                                               i);
3652                                 break;
3653                         }
3654                         udelay(1); /* should be 0.5us */
3655                 }
3656                 if (i == 4) {
3657                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
3658                         continue;
3659                 }
3660
3661                 /* Train 2 */
3662                 reg = FDI_TX_CTL(pipe);
3663                 temp = I915_READ(reg);
3664                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3665                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
3666                 I915_WRITE(reg, temp);
3667
3668                 reg = FDI_RX_CTL(pipe);
3669                 temp = I915_READ(reg);
3670                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3671                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3672                 I915_WRITE(reg, temp);
3673
3674                 POSTING_READ(reg);
3675                 udelay(2); /* should be 1.5us */
3676
3677                 for (i = 0; i < 4; i++) {
3678                         reg = FDI_RX_IIR(pipe);
3679                         temp = I915_READ(reg);
3680                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3681
3682                         if (temp & FDI_RX_SYMBOL_LOCK ||
3683                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
3684                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3685                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
3686                                               i);
3687                                 goto train_done;
3688                         }
3689                         udelay(2); /* should be 1.5us */
3690                 }
3691                 if (i == 4)
3692                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
3693         }
3694
3695 train_done:
3696         DRM_DEBUG_KMS("FDI train done.\n");
3697 }
3698
3699 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
3700 {
3701         struct drm_device *dev = intel_crtc->base.dev;
3702         struct drm_i915_private *dev_priv = dev->dev_private;
3703         int pipe = intel_crtc->pipe;
3704         u32 reg, temp;
3705
3706
3707         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
3708         reg = FDI_RX_CTL(pipe);
3709         temp = I915_READ(reg);
3710         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
3711         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3712         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3713         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
3714
3715         POSTING_READ(reg);
3716         udelay(200);
3717
3718         /* Switch from Rawclk to PCDclk */
3719         temp = I915_READ(reg);
3720         I915_WRITE(reg, temp | FDI_PCDCLK);
3721
3722         POSTING_READ(reg);
3723         udelay(200);
3724
3725         /* Enable CPU FDI TX PLL, always on for Ironlake */
3726         reg = FDI_TX_CTL(pipe);
3727         temp = I915_READ(reg);
3728         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
3729                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
3730
3731                 POSTING_READ(reg);
3732                 udelay(100);
3733         }
3734 }
3735
3736 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
3737 {
3738         struct drm_device *dev = intel_crtc->base.dev;
3739         struct drm_i915_private *dev_priv = dev->dev_private;
3740         int pipe = intel_crtc->pipe;
3741         u32 reg, temp;
3742
3743         /* Switch from PCDclk to Rawclk */
3744         reg = FDI_RX_CTL(pipe);
3745         temp = I915_READ(reg);
3746         I915_WRITE(reg, temp & ~FDI_PCDCLK);
3747
3748         /* Disable CPU FDI TX PLL */
3749         reg = FDI_TX_CTL(pipe);
3750         temp = I915_READ(reg);
3751         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
3752
3753         POSTING_READ(reg);
3754         udelay(100);
3755
3756         reg = FDI_RX_CTL(pipe);
3757         temp = I915_READ(reg);
3758         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
3759
3760         /* Wait for the clocks to turn off. */
3761         POSTING_READ(reg);
3762         udelay(100);
3763 }
3764
3765 static void ironlake_fdi_disable(struct drm_crtc *crtc)
3766 {
3767         struct drm_device *dev = crtc->dev;
3768         struct drm_i915_private *dev_priv = dev->dev_private;
3769         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3770         int pipe = intel_crtc->pipe;
3771         u32 reg, temp;
3772
3773         /* disable CPU FDI tx and PCH FDI rx */
3774         reg = FDI_TX_CTL(pipe);
3775         temp = I915_READ(reg);
3776         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
3777         POSTING_READ(reg);
3778
3779         reg = FDI_RX_CTL(pipe);
3780         temp = I915_READ(reg);
3781         temp &= ~(0x7 << 16);
3782         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3783         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
3784
3785         POSTING_READ(reg);
3786         udelay(100);
3787
3788         /* Ironlake workaround, disable clock pointer after downing FDI */
3789         if (HAS_PCH_IBX(dev))
3790                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3791
3792         /* still set train pattern 1 */
3793         reg = FDI_TX_CTL(pipe);
3794         temp = I915_READ(reg);
3795         temp &= ~FDI_LINK_TRAIN_NONE;
3796         temp |= FDI_LINK_TRAIN_PATTERN_1;
3797         I915_WRITE(reg, temp);
3798
3799         reg = FDI_RX_CTL(pipe);
3800         temp = I915_READ(reg);
3801         if (HAS_PCH_CPT(dev)) {
3802                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3803                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3804         } else {
3805                 temp &= ~FDI_LINK_TRAIN_NONE;
3806                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3807         }
3808         /* BPC in FDI rx is consistent with that in PIPECONF */
3809         temp &= ~(0x07 << 16);
3810         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3811         I915_WRITE(reg, temp);
3812
3813         POSTING_READ(reg);
3814         udelay(100);
3815 }
3816
3817 bool intel_has_pending_fb_unpin(struct drm_device *dev)
3818 {
3819         struct intel_crtc *crtc;
3820
3821         /* Note that we don't need to be called with mode_config.lock here
3822          * as our list of CRTC objects is static for the lifetime of the
3823          * device and so cannot disappear as we iterate. Similarly, we can
3824          * happily treat the predicates as racy, atomic checks as userspace
3825          * cannot claim and pin a new fb without at least acquring the
3826          * struct_mutex and so serialising with us.
3827          */
3828         for_each_intel_crtc(dev, crtc) {
3829                 if (atomic_read(&crtc->unpin_work_count) == 0)
3830                         continue;
3831
3832                 if (crtc->unpin_work)
3833                         intel_wait_for_vblank(dev, crtc->pipe);
3834
3835                 return true;
3836         }
3837
3838         return false;
3839 }
3840
3841 static void page_flip_completed(struct intel_crtc *intel_crtc)
3842 {
3843         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
3844         struct intel_unpin_work *work = intel_crtc->unpin_work;
3845
3846         /* ensure that the unpin work is consistent wrt ->pending. */
3847         smp_rmb();
3848         intel_crtc->unpin_work = NULL;
3849
3850         if (work->event)
3851                 drm_send_vblank_event(intel_crtc->base.dev,
3852                                       intel_crtc->pipe,
3853                                       work->event);
3854
3855         drm_crtc_vblank_put(&intel_crtc->base);
3856
3857         wake_up_all(&dev_priv->pending_flip_queue);
3858         queue_work(dev_priv->wq, &work->work);
3859
3860         trace_i915_flip_complete(intel_crtc->plane,
3861                                  work->pending_flip_obj);
3862 }
3863
3864 void intel_crtc_wait_for_pending_flips(struct drm_crtc *crtc)
3865 {
3866         struct drm_device *dev = crtc->dev;
3867         struct drm_i915_private *dev_priv = dev->dev_private;
3868
3869         WARN_ON(waitqueue_active(&dev_priv->pending_flip_queue));
3870         if (WARN_ON(wait_event_timeout(dev_priv->pending_flip_queue,
3871                                        !intel_crtc_has_pending_flip(crtc),
3872                                        60*HZ) == 0)) {
3873                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3874
3875                 spin_lock_irq(&dev->event_lock);
3876                 if (intel_crtc->unpin_work) {
3877                         WARN_ONCE(1, "Removing stuck page flip\n");
3878                         page_flip_completed(intel_crtc);
3879                 }
3880                 spin_unlock_irq(&dev->event_lock);
3881         }
3882
3883         if (crtc->primary->fb) {
3884                 mutex_lock(&dev->struct_mutex);
3885                 intel_finish_fb(crtc->primary->fb);
3886                 mutex_unlock(&dev->struct_mutex);
3887         }
3888 }
3889
3890 /* Program iCLKIP clock to the desired frequency */
3891 static void lpt_program_iclkip(struct drm_crtc *crtc)
3892 {
3893         struct drm_device *dev = crtc->dev;
3894         struct drm_i915_private *dev_priv = dev->dev_private;
3895         int clock = to_intel_crtc(crtc)->config->base.adjusted_mode.crtc_clock;
3896         u32 divsel, phaseinc, auxdiv, phasedir = 0;
3897         u32 temp;
3898
3899         mutex_lock(&dev_priv->sb_lock);
3900
3901         /* It is necessary to ungate the pixclk gate prior to programming
3902          * the divisors, and gate it back when it is done.
3903          */
3904         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
3905
3906         /* Disable SSCCTL */
3907         intel_sbi_write(dev_priv, SBI_SSCCTL6,
3908                         intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK) |
3909                                 SBI_SSCCTL_DISABLE,
3910                         SBI_ICLK);
3911
3912         /* 20MHz is a corner case which is out of range for the 7-bit divisor */
3913         if (clock == 20000) {
3914                 auxdiv = 1;
3915                 divsel = 0x41;
3916                 phaseinc = 0x20;
3917         } else {
3918                 /* The iCLK virtual clock root frequency is in MHz,
3919                  * but the adjusted_mode->crtc_clock in in KHz. To get the
3920                  * divisors, it is necessary to divide one by another, so we
3921                  * convert the virtual clock precision to KHz here for higher
3922                  * precision.
3923                  */
3924                 u32 iclk_virtual_root_freq = 172800 * 1000;
3925                 u32 iclk_pi_range = 64;
3926                 u32 desired_divisor, msb_divisor_value, pi_value;
3927
3928                 desired_divisor = (iclk_virtual_root_freq / clock);
3929                 msb_divisor_value = desired_divisor / iclk_pi_range;
3930                 pi_value = desired_divisor % iclk_pi_range;
3931
3932                 auxdiv = 0;
3933                 divsel = msb_divisor_value - 2;
3934                 phaseinc = pi_value;
3935         }
3936
3937         /* This should not happen with any sane values */
3938         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
3939                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
3940         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
3941                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
3942
3943         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
3944                         clock,
3945                         auxdiv,
3946                         divsel,
3947                         phasedir,
3948                         phaseinc);
3949
3950         /* Program SSCDIVINTPHASE6 */
3951         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
3952         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
3953         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
3954         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
3955         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
3956         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
3957         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
3958         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
3959
3960         /* Program SSCAUXDIV */
3961         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
3962         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
3963         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
3964         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
3965
3966         /* Enable modulator and associated divider */
3967         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3968         temp &= ~SBI_SSCCTL_DISABLE;
3969         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
3970
3971         /* Wait for initialization time */
3972         udelay(24);
3973
3974         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
3975
3976         mutex_unlock(&dev_priv->sb_lock);
3977 }
3978
3979 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
3980                                                 enum pipe pch_transcoder)
3981 {
3982         struct drm_device *dev = crtc->base.dev;
3983         struct drm_i915_private *dev_priv = dev->dev_private;
3984         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
3985
3986         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
3987                    I915_READ(HTOTAL(cpu_transcoder)));
3988         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
3989                    I915_READ(HBLANK(cpu_transcoder)));
3990         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
3991                    I915_READ(HSYNC(cpu_transcoder)));
3992
3993         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
3994                    I915_READ(VTOTAL(cpu_transcoder)));
3995         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
3996                    I915_READ(VBLANK(cpu_transcoder)));
3997         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
3998                    I915_READ(VSYNC(cpu_transcoder)));
3999         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4000                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4001 }
4002
4003 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4004 {
4005         struct drm_i915_private *dev_priv = dev->dev_private;
4006         uint32_t temp;
4007
4008         temp = I915_READ(SOUTH_CHICKEN1);
4009         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4010                 return;
4011
4012         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4013         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4014
4015         temp &= ~FDI_BC_BIFURCATION_SELECT;
4016         if (enable)
4017                 temp |= FDI_BC_BIFURCATION_SELECT;
4018
4019         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4020         I915_WRITE(SOUTH_CHICKEN1, temp);
4021         POSTING_READ(SOUTH_CHICKEN1);
4022 }
4023
4024 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4025 {
4026         struct drm_device *dev = intel_crtc->base.dev;
4027
4028         switch (intel_crtc->pipe) {
4029         case PIPE_A:
4030                 break;
4031         case PIPE_B:
4032                 if (intel_crtc->config->fdi_lanes > 2)
4033                         cpt_set_fdi_bc_bifurcation(dev, false);
4034                 else
4035                         cpt_set_fdi_bc_bifurcation(dev, true);
4036
4037                 break;
4038         case PIPE_C:
4039                 cpt_set_fdi_bc_bifurcation(dev, true);
4040
4041                 break;
4042         default:
4043                 BUG();
4044         }
4045 }
4046
4047 /*
4048  * Enable PCH resources required for PCH ports:
4049  *   - PCH PLLs
4050  *   - FDI training & RX/TX
4051  *   - update transcoder timings
4052  *   - DP transcoding bits
4053  *   - transcoder
4054  */
4055 static void ironlake_pch_enable(struct drm_crtc *crtc)
4056 {
4057         struct drm_device *dev = crtc->dev;
4058         struct drm_i915_private *dev_priv = dev->dev_private;
4059         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4060         int pipe = intel_crtc->pipe;
4061         u32 reg, temp;
4062
4063         assert_pch_transcoder_disabled(dev_priv, pipe);
4064
4065         if (IS_IVYBRIDGE(dev))
4066                 ivybridge_update_fdi_bc_bifurcation(intel_crtc);
4067
4068         /* Write the TU size bits before fdi link training, so that error
4069          * detection works. */
4070         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4071                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4072
4073         /* For PCH output, training FDI link */
4074         dev_priv->display.fdi_link_train(crtc);
4075
4076         /* We need to program the right clock selection before writing the pixel
4077          * mutliplier into the DPLL. */
4078         if (HAS_PCH_CPT(dev)) {
4079                 u32 sel;
4080
4081                 temp = I915_READ(PCH_DPLL_SEL);
4082                 temp |= TRANS_DPLL_ENABLE(pipe);
4083                 sel = TRANS_DPLLB_SEL(pipe);
4084                 if (intel_crtc->config->shared_dpll == DPLL_ID_PCH_PLL_B)
4085                         temp |= sel;
4086                 else
4087                         temp &= ~sel;
4088                 I915_WRITE(PCH_DPLL_SEL, temp);
4089         }
4090
4091         /* XXX: pch pll's can be enabled any time before we enable the PCH
4092          * transcoder, and we actually should do this to not upset any PCH
4093          * transcoder that already use the clock when we share it.
4094          *
4095          * Note that enable_shared_dpll tries to do the right thing, but
4096          * get_shared_dpll unconditionally resets the pll - we need that to have
4097          * the right LVDS enable sequence. */
4098         intel_enable_shared_dpll(intel_crtc);
4099
4100         /* set transcoder timing, panel must allow it */
4101         assert_panel_unlocked(dev_priv, pipe);
4102         ironlake_pch_transcoder_set_timings(intel_crtc, pipe);
4103
4104         intel_fdi_normal_train(crtc);
4105
4106         /* For PCH DP, enable TRANS_DP_CTL */
4107         if (HAS_PCH_CPT(dev) && intel_crtc->config->has_dp_encoder) {
4108                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4109                 reg = TRANS_DP_CTL(pipe);
4110                 temp = I915_READ(reg);
4111                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4112                           TRANS_DP_SYNC_MASK |
4113                           TRANS_DP_BPC_MASK);
4114                 temp |= TRANS_DP_OUTPUT_ENABLE;
4115                 temp |= bpc << 9; /* same format but at 11:9 */
4116
4117                 if (crtc->mode.flags & DRM_MODE_FLAG_PHSYNC)
4118                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4119                 if (crtc->mode.flags & DRM_MODE_FLAG_PVSYNC)
4120                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4121
4122                 switch (intel_trans_dp_port_sel(crtc)) {
4123                 case PCH_DP_B:
4124                         temp |= TRANS_DP_PORT_SEL_B;
4125                         break;
4126                 case PCH_DP_C:
4127                         temp |= TRANS_DP_PORT_SEL_C;
4128                         break;
4129                 case PCH_DP_D:
4130                         temp |= TRANS_DP_PORT_SEL_D;
4131                         break;
4132                 default:
4133                         BUG();
4134                 }
4135
4136                 I915_WRITE(reg, temp);
4137         }
4138
4139         ironlake_enable_pch_transcoder(dev_priv, pipe);
4140 }
4141
4142 static void lpt_pch_enable(struct drm_crtc *crtc)
4143 {
4144         struct drm_device *dev = crtc->dev;
4145         struct drm_i915_private *dev_priv = dev->dev_private;
4146         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4147         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4148
4149         assert_pch_transcoder_disabled(dev_priv, TRANSCODER_A);
4150
4151         lpt_program_iclkip(crtc);
4152
4153         /* Set transcoder timing. */
4154         ironlake_pch_transcoder_set_timings(intel_crtc, PIPE_A);
4155
4156         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4157 }
4158
4159 struct intel_shared_dpll *intel_get_shared_dpll(struct intel_crtc *crtc,
4160                                                 struct intel_crtc_state *crtc_state)
4161 {
4162         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
4163         struct intel_shared_dpll *pll;
4164         struct intel_shared_dpll_config *shared_dpll;
4165         enum intel_dpll_id i;
4166
4167         shared_dpll = intel_atomic_get_shared_dpll_state(crtc_state->base.state);
4168
4169         if (HAS_PCH_IBX(dev_priv->dev)) {
4170                 /* Ironlake PCH has a fixed PLL->PCH pipe mapping. */
4171                 i = (enum intel_dpll_id) crtc->pipe;
4172                 pll = &dev_priv->shared_dplls[i];
4173
4174                 DRM_DEBUG_KMS("CRTC:%d using pre-allocated %s\n",
4175                               crtc->base.base.id, pll->name);
4176
4177                 WARN_ON(shared_dpll[i].crtc_mask);
4178
4179                 goto found;
4180         }
4181
4182         if (IS_BROXTON(dev_priv->dev)) {
4183                 /* PLL is attached to port in bxt */
4184                 struct intel_encoder *encoder;
4185                 struct intel_digital_port *intel_dig_port;
4186
4187                 encoder = intel_ddi_get_crtc_new_encoder(crtc_state);
4188                 if (WARN_ON(!encoder))
4189                         return NULL;
4190
4191                 intel_dig_port = enc_to_dig_port(&encoder->base);
4192                 /* 1:1 mapping between ports and PLLs */
4193                 i = (enum intel_dpll_id)intel_dig_port->port;
4194                 pll = &dev_priv->shared_dplls[i];
4195                 DRM_DEBUG_KMS("CRTC:%d using pre-allocated %s\n",
4196                         crtc->base.base.id, pll->name);
4197                 WARN_ON(shared_dpll[i].crtc_mask);
4198
4199                 goto found;
4200         }
4201
4202         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4203                 pll = &dev_priv->shared_dplls[i];
4204
4205                 /* Only want to check enabled timings first */
4206                 if (shared_dpll[i].crtc_mask == 0)
4207                         continue;
4208
4209                 if (memcmp(&crtc_state->dpll_hw_state,
4210                            &shared_dpll[i].hw_state,
4211                            sizeof(crtc_state->dpll_hw_state)) == 0) {
4212                         DRM_DEBUG_KMS("CRTC:%d sharing existing %s (crtc mask 0x%08x, ative %d)\n",
4213                                       crtc->base.base.id, pll->name,
4214                                       shared_dpll[i].crtc_mask,
4215                                       pll->active);
4216                         goto found;
4217                 }
4218         }
4219
4220         /* Ok no matching timings, maybe there's a free one? */
4221         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4222                 pll = &dev_priv->shared_dplls[i];
4223                 if (shared_dpll[i].crtc_mask == 0) {
4224                         DRM_DEBUG_KMS("CRTC:%d allocated %s\n",
4225                                       crtc->base.base.id, pll->name);
4226                         goto found;
4227                 }
4228         }
4229
4230         return NULL;
4231
4232 found:
4233         if (shared_dpll[i].crtc_mask == 0)
4234                 shared_dpll[i].hw_state =
4235                         crtc_state->dpll_hw_state;
4236
4237         crtc_state->shared_dpll = i;
4238         DRM_DEBUG_DRIVER("using %s for pipe %c\n", pll->name,
4239                          pipe_name(crtc->pipe));
4240
4241         shared_dpll[i].crtc_mask |= 1 << crtc->pipe;
4242
4243         return pll;
4244 }
4245
4246 static void intel_shared_dpll_commit(struct drm_atomic_state *state)
4247 {
4248         struct drm_i915_private *dev_priv = to_i915(state->dev);
4249         struct intel_shared_dpll_config *shared_dpll;
4250         struct intel_shared_dpll *pll;
4251         enum intel_dpll_id i;
4252
4253         if (!to_intel_atomic_state(state)->dpll_set)
4254                 return;
4255
4256         shared_dpll = to_intel_atomic_state(state)->shared_dpll;
4257         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4258                 pll = &dev_priv->shared_dplls[i];
4259                 pll->config = shared_dpll[i];
4260         }
4261 }
4262
4263 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4264 {
4265         struct drm_i915_private *dev_priv = dev->dev_private;
4266         int dslreg = PIPEDSL(pipe);
4267         u32 temp;
4268
4269         temp = I915_READ(dslreg);
4270         udelay(500);
4271         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4272                 if (wait_for(I915_READ(dslreg) != temp, 5))
4273                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4274         }
4275 }
4276
4277 static int
4278 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4279                   unsigned scaler_user, int *scaler_id, unsigned int rotation,
4280                   int src_w, int src_h, int dst_w, int dst_h)
4281 {
4282         struct intel_crtc_scaler_state *scaler_state =
4283                 &crtc_state->scaler_state;
4284         struct intel_crtc *intel_crtc =
4285                 to_intel_crtc(crtc_state->base.crtc);
4286         int need_scaling;
4287
4288         need_scaling = intel_rotation_90_or_270(rotation) ?
4289                 (src_h != dst_w || src_w != dst_h):
4290                 (src_w != dst_w || src_h != dst_h);
4291
4292         /*
4293          * if plane is being disabled or scaler is no more required or force detach
4294          *  - free scaler binded to this plane/crtc
4295          *  - in order to do this, update crtc->scaler_usage
4296          *
4297          * Here scaler state in crtc_state is set free so that
4298          * scaler can be assigned to other user. Actual register
4299          * update to free the scaler is done in plane/panel-fit programming.
4300          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4301          */
4302         if (force_detach || !need_scaling) {
4303                 if (*scaler_id >= 0) {
4304                         scaler_state->scaler_users &= ~(1 << scaler_user);
4305                         scaler_state->scalers[*scaler_id].in_use = 0;
4306
4307                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4308                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4309                                 intel_crtc->pipe, scaler_user, *scaler_id,
4310                                 scaler_state->scaler_users);
4311                         *scaler_id = -1;
4312                 }
4313                 return 0;
4314         }
4315
4316         /* range checks */
4317         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4318                 dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4319
4320                 src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4321                 dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H) {
4322                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4323                         "size is out of scaler range\n",
4324                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4325                 return -EINVAL;
4326         }
4327
4328         /* mark this plane as a scaler user in crtc_state */
4329         scaler_state->scaler_users |= (1 << scaler_user);
4330         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4331                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4332                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4333                 scaler_state->scaler_users);
4334
4335         return 0;
4336 }
4337
4338 /**
4339  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4340  *
4341  * @state: crtc's scaler state
4342  *
4343  * Return
4344  *     0 - scaler_usage updated successfully
4345  *    error - requested scaling cannot be supported or other error condition
4346  */
4347 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4348 {
4349         struct intel_crtc *intel_crtc = to_intel_crtc(state->base.crtc);
4350         struct drm_display_mode *adjusted_mode =
4351                 &state->base.adjusted_mode;
4352
4353         DRM_DEBUG_KMS("Updating scaler for [CRTC:%i] scaler_user index %u.%u\n",
4354                       intel_crtc->base.base.id, intel_crtc->pipe, SKL_CRTC_INDEX);
4355
4356         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4357                 &state->scaler_state.scaler_id, DRM_ROTATE_0,
4358                 state->pipe_src_w, state->pipe_src_h,
4359                 adjusted_mode->hdisplay, adjusted_mode->vdisplay);
4360 }
4361
4362 /**
4363  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4364  *
4365  * @state: crtc's scaler state
4366  * @plane_state: atomic plane state to update
4367  *
4368  * Return
4369  *     0 - scaler_usage updated successfully
4370  *    error - requested scaling cannot be supported or other error condition
4371  */
4372 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4373                                    struct intel_plane_state *plane_state)
4374 {
4375
4376         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
4377         struct intel_plane *intel_plane =
4378                 to_intel_plane(plane_state->base.plane);
4379         struct drm_framebuffer *fb = plane_state->base.fb;
4380         int ret;
4381
4382         bool force_detach = !fb || !plane_state->visible;
4383
4384         DRM_DEBUG_KMS("Updating scaler for [PLANE:%d] scaler_user index %u.%u\n",
4385                       intel_plane->base.base.id, intel_crtc->pipe,
4386                       drm_plane_index(&intel_plane->base));
4387
4388         ret = skl_update_scaler(crtc_state, force_detach,
4389                                 drm_plane_index(&intel_plane->base),
4390                                 &plane_state->scaler_id,
4391                                 plane_state->base.rotation,
4392                                 drm_rect_width(&plane_state->src) >> 16,
4393                                 drm_rect_height(&plane_state->src) >> 16,
4394                                 drm_rect_width(&plane_state->dst),
4395                                 drm_rect_height(&plane_state->dst));
4396
4397         if (ret || plane_state->scaler_id < 0)
4398                 return ret;
4399
4400         /* check colorkey */
4401         if (plane_state->ckey.flags != I915_SET_COLORKEY_NONE) {
4402                 DRM_DEBUG_KMS("[PLANE:%d] scaling with color key not allowed",
4403                               intel_plane->base.base.id);
4404                 return -EINVAL;
4405         }
4406
4407         /* Check src format */
4408         switch (fb->pixel_format) {
4409         case DRM_FORMAT_RGB565:
4410         case DRM_FORMAT_XBGR8888:
4411         case DRM_FORMAT_XRGB8888:
4412         case DRM_FORMAT_ABGR8888:
4413         case DRM_FORMAT_ARGB8888:
4414         case DRM_FORMAT_XRGB2101010:
4415         case DRM_FORMAT_XBGR2101010:
4416         case DRM_FORMAT_YUYV:
4417         case DRM_FORMAT_YVYU:
4418         case DRM_FORMAT_UYVY:
4419         case DRM_FORMAT_VYUY:
4420                 break;
4421         default:
4422                 DRM_DEBUG_KMS("[PLANE:%d] FB:%d unsupported scaling format 0x%x\n",
4423                         intel_plane->base.base.id, fb->base.id, fb->pixel_format);
4424                 return -EINVAL;
4425         }
4426
4427         return 0;
4428 }
4429
4430 static void skylake_scaler_disable(struct intel_crtc *crtc)
4431 {
4432         int i;
4433
4434         for (i = 0; i < crtc->num_scalers; i++)
4435                 skl_detach_scaler(crtc, i);
4436 }
4437
4438 static void skylake_pfit_enable(struct intel_crtc *crtc)
4439 {
4440         struct drm_device *dev = crtc->base.dev;
4441         struct drm_i915_private *dev_priv = dev->dev_private;
4442         int pipe = crtc->pipe;
4443         struct intel_crtc_scaler_state *scaler_state =
4444                 &crtc->config->scaler_state;
4445
4446         DRM_DEBUG_KMS("for crtc_state = %p\n", crtc->config);
4447
4448         if (crtc->config->pch_pfit.enabled) {
4449                 int id;
4450
4451                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0)) {
4452                         DRM_ERROR("Requesting pfit without getting a scaler first\n");
4453                         return;
4454                 }
4455
4456                 id = scaler_state->scaler_id;
4457                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4458                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4459                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
4460                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
4461
4462                 DRM_DEBUG_KMS("for crtc_state = %p scaler_id = %d\n", crtc->config, id);
4463         }
4464 }
4465
4466 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4467 {
4468         struct drm_device *dev = crtc->base.dev;
4469         struct drm_i915_private *dev_priv = dev->dev_private;
4470         int pipe = crtc->pipe;
4471
4472         if (crtc->config->pch_pfit.enabled) {
4473                 /* Force use of hard-coded filter coefficients
4474                  * as some pre-programmed values are broken,
4475                  * e.g. x201.
4476                  */
4477                 if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev))
4478                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4479                                                  PF_PIPE_SEL_IVB(pipe));
4480                 else
4481                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4482                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4483                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4484         }
4485 }
4486
4487 void hsw_enable_ips(struct intel_crtc *crtc)
4488 {
4489         struct drm_device *dev = crtc->base.dev;
4490         struct drm_i915_private *dev_priv = dev->dev_private;
4491
4492         if (!crtc->config->ips_enabled)
4493                 return;
4494
4495         /* We can only enable IPS after we enable a plane and wait for a vblank */
4496         intel_wait_for_vblank(dev, crtc->pipe);
4497
4498         assert_plane_enabled(dev_priv, crtc->plane);
4499         if (IS_BROADWELL(dev)) {
4500                 mutex_lock(&dev_priv->rps.hw_lock);
4501                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0xc0000000));
4502                 mutex_unlock(&dev_priv->rps.hw_lock);
4503                 /* Quoting Art Runyan: "its not safe to expect any particular
4504                  * value in IPS_CTL bit 31 after enabling IPS through the
4505                  * mailbox." Moreover, the mailbox may return a bogus state,
4506                  * so we need to just enable it and continue on.
4507                  */
4508         } else {
4509                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4510                 /* The bit only becomes 1 in the next vblank, so this wait here
4511                  * is essentially intel_wait_for_vblank. If we don't have this
4512                  * and don't wait for vblanks until the end of crtc_enable, then
4513                  * the HW state readout code will complain that the expected
4514                  * IPS_CTL value is not the one we read. */
4515                 if (wait_for(I915_READ_NOTRACE(IPS_CTL) & IPS_ENABLE, 50))
4516                         DRM_ERROR("Timed out waiting for IPS enable\n");
4517         }
4518 }
4519
4520 void hsw_disable_ips(struct intel_crtc *crtc)
4521 {
4522         struct drm_device *dev = crtc->base.dev;
4523         struct drm_i915_private *dev_priv = dev->dev_private;
4524
4525         if (!crtc->config->ips_enabled)
4526                 return;
4527
4528         assert_plane_enabled(dev_priv, crtc->plane);
4529         if (IS_BROADWELL(dev)) {
4530                 mutex_lock(&dev_priv->rps.hw_lock);
4531                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4532                 mutex_unlock(&dev_priv->rps.hw_lock);
4533                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4534                 if (wait_for((I915_READ(IPS_CTL) & IPS_ENABLE) == 0, 42))
4535                         DRM_ERROR("Timed out waiting for IPS disable\n");
4536         } else {
4537                 I915_WRITE(IPS_CTL, 0);
4538                 POSTING_READ(IPS_CTL);
4539         }
4540
4541         /* We need to wait for a vblank before we can disable the plane. */
4542         intel_wait_for_vblank(dev, crtc->pipe);
4543 }
4544
4545 /** Loads the palette/gamma unit for the CRTC with the prepared values */
4546 static void intel_crtc_load_lut(struct drm_crtc *crtc)
4547 {
4548         struct drm_device *dev = crtc->dev;
4549         struct drm_i915_private *dev_priv = dev->dev_private;
4550         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4551         enum pipe pipe = intel_crtc->pipe;
4552         int palreg = PALETTE(pipe);
4553         int i;
4554         bool reenable_ips = false;
4555
4556         /* The clocks have to be on to load the palette. */
4557         if (!crtc->state->active)
4558                 return;
4559
4560         if (HAS_GMCH_DISPLAY(dev_priv->dev)) {
4561                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_DSI))
4562                         assert_dsi_pll_enabled(dev_priv);
4563                 else
4564                         assert_pll_enabled(dev_priv, pipe);
4565         }
4566
4567         /* use legacy palette for Ironlake */
4568         if (!HAS_GMCH_DISPLAY(dev))
4569                 palreg = LGC_PALETTE(pipe);
4570
4571         /* Workaround : Do not read or write the pipe palette/gamma data while
4572          * GAMMA_MODE is configured for split gamma and IPS_CTL has IPS enabled.
4573          */
4574         if (IS_HASWELL(dev) && intel_crtc->config->ips_enabled &&
4575             ((I915_READ(GAMMA_MODE(pipe)) & GAMMA_MODE_MODE_MASK) ==
4576              GAMMA_MODE_MODE_SPLIT)) {
4577                 hsw_disable_ips(intel_crtc);
4578                 reenable_ips = true;
4579         }
4580
4581         for (i = 0; i < 256; i++) {
4582                 I915_WRITE(palreg + 4 * i,
4583                            (intel_crtc->lut_r[i] << 16) |
4584                            (intel_crtc->lut_g[i] << 8) |
4585                            intel_crtc->lut_b[i]);
4586         }
4587
4588         if (reenable_ips)
4589                 hsw_enable_ips(intel_crtc);
4590 }
4591
4592 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
4593 {
4594         if (intel_crtc->overlay) {
4595                 struct drm_device *dev = intel_crtc->base.dev;
4596                 struct drm_i915_private *dev_priv = dev->dev_private;
4597
4598                 mutex_lock(&dev->struct_mutex);
4599                 dev_priv->mm.interruptible = false;
4600                 (void) intel_overlay_switch_off(intel_crtc->overlay);
4601                 dev_priv->mm.interruptible = true;
4602                 mutex_unlock(&dev->struct_mutex);
4603         }
4604
4605         /* Let userspace switch the overlay on again. In most cases userspace
4606          * has to recompute where to put it anyway.
4607          */
4608 }
4609
4610 /**
4611  * intel_post_enable_primary - Perform operations after enabling primary plane
4612  * @crtc: the CRTC whose primary plane was just enabled
4613  *
4614  * Performs potentially sleeping operations that must be done after the primary
4615  * plane is enabled, such as updating FBC and IPS.  Note that this may be
4616  * called due to an explicit primary plane update, or due to an implicit
4617  * re-enable that is caused when a sprite plane is updated to no longer
4618  * completely hide the primary plane.
4619  */
4620 static void
4621 intel_post_enable_primary(struct drm_crtc *crtc)
4622 {
4623         struct drm_device *dev = crtc->dev;
4624         struct drm_i915_private *dev_priv = dev->dev_private;
4625         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4626         int pipe = intel_crtc->pipe;
4627
4628         /*
4629          * BDW signals flip done immediately if the plane
4630          * is disabled, even if the plane enable is already
4631          * armed to occur at the next vblank :(
4632          */
4633         if (IS_BROADWELL(dev))
4634                 intel_wait_for_vblank(dev, pipe);
4635
4636         /*
4637          * FIXME IPS should be fine as long as one plane is
4638          * enabled, but in practice it seems to have problems
4639          * when going from primary only to sprite only and vice
4640          * versa.
4641          */
4642         hsw_enable_ips(intel_crtc);
4643
4644         /*
4645          * Gen2 reports pipe underruns whenever all planes are disabled.
4646          * So don't enable underrun reporting before at least some planes
4647          * are enabled.
4648          * FIXME: Need to fix the logic to work when we turn off all planes
4649          * but leave the pipe running.
4650          */
4651         if (IS_GEN2(dev))
4652                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4653
4654         /* Underruns don't raise interrupts, so check manually. */
4655         if (HAS_GMCH_DISPLAY(dev))
4656                 i9xx_check_fifo_underruns(dev_priv);
4657 }
4658
4659 /**
4660  * intel_pre_disable_primary - Perform operations before disabling primary plane
4661  * @crtc: the CRTC whose primary plane is to be disabled
4662  *
4663  * Performs potentially sleeping operations that must be done before the
4664  * primary plane is disabled, such as updating FBC and IPS.  Note that this may
4665  * be called due to an explicit primary plane update, or due to an implicit
4666  * disable that is caused when a sprite plane completely hides the primary
4667  * plane.
4668  */
4669 static void
4670 intel_pre_disable_primary(struct drm_crtc *crtc)
4671 {
4672         struct drm_device *dev = crtc->dev;
4673         struct drm_i915_private *dev_priv = dev->dev_private;
4674         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4675         int pipe = intel_crtc->pipe;
4676
4677         /*
4678          * Gen2 reports pipe underruns whenever all planes are disabled.
4679          * So diasble underrun reporting before all the planes get disabled.
4680          * FIXME: Need to fix the logic to work when we turn off all planes
4681          * but leave the pipe running.
4682          */
4683         if (IS_GEN2(dev))
4684                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4685
4686         /*
4687          * Vblank time updates from the shadow to live plane control register
4688          * are blocked if the memory self-refresh mode is active at that
4689          * moment. So to make sure the plane gets truly disabled, disable
4690          * first the self-refresh mode. The self-refresh enable bit in turn
4691          * will be checked/applied by the HW only at the next frame start
4692          * event which is after the vblank start event, so we need to have a
4693          * wait-for-vblank between disabling the plane and the pipe.
4694          */
4695         if (HAS_GMCH_DISPLAY(dev)) {
4696                 intel_set_memory_cxsr(dev_priv, false);
4697                 dev_priv->wm.vlv.cxsr = false;
4698                 intel_wait_for_vblank(dev, pipe);
4699         }
4700
4701         /*
4702          * FIXME IPS should be fine as long as one plane is
4703          * enabled, but in practice it seems to have problems
4704          * when going from primary only to sprite only and vice
4705          * versa.
4706          */
4707         hsw_disable_ips(intel_crtc);
4708 }
4709
4710 static void intel_post_plane_update(struct intel_crtc *crtc)
4711 {
4712         struct intel_crtc_atomic_commit *atomic = &crtc->atomic;
4713         struct drm_device *dev = crtc->base.dev;
4714         struct drm_i915_private *dev_priv = dev->dev_private;
4715         struct drm_plane *plane;
4716
4717         if (atomic->wait_vblank)
4718                 intel_wait_for_vblank(dev, crtc->pipe);
4719
4720         intel_frontbuffer_flip(dev, atomic->fb_bits);
4721
4722         if (atomic->disable_cxsr)
4723                 crtc->wm.cxsr_allowed = true;
4724
4725         if (crtc->atomic.update_wm_post)
4726                 intel_update_watermarks(&crtc->base);
4727
4728         if (atomic->update_fbc)
4729                 intel_fbc_update(dev_priv);
4730
4731         if (atomic->post_enable_primary)
4732                 intel_post_enable_primary(&crtc->base);
4733
4734         drm_for_each_plane_mask(plane, dev, atomic->update_sprite_watermarks)
4735                 intel_update_sprite_watermarks(plane, &crtc->base,
4736                                                0, 0, 0, false, false);
4737
4738         memset(atomic, 0, sizeof(*atomic));
4739 }
4740
4741 static void intel_pre_plane_update(struct intel_crtc *crtc)
4742 {
4743         struct drm_device *dev = crtc->base.dev;
4744         struct drm_i915_private *dev_priv = dev->dev_private;
4745         struct intel_crtc_atomic_commit *atomic = &crtc->atomic;
4746         struct drm_plane *p;
4747
4748         /* Track fb's for any planes being disabled */
4749         drm_for_each_plane_mask(p, dev, atomic->disabled_planes) {
4750                 struct intel_plane *plane = to_intel_plane(p);
4751
4752                 mutex_lock(&dev->struct_mutex);
4753                 i915_gem_track_fb(intel_fb_obj(plane->base.fb), NULL,
4754                                   plane->frontbuffer_bit);
4755                 mutex_unlock(&dev->struct_mutex);
4756         }
4757
4758         if (atomic->wait_for_flips)
4759                 intel_crtc_wait_for_pending_flips(&crtc->base);
4760
4761         if (atomic->disable_fbc)
4762                 intel_fbc_disable_crtc(crtc);
4763
4764         if (crtc->atomic.disable_ips)
4765                 hsw_disable_ips(crtc);
4766
4767         if (atomic->pre_disable_primary)
4768                 intel_pre_disable_primary(&crtc->base);
4769
4770         if (atomic->disable_cxsr) {
4771                 crtc->wm.cxsr_allowed = false;
4772                 intel_set_memory_cxsr(dev_priv, false);
4773         }
4774 }
4775
4776 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
4777 {
4778         struct drm_device *dev = crtc->dev;
4779         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4780         struct drm_plane *p;
4781         int pipe = intel_crtc->pipe;
4782
4783         intel_crtc_dpms_overlay_disable(intel_crtc);
4784
4785         drm_for_each_plane_mask(p, dev, plane_mask)
4786                 to_intel_plane(p)->disable_plane(p, crtc);
4787
4788         /*
4789          * FIXME: Once we grow proper nuclear flip support out of this we need
4790          * to compute the mask of flip planes precisely. For the time being
4791          * consider this a flip to a NULL plane.
4792          */
4793         intel_frontbuffer_flip(dev, INTEL_FRONTBUFFER_ALL_MASK(pipe));
4794 }
4795
4796 static void ironlake_crtc_enable(struct drm_crtc *crtc)
4797 {
4798         struct drm_device *dev = crtc->dev;
4799         struct drm_i915_private *dev_priv = dev->dev_private;
4800         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4801         struct intel_encoder *encoder;
4802         int pipe = intel_crtc->pipe;
4803
4804         if (WARN_ON(intel_crtc->active))
4805                 return;
4806
4807         if (intel_crtc->config->has_pch_encoder)
4808                 intel_prepare_shared_dpll(intel_crtc);
4809
4810         if (intel_crtc->config->has_dp_encoder)
4811                 intel_dp_set_m_n(intel_crtc, M1_N1);
4812
4813         intel_set_pipe_timings(intel_crtc);
4814
4815         if (intel_crtc->config->has_pch_encoder) {
4816                 intel_cpu_transcoder_set_m_n(intel_crtc,
4817                                      &intel_crtc->config->fdi_m_n, NULL);
4818         }
4819
4820         ironlake_set_pipeconf(crtc);
4821
4822         intel_crtc->active = true;
4823
4824         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4825         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
4826
4827         for_each_encoder_on_crtc(dev, crtc, encoder)
4828                 if (encoder->pre_enable)
4829                         encoder->pre_enable(encoder);
4830
4831         if (intel_crtc->config->has_pch_encoder) {
4832                 /* Note: FDI PLL enabling _must_ be done before we enable the
4833                  * cpu pipes, hence this is separate from all the other fdi/pch
4834                  * enabling. */
4835                 ironlake_fdi_pll_enable(intel_crtc);
4836         } else {
4837                 assert_fdi_tx_disabled(dev_priv, pipe);
4838                 assert_fdi_rx_disabled(dev_priv, pipe);
4839         }
4840
4841         ironlake_pfit_enable(intel_crtc);
4842
4843         /*
4844          * On ILK+ LUT must be loaded before the pipe is running but with
4845          * clocks enabled
4846          */
4847         intel_crtc_load_lut(crtc);
4848
4849         intel_update_watermarks(crtc);
4850         intel_enable_pipe(intel_crtc);
4851
4852         if (intel_crtc->config->has_pch_encoder)
4853                 ironlake_pch_enable(crtc);
4854
4855         assert_vblank_disabled(crtc);
4856         drm_crtc_vblank_on(crtc);
4857
4858         for_each_encoder_on_crtc(dev, crtc, encoder)
4859                 encoder->enable(encoder);
4860
4861         if (HAS_PCH_CPT(dev))
4862                 cpt_verify_modeset(dev, intel_crtc->pipe);
4863 }
4864
4865 /* IPS only exists on ULT machines and is tied to pipe A. */
4866 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
4867 {
4868         return HAS_IPS(crtc->base.dev) && crtc->pipe == PIPE_A;
4869 }
4870
4871 static void haswell_crtc_enable(struct drm_crtc *crtc)
4872 {
4873         struct drm_device *dev = crtc->dev;
4874         struct drm_i915_private *dev_priv = dev->dev_private;
4875         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4876         struct intel_encoder *encoder;
4877         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
4878         struct intel_crtc_state *pipe_config =
4879                 to_intel_crtc_state(crtc->state);
4880
4881         if (WARN_ON(intel_crtc->active))
4882                 return;
4883
4884         if (intel_crtc_to_shared_dpll(intel_crtc))
4885                 intel_enable_shared_dpll(intel_crtc);
4886
4887         if (intel_crtc->config->has_dp_encoder)
4888                 intel_dp_set_m_n(intel_crtc, M1_N1);
4889
4890         intel_set_pipe_timings(intel_crtc);
4891
4892         if (intel_crtc->config->cpu_transcoder != TRANSCODER_EDP) {
4893                 I915_WRITE(PIPE_MULT(intel_crtc->config->cpu_transcoder),
4894                            intel_crtc->config->pixel_multiplier - 1);
4895         }
4896
4897         if (intel_crtc->config->has_pch_encoder) {
4898                 intel_cpu_transcoder_set_m_n(intel_crtc,
4899                                      &intel_crtc->config->fdi_m_n, NULL);
4900         }
4901
4902         haswell_set_pipeconf(crtc);
4903
4904         intel_set_pipe_csc(crtc);
4905
4906         intel_crtc->active = true;
4907
4908         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4909         for_each_encoder_on_crtc(dev, crtc, encoder)
4910                 if (encoder->pre_enable)
4911                         encoder->pre_enable(encoder);
4912
4913         if (intel_crtc->config->has_pch_encoder) {
4914                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4915                                                       true);
4916                 dev_priv->display.fdi_link_train(crtc);
4917         }
4918
4919         intel_ddi_enable_pipe_clock(intel_crtc);
4920
4921         if (INTEL_INFO(dev)->gen >= 9)
4922                 skylake_pfit_enable(intel_crtc);
4923         else
4924                 ironlake_pfit_enable(intel_crtc);
4925
4926         /*
4927          * On ILK+ LUT must be loaded before the pipe is running but with
4928          * clocks enabled
4929          */
4930         intel_crtc_load_lut(crtc);
4931
4932         intel_ddi_set_pipe_settings(crtc);
4933         intel_ddi_enable_transcoder_func(crtc);
4934
4935         intel_update_watermarks(crtc);
4936         intel_enable_pipe(intel_crtc);
4937
4938         if (intel_crtc->config->has_pch_encoder)
4939                 lpt_pch_enable(crtc);
4940
4941         if (intel_crtc->config->dp_encoder_is_mst)
4942                 intel_ddi_set_vc_payload_alloc(crtc, true);
4943
4944         assert_vblank_disabled(crtc);
4945         drm_crtc_vblank_on(crtc);
4946
4947         for_each_encoder_on_crtc(dev, crtc, encoder) {
4948                 encoder->enable(encoder);
4949                 intel_opregion_notify_encoder(encoder, true);
4950         }
4951
4952         /* If we change the relative order between pipe/planes enabling, we need
4953          * to change the workaround. */
4954         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
4955         if (IS_HASWELL(dev) && hsw_workaround_pipe != INVALID_PIPE) {
4956                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
4957                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
4958         }
4959 }
4960
4961 static void ironlake_pfit_disable(struct intel_crtc *crtc)
4962 {
4963         struct drm_device *dev = crtc->base.dev;
4964         struct drm_i915_private *dev_priv = dev->dev_private;
4965         int pipe = crtc->pipe;
4966
4967         /* To avoid upsetting the power well on haswell only disable the pfit if
4968          * it's in use. The hw state code will make sure we get this right. */
4969         if (crtc->config->pch_pfit.enabled) {
4970                 I915_WRITE(PF_CTL(pipe), 0);
4971                 I915_WRITE(PF_WIN_POS(pipe), 0);
4972                 I915_WRITE(PF_WIN_SZ(pipe), 0);
4973         }
4974 }
4975
4976 static void ironlake_crtc_disable(struct drm_crtc *crtc)
4977 {
4978         struct drm_device *dev = crtc->dev;
4979         struct drm_i915_private *dev_priv = dev->dev_private;
4980         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4981         struct intel_encoder *encoder;
4982         int pipe = intel_crtc->pipe;
4983         u32 reg, temp;
4984
4985         for_each_encoder_on_crtc(dev, crtc, encoder)
4986                 encoder->disable(encoder);
4987
4988         drm_crtc_vblank_off(crtc);
4989         assert_vblank_disabled(crtc);
4990
4991         if (intel_crtc->config->has_pch_encoder)
4992                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
4993
4994         intel_disable_pipe(intel_crtc);
4995
4996         ironlake_pfit_disable(intel_crtc);
4997
4998         if (intel_crtc->config->has_pch_encoder)
4999                 ironlake_fdi_disable(crtc);
5000
5001         for_each_encoder_on_crtc(dev, crtc, encoder)
5002                 if (encoder->post_disable)
5003                         encoder->post_disable(encoder);
5004
5005         if (intel_crtc->config->has_pch_encoder) {
5006                 ironlake_disable_pch_transcoder(dev_priv, pipe);
5007
5008                 if (HAS_PCH_CPT(dev)) {
5009                         /* disable TRANS_DP_CTL */
5010                         reg = TRANS_DP_CTL(pipe);
5011                         temp = I915_READ(reg);
5012                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5013                                   TRANS_DP_PORT_SEL_MASK);
5014                         temp |= TRANS_DP_PORT_SEL_NONE;
5015                         I915_WRITE(reg, temp);
5016
5017                         /* disable DPLL_SEL */
5018                         temp = I915_READ(PCH_DPLL_SEL);
5019                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5020                         I915_WRITE(PCH_DPLL_SEL, temp);
5021                 }
5022
5023                 ironlake_fdi_pll_disable(intel_crtc);
5024         }
5025
5026         intel_crtc->active = false;
5027         intel_update_watermarks(crtc);
5028 }
5029
5030 static void haswell_crtc_disable(struct drm_crtc *crtc)
5031 {
5032         struct drm_device *dev = crtc->dev;
5033         struct drm_i915_private *dev_priv = dev->dev_private;
5034         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5035         struct intel_encoder *encoder;
5036         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5037
5038         for_each_encoder_on_crtc(dev, crtc, encoder) {
5039                 intel_opregion_notify_encoder(encoder, false);
5040                 encoder->disable(encoder);
5041         }
5042
5043         drm_crtc_vblank_off(crtc);
5044         assert_vblank_disabled(crtc);
5045
5046         if (intel_crtc->config->has_pch_encoder)
5047                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5048                                                       false);
5049         intel_disable_pipe(intel_crtc);
5050
5051         if (intel_crtc->config->dp_encoder_is_mst)
5052                 intel_ddi_set_vc_payload_alloc(crtc, false);
5053
5054         intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
5055
5056         if (INTEL_INFO(dev)->gen >= 9)
5057                 skylake_scaler_disable(intel_crtc);
5058         else
5059                 ironlake_pfit_disable(intel_crtc);
5060
5061         intel_ddi_disable_pipe_clock(intel_crtc);
5062
5063         if (intel_crtc->config->has_pch_encoder) {
5064                 lpt_disable_pch_transcoder(dev_priv);
5065                 intel_ddi_fdi_disable(crtc);
5066         }
5067
5068         for_each_encoder_on_crtc(dev, crtc, encoder)
5069                 if (encoder->post_disable)
5070                         encoder->post_disable(encoder);
5071
5072         intel_crtc->active = false;
5073         intel_update_watermarks(crtc);
5074 }
5075
5076 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5077 {
5078         struct drm_device *dev = crtc->base.dev;
5079         struct drm_i915_private *dev_priv = dev->dev_private;
5080         struct intel_crtc_state *pipe_config = crtc->config;
5081
5082         if (!pipe_config->gmch_pfit.control)
5083                 return;
5084
5085         /*
5086          * The panel fitter should only be adjusted whilst the pipe is disabled,
5087          * according to register description and PRM.
5088          */
5089         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5090         assert_pipe_disabled(dev_priv, crtc->pipe);
5091
5092         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5093         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5094
5095         /* Border color in case we don't scale up to the full screen. Black by
5096          * default, change to something else for debugging. */
5097         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5098 }
5099
5100 static enum intel_display_power_domain port_to_power_domain(enum port port)
5101 {
5102         switch (port) {
5103         case PORT_A:
5104                 return POWER_DOMAIN_PORT_DDI_A_4_LANES;
5105         case PORT_B:
5106                 return POWER_DOMAIN_PORT_DDI_B_4_LANES;
5107         case PORT_C:
5108                 return POWER_DOMAIN_PORT_DDI_C_4_LANES;
5109         case PORT_D:
5110                 return POWER_DOMAIN_PORT_DDI_D_4_LANES;
5111         case PORT_E:
5112                 return POWER_DOMAIN_PORT_DDI_E_2_LANES;
5113         default:
5114                 WARN_ON_ONCE(1);
5115                 return POWER_DOMAIN_PORT_OTHER;
5116         }
5117 }
5118
5119 #define for_each_power_domain(domain, mask)                             \
5120         for ((domain) = 0; (domain) < POWER_DOMAIN_NUM; (domain)++)     \
5121                 if ((1 << (domain)) & (mask))
5122
5123 enum intel_display_power_domain
5124 intel_display_port_power_domain(struct intel_encoder *intel_encoder)
5125 {
5126         struct drm_device *dev = intel_encoder->base.dev;
5127         struct intel_digital_port *intel_dig_port;
5128
5129         switch (intel_encoder->type) {
5130         case INTEL_OUTPUT_UNKNOWN:
5131                 /* Only DDI platforms should ever use this output type */
5132                 WARN_ON_ONCE(!HAS_DDI(dev));
5133         case INTEL_OUTPUT_DISPLAYPORT:
5134         case INTEL_OUTPUT_HDMI:
5135         case INTEL_OUTPUT_EDP:
5136                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5137                 return port_to_power_domain(intel_dig_port->port);
5138         case INTEL_OUTPUT_DP_MST:
5139                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5140                 return port_to_power_domain(intel_dig_port->port);
5141         case INTEL_OUTPUT_ANALOG:
5142                 return POWER_DOMAIN_PORT_CRT;
5143         case INTEL_OUTPUT_DSI:
5144                 return POWER_DOMAIN_PORT_DSI;
5145         default:
5146                 return POWER_DOMAIN_PORT_OTHER;
5147         }
5148 }
5149
5150 static unsigned long get_crtc_power_domains(struct drm_crtc *crtc)
5151 {
5152         struct drm_device *dev = crtc->dev;
5153         struct intel_encoder *intel_encoder;
5154         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5155         enum pipe pipe = intel_crtc->pipe;
5156         unsigned long mask;
5157         enum transcoder transcoder;
5158
5159         if (!crtc->state->active)
5160                 return 0;
5161
5162         transcoder = intel_pipe_to_cpu_transcoder(dev->dev_private, pipe);
5163
5164         mask = BIT(POWER_DOMAIN_PIPE(pipe));
5165         mask |= BIT(POWER_DOMAIN_TRANSCODER(transcoder));
5166         if (intel_crtc->config->pch_pfit.enabled ||
5167             intel_crtc->config->pch_pfit.force_thru)
5168                 mask |= BIT(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5169
5170         for_each_encoder_on_crtc(dev, crtc, intel_encoder)
5171                 mask |= BIT(intel_display_port_power_domain(intel_encoder));
5172
5173         return mask;
5174 }
5175
5176 static unsigned long modeset_get_crtc_power_domains(struct drm_crtc *crtc)
5177 {
5178         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
5179         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5180         enum intel_display_power_domain domain;
5181         unsigned long domains, new_domains, old_domains;
5182
5183         old_domains = intel_crtc->enabled_power_domains;
5184         intel_crtc->enabled_power_domains = new_domains = get_crtc_power_domains(crtc);
5185
5186         domains = new_domains & ~old_domains;
5187
5188         for_each_power_domain(domain, domains)
5189                 intel_display_power_get(dev_priv, domain);
5190
5191         return old_domains & ~new_domains;
5192 }
5193
5194 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
5195                                       unsigned long domains)
5196 {
5197         enum intel_display_power_domain domain;
5198
5199         for_each_power_domain(domain, domains)
5200                 intel_display_power_put(dev_priv, domain);
5201 }
5202
5203 static void modeset_update_crtc_power_domains(struct drm_atomic_state *state)
5204 {
5205         struct drm_device *dev = state->dev;
5206         struct drm_i915_private *dev_priv = dev->dev_private;
5207         unsigned long put_domains[I915_MAX_PIPES] = {};
5208         struct drm_crtc_state *crtc_state;
5209         struct drm_crtc *crtc;
5210         int i;
5211
5212         for_each_crtc_in_state(state, crtc, crtc_state, i) {
5213                 if (needs_modeset(crtc->state))
5214                         put_domains[to_intel_crtc(crtc)->pipe] =
5215                                 modeset_get_crtc_power_domains(crtc);
5216         }
5217
5218         if (dev_priv->display.modeset_commit_cdclk) {
5219                 unsigned int cdclk = to_intel_atomic_state(state)->cdclk;
5220
5221                 if (cdclk != dev_priv->cdclk_freq &&
5222                     !WARN_ON(!state->allow_modeset))
5223                         dev_priv->display.modeset_commit_cdclk(state);
5224         }
5225
5226         for (i = 0; i < I915_MAX_PIPES; i++)
5227                 if (put_domains[i])
5228                         modeset_put_power_domains(dev_priv, put_domains[i]);
5229 }
5230
5231 static int intel_compute_max_dotclk(struct drm_i915_private *dev_priv)
5232 {
5233         int max_cdclk_freq = dev_priv->max_cdclk_freq;
5234
5235         if (INTEL_INFO(dev_priv)->gen >= 9 ||
5236             IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
5237                 return max_cdclk_freq;
5238         else if (IS_CHERRYVIEW(dev_priv))
5239                 return max_cdclk_freq*95/100;
5240         else if (INTEL_INFO(dev_priv)->gen < 4)
5241                 return 2*max_cdclk_freq*90/100;
5242         else
5243                 return max_cdclk_freq*90/100;
5244 }
5245
5246 static void intel_update_max_cdclk(struct drm_device *dev)
5247 {
5248         struct drm_i915_private *dev_priv = dev->dev_private;
5249
5250         if (IS_SKYLAKE(dev)) {
5251                 u32 limit = I915_READ(SKL_DFSM) & SKL_DFSM_CDCLK_LIMIT_MASK;
5252
5253                 if (limit == SKL_DFSM_CDCLK_LIMIT_675)
5254                         dev_priv->max_cdclk_freq = 675000;
5255                 else if (limit == SKL_DFSM_CDCLK_LIMIT_540)
5256                         dev_priv->max_cdclk_freq = 540000;
5257                 else if (limit == SKL_DFSM_CDCLK_LIMIT_450)
5258                         dev_priv->max_cdclk_freq = 450000;
5259                 else
5260                         dev_priv->max_cdclk_freq = 337500;
5261         } else if (IS_BROADWELL(dev))  {
5262                 /*
5263                  * FIXME with extra cooling we can allow
5264                  * 540 MHz for ULX and 675 Mhz for ULT.
5265                  * How can we know if extra cooling is
5266                  * available? PCI ID, VTB, something else?
5267                  */
5268                 if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
5269                         dev_priv->max_cdclk_freq = 450000;
5270                 else if (IS_BDW_ULX(dev))
5271                         dev_priv->max_cdclk_freq = 450000;
5272                 else if (IS_BDW_ULT(dev))
5273                         dev_priv->max_cdclk_freq = 540000;
5274                 else
5275                         dev_priv->max_cdclk_freq = 675000;
5276         } else if (IS_CHERRYVIEW(dev)) {
5277                 dev_priv->max_cdclk_freq = 320000;
5278         } else if (IS_VALLEYVIEW(dev)) {
5279                 dev_priv->max_cdclk_freq = 400000;
5280         } else {
5281                 /* otherwise assume cdclk is fixed */
5282                 dev_priv->max_cdclk_freq = dev_priv->cdclk_freq;
5283         }
5284
5285         dev_priv->max_dotclk_freq = intel_compute_max_dotclk(dev_priv);
5286
5287         DRM_DEBUG_DRIVER("Max CD clock rate: %d kHz\n",
5288                          dev_priv->max_cdclk_freq);
5289
5290         DRM_DEBUG_DRIVER("Max dotclock rate: %d kHz\n",
5291                          dev_priv->max_dotclk_freq);
5292 }
5293
5294 static void intel_update_cdclk(struct drm_device *dev)
5295 {
5296         struct drm_i915_private *dev_priv = dev->dev_private;
5297
5298         dev_priv->cdclk_freq = dev_priv->display.get_display_clock_speed(dev);
5299         DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz\n",
5300                          dev_priv->cdclk_freq);
5301
5302         /*
5303          * Program the gmbus_freq based on the cdclk frequency.
5304          * BSpec erroneously claims we should aim for 4MHz, but
5305          * in fact 1MHz is the correct frequency.
5306          */
5307         if (IS_VALLEYVIEW(dev)) {
5308                 /*
5309                  * Program the gmbus_freq based on the cdclk frequency.
5310                  * BSpec erroneously claims we should aim for 4MHz, but
5311                  * in fact 1MHz is the correct frequency.
5312                  */
5313                 I915_WRITE(GMBUSFREQ_VLV, DIV_ROUND_UP(dev_priv->cdclk_freq, 1000));
5314         }
5315
5316         if (dev_priv->max_cdclk_freq == 0)
5317                 intel_update_max_cdclk(dev);
5318 }
5319
5320 static void broxton_set_cdclk(struct drm_device *dev, int frequency)
5321 {
5322         struct drm_i915_private *dev_priv = dev->dev_private;
5323         uint32_t divider;
5324         uint32_t ratio;
5325         uint32_t current_freq;
5326         int ret;
5327
5328         /* frequency = 19.2MHz * ratio / 2 / div{1,1.5,2,4} */
5329         switch (frequency) {
5330         case 144000:
5331                 divider = BXT_CDCLK_CD2X_DIV_SEL_4;
5332                 ratio = BXT_DE_PLL_RATIO(60);
5333                 break;
5334         case 288000:
5335                 divider = BXT_CDCLK_CD2X_DIV_SEL_2;
5336                 ratio = BXT_DE_PLL_RATIO(60);
5337                 break;
5338         case 384000:
5339                 divider = BXT_CDCLK_CD2X_DIV_SEL_1_5;
5340                 ratio = BXT_DE_PLL_RATIO(60);
5341                 break;
5342         case 576000:
5343                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5344                 ratio = BXT_DE_PLL_RATIO(60);
5345                 break;
5346         case 624000:
5347                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5348                 ratio = BXT_DE_PLL_RATIO(65);
5349                 break;
5350         case 19200:
5351                 /*
5352                  * Bypass frequency with DE PLL disabled. Init ratio, divider
5353                  * to suppress GCC warning.
5354                  */
5355                 ratio = 0;
5356                 divider = 0;
5357                 break;
5358         default:
5359                 DRM_ERROR("unsupported CDCLK freq %d", frequency);
5360
5361                 return;
5362         }
5363
5364         mutex_lock(&dev_priv->rps.hw_lock);
5365         /* Inform power controller of upcoming frequency change */
5366         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5367                                       0x80000000);
5368         mutex_unlock(&dev_priv->rps.hw_lock);
5369
5370         if (ret) {
5371                 DRM_ERROR("PCode CDCLK freq change notify failed (err %d, freq %d)\n",
5372                           ret, frequency);
5373                 return;
5374         }
5375
5376         current_freq = I915_READ(CDCLK_CTL) & CDCLK_FREQ_DECIMAL_MASK;
5377         /* convert from .1 fixpoint MHz with -1MHz offset to kHz */
5378         current_freq = current_freq * 500 + 1000;
5379
5380         /*
5381          * DE PLL has to be disabled when
5382          * - setting to 19.2MHz (bypass, PLL isn't used)
5383          * - before setting to 624MHz (PLL needs toggling)
5384          * - before setting to any frequency from 624MHz (PLL needs toggling)
5385          */
5386         if (frequency == 19200 || frequency == 624000 ||
5387             current_freq == 624000) {
5388                 I915_WRITE(BXT_DE_PLL_ENABLE, ~BXT_DE_PLL_PLL_ENABLE);
5389                 /* Timeout 200us */
5390                 if (wait_for(!(I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_LOCK),
5391                              1))
5392                         DRM_ERROR("timout waiting for DE PLL unlock\n");
5393         }
5394
5395         if (frequency != 19200) {
5396                 uint32_t val;
5397
5398                 val = I915_READ(BXT_DE_PLL_CTL);
5399                 val &= ~BXT_DE_PLL_RATIO_MASK;
5400                 val |= ratio;
5401                 I915_WRITE(BXT_DE_PLL_CTL, val);
5402
5403                 I915_WRITE(BXT_DE_PLL_ENABLE, BXT_DE_PLL_PLL_ENABLE);
5404                 /* Timeout 200us */
5405                 if (wait_for(I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_LOCK, 1))
5406                         DRM_ERROR("timeout waiting for DE PLL lock\n");
5407
5408                 val = I915_READ(CDCLK_CTL);
5409                 val &= ~BXT_CDCLK_CD2X_DIV_SEL_MASK;
5410                 val |= divider;
5411                 /*
5412                  * Disable SSA Precharge when CD clock frequency < 500 MHz,
5413                  * enable otherwise.
5414                  */
5415                 val &= ~BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5416                 if (frequency >= 500000)
5417                         val |= BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5418
5419                 val &= ~CDCLK_FREQ_DECIMAL_MASK;
5420                 /* convert from kHz to .1 fixpoint MHz with -1MHz offset */
5421                 val |= (frequency - 1000) / 500;
5422                 I915_WRITE(CDCLK_CTL, val);
5423         }
5424
5425         mutex_lock(&dev_priv->rps.hw_lock);
5426         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5427                                       DIV_ROUND_UP(frequency, 25000));
5428         mutex_unlock(&dev_priv->rps.hw_lock);
5429
5430         if (ret) {
5431                 DRM_ERROR("PCode CDCLK freq set failed, (err %d, freq %d)\n",
5432                           ret, frequency);
5433                 return;
5434         }
5435
5436         intel_update_cdclk(dev);
5437 }
5438
5439 void broxton_init_cdclk(struct drm_device *dev)
5440 {
5441         struct drm_i915_private *dev_priv = dev->dev_private;
5442         uint32_t val;
5443
5444         /*
5445          * NDE_RSTWRN_OPT RST PCH Handshake En must always be 0b on BXT
5446          * or else the reset will hang because there is no PCH to respond.
5447          * Move the handshake programming to initialization sequence.
5448          * Previously was left up to BIOS.
5449          */
5450         val = I915_READ(HSW_NDE_RSTWRN_OPT);
5451         val &= ~RESET_PCH_HANDSHAKE_ENABLE;
5452         I915_WRITE(HSW_NDE_RSTWRN_OPT, val);
5453
5454         /* Enable PG1 for cdclk */
5455         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
5456
5457         /* check if cd clock is enabled */
5458         if (I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_PLL_ENABLE) {
5459                 DRM_DEBUG_KMS("Display already initialized\n");
5460                 return;
5461         }
5462
5463         /*
5464          * FIXME:
5465          * - The initial CDCLK needs to be read from VBT.
5466          *   Need to make this change after VBT has changes for BXT.
5467          * - check if setting the max (or any) cdclk freq is really necessary
5468          *   here, it belongs to modeset time
5469          */
5470         broxton_set_cdclk(dev, 624000);
5471
5472         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) | DBUF_POWER_REQUEST);
5473         POSTING_READ(DBUF_CTL);
5474
5475         udelay(10);
5476
5477         if (!(I915_READ(DBUF_CTL) & DBUF_POWER_STATE))
5478                 DRM_ERROR("DBuf power enable timeout!\n");
5479 }
5480
5481 void broxton_uninit_cdclk(struct drm_device *dev)
5482 {
5483         struct drm_i915_private *dev_priv = dev->dev_private;
5484
5485         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) & ~DBUF_POWER_REQUEST);
5486         POSTING_READ(DBUF_CTL);
5487
5488         udelay(10);
5489
5490         if (I915_READ(DBUF_CTL) & DBUF_POWER_STATE)
5491                 DRM_ERROR("DBuf power disable timeout!\n");
5492
5493         /* Set minimum (bypass) frequency, in effect turning off the DE PLL */
5494         broxton_set_cdclk(dev, 19200);
5495
5496         intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS);
5497 }
5498
5499 static const struct skl_cdclk_entry {
5500         unsigned int freq;
5501         unsigned int vco;
5502 } skl_cdclk_frequencies[] = {
5503         { .freq = 308570, .vco = 8640 },
5504         { .freq = 337500, .vco = 8100 },
5505         { .freq = 432000, .vco = 8640 },
5506         { .freq = 450000, .vco = 8100 },
5507         { .freq = 540000, .vco = 8100 },
5508         { .freq = 617140, .vco = 8640 },
5509         { .freq = 675000, .vco = 8100 },
5510 };
5511
5512 static unsigned int skl_cdclk_decimal(unsigned int freq)
5513 {
5514         return (freq - 1000) / 500;
5515 }
5516
5517 static unsigned int skl_cdclk_get_vco(unsigned int freq)
5518 {
5519         unsigned int i;
5520
5521         for (i = 0; i < ARRAY_SIZE(skl_cdclk_frequencies); i++) {
5522                 const struct skl_cdclk_entry *e = &skl_cdclk_frequencies[i];
5523
5524                 if (e->freq == freq)
5525                         return e->vco;
5526         }
5527
5528         return 8100;
5529 }
5530
5531 static void
5532 skl_dpll0_enable(struct drm_i915_private *dev_priv, unsigned int required_vco)
5533 {
5534         unsigned int min_freq;
5535         u32 val;
5536
5537         /* select the minimum CDCLK before enabling DPLL 0 */
5538         val = I915_READ(CDCLK_CTL);
5539         val &= ~CDCLK_FREQ_SEL_MASK | ~CDCLK_FREQ_DECIMAL_MASK;
5540         val |= CDCLK_FREQ_337_308;
5541
5542         if (required_vco == 8640)
5543                 min_freq = 308570;
5544         else
5545                 min_freq = 337500;
5546
5547         val = CDCLK_FREQ_337_308 | skl_cdclk_decimal(min_freq);
5548
5549         I915_WRITE(CDCLK_CTL, val);
5550         POSTING_READ(CDCLK_CTL);
5551
5552         /*
5553          * We always enable DPLL0 with the lowest link rate possible, but still
5554          * taking into account the VCO required to operate the eDP panel at the
5555          * desired frequency. The usual DP link rates operate with a VCO of
5556          * 8100 while the eDP 1.4 alternate link rates need a VCO of 8640.
5557          * The modeset code is responsible for the selection of the exact link
5558          * rate later on, with the constraint of choosing a frequency that
5559          * works with required_vco.
5560          */
5561         val = I915_READ(DPLL_CTRL1);
5562
5563         val &= ~(DPLL_CTRL1_HDMI_MODE(SKL_DPLL0) | DPLL_CTRL1_SSC(SKL_DPLL0) |
5564                  DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0));
5565         val |= DPLL_CTRL1_OVERRIDE(SKL_DPLL0);
5566         if (required_vco == 8640)
5567                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1080,
5568                                             SKL_DPLL0);
5569         else
5570                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_810,
5571                                             SKL_DPLL0);
5572
5573         I915_WRITE(DPLL_CTRL1, val);
5574         POSTING_READ(DPLL_CTRL1);
5575
5576         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) | LCPLL_PLL_ENABLE);
5577
5578         if (wait_for(I915_READ(LCPLL1_CTL) & LCPLL_PLL_LOCK, 5))
5579                 DRM_ERROR("DPLL0 not locked\n");
5580 }
5581
5582 static bool skl_cdclk_pcu_ready(struct drm_i915_private *dev_priv)
5583 {
5584         int ret;
5585         u32 val;
5586
5587         /* inform PCU we want to change CDCLK */
5588         val = SKL_CDCLK_PREPARE_FOR_CHANGE;
5589         mutex_lock(&dev_priv->rps.hw_lock);
5590         ret = sandybridge_pcode_read(dev_priv, SKL_PCODE_CDCLK_CONTROL, &val);
5591         mutex_unlock(&dev_priv->rps.hw_lock);
5592
5593         return ret == 0 && (val & SKL_CDCLK_READY_FOR_CHANGE);
5594 }
5595
5596 static bool skl_cdclk_wait_for_pcu_ready(struct drm_i915_private *dev_priv)
5597 {
5598         unsigned int i;
5599
5600         for (i = 0; i < 15; i++) {
5601                 if (skl_cdclk_pcu_ready(dev_priv))
5602                         return true;
5603                 udelay(10);
5604         }
5605
5606         return false;
5607 }
5608
5609 static void skl_set_cdclk(struct drm_i915_private *dev_priv, unsigned int freq)
5610 {
5611         struct drm_device *dev = dev_priv->dev;
5612         u32 freq_select, pcu_ack;
5613
5614         DRM_DEBUG_DRIVER("Changing CDCLK to %dKHz\n", freq);
5615
5616         if (!skl_cdclk_wait_for_pcu_ready(dev_priv)) {
5617                 DRM_ERROR("failed to inform PCU about cdclk change\n");
5618                 return;
5619         }
5620
5621         /* set CDCLK_CTL */
5622         switch(freq) {
5623         case 450000:
5624         case 432000:
5625                 freq_select = CDCLK_FREQ_450_432;
5626                 pcu_ack = 1;
5627                 break;
5628         case 540000:
5629                 freq_select = CDCLK_FREQ_540;
5630                 pcu_ack = 2;
5631                 break;
5632         case 308570:
5633         case 337500:
5634         default:
5635                 freq_select = CDCLK_FREQ_337_308;
5636                 pcu_ack = 0;
5637                 break;
5638         case 617140:
5639         case 675000:
5640                 freq_select = CDCLK_FREQ_675_617;
5641                 pcu_ack = 3;
5642                 break;
5643         }
5644
5645         I915_WRITE(CDCLK_CTL, freq_select | skl_cdclk_decimal(freq));
5646         POSTING_READ(CDCLK_CTL);
5647
5648         /* inform PCU of the change */
5649         mutex_lock(&dev_priv->rps.hw_lock);
5650         sandybridge_pcode_write(dev_priv, SKL_PCODE_CDCLK_CONTROL, pcu_ack);
5651         mutex_unlock(&dev_priv->rps.hw_lock);
5652
5653         intel_update_cdclk(dev);
5654 }
5655
5656 void skl_uninit_cdclk(struct drm_i915_private *dev_priv)
5657 {
5658         /* disable DBUF power */
5659         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) & ~DBUF_POWER_REQUEST);
5660         POSTING_READ(DBUF_CTL);
5661
5662         udelay(10);
5663
5664         if (I915_READ(DBUF_CTL) & DBUF_POWER_STATE)
5665                 DRM_ERROR("DBuf power disable timeout\n");
5666
5667         /* disable DPLL0 */
5668         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) & ~LCPLL_PLL_ENABLE);
5669         if (wait_for(!(I915_READ(LCPLL1_CTL) & LCPLL_PLL_LOCK), 1))
5670                 DRM_ERROR("Couldn't disable DPLL0\n");
5671
5672         intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS);
5673 }
5674
5675 void skl_init_cdclk(struct drm_i915_private *dev_priv)
5676 {
5677         u32 val;
5678         unsigned int required_vco;
5679
5680         /* enable PCH reset handshake */
5681         val = I915_READ(HSW_NDE_RSTWRN_OPT);
5682         I915_WRITE(HSW_NDE_RSTWRN_OPT, val | RESET_PCH_HANDSHAKE_ENABLE);
5683
5684         /* enable PG1 and Misc I/O */
5685         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
5686
5687         /* DPLL0 not enabled (happens on early BIOS versions) */
5688         if (!(I915_READ(LCPLL1_CTL) & LCPLL_PLL_ENABLE)) {
5689                 /* enable DPLL0 */
5690                 required_vco = skl_cdclk_get_vco(dev_priv->skl_boot_cdclk);
5691                 skl_dpll0_enable(dev_priv, required_vco);
5692         }
5693
5694         /* set CDCLK to the frequency the BIOS chose */
5695         skl_set_cdclk(dev_priv, dev_priv->skl_boot_cdclk);
5696
5697         /* enable DBUF power */
5698         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) | DBUF_POWER_REQUEST);
5699         POSTING_READ(DBUF_CTL);
5700
5701         udelay(10);
5702
5703         if (!(I915_READ(DBUF_CTL) & DBUF_POWER_STATE))
5704                 DRM_ERROR("DBuf power enable timeout\n");
5705 }
5706
5707 /* returns HPLL frequency in kHz */
5708 static int valleyview_get_vco(struct drm_i915_private *dev_priv)
5709 {
5710         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
5711
5712         /* Obtain SKU information */
5713         mutex_lock(&dev_priv->sb_lock);
5714         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
5715                 CCK_FUSE_HPLL_FREQ_MASK;
5716         mutex_unlock(&dev_priv->sb_lock);
5717
5718         return vco_freq[hpll_freq] * 1000;
5719 }
5720
5721 /* Adjust CDclk dividers to allow high res or save power if possible */
5722 static void valleyview_set_cdclk(struct drm_device *dev, int cdclk)
5723 {
5724         struct drm_i915_private *dev_priv = dev->dev_private;
5725         u32 val, cmd;
5726
5727         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5728                                         != dev_priv->cdclk_freq);
5729
5730         if (cdclk >= 320000) /* jump to highest voltage for 400MHz too */
5731                 cmd = 2;
5732         else if (cdclk == 266667)
5733                 cmd = 1;
5734         else
5735                 cmd = 0;
5736
5737         mutex_lock(&dev_priv->rps.hw_lock);
5738         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5739         val &= ~DSPFREQGUAR_MASK;
5740         val |= (cmd << DSPFREQGUAR_SHIFT);
5741         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5742         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5743                       DSPFREQSTAT_MASK) == (cmd << DSPFREQSTAT_SHIFT),
5744                      50)) {
5745                 DRM_ERROR("timed out waiting for CDclk change\n");
5746         }
5747         mutex_unlock(&dev_priv->rps.hw_lock);
5748
5749         mutex_lock(&dev_priv->sb_lock);
5750
5751         if (cdclk == 400000) {
5752                 u32 divider;
5753
5754                 divider = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5755
5756                 /* adjust cdclk divider */
5757                 val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
5758                 val &= ~DISPLAY_FREQUENCY_VALUES;
5759                 val |= divider;
5760                 vlv_cck_write(dev_priv, CCK_DISPLAY_CLOCK_CONTROL, val);
5761
5762                 if (wait_for((vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL) &
5763                               DISPLAY_FREQUENCY_STATUS) == (divider << DISPLAY_FREQUENCY_STATUS_SHIFT),
5764                              50))
5765                         DRM_ERROR("timed out waiting for CDclk change\n");
5766         }
5767
5768         /* adjust self-refresh exit latency value */
5769         val = vlv_bunit_read(dev_priv, BUNIT_REG_BISOC);
5770         val &= ~0x7f;
5771
5772         /*
5773          * For high bandwidth configs, we set a higher latency in the bunit
5774          * so that the core display fetch happens in time to avoid underruns.
5775          */
5776         if (cdclk == 400000)
5777                 val |= 4500 / 250; /* 4.5 usec */
5778         else
5779                 val |= 3000 / 250; /* 3.0 usec */
5780         vlv_bunit_write(dev_priv, BUNIT_REG_BISOC, val);
5781
5782         mutex_unlock(&dev_priv->sb_lock);
5783
5784         intel_update_cdclk(dev);
5785 }
5786
5787 static void cherryview_set_cdclk(struct drm_device *dev, int cdclk)
5788 {
5789         struct drm_i915_private *dev_priv = dev->dev_private;
5790         u32 val, cmd;
5791
5792         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5793                                                 != dev_priv->cdclk_freq);
5794
5795         switch (cdclk) {
5796         case 333333:
5797         case 320000:
5798         case 266667:
5799         case 200000:
5800                 break;
5801         default:
5802                 MISSING_CASE(cdclk);
5803                 return;
5804         }
5805
5806         /*
5807          * Specs are full of misinformation, but testing on actual
5808          * hardware has shown that we just need to write the desired
5809          * CCK divider into the Punit register.
5810          */
5811         cmd = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5812
5813         mutex_lock(&dev_priv->rps.hw_lock);
5814         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5815         val &= ~DSPFREQGUAR_MASK_CHV;
5816         val |= (cmd << DSPFREQGUAR_SHIFT_CHV);
5817         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5818         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5819                       DSPFREQSTAT_MASK_CHV) == (cmd << DSPFREQSTAT_SHIFT_CHV),
5820                      50)) {
5821                 DRM_ERROR("timed out waiting for CDclk change\n");
5822         }
5823         mutex_unlock(&dev_priv->rps.hw_lock);
5824
5825         intel_update_cdclk(dev);
5826 }
5827
5828 static int valleyview_calc_cdclk(struct drm_i915_private *dev_priv,
5829                                  int max_pixclk)
5830 {
5831         int freq_320 = (dev_priv->hpll_freq <<  1) % 320000 != 0 ? 333333 : 320000;
5832         int limit = IS_CHERRYVIEW(dev_priv) ? 95 : 90;
5833
5834         /*
5835          * Really only a few cases to deal with, as only 4 CDclks are supported:
5836          *   200MHz
5837          *   267MHz
5838          *   320/333MHz (depends on HPLL freq)
5839          *   400MHz (VLV only)
5840          * So we check to see whether we're above 90% (VLV) or 95% (CHV)
5841          * of the lower bin and adjust if needed.
5842          *
5843          * We seem to get an unstable or solid color picture at 200MHz.
5844          * Not sure what's wrong. For now use 200MHz only when all pipes
5845          * are off.
5846          */
5847         if (!IS_CHERRYVIEW(dev_priv) &&
5848             max_pixclk > freq_320*limit/100)
5849                 return 400000;
5850         else if (max_pixclk > 266667*limit/100)
5851                 return freq_320;
5852         else if (max_pixclk > 0)
5853                 return 266667;
5854         else
5855                 return 200000;
5856 }
5857
5858 static int broxton_calc_cdclk(struct drm_i915_private *dev_priv,
5859                               int max_pixclk)
5860 {
5861         /*
5862          * FIXME:
5863          * - remove the guardband, it's not needed on BXT
5864          * - set 19.2MHz bypass frequency if there are no active pipes
5865          */
5866         if (max_pixclk > 576000*9/10)
5867                 return 624000;
5868         else if (max_pixclk > 384000*9/10)
5869                 return 576000;
5870         else if (max_pixclk > 288000*9/10)
5871                 return 384000;
5872         else if (max_pixclk > 144000*9/10)
5873                 return 288000;
5874         else
5875                 return 144000;
5876 }
5877
5878 /* Compute the max pixel clock for new configuration. Uses atomic state if
5879  * that's non-NULL, look at current state otherwise. */
5880 static int intel_mode_max_pixclk(struct drm_device *dev,
5881                                  struct drm_atomic_state *state)
5882 {
5883         struct intel_crtc *intel_crtc;
5884         struct intel_crtc_state *crtc_state;
5885         int max_pixclk = 0;
5886
5887         for_each_intel_crtc(dev, intel_crtc) {
5888                 crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
5889                 if (IS_ERR(crtc_state))
5890                         return PTR_ERR(crtc_state);
5891
5892                 if (!crtc_state->base.enable)
5893                         continue;
5894
5895                 max_pixclk = max(max_pixclk,
5896                                  crtc_state->base.adjusted_mode.crtc_clock);
5897         }
5898
5899         return max_pixclk;
5900 }
5901
5902 static int valleyview_modeset_calc_cdclk(struct drm_atomic_state *state)
5903 {
5904         struct drm_device *dev = state->dev;
5905         struct drm_i915_private *dev_priv = dev->dev_private;
5906         int max_pixclk = intel_mode_max_pixclk(dev, state);
5907
5908         if (max_pixclk < 0)
5909                 return max_pixclk;
5910
5911         to_intel_atomic_state(state)->cdclk =
5912                 valleyview_calc_cdclk(dev_priv, max_pixclk);
5913
5914         return 0;
5915 }
5916
5917 static int broxton_modeset_calc_cdclk(struct drm_atomic_state *state)
5918 {
5919         struct drm_device *dev = state->dev;
5920         struct drm_i915_private *dev_priv = dev->dev_private;
5921         int max_pixclk = intel_mode_max_pixclk(dev, state);
5922
5923         if (max_pixclk < 0)
5924                 return max_pixclk;
5925
5926         to_intel_atomic_state(state)->cdclk =
5927                 broxton_calc_cdclk(dev_priv, max_pixclk);
5928
5929         return 0;
5930 }
5931
5932 static void vlv_program_pfi_credits(struct drm_i915_private *dev_priv)
5933 {
5934         unsigned int credits, default_credits;
5935
5936         if (IS_CHERRYVIEW(dev_priv))
5937                 default_credits = PFI_CREDIT(12);
5938         else
5939                 default_credits = PFI_CREDIT(8);
5940
5941         if (DIV_ROUND_CLOSEST(dev_priv->cdclk_freq, 1000) >= dev_priv->rps.cz_freq) {
5942                 /* CHV suggested value is 31 or 63 */
5943                 if (IS_CHERRYVIEW(dev_priv))
5944                         credits = PFI_CREDIT_63;
5945                 else
5946                         credits = PFI_CREDIT(15);
5947         } else {
5948                 credits = default_credits;
5949         }
5950
5951         /*
5952          * WA - write default credits before re-programming
5953          * FIXME: should we also set the resend bit here?
5954          */
5955         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
5956                    default_credits);
5957
5958         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
5959                    credits | PFI_CREDIT_RESEND);
5960
5961         /*
5962          * FIXME is this guaranteed to clear
5963          * immediately or should we poll for it?
5964          */
5965         WARN_ON(I915_READ(GCI_CONTROL) & PFI_CREDIT_RESEND);
5966 }
5967
5968 static void valleyview_modeset_commit_cdclk(struct drm_atomic_state *old_state)
5969 {
5970         struct drm_device *dev = old_state->dev;
5971         unsigned int req_cdclk = to_intel_atomic_state(old_state)->cdclk;
5972         struct drm_i915_private *dev_priv = dev->dev_private;
5973
5974         /*
5975          * FIXME: We can end up here with all power domains off, yet
5976          * with a CDCLK frequency other than the minimum. To account
5977          * for this take the PIPE-A power domain, which covers the HW
5978          * blocks needed for the following programming. This can be
5979          * removed once it's guaranteed that we get here either with
5980          * the minimum CDCLK set, or the required power domains
5981          * enabled.
5982          */
5983         intel_display_power_get(dev_priv, POWER_DOMAIN_PIPE_A);
5984
5985         if (IS_CHERRYVIEW(dev))
5986                 cherryview_set_cdclk(dev, req_cdclk);
5987         else
5988                 valleyview_set_cdclk(dev, req_cdclk);
5989
5990         vlv_program_pfi_credits(dev_priv);
5991
5992         intel_display_power_put(dev_priv, POWER_DOMAIN_PIPE_A);
5993 }
5994
5995 static void valleyview_crtc_enable(struct drm_crtc *crtc)
5996 {
5997         struct drm_device *dev = crtc->dev;
5998         struct drm_i915_private *dev_priv = to_i915(dev);
5999         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6000         struct intel_encoder *encoder;
6001         int pipe = intel_crtc->pipe;
6002         bool is_dsi;
6003
6004         if (WARN_ON(intel_crtc->active))
6005                 return;
6006
6007         is_dsi = intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_DSI);
6008
6009         if (intel_crtc->config->has_dp_encoder)
6010                 intel_dp_set_m_n(intel_crtc, M1_N1);
6011
6012         intel_set_pipe_timings(intel_crtc);
6013
6014         if (IS_CHERRYVIEW(dev) && pipe == PIPE_B) {
6015                 struct drm_i915_private *dev_priv = dev->dev_private;
6016
6017                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6018                 I915_WRITE(CHV_CANVAS(pipe), 0);
6019         }
6020
6021         i9xx_set_pipeconf(intel_crtc);
6022
6023         intel_crtc->active = true;
6024
6025         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6026
6027         for_each_encoder_on_crtc(dev, crtc, encoder)
6028                 if (encoder->pre_pll_enable)
6029                         encoder->pre_pll_enable(encoder);
6030
6031         if (!is_dsi) {
6032                 if (IS_CHERRYVIEW(dev)) {
6033                         chv_prepare_pll(intel_crtc, intel_crtc->config);
6034                         chv_enable_pll(intel_crtc, intel_crtc->config);
6035                 } else {
6036                         vlv_prepare_pll(intel_crtc, intel_crtc->config);
6037                         vlv_enable_pll(intel_crtc, intel_crtc->config);
6038                 }
6039         }
6040
6041         for_each_encoder_on_crtc(dev, crtc, encoder)
6042                 if (encoder->pre_enable)
6043                         encoder->pre_enable(encoder);
6044
6045         i9xx_pfit_enable(intel_crtc);
6046
6047         intel_crtc_load_lut(crtc);
6048
6049         intel_enable_pipe(intel_crtc);
6050
6051         assert_vblank_disabled(crtc);
6052         drm_crtc_vblank_on(crtc);
6053
6054         for_each_encoder_on_crtc(dev, crtc, encoder)
6055                 encoder->enable(encoder);
6056 }
6057
6058 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
6059 {
6060         struct drm_device *dev = crtc->base.dev;
6061         struct drm_i915_private *dev_priv = dev->dev_private;
6062
6063         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
6064         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
6065 }
6066
6067 static void i9xx_crtc_enable(struct drm_crtc *crtc)
6068 {
6069         struct drm_device *dev = crtc->dev;
6070         struct drm_i915_private *dev_priv = to_i915(dev);
6071         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6072         struct intel_encoder *encoder;
6073         int pipe = intel_crtc->pipe;
6074
6075         if (WARN_ON(intel_crtc->active))
6076                 return;
6077
6078         i9xx_set_pll_dividers(intel_crtc);
6079
6080         if (intel_crtc->config->has_dp_encoder)
6081                 intel_dp_set_m_n(intel_crtc, M1_N1);
6082
6083         intel_set_pipe_timings(intel_crtc);
6084
6085         i9xx_set_pipeconf(intel_crtc);
6086
6087         intel_crtc->active = true;
6088
6089         if (!IS_GEN2(dev))
6090                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6091
6092         for_each_encoder_on_crtc(dev, crtc, encoder)
6093                 if (encoder->pre_enable)
6094                         encoder->pre_enable(encoder);
6095
6096         i9xx_enable_pll(intel_crtc);
6097
6098         i9xx_pfit_enable(intel_crtc);
6099
6100         intel_crtc_load_lut(crtc);
6101
6102         intel_update_watermarks(crtc);
6103         intel_enable_pipe(intel_crtc);
6104
6105         assert_vblank_disabled(crtc);
6106         drm_crtc_vblank_on(crtc);
6107
6108         for_each_encoder_on_crtc(dev, crtc, encoder)
6109                 encoder->enable(encoder);
6110 }
6111
6112 static void i9xx_pfit_disable(struct intel_crtc *crtc)
6113 {
6114         struct drm_device *dev = crtc->base.dev;
6115         struct drm_i915_private *dev_priv = dev->dev_private;
6116
6117         if (!crtc->config->gmch_pfit.control)
6118                 return;
6119
6120         assert_pipe_disabled(dev_priv, crtc->pipe);
6121
6122         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
6123                          I915_READ(PFIT_CONTROL));
6124         I915_WRITE(PFIT_CONTROL, 0);
6125 }
6126
6127 static void i9xx_crtc_disable(struct drm_crtc *crtc)
6128 {
6129         struct drm_device *dev = crtc->dev;
6130         struct drm_i915_private *dev_priv = dev->dev_private;
6131         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6132         struct intel_encoder *encoder;
6133         int pipe = intel_crtc->pipe;
6134
6135         /*
6136          * On gen2 planes are double buffered but the pipe isn't, so we must
6137          * wait for planes to fully turn off before disabling the pipe.
6138          * We also need to wait on all gmch platforms because of the
6139          * self-refresh mode constraint explained above.
6140          */
6141         intel_wait_for_vblank(dev, pipe);
6142
6143         for_each_encoder_on_crtc(dev, crtc, encoder)
6144                 encoder->disable(encoder);
6145
6146         drm_crtc_vblank_off(crtc);
6147         assert_vblank_disabled(crtc);
6148
6149         intel_disable_pipe(intel_crtc);
6150
6151         i9xx_pfit_disable(intel_crtc);
6152
6153         for_each_encoder_on_crtc(dev, crtc, encoder)
6154                 if (encoder->post_disable)
6155                         encoder->post_disable(encoder);
6156
6157         if (!intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_DSI)) {
6158                 if (IS_CHERRYVIEW(dev))
6159                         chv_disable_pll(dev_priv, pipe);
6160                 else if (IS_VALLEYVIEW(dev))
6161                         vlv_disable_pll(dev_priv, pipe);
6162                 else
6163                         i9xx_disable_pll(intel_crtc);
6164         }
6165
6166         for_each_encoder_on_crtc(dev, crtc, encoder)
6167                 if (encoder->post_pll_disable)
6168                         encoder->post_pll_disable(encoder);
6169
6170         if (!IS_GEN2(dev))
6171                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6172
6173         intel_crtc->active = false;
6174         intel_update_watermarks(crtc);
6175 }
6176
6177 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc)
6178 {
6179         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6180         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6181         enum intel_display_power_domain domain;
6182         unsigned long domains;
6183
6184         if (!intel_crtc->active)
6185                 return;
6186
6187         if (to_intel_plane_state(crtc->primary->state)->visible) {
6188                 intel_crtc_wait_for_pending_flips(crtc);
6189                 intel_pre_disable_primary(crtc);
6190         }
6191
6192         intel_crtc_disable_planes(crtc, crtc->state->plane_mask);
6193         dev_priv->display.crtc_disable(crtc);
6194         intel_disable_shared_dpll(intel_crtc);
6195
6196         domains = intel_crtc->enabled_power_domains;
6197         for_each_power_domain(domain, domains)
6198                 intel_display_power_put(dev_priv, domain);
6199         intel_crtc->enabled_power_domains = 0;
6200 }
6201
6202 /*
6203  * turn all crtc's off, but do not adjust state
6204  * This has to be paired with a call to intel_modeset_setup_hw_state.
6205  */
6206 int intel_display_suspend(struct drm_device *dev)
6207 {
6208         struct drm_mode_config *config = &dev->mode_config;
6209         struct drm_modeset_acquire_ctx *ctx = config->acquire_ctx;
6210         struct drm_atomic_state *state;
6211         struct drm_crtc *crtc;
6212         unsigned crtc_mask = 0;
6213         int ret = 0;
6214
6215         if (WARN_ON(!ctx))
6216                 return 0;
6217
6218         lockdep_assert_held(&ctx->ww_ctx);
6219         state = drm_atomic_state_alloc(dev);
6220         if (WARN_ON(!state))
6221                 return -ENOMEM;
6222
6223         state->acquire_ctx = ctx;
6224         state->allow_modeset = true;
6225
6226         for_each_crtc(dev, crtc) {
6227                 struct drm_crtc_state *crtc_state =
6228                         drm_atomic_get_crtc_state(state, crtc);
6229
6230                 ret = PTR_ERR_OR_ZERO(crtc_state);
6231                 if (ret)
6232                         goto free;
6233
6234                 if (!crtc_state->active)
6235                         continue;
6236
6237                 crtc_state->active = false;
6238                 crtc_mask |= 1 << drm_crtc_index(crtc);
6239         }
6240
6241         if (crtc_mask) {
6242                 ret = drm_atomic_commit(state);
6243
6244                 if (!ret) {
6245                         for_each_crtc(dev, crtc)
6246                                 if (crtc_mask & (1 << drm_crtc_index(crtc)))
6247                                         crtc->state->active = true;
6248
6249                         return ret;
6250                 }
6251         }
6252
6253 free:
6254         if (ret)
6255                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6256         drm_atomic_state_free(state);
6257         return ret;
6258 }
6259
6260 void intel_encoder_destroy(struct drm_encoder *encoder)
6261 {
6262         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6263
6264         drm_encoder_cleanup(encoder);
6265         kfree(intel_encoder);
6266 }
6267
6268 /* Cross check the actual hw state with our own modeset state tracking (and it's
6269  * internal consistency). */
6270 static void intel_connector_check_state(struct intel_connector *connector)
6271 {
6272         struct drm_crtc *crtc = connector->base.state->crtc;
6273
6274         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6275                       connector->base.base.id,
6276                       connector->base.name);
6277
6278         if (connector->get_hw_state(connector)) {
6279                 struct drm_encoder *encoder = &connector->encoder->base;
6280                 struct drm_connector_state *conn_state = connector->base.state;
6281
6282                 I915_STATE_WARN(!crtc,
6283                          "connector enabled without attached crtc\n");
6284
6285                 if (!crtc)
6286                         return;
6287
6288                 I915_STATE_WARN(!crtc->state->active,
6289                       "connector is active, but attached crtc isn't\n");
6290
6291                 if (!encoder)
6292                         return;
6293
6294                 I915_STATE_WARN(conn_state->best_encoder != encoder,
6295                         "atomic encoder doesn't match attached encoder\n");
6296
6297                 I915_STATE_WARN(conn_state->crtc != encoder->crtc,
6298                         "attached encoder crtc differs from connector crtc\n");
6299         } else {
6300                 I915_STATE_WARN(crtc && crtc->state->active,
6301                         "attached crtc is active, but connector isn't\n");
6302                 I915_STATE_WARN(!crtc && connector->base.state->best_encoder,
6303                         "best encoder set without crtc!\n");
6304         }
6305 }
6306
6307 int intel_connector_init(struct intel_connector *connector)
6308 {
6309         struct drm_connector_state *connector_state;
6310
6311         connector_state = kzalloc(sizeof *connector_state, GFP_KERNEL);
6312         if (!connector_state)
6313                 return -ENOMEM;
6314
6315         connector->base.state = connector_state;
6316         return 0;
6317 }
6318
6319 struct intel_connector *intel_connector_alloc(void)
6320 {
6321         struct intel_connector *connector;
6322
6323         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6324         if (!connector)
6325                 return NULL;
6326
6327         if (intel_connector_init(connector) < 0) {
6328                 kfree(connector);
6329                 return NULL;
6330         }
6331
6332         return connector;
6333 }
6334
6335 /* Simple connector->get_hw_state implementation for encoders that support only
6336  * one connector and no cloning and hence the encoder state determines the state
6337  * of the connector. */
6338 bool intel_connector_get_hw_state(struct intel_connector *connector)
6339 {
6340         enum pipe pipe = 0;
6341         struct intel_encoder *encoder = connector->encoder;
6342
6343         return encoder->get_hw_state(encoder, &pipe);
6344 }
6345
6346 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6347 {
6348         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6349                 return crtc_state->fdi_lanes;
6350
6351         return 0;
6352 }
6353
6354 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6355                                      struct intel_crtc_state *pipe_config)
6356 {
6357         struct drm_atomic_state *state = pipe_config->base.state;
6358         struct intel_crtc *other_crtc;
6359         struct intel_crtc_state *other_crtc_state;
6360
6361         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6362                       pipe_name(pipe), pipe_config->fdi_lanes);
6363         if (pipe_config->fdi_lanes > 4) {
6364                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6365                               pipe_name(pipe), pipe_config->fdi_lanes);
6366                 return -EINVAL;
6367         }
6368
6369         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
6370                 if (pipe_config->fdi_lanes > 2) {
6371                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6372                                       pipe_config->fdi_lanes);
6373                         return -EINVAL;
6374                 } else {
6375                         return 0;
6376                 }
6377         }
6378
6379         if (INTEL_INFO(dev)->num_pipes == 2)
6380                 return 0;
6381
6382         /* Ivybridge 3 pipe is really complicated */
6383         switch (pipe) {
6384         case PIPE_A:
6385                 return 0;
6386         case PIPE_B:
6387                 if (pipe_config->fdi_lanes <= 2)
6388                         return 0;
6389
6390                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_C));
6391                 other_crtc_state =
6392                         intel_atomic_get_crtc_state(state, other_crtc);
6393                 if (IS_ERR(other_crtc_state))
6394                         return PTR_ERR(other_crtc_state);
6395
6396                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6397                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6398                                       pipe_name(pipe), pipe_config->fdi_lanes);
6399                         return -EINVAL;
6400                 }
6401                 return 0;
6402         case PIPE_C:
6403                 if (pipe_config->fdi_lanes > 2) {
6404                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6405                                       pipe_name(pipe), pipe_config->fdi_lanes);
6406                         return -EINVAL;
6407                 }
6408
6409                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_B));
6410                 other_crtc_state =
6411                         intel_atomic_get_crtc_state(state, other_crtc);
6412                 if (IS_ERR(other_crtc_state))
6413                         return PTR_ERR(other_crtc_state);
6414
6415                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6416                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6417                         return -EINVAL;
6418                 }
6419                 return 0;
6420         default:
6421                 BUG();
6422         }
6423 }
6424
6425 #define RETRY 1
6426 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6427                                        struct intel_crtc_state *pipe_config)
6428 {
6429         struct drm_device *dev = intel_crtc->base.dev;
6430         struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6431         int lane, link_bw, fdi_dotclock, ret;
6432         bool needs_recompute = false;
6433
6434 retry:
6435         /* FDI is a binary signal running at ~2.7GHz, encoding
6436          * each output octet as 10 bits. The actual frequency
6437          * is stored as a divider into a 100MHz clock, and the
6438          * mode pixel clock is stored in units of 1KHz.
6439          * Hence the bw of each lane in terms of the mode signal
6440          * is:
6441          */
6442         link_bw = intel_fdi_link_freq(dev) * MHz(100)/KHz(1)/10;
6443
6444         fdi_dotclock = adjusted_mode->crtc_clock;
6445
6446         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6447                                            pipe_config->pipe_bpp);
6448
6449         pipe_config->fdi_lanes = lane;
6450
6451         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6452                                link_bw, &pipe_config->fdi_m_n);
6453
6454         ret = ironlake_check_fdi_lanes(intel_crtc->base.dev,
6455                                        intel_crtc->pipe, pipe_config);
6456         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6457                 pipe_config->pipe_bpp -= 2*3;
6458                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6459                               pipe_config->pipe_bpp);
6460                 needs_recompute = true;
6461                 pipe_config->bw_constrained = true;
6462
6463                 goto retry;
6464         }
6465
6466         if (needs_recompute)
6467                 return RETRY;
6468
6469         return ret;
6470 }
6471
6472 static bool pipe_config_supports_ips(struct drm_i915_private *dev_priv,
6473                                      struct intel_crtc_state *pipe_config)
6474 {
6475         if (pipe_config->pipe_bpp > 24)
6476                 return false;
6477
6478         /* HSW can handle pixel rate up to cdclk? */
6479         if (IS_HASWELL(dev_priv->dev))
6480                 return true;
6481
6482         /*
6483          * We compare against max which means we must take
6484          * the increased cdclk requirement into account when
6485          * calculating the new cdclk.
6486          *
6487          * Should measure whether using a lower cdclk w/o IPS
6488          */
6489         return ilk_pipe_pixel_rate(pipe_config) <=
6490                 dev_priv->max_cdclk_freq * 95 / 100;
6491 }
6492
6493 static void hsw_compute_ips_config(struct intel_crtc *crtc,
6494                                    struct intel_crtc_state *pipe_config)
6495 {
6496         struct drm_device *dev = crtc->base.dev;
6497         struct drm_i915_private *dev_priv = dev->dev_private;
6498
6499         pipe_config->ips_enabled = i915.enable_ips &&
6500                 hsw_crtc_supports_ips(crtc) &&
6501                 pipe_config_supports_ips(dev_priv, pipe_config);
6502 }
6503
6504 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6505                                      struct intel_crtc_state *pipe_config)
6506 {
6507         struct drm_device *dev = crtc->base.dev;
6508         struct drm_i915_private *dev_priv = dev->dev_private;
6509         struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6510
6511         /* FIXME should check pixel clock limits on all platforms */
6512         if (INTEL_INFO(dev)->gen < 4) {
6513                 int clock_limit = dev_priv->max_cdclk_freq;
6514
6515                 /*
6516                  * Enable pixel doubling when the dot clock
6517                  * is > 90% of the (display) core speed.
6518                  *
6519                  * GDG double wide on either pipe,
6520                  * otherwise pipe A only.
6521                  */
6522                 if ((crtc->pipe == PIPE_A || IS_I915G(dev)) &&
6523                     adjusted_mode->crtc_clock > clock_limit * 9 / 10) {
6524                         clock_limit *= 2;
6525                         pipe_config->double_wide = true;
6526                 }
6527
6528                 if (adjusted_mode->crtc_clock > clock_limit * 9 / 10)
6529                         return -EINVAL;
6530         }
6531
6532         /*
6533          * Pipe horizontal size must be even in:
6534          * - DVO ganged mode
6535          * - LVDS dual channel mode
6536          * - Double wide pipe
6537          */
6538         if ((intel_pipe_will_have_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6539              intel_is_dual_link_lvds(dev)) || pipe_config->double_wide)
6540                 pipe_config->pipe_src_w &= ~1;
6541
6542         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6543          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6544          */
6545         if ((INTEL_INFO(dev)->gen > 4 || IS_G4X(dev)) &&
6546                 adjusted_mode->hsync_start == adjusted_mode->hdisplay)
6547                 return -EINVAL;
6548
6549         if (HAS_IPS(dev))
6550                 hsw_compute_ips_config(crtc, pipe_config);
6551
6552         if (pipe_config->has_pch_encoder)
6553                 return ironlake_fdi_compute_config(crtc, pipe_config);
6554
6555         return 0;
6556 }
6557
6558 static int skylake_get_display_clock_speed(struct drm_device *dev)
6559 {
6560         struct drm_i915_private *dev_priv = to_i915(dev);
6561         uint32_t lcpll1 = I915_READ(LCPLL1_CTL);
6562         uint32_t cdctl = I915_READ(CDCLK_CTL);
6563         uint32_t linkrate;
6564
6565         if (!(lcpll1 & LCPLL_PLL_ENABLE))
6566                 return 24000; /* 24MHz is the cd freq with NSSC ref */
6567
6568         if ((cdctl & CDCLK_FREQ_SEL_MASK) == CDCLK_FREQ_540)
6569                 return 540000;
6570
6571         linkrate = (I915_READ(DPLL_CTRL1) &
6572                     DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0)) >> 1;
6573
6574         if (linkrate == DPLL_CTRL1_LINK_RATE_2160 ||
6575             linkrate == DPLL_CTRL1_LINK_RATE_1080) {
6576                 /* vco 8640 */
6577                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6578                 case CDCLK_FREQ_450_432:
6579                         return 432000;
6580                 case CDCLK_FREQ_337_308:
6581                         return 308570;
6582                 case CDCLK_FREQ_675_617:
6583                         return 617140;
6584                 default:
6585                         WARN(1, "Unknown cd freq selection\n");
6586                 }
6587         } else {
6588                 /* vco 8100 */
6589                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6590                 case CDCLK_FREQ_450_432:
6591                         return 450000;
6592                 case CDCLK_FREQ_337_308:
6593                         return 337500;
6594                 case CDCLK_FREQ_675_617:
6595                         return 675000;
6596                 default:
6597                         WARN(1, "Unknown cd freq selection\n");
6598                 }
6599         }
6600
6601         /* error case, do as if DPLL0 isn't enabled */
6602         return 24000;
6603 }
6604
6605 static int broxton_get_display_clock_speed(struct drm_device *dev)
6606 {
6607         struct drm_i915_private *dev_priv = to_i915(dev);
6608         uint32_t cdctl = I915_READ(CDCLK_CTL);
6609         uint32_t pll_ratio = I915_READ(BXT_DE_PLL_CTL) & BXT_DE_PLL_RATIO_MASK;
6610         uint32_t pll_enab = I915_READ(BXT_DE_PLL_ENABLE);
6611         int cdclk;
6612
6613         if (!(pll_enab & BXT_DE_PLL_PLL_ENABLE))
6614                 return 19200;
6615
6616         cdclk = 19200 * pll_ratio / 2;
6617
6618         switch (cdctl & BXT_CDCLK_CD2X_DIV_SEL_MASK) {
6619         case BXT_CDCLK_CD2X_DIV_SEL_1:
6620                 return cdclk;  /* 576MHz or 624MHz */
6621         case BXT_CDCLK_CD2X_DIV_SEL_1_5:
6622                 return cdclk * 2 / 3; /* 384MHz */
6623         case BXT_CDCLK_CD2X_DIV_SEL_2:
6624                 return cdclk / 2; /* 288MHz */
6625         case BXT_CDCLK_CD2X_DIV_SEL_4:
6626                 return cdclk / 4; /* 144MHz */
6627         }
6628
6629         /* error case, do as if DE PLL isn't enabled */
6630         return 19200;
6631 }
6632
6633 static int broadwell_get_display_clock_speed(struct drm_device *dev)
6634 {
6635         struct drm_i915_private *dev_priv = dev->dev_private;
6636         uint32_t lcpll = I915_READ(LCPLL_CTL);
6637         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6638
6639         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6640                 return 800000;
6641         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6642                 return 450000;
6643         else if (freq == LCPLL_CLK_FREQ_450)
6644                 return 450000;
6645         else if (freq == LCPLL_CLK_FREQ_54O_BDW)
6646                 return 540000;
6647         else if (freq == LCPLL_CLK_FREQ_337_5_BDW)
6648                 return 337500;
6649         else
6650                 return 675000;
6651 }
6652
6653 static int haswell_get_display_clock_speed(struct drm_device *dev)
6654 {
6655         struct drm_i915_private *dev_priv = dev->dev_private;
6656         uint32_t lcpll = I915_READ(LCPLL_CTL);
6657         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6658
6659         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6660                 return 800000;
6661         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6662                 return 450000;
6663         else if (freq == LCPLL_CLK_FREQ_450)
6664                 return 450000;
6665         else if (IS_HSW_ULT(dev))
6666                 return 337500;
6667         else
6668                 return 540000;
6669 }
6670
6671 static int valleyview_get_display_clock_speed(struct drm_device *dev)
6672 {
6673         struct drm_i915_private *dev_priv = dev->dev_private;
6674         u32 val;
6675         int divider;
6676
6677         if (dev_priv->hpll_freq == 0)
6678                 dev_priv->hpll_freq = valleyview_get_vco(dev_priv);
6679
6680         mutex_lock(&dev_priv->sb_lock);
6681         val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
6682         mutex_unlock(&dev_priv->sb_lock);
6683
6684         divider = val & DISPLAY_FREQUENCY_VALUES;
6685
6686         WARN((val & DISPLAY_FREQUENCY_STATUS) !=
6687              (divider << DISPLAY_FREQUENCY_STATUS_SHIFT),
6688              "cdclk change in progress\n");
6689
6690         return DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, divider + 1);
6691 }
6692
6693 static int ilk_get_display_clock_speed(struct drm_device *dev)
6694 {
6695         return 450000;
6696 }
6697
6698 static int i945_get_display_clock_speed(struct drm_device *dev)
6699 {
6700         return 400000;
6701 }
6702
6703 static int i915_get_display_clock_speed(struct drm_device *dev)
6704 {
6705         return 333333;
6706 }
6707
6708 static int i9xx_misc_get_display_clock_speed(struct drm_device *dev)
6709 {
6710         return 200000;
6711 }
6712
6713 static int pnv_get_display_clock_speed(struct drm_device *dev)
6714 {
6715         u16 gcfgc = 0;
6716
6717         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6718
6719         switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6720         case GC_DISPLAY_CLOCK_267_MHZ_PNV:
6721                 return 266667;
6722         case GC_DISPLAY_CLOCK_333_MHZ_PNV:
6723                 return 333333;
6724         case GC_DISPLAY_CLOCK_444_MHZ_PNV:
6725                 return 444444;
6726         case GC_DISPLAY_CLOCK_200_MHZ_PNV:
6727                 return 200000;
6728         default:
6729                 DRM_ERROR("Unknown pnv display core clock 0x%04x\n", gcfgc);
6730         case GC_DISPLAY_CLOCK_133_MHZ_PNV:
6731                 return 133333;
6732         case GC_DISPLAY_CLOCK_167_MHZ_PNV:
6733                 return 166667;
6734         }
6735 }
6736
6737 static int i915gm_get_display_clock_speed(struct drm_device *dev)
6738 {
6739         u16 gcfgc = 0;
6740
6741         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6742
6743         if (gcfgc & GC_LOW_FREQUENCY_ENABLE)
6744                 return 133333;
6745         else {
6746                 switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6747                 case GC_DISPLAY_CLOCK_333_MHZ:
6748                         return 333333;
6749                 default:
6750                 case GC_DISPLAY_CLOCK_190_200_MHZ:
6751                         return 190000;
6752                 }
6753         }
6754 }
6755
6756 static int i865_get_display_clock_speed(struct drm_device *dev)
6757 {
6758         return 266667;
6759 }
6760
6761 static int i85x_get_display_clock_speed(struct drm_device *dev)
6762 {
6763         u16 hpllcc = 0;
6764
6765         /*
6766          * 852GM/852GMV only supports 133 MHz and the HPLLCC
6767          * encoding is different :(
6768          * FIXME is this the right way to detect 852GM/852GMV?
6769          */
6770         if (dev->pdev->revision == 0x1)
6771                 return 133333;
6772
6773         pci_bus_read_config_word(dev->pdev->bus,
6774                                  PCI_DEVFN(0, 3), HPLLCC, &hpllcc);
6775
6776         /* Assume that the hardware is in the high speed state.  This
6777          * should be the default.
6778          */
6779         switch (hpllcc & GC_CLOCK_CONTROL_MASK) {
6780         case GC_CLOCK_133_200:
6781         case GC_CLOCK_133_200_2:
6782         case GC_CLOCK_100_200:
6783                 return 200000;
6784         case GC_CLOCK_166_250:
6785                 return 250000;
6786         case GC_CLOCK_100_133:
6787                 return 133333;
6788         case GC_CLOCK_133_266:
6789         case GC_CLOCK_133_266_2:
6790         case GC_CLOCK_166_266:
6791                 return 266667;
6792         }
6793
6794         /* Shouldn't happen */
6795         return 0;
6796 }
6797
6798 static int i830_get_display_clock_speed(struct drm_device *dev)
6799 {
6800         return 133333;
6801 }
6802
6803 static unsigned int intel_hpll_vco(struct drm_device *dev)
6804 {
6805         struct drm_i915_private *dev_priv = dev->dev_private;
6806         static const unsigned int blb_vco[8] = {
6807                 [0] = 3200000,
6808                 [1] = 4000000,
6809                 [2] = 5333333,
6810                 [3] = 4800000,
6811                 [4] = 6400000,
6812         };
6813         static const unsigned int pnv_vco[8] = {
6814                 [0] = 3200000,
6815                 [1] = 4000000,
6816                 [2] = 5333333,
6817                 [3] = 4800000,
6818                 [4] = 2666667,
6819         };
6820         static const unsigned int cl_vco[8] = {
6821                 [0] = 3200000,
6822                 [1] = 4000000,
6823                 [2] = 5333333,
6824                 [3] = 6400000,
6825                 [4] = 3333333,
6826                 [5] = 3566667,
6827                 [6] = 4266667,
6828         };
6829         static const unsigned int elk_vco[8] = {
6830                 [0] = 3200000,
6831                 [1] = 4000000,
6832                 [2] = 5333333,
6833                 [3] = 4800000,
6834         };
6835         static const unsigned int ctg_vco[8] = {
6836                 [0] = 3200000,
6837                 [1] = 4000000,
6838                 [2] = 5333333,
6839                 [3] = 6400000,
6840                 [4] = 2666667,
6841                 [5] = 4266667,
6842         };
6843         const unsigned int *vco_table;
6844         unsigned int vco;
6845         uint8_t tmp = 0;
6846
6847         /* FIXME other chipsets? */
6848         if (IS_GM45(dev))
6849                 vco_table = ctg_vco;
6850         else if (IS_G4X(dev))
6851                 vco_table = elk_vco;
6852         else if (IS_CRESTLINE(dev))
6853                 vco_table = cl_vco;
6854         else if (IS_PINEVIEW(dev))
6855                 vco_table = pnv_vco;
6856         else if (IS_G33(dev))
6857                 vco_table = blb_vco;
6858         else
6859                 return 0;
6860
6861         tmp = I915_READ(IS_MOBILE(dev) ? HPLLVCO_MOBILE : HPLLVCO);
6862
6863         vco = vco_table[tmp & 0x7];
6864         if (vco == 0)
6865                 DRM_ERROR("Bad HPLL VCO (HPLLVCO=0x%02x)\n", tmp);
6866         else
6867                 DRM_DEBUG_KMS("HPLL VCO %u kHz\n", vco);
6868
6869         return vco;
6870 }
6871
6872 static int gm45_get_display_clock_speed(struct drm_device *dev)
6873 {
6874         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
6875         uint16_t tmp = 0;
6876
6877         pci_read_config_word(dev->pdev, GCFGC, &tmp);
6878
6879         cdclk_sel = (tmp >> 12) & 0x1;
6880
6881         switch (vco) {
6882         case 2666667:
6883         case 4000000:
6884         case 5333333:
6885                 return cdclk_sel ? 333333 : 222222;
6886         case 3200000:
6887                 return cdclk_sel ? 320000 : 228571;
6888         default:
6889                 DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u, CFGC=0x%04x\n", vco, tmp);
6890                 return 222222;
6891         }
6892 }
6893
6894 static int i965gm_get_display_clock_speed(struct drm_device *dev)
6895 {
6896         static const uint8_t div_3200[] = { 16, 10,  8 };
6897         static const uint8_t div_4000[] = { 20, 12, 10 };
6898         static const uint8_t div_5333[] = { 24, 16, 14 };
6899         const uint8_t *div_table;
6900         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
6901         uint16_t tmp = 0;
6902
6903         pci_read_config_word(dev->pdev, GCFGC, &tmp);
6904
6905         cdclk_sel = ((tmp >> 8) & 0x1f) - 1;
6906
6907         if (cdclk_sel >= ARRAY_SIZE(div_3200))
6908                 goto fail;
6909
6910         switch (vco) {
6911         case 3200000:
6912                 div_table = div_3200;
6913                 break;
6914         case 4000000:
6915                 div_table = div_4000;
6916                 break;
6917         case 5333333:
6918                 div_table = div_5333;
6919                 break;
6920         default:
6921                 goto fail;
6922         }
6923
6924         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
6925
6926 fail:
6927         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%04x\n", vco, tmp);
6928         return 200000;
6929 }
6930
6931 static int g33_get_display_clock_speed(struct drm_device *dev)
6932 {
6933         static const uint8_t div_3200[] = { 12, 10,  8,  7, 5, 16 };
6934         static const uint8_t div_4000[] = { 14, 12, 10,  8, 6, 20 };
6935         static const uint8_t div_4800[] = { 20, 14, 12, 10, 8, 24 };
6936         static const uint8_t div_5333[] = { 20, 16, 12, 12, 8, 28 };
6937         const uint8_t *div_table;
6938         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
6939         uint16_t tmp = 0;
6940
6941         pci_read_config_word(dev->pdev, GCFGC, &tmp);
6942
6943         cdclk_sel = (tmp >> 4) & 0x7;
6944
6945         if (cdclk_sel >= ARRAY_SIZE(div_3200))
6946                 goto fail;
6947
6948         switch (vco) {
6949         case 3200000:
6950                 div_table = div_3200;
6951                 break;
6952         case 4000000:
6953                 div_table = div_4000;
6954                 break;
6955         case 4800000:
6956                 div_table = div_4800;
6957                 break;
6958         case 5333333:
6959                 div_table = div_5333;
6960                 break;
6961         default:
6962                 goto fail;
6963         }
6964
6965         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
6966
6967 fail:
6968         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%08x\n", vco, tmp);
6969         return 190476;
6970 }
6971
6972 static void
6973 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
6974 {
6975         while (*num > DATA_LINK_M_N_MASK ||
6976                *den > DATA_LINK_M_N_MASK) {
6977                 *num >>= 1;
6978                 *den >>= 1;
6979         }
6980 }
6981
6982 static void compute_m_n(unsigned int m, unsigned int n,
6983                         uint32_t *ret_m, uint32_t *ret_n)
6984 {
6985         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
6986         *ret_m = div_u64((uint64_t) m * *ret_n, n);
6987         intel_reduce_m_n_ratio(ret_m, ret_n);
6988 }
6989
6990 void
6991 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
6992                        int pixel_clock, int link_clock,
6993                        struct intel_link_m_n *m_n)
6994 {
6995         m_n->tu = 64;
6996
6997         compute_m_n(bits_per_pixel * pixel_clock,
6998                     link_clock * nlanes * 8,
6999                     &m_n->gmch_m, &m_n->gmch_n);
7000
7001         compute_m_n(pixel_clock, link_clock,
7002                     &m_n->link_m, &m_n->link_n);
7003 }
7004
7005 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
7006 {
7007         if (i915.panel_use_ssc >= 0)
7008                 return i915.panel_use_ssc != 0;
7009         return dev_priv->vbt.lvds_use_ssc
7010                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
7011 }
7012
7013 static int i9xx_get_refclk(const struct intel_crtc_state *crtc_state,
7014                            int num_connectors)
7015 {
7016         struct drm_device *dev = crtc_state->base.crtc->dev;
7017         struct drm_i915_private *dev_priv = dev->dev_private;
7018         int refclk;
7019
7020         WARN_ON(!crtc_state->base.state);
7021
7022         if (IS_VALLEYVIEW(dev) || IS_BROXTON(dev)) {
7023                 refclk = 100000;
7024         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7025             intel_panel_use_ssc(dev_priv) && num_connectors < 2) {
7026                 refclk = dev_priv->vbt.lvds_ssc_freq;
7027                 DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7028         } else if (!IS_GEN2(dev)) {
7029                 refclk = 96000;
7030         } else {
7031                 refclk = 48000;
7032         }
7033
7034         return refclk;
7035 }
7036
7037 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
7038 {
7039         return (1 << dpll->n) << 16 | dpll->m2;
7040 }
7041
7042 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
7043 {
7044         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
7045 }
7046
7047 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
7048                                      struct intel_crtc_state *crtc_state,
7049                                      intel_clock_t *reduced_clock)
7050 {
7051         struct drm_device *dev = crtc->base.dev;
7052         u32 fp, fp2 = 0;
7053
7054         if (IS_PINEVIEW(dev)) {
7055                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
7056                 if (reduced_clock)
7057                         fp2 = pnv_dpll_compute_fp(reduced_clock);
7058         } else {
7059                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
7060                 if (reduced_clock)
7061                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
7062         }
7063
7064         crtc_state->dpll_hw_state.fp0 = fp;
7065
7066         crtc->lowfreq_avail = false;
7067         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7068             reduced_clock) {
7069                 crtc_state->dpll_hw_state.fp1 = fp2;
7070                 crtc->lowfreq_avail = true;
7071         } else {
7072                 crtc_state->dpll_hw_state.fp1 = fp;
7073         }
7074 }
7075
7076 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
7077                 pipe)
7078 {
7079         u32 reg_val;
7080
7081         /*
7082          * PLLB opamp always calibrates to max value of 0x3f, force enable it
7083          * and set it to a reasonable value instead.
7084          */
7085         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7086         reg_val &= 0xffffff00;
7087         reg_val |= 0x00000030;
7088         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7089
7090         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7091         reg_val &= 0x8cffffff;
7092         reg_val = 0x8c000000;
7093         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7094
7095         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7096         reg_val &= 0xffffff00;
7097         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7098
7099         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7100         reg_val &= 0x00ffffff;
7101         reg_val |= 0xb0000000;
7102         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7103 }
7104
7105 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
7106                                          struct intel_link_m_n *m_n)
7107 {
7108         struct drm_device *dev = crtc->base.dev;
7109         struct drm_i915_private *dev_priv = dev->dev_private;
7110         int pipe = crtc->pipe;
7111
7112         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7113         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
7114         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
7115         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
7116 }
7117
7118 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
7119                                          struct intel_link_m_n *m_n,
7120                                          struct intel_link_m_n *m2_n2)
7121 {
7122         struct drm_device *dev = crtc->base.dev;
7123         struct drm_i915_private *dev_priv = dev->dev_private;
7124         int pipe = crtc->pipe;
7125         enum transcoder transcoder = crtc->config->cpu_transcoder;
7126
7127         if (INTEL_INFO(dev)->gen >= 5) {
7128                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
7129                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
7130                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
7131                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
7132                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
7133                  * for gen < 8) and if DRRS is supported (to make sure the
7134                  * registers are not unnecessarily accessed).
7135                  */
7136                 if (m2_n2 && (IS_CHERRYVIEW(dev) || INTEL_INFO(dev)->gen < 8) &&
7137                         crtc->config->has_drrs) {
7138                         I915_WRITE(PIPE_DATA_M2(transcoder),
7139                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
7140                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
7141                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
7142                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
7143                 }
7144         } else {
7145                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7146                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
7147                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
7148                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
7149         }
7150 }
7151
7152 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
7153 {
7154         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
7155
7156         if (m_n == M1_N1) {
7157                 dp_m_n = &crtc->config->dp_m_n;
7158                 dp_m2_n2 = &crtc->config->dp_m2_n2;
7159         } else if (m_n == M2_N2) {
7160
7161                 /*
7162                  * M2_N2 registers are not supported. Hence m2_n2 divider value
7163                  * needs to be programmed into M1_N1.
7164                  */
7165                 dp_m_n = &crtc->config->dp_m2_n2;
7166         } else {
7167                 DRM_ERROR("Unsupported divider value\n");
7168                 return;
7169         }
7170
7171         if (crtc->config->has_pch_encoder)
7172                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
7173         else
7174                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
7175 }
7176
7177 static void vlv_compute_dpll(struct intel_crtc *crtc,
7178                              struct intel_crtc_state *pipe_config)
7179 {
7180         u32 dpll, dpll_md;
7181
7182         /*
7183          * Enable DPIO clock input. We should never disable the reference
7184          * clock for pipe B, since VGA hotplug / manual detection depends
7185          * on it.
7186          */
7187         dpll = DPLL_EXT_BUFFER_ENABLE_VLV | DPLL_REF_CLK_ENABLE_VLV |
7188                 DPLL_VGA_MODE_DIS | DPLL_INTEGRATED_REF_CLK_VLV;
7189         /* We should never disable this, set it here for state tracking */
7190         if (crtc->pipe == PIPE_B)
7191                 dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7192         dpll |= DPLL_VCO_ENABLE;
7193         pipe_config->dpll_hw_state.dpll = dpll;
7194
7195         dpll_md = (pipe_config->pixel_multiplier - 1)
7196                 << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7197         pipe_config->dpll_hw_state.dpll_md = dpll_md;
7198 }
7199
7200 static void vlv_prepare_pll(struct intel_crtc *crtc,
7201                             const struct intel_crtc_state *pipe_config)
7202 {
7203         struct drm_device *dev = crtc->base.dev;
7204         struct drm_i915_private *dev_priv = dev->dev_private;
7205         int pipe = crtc->pipe;
7206         u32 mdiv;
7207         u32 bestn, bestm1, bestm2, bestp1, bestp2;
7208         u32 coreclk, reg_val;
7209
7210         mutex_lock(&dev_priv->sb_lock);
7211
7212         bestn = pipe_config->dpll.n;
7213         bestm1 = pipe_config->dpll.m1;
7214         bestm2 = pipe_config->dpll.m2;
7215         bestp1 = pipe_config->dpll.p1;
7216         bestp2 = pipe_config->dpll.p2;
7217
7218         /* See eDP HDMI DPIO driver vbios notes doc */
7219
7220         /* PLL B needs special handling */
7221         if (pipe == PIPE_B)
7222                 vlv_pllb_recal_opamp(dev_priv, pipe);
7223
7224         /* Set up Tx target for periodic Rcomp update */
7225         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
7226
7227         /* Disable target IRef on PLL */
7228         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
7229         reg_val &= 0x00ffffff;
7230         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
7231
7232         /* Disable fast lock */
7233         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
7234
7235         /* Set idtafcrecal before PLL is enabled */
7236         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
7237         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
7238         mdiv |= ((bestn << DPIO_N_SHIFT));
7239         mdiv |= (1 << DPIO_K_SHIFT);
7240
7241         /*
7242          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
7243          * but we don't support that).
7244          * Note: don't use the DAC post divider as it seems unstable.
7245          */
7246         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
7247         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7248
7249         mdiv |= DPIO_ENABLE_CALIBRATION;
7250         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7251
7252         /* Set HBR and RBR LPF coefficients */
7253         if (pipe_config->port_clock == 162000 ||
7254             intel_pipe_has_type(crtc, INTEL_OUTPUT_ANALOG) ||
7255             intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI))
7256                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7257                                  0x009f0003);
7258         else
7259                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7260                                  0x00d0000f);
7261
7262         if (pipe_config->has_dp_encoder) {
7263                 /* Use SSC source */
7264                 if (pipe == PIPE_A)
7265                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7266                                          0x0df40000);
7267                 else
7268                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7269                                          0x0df70000);
7270         } else { /* HDMI or VGA */
7271                 /* Use bend source */
7272                 if (pipe == PIPE_A)
7273                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7274                                          0x0df70000);
7275                 else
7276                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7277                                          0x0df40000);
7278         }
7279
7280         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
7281         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
7282         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DISPLAYPORT) ||
7283             intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP))
7284                 coreclk |= 0x01000000;
7285         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
7286
7287         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
7288         mutex_unlock(&dev_priv->sb_lock);
7289 }
7290
7291 static void chv_compute_dpll(struct intel_crtc *crtc,
7292                              struct intel_crtc_state *pipe_config)
7293 {
7294         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
7295                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS |
7296                 DPLL_VCO_ENABLE;
7297         if (crtc->pipe != PIPE_A)
7298                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7299
7300         pipe_config->dpll_hw_state.dpll_md =
7301                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7302 }
7303
7304 static void chv_prepare_pll(struct intel_crtc *crtc,
7305                             const struct intel_crtc_state *pipe_config)
7306 {
7307         struct drm_device *dev = crtc->base.dev;
7308         struct drm_i915_private *dev_priv = dev->dev_private;
7309         int pipe = crtc->pipe;
7310         int dpll_reg = DPLL(crtc->pipe);
7311         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7312         u32 loopfilter, tribuf_calcntr;
7313         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
7314         u32 dpio_val;
7315         int vco;
7316
7317         bestn = pipe_config->dpll.n;
7318         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
7319         bestm1 = pipe_config->dpll.m1;
7320         bestm2 = pipe_config->dpll.m2 >> 22;
7321         bestp1 = pipe_config->dpll.p1;
7322         bestp2 = pipe_config->dpll.p2;
7323         vco = pipe_config->dpll.vco;
7324         dpio_val = 0;
7325         loopfilter = 0;
7326
7327         /*
7328          * Enable Refclk and SSC
7329          */
7330         I915_WRITE(dpll_reg,
7331                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
7332
7333         mutex_lock(&dev_priv->sb_lock);
7334
7335         /* p1 and p2 divider */
7336         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
7337                         5 << DPIO_CHV_S1_DIV_SHIFT |
7338                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
7339                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
7340                         1 << DPIO_CHV_K_DIV_SHIFT);
7341
7342         /* Feedback post-divider - m2 */
7343         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
7344
7345         /* Feedback refclk divider - n and m1 */
7346         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
7347                         DPIO_CHV_M1_DIV_BY_2 |
7348                         1 << DPIO_CHV_N_DIV_SHIFT);
7349
7350         /* M2 fraction division */
7351         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
7352
7353         /* M2 fraction division enable */
7354         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7355         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
7356         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
7357         if (bestm2_frac)
7358                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
7359         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
7360
7361         /* Program digital lock detect threshold */
7362         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
7363         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
7364                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
7365         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
7366         if (!bestm2_frac)
7367                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
7368         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
7369
7370         /* Loop filter */
7371         if (vco == 5400000) {
7372                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
7373                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
7374                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
7375                 tribuf_calcntr = 0x9;
7376         } else if (vco <= 6200000) {
7377                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
7378                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
7379                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7380                 tribuf_calcntr = 0x9;
7381         } else if (vco <= 6480000) {
7382                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7383                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7384                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7385                 tribuf_calcntr = 0x8;
7386         } else {
7387                 /* Not supported. Apply the same limits as in the max case */
7388                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7389                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7390                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7391                 tribuf_calcntr = 0;
7392         }
7393         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
7394
7395         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
7396         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
7397         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
7398         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
7399
7400         /* AFC Recal */
7401         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
7402                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
7403                         DPIO_AFC_RECAL);
7404
7405         mutex_unlock(&dev_priv->sb_lock);
7406 }
7407
7408 /**
7409  * vlv_force_pll_on - forcibly enable just the PLL
7410  * @dev_priv: i915 private structure
7411  * @pipe: pipe PLL to enable
7412  * @dpll: PLL configuration
7413  *
7414  * Enable the PLL for @pipe using the supplied @dpll config. To be used
7415  * in cases where we need the PLL enabled even when @pipe is not going to
7416  * be enabled.
7417  */
7418 void vlv_force_pll_on(struct drm_device *dev, enum pipe pipe,
7419                       const struct dpll *dpll)
7420 {
7421         struct intel_crtc *crtc =
7422                 to_intel_crtc(intel_get_crtc_for_pipe(dev, pipe));
7423         struct intel_crtc_state pipe_config = {
7424                 .base.crtc = &crtc->base,
7425                 .pixel_multiplier = 1,
7426                 .dpll = *dpll,
7427         };
7428
7429         if (IS_CHERRYVIEW(dev)) {
7430                 chv_compute_dpll(crtc, &pipe_config);
7431                 chv_prepare_pll(crtc, &pipe_config);
7432                 chv_enable_pll(crtc, &pipe_config);
7433         } else {
7434                 vlv_compute_dpll(crtc, &pipe_config);
7435                 vlv_prepare_pll(crtc, &pipe_config);
7436                 vlv_enable_pll(crtc, &pipe_config);
7437         }
7438 }
7439
7440 /**
7441  * vlv_force_pll_off - forcibly disable just the PLL
7442  * @dev_priv: i915 private structure
7443  * @pipe: pipe PLL to disable
7444  *
7445  * Disable the PLL for @pipe. To be used in cases where we need
7446  * the PLL enabled even when @pipe is not going to be enabled.
7447  */
7448 void vlv_force_pll_off(struct drm_device *dev, enum pipe pipe)
7449 {
7450         if (IS_CHERRYVIEW(dev))
7451                 chv_disable_pll(to_i915(dev), pipe);
7452         else
7453                 vlv_disable_pll(to_i915(dev), pipe);
7454 }
7455
7456 static void i9xx_compute_dpll(struct intel_crtc *crtc,
7457                               struct intel_crtc_state *crtc_state,
7458                               intel_clock_t *reduced_clock,
7459                               int num_connectors)
7460 {
7461         struct drm_device *dev = crtc->base.dev;
7462         struct drm_i915_private *dev_priv = dev->dev_private;
7463         u32 dpll;
7464         bool is_sdvo;
7465         struct dpll *clock = &crtc_state->dpll;
7466
7467         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7468
7469         is_sdvo = intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7470                 intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_HDMI);
7471
7472         dpll = DPLL_VGA_MODE_DIS;
7473
7474         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
7475                 dpll |= DPLLB_MODE_LVDS;
7476         else
7477                 dpll |= DPLLB_MODE_DAC_SERIAL;
7478
7479         if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
7480                 dpll |= (crtc_state->pixel_multiplier - 1)
7481                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7482         }
7483
7484         if (is_sdvo)
7485                 dpll |= DPLL_SDVO_HIGH_SPEED;
7486
7487         if (crtc_state->has_dp_encoder)
7488                 dpll |= DPLL_SDVO_HIGH_SPEED;
7489
7490         /* compute bitmask from p1 value */
7491         if (IS_PINEVIEW(dev))
7492                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7493         else {
7494                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7495                 if (IS_G4X(dev) && reduced_clock)
7496                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7497         }
7498         switch (clock->p2) {
7499         case 5:
7500                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7501                 break;
7502         case 7:
7503                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7504                 break;
7505         case 10:
7506                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7507                 break;
7508         case 14:
7509                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7510                 break;
7511         }
7512         if (INTEL_INFO(dev)->gen >= 4)
7513                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7514
7515         if (crtc_state->sdvo_tv_clock)
7516                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7517         else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7518                  intel_panel_use_ssc(dev_priv) && num_connectors < 2)
7519                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7520         else
7521                 dpll |= PLL_REF_INPUT_DREFCLK;
7522
7523         dpll |= DPLL_VCO_ENABLE;
7524         crtc_state->dpll_hw_state.dpll = dpll;
7525
7526         if (INTEL_INFO(dev)->gen >= 4) {
7527                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7528                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7529                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7530         }
7531 }
7532
7533 static void i8xx_compute_dpll(struct intel_crtc *crtc,
7534                               struct intel_crtc_state *crtc_state,
7535                               intel_clock_t *reduced_clock,
7536                               int num_connectors)
7537 {
7538         struct drm_device *dev = crtc->base.dev;
7539         struct drm_i915_private *dev_priv = dev->dev_private;
7540         u32 dpll;
7541         struct dpll *clock = &crtc_state->dpll;
7542
7543         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7544
7545         dpll = DPLL_VGA_MODE_DIS;
7546
7547         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7548                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7549         } else {
7550                 if (clock->p1 == 2)
7551                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7552                 else
7553                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7554                 if (clock->p2 == 4)
7555                         dpll |= PLL_P2_DIVIDE_BY_4;
7556         }
7557
7558         if (!IS_I830(dev) && intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_DVO))
7559                 dpll |= DPLL_DVO_2X_MODE;
7560
7561         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7562                  intel_panel_use_ssc(dev_priv) && num_connectors < 2)
7563                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7564         else
7565                 dpll |= PLL_REF_INPUT_DREFCLK;
7566
7567         dpll |= DPLL_VCO_ENABLE;
7568         crtc_state->dpll_hw_state.dpll = dpll;
7569 }
7570
7571 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
7572 {
7573         struct drm_device *dev = intel_crtc->base.dev;
7574         struct drm_i915_private *dev_priv = dev->dev_private;
7575         enum pipe pipe = intel_crtc->pipe;
7576         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
7577         struct drm_display_mode *adjusted_mode =
7578                 &intel_crtc->config->base.adjusted_mode;
7579         uint32_t crtc_vtotal, crtc_vblank_end;
7580         int vsyncshift = 0;
7581
7582         /* We need to be careful not to changed the adjusted mode, for otherwise
7583          * the hw state checker will get angry at the mismatch. */
7584         crtc_vtotal = adjusted_mode->crtc_vtotal;
7585         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7586
7587         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7588                 /* the chip adds 2 halflines automatically */
7589                 crtc_vtotal -= 1;
7590                 crtc_vblank_end -= 1;
7591
7592                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
7593                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7594                 else
7595                         vsyncshift = adjusted_mode->crtc_hsync_start -
7596                                 adjusted_mode->crtc_htotal / 2;
7597                 if (vsyncshift < 0)
7598                         vsyncshift += adjusted_mode->crtc_htotal;
7599         }
7600
7601         if (INTEL_INFO(dev)->gen > 3)
7602                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7603
7604         I915_WRITE(HTOTAL(cpu_transcoder),
7605                    (adjusted_mode->crtc_hdisplay - 1) |
7606                    ((adjusted_mode->crtc_htotal - 1) << 16));
7607         I915_WRITE(HBLANK(cpu_transcoder),
7608                    (adjusted_mode->crtc_hblank_start - 1) |
7609                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7610         I915_WRITE(HSYNC(cpu_transcoder),
7611                    (adjusted_mode->crtc_hsync_start - 1) |
7612                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7613
7614         I915_WRITE(VTOTAL(cpu_transcoder),
7615                    (adjusted_mode->crtc_vdisplay - 1) |
7616                    ((crtc_vtotal - 1) << 16));
7617         I915_WRITE(VBLANK(cpu_transcoder),
7618                    (adjusted_mode->crtc_vblank_start - 1) |
7619                    ((crtc_vblank_end - 1) << 16));
7620         I915_WRITE(VSYNC(cpu_transcoder),
7621                    (adjusted_mode->crtc_vsync_start - 1) |
7622                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7623
7624         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7625          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7626          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7627          * bits. */
7628         if (IS_HASWELL(dev) && cpu_transcoder == TRANSCODER_EDP &&
7629             (pipe == PIPE_B || pipe == PIPE_C))
7630                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7631
7632         /* pipesrc controls the size that is scaled from, which should
7633          * always be the user's requested size.
7634          */
7635         I915_WRITE(PIPESRC(pipe),
7636                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
7637                    (intel_crtc->config->pipe_src_h - 1));
7638 }
7639
7640 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7641                                    struct intel_crtc_state *pipe_config)
7642 {
7643         struct drm_device *dev = crtc->base.dev;
7644         struct drm_i915_private *dev_priv = dev->dev_private;
7645         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7646         uint32_t tmp;
7647
7648         tmp = I915_READ(HTOTAL(cpu_transcoder));
7649         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7650         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7651         tmp = I915_READ(HBLANK(cpu_transcoder));
7652         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7653         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7654         tmp = I915_READ(HSYNC(cpu_transcoder));
7655         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7656         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7657
7658         tmp = I915_READ(VTOTAL(cpu_transcoder));
7659         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7660         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7661         tmp = I915_READ(VBLANK(cpu_transcoder));
7662         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7663         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7664         tmp = I915_READ(VSYNC(cpu_transcoder));
7665         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7666         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7667
7668         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7669                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7670                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7671                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7672         }
7673
7674         tmp = I915_READ(PIPESRC(crtc->pipe));
7675         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7676         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7677
7678         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7679         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7680 }
7681
7682 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7683                                  struct intel_crtc_state *pipe_config)
7684 {
7685         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7686         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7687         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7688         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7689
7690         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7691         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7692         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7693         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7694
7695         mode->flags = pipe_config->base.adjusted_mode.flags;
7696         mode->type = DRM_MODE_TYPE_DRIVER;
7697
7698         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7699         mode->flags |= pipe_config->base.adjusted_mode.flags;
7700
7701         mode->hsync = drm_mode_hsync(mode);
7702         mode->vrefresh = drm_mode_vrefresh(mode);
7703         drm_mode_set_name(mode);
7704 }
7705
7706 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
7707 {
7708         struct drm_device *dev = intel_crtc->base.dev;
7709         struct drm_i915_private *dev_priv = dev->dev_private;
7710         uint32_t pipeconf;
7711
7712         pipeconf = 0;
7713
7714         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
7715             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
7716                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
7717
7718         if (intel_crtc->config->double_wide)
7719                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7720
7721         /* only g4x and later have fancy bpc/dither controls */
7722         if (IS_G4X(dev) || IS_VALLEYVIEW(dev)) {
7723                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7724                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
7725                         pipeconf |= PIPECONF_DITHER_EN |
7726                                     PIPECONF_DITHER_TYPE_SP;
7727
7728                 switch (intel_crtc->config->pipe_bpp) {
7729                 case 18:
7730                         pipeconf |= PIPECONF_6BPC;
7731                         break;
7732                 case 24:
7733                         pipeconf |= PIPECONF_8BPC;
7734                         break;
7735                 case 30:
7736                         pipeconf |= PIPECONF_10BPC;
7737                         break;
7738                 default:
7739                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7740                         BUG();
7741                 }
7742         }
7743
7744         if (HAS_PIPE_CXSR(dev)) {
7745                 if (intel_crtc->lowfreq_avail) {
7746                         DRM_DEBUG_KMS("enabling CxSR downclocking\n");
7747                         pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
7748                 } else {
7749                         DRM_DEBUG_KMS("disabling CxSR downclocking\n");
7750                 }
7751         }
7752
7753         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7754                 if (INTEL_INFO(dev)->gen < 4 ||
7755                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
7756                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7757                 else
7758                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7759         } else
7760                 pipeconf |= PIPECONF_PROGRESSIVE;
7761
7762         if (IS_VALLEYVIEW(dev) && intel_crtc->config->limited_color_range)
7763                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7764
7765         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
7766         POSTING_READ(PIPECONF(intel_crtc->pipe));
7767 }
7768
7769 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7770                                    struct intel_crtc_state *crtc_state)
7771 {
7772         struct drm_device *dev = crtc->base.dev;
7773         struct drm_i915_private *dev_priv = dev->dev_private;
7774         int refclk, num_connectors = 0;
7775         intel_clock_t clock;
7776         bool ok;
7777         bool is_dsi = false;
7778         struct intel_encoder *encoder;
7779         const intel_limit_t *limit;
7780         struct drm_atomic_state *state = crtc_state->base.state;
7781         struct drm_connector *connector;
7782         struct drm_connector_state *connector_state;
7783         int i;
7784
7785         memset(&crtc_state->dpll_hw_state, 0,
7786                sizeof(crtc_state->dpll_hw_state));
7787
7788         for_each_connector_in_state(state, connector, connector_state, i) {
7789                 if (connector_state->crtc != &crtc->base)
7790                         continue;
7791
7792                 encoder = to_intel_encoder(connector_state->best_encoder);
7793
7794                 switch (encoder->type) {
7795                 case INTEL_OUTPUT_DSI:
7796                         is_dsi = true;
7797                         break;
7798                 default:
7799                         break;
7800                 }
7801
7802                 num_connectors++;
7803         }
7804
7805         if (is_dsi)
7806                 return 0;
7807
7808         if (!crtc_state->clock_set) {
7809                 refclk = i9xx_get_refclk(crtc_state, num_connectors);
7810
7811                 /*
7812                  * Returns a set of divisors for the desired target clock with
7813                  * the given refclk, or FALSE.  The returned values represent
7814                  * the clock equation: reflck * (5 * (m1 + 2) + (m2 + 2)) / (n +
7815                  * 2) / p1 / p2.
7816                  */
7817                 limit = intel_limit(crtc_state, refclk);
7818                 ok = dev_priv->display.find_dpll(limit, crtc_state,
7819                                                  crtc_state->port_clock,
7820                                                  refclk, NULL, &clock);
7821                 if (!ok) {
7822                         DRM_ERROR("Couldn't find PLL settings for mode!\n");
7823                         return -EINVAL;
7824                 }
7825
7826                 /* Compat-code for transition, will disappear. */
7827                 crtc_state->dpll.n = clock.n;
7828                 crtc_state->dpll.m1 = clock.m1;
7829                 crtc_state->dpll.m2 = clock.m2;
7830                 crtc_state->dpll.p1 = clock.p1;
7831                 crtc_state->dpll.p2 = clock.p2;
7832         }
7833
7834         if (IS_GEN2(dev)) {
7835                 i8xx_compute_dpll(crtc, crtc_state, NULL,
7836                                   num_connectors);
7837         } else if (IS_CHERRYVIEW(dev)) {
7838                 chv_compute_dpll(crtc, crtc_state);
7839         } else if (IS_VALLEYVIEW(dev)) {
7840                 vlv_compute_dpll(crtc, crtc_state);
7841         } else {
7842                 i9xx_compute_dpll(crtc, crtc_state, NULL,
7843                                   num_connectors);
7844         }
7845
7846         return 0;
7847 }
7848
7849 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
7850                                  struct intel_crtc_state *pipe_config)
7851 {
7852         struct drm_device *dev = crtc->base.dev;
7853         struct drm_i915_private *dev_priv = dev->dev_private;
7854         uint32_t tmp;
7855
7856         if (INTEL_INFO(dev)->gen <= 3 && (IS_I830(dev) || !IS_MOBILE(dev)))
7857                 return;
7858
7859         tmp = I915_READ(PFIT_CONTROL);
7860         if (!(tmp & PFIT_ENABLE))
7861                 return;
7862
7863         /* Check whether the pfit is attached to our pipe. */
7864         if (INTEL_INFO(dev)->gen < 4) {
7865                 if (crtc->pipe != PIPE_B)
7866                         return;
7867         } else {
7868                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
7869                         return;
7870         }
7871
7872         pipe_config->gmch_pfit.control = tmp;
7873         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
7874         if (INTEL_INFO(dev)->gen < 5)
7875                 pipe_config->gmch_pfit.lvds_border_bits =
7876                         I915_READ(LVDS) & LVDS_BORDER_ENABLE;
7877 }
7878
7879 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
7880                                struct intel_crtc_state *pipe_config)
7881 {
7882         struct drm_device *dev = crtc->base.dev;
7883         struct drm_i915_private *dev_priv = dev->dev_private;
7884         int pipe = pipe_config->cpu_transcoder;
7885         intel_clock_t clock;
7886         u32 mdiv;
7887         int refclk = 100000;
7888
7889         /* In case of MIPI DPLL will not even be used */
7890         if (!(pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE))
7891                 return;
7892
7893         mutex_lock(&dev_priv->sb_lock);
7894         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
7895         mutex_unlock(&dev_priv->sb_lock);
7896
7897         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
7898         clock.m2 = mdiv & DPIO_M2DIV_MASK;
7899         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
7900         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
7901         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
7902
7903         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
7904 }
7905
7906 static void
7907 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
7908                               struct intel_initial_plane_config *plane_config)
7909 {
7910         struct drm_device *dev = crtc->base.dev;
7911         struct drm_i915_private *dev_priv = dev->dev_private;
7912         u32 val, base, offset;
7913         int pipe = crtc->pipe, plane = crtc->plane;
7914         int fourcc, pixel_format;
7915         unsigned int aligned_height;
7916         struct drm_framebuffer *fb;
7917         struct intel_framebuffer *intel_fb;
7918
7919         val = I915_READ(DSPCNTR(plane));
7920         if (!(val & DISPLAY_PLANE_ENABLE))
7921                 return;
7922
7923         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
7924         if (!intel_fb) {
7925                 DRM_DEBUG_KMS("failed to alloc fb\n");
7926                 return;
7927         }
7928
7929         fb = &intel_fb->base;
7930
7931         if (INTEL_INFO(dev)->gen >= 4) {
7932                 if (val & DISPPLANE_TILED) {
7933                         plane_config->tiling = I915_TILING_X;
7934                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
7935                 }
7936         }
7937
7938         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
7939         fourcc = i9xx_format_to_fourcc(pixel_format);
7940         fb->pixel_format = fourcc;
7941         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
7942
7943         if (INTEL_INFO(dev)->gen >= 4) {
7944                 if (plane_config->tiling)
7945                         offset = I915_READ(DSPTILEOFF(plane));
7946                 else
7947                         offset = I915_READ(DSPLINOFF(plane));
7948                 base = I915_READ(DSPSURF(plane)) & 0xfffff000;
7949         } else {
7950                 base = I915_READ(DSPADDR(plane));
7951         }
7952         plane_config->base = base;
7953
7954         val = I915_READ(PIPESRC(pipe));
7955         fb->width = ((val >> 16) & 0xfff) + 1;
7956         fb->height = ((val >> 0) & 0xfff) + 1;
7957
7958         val = I915_READ(DSPSTRIDE(pipe));
7959         fb->pitches[0] = val & 0xffffffc0;
7960
7961         aligned_height = intel_fb_align_height(dev, fb->height,
7962                                                fb->pixel_format,
7963                                                fb->modifier[0]);
7964
7965         plane_config->size = fb->pitches[0] * aligned_height;
7966
7967         DRM_DEBUG_KMS("pipe/plane %c/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
7968                       pipe_name(pipe), plane, fb->width, fb->height,
7969                       fb->bits_per_pixel, base, fb->pitches[0],
7970                       plane_config->size);
7971
7972         plane_config->fb = intel_fb;
7973 }
7974
7975 static void chv_crtc_clock_get(struct intel_crtc *crtc,
7976                                struct intel_crtc_state *pipe_config)
7977 {
7978         struct drm_device *dev = crtc->base.dev;
7979         struct drm_i915_private *dev_priv = dev->dev_private;
7980         int pipe = pipe_config->cpu_transcoder;
7981         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7982         intel_clock_t clock;
7983         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
7984         int refclk = 100000;
7985
7986         mutex_lock(&dev_priv->sb_lock);
7987         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
7988         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
7989         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
7990         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
7991         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7992         mutex_unlock(&dev_priv->sb_lock);
7993
7994         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
7995         clock.m2 = (pll_dw0 & 0xff) << 22;
7996         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
7997                 clock.m2 |= pll_dw2 & 0x3fffff;
7998         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
7999         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
8000         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
8001
8002         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
8003 }
8004
8005 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
8006                                  struct intel_crtc_state *pipe_config)
8007 {
8008         struct drm_device *dev = crtc->base.dev;
8009         struct drm_i915_private *dev_priv = dev->dev_private;
8010         uint32_t tmp;
8011
8012         if (!intel_display_power_is_enabled(dev_priv,
8013                                             POWER_DOMAIN_PIPE(crtc->pipe)))
8014                 return false;
8015
8016         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8017         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
8018
8019         tmp = I915_READ(PIPECONF(crtc->pipe));
8020         if (!(tmp & PIPECONF_ENABLE))
8021                 return false;
8022
8023         if (IS_G4X(dev) || IS_VALLEYVIEW(dev)) {
8024                 switch (tmp & PIPECONF_BPC_MASK) {
8025                 case PIPECONF_6BPC:
8026                         pipe_config->pipe_bpp = 18;
8027                         break;
8028                 case PIPECONF_8BPC:
8029                         pipe_config->pipe_bpp = 24;
8030                         break;
8031                 case PIPECONF_10BPC:
8032                         pipe_config->pipe_bpp = 30;
8033                         break;
8034                 default:
8035                         break;
8036                 }
8037         }
8038
8039         if (IS_VALLEYVIEW(dev) && (tmp & PIPECONF_COLOR_RANGE_SELECT))
8040                 pipe_config->limited_color_range = true;
8041
8042         if (INTEL_INFO(dev)->gen < 4)
8043                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
8044
8045         intel_get_pipe_timings(crtc, pipe_config);
8046
8047         i9xx_get_pfit_config(crtc, pipe_config);
8048
8049         if (INTEL_INFO(dev)->gen >= 4) {
8050                 tmp = I915_READ(DPLL_MD(crtc->pipe));
8051                 pipe_config->pixel_multiplier =
8052                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
8053                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
8054                 pipe_config->dpll_hw_state.dpll_md = tmp;
8055         } else if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
8056                 tmp = I915_READ(DPLL(crtc->pipe));
8057                 pipe_config->pixel_multiplier =
8058                         ((tmp & SDVO_MULTIPLIER_MASK)
8059                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
8060         } else {
8061                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
8062                  * port and will be fixed up in the encoder->get_config
8063                  * function. */
8064                 pipe_config->pixel_multiplier = 1;
8065         }
8066         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
8067         if (!IS_VALLEYVIEW(dev)) {
8068                 /*
8069                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
8070                  * on 830. Filter it out here so that we don't
8071                  * report errors due to that.
8072                  */
8073                 if (IS_I830(dev))
8074                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
8075
8076                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
8077                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
8078         } else {
8079                 /* Mask out read-only status bits. */
8080                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
8081                                                      DPLL_PORTC_READY_MASK |
8082                                                      DPLL_PORTB_READY_MASK);
8083         }
8084
8085         if (IS_CHERRYVIEW(dev))
8086                 chv_crtc_clock_get(crtc, pipe_config);
8087         else if (IS_VALLEYVIEW(dev))
8088                 vlv_crtc_clock_get(crtc, pipe_config);
8089         else
8090                 i9xx_crtc_clock_get(crtc, pipe_config);
8091
8092         /*
8093          * Normally the dotclock is filled in by the encoder .get_config()
8094          * but in case the pipe is enabled w/o any ports we need a sane
8095          * default.
8096          */
8097         pipe_config->base.adjusted_mode.crtc_clock =
8098                 pipe_config->port_clock / pipe_config->pixel_multiplier;
8099
8100         return true;
8101 }
8102
8103 static void ironlake_init_pch_refclk(struct drm_device *dev)
8104 {
8105         struct drm_i915_private *dev_priv = dev->dev_private;
8106         struct intel_encoder *encoder;
8107         u32 val, final;
8108         bool has_lvds = false;
8109         bool has_cpu_edp = false;
8110         bool has_panel = false;
8111         bool has_ck505 = false;
8112         bool can_ssc = false;
8113
8114         /* We need to take the global config into account */
8115         for_each_intel_encoder(dev, encoder) {
8116                 switch (encoder->type) {
8117                 case INTEL_OUTPUT_LVDS:
8118                         has_panel = true;
8119                         has_lvds = true;
8120                         break;
8121                 case INTEL_OUTPUT_EDP:
8122                         has_panel = true;
8123                         if (enc_to_dig_port(&encoder->base)->port == PORT_A)
8124                                 has_cpu_edp = true;
8125                         break;
8126                 default:
8127                         break;
8128                 }
8129         }
8130
8131         if (HAS_PCH_IBX(dev)) {
8132                 has_ck505 = dev_priv->vbt.display_clock_mode;
8133                 can_ssc = has_ck505;
8134         } else {
8135                 has_ck505 = false;
8136                 can_ssc = true;
8137         }
8138
8139         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d\n",
8140                       has_panel, has_lvds, has_ck505);
8141
8142         /* Ironlake: try to setup display ref clock before DPLL
8143          * enabling. This is only under driver's control after
8144          * PCH B stepping, previous chipset stepping should be
8145          * ignoring this setting.
8146          */
8147         val = I915_READ(PCH_DREF_CONTROL);
8148
8149         /* As we must carefully and slowly disable/enable each source in turn,
8150          * compute the final state we want first and check if we need to
8151          * make any changes at all.
8152          */
8153         final = val;
8154         final &= ~DREF_NONSPREAD_SOURCE_MASK;
8155         if (has_ck505)
8156                 final |= DREF_NONSPREAD_CK505_ENABLE;
8157         else
8158                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
8159
8160         final &= ~DREF_SSC_SOURCE_MASK;
8161         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8162         final &= ~DREF_SSC1_ENABLE;
8163
8164         if (has_panel) {
8165                 final |= DREF_SSC_SOURCE_ENABLE;
8166
8167                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
8168                         final |= DREF_SSC1_ENABLE;
8169
8170                 if (has_cpu_edp) {
8171                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
8172                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8173                         else
8174                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8175                 } else
8176                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8177         } else {
8178                 final |= DREF_SSC_SOURCE_DISABLE;
8179                 final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8180         }
8181
8182         if (final == val)
8183                 return;
8184
8185         /* Always enable nonspread source */
8186         val &= ~DREF_NONSPREAD_SOURCE_MASK;
8187
8188         if (has_ck505)
8189                 val |= DREF_NONSPREAD_CK505_ENABLE;
8190         else
8191                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
8192
8193         if (has_panel) {
8194                 val &= ~DREF_SSC_SOURCE_MASK;
8195                 val |= DREF_SSC_SOURCE_ENABLE;
8196
8197                 /* SSC must be turned on before enabling the CPU output  */
8198                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8199                         DRM_DEBUG_KMS("Using SSC on panel\n");
8200                         val |= DREF_SSC1_ENABLE;
8201                 } else
8202                         val &= ~DREF_SSC1_ENABLE;
8203
8204                 /* Get SSC going before enabling the outputs */
8205                 I915_WRITE(PCH_DREF_CONTROL, val);
8206                 POSTING_READ(PCH_DREF_CONTROL);
8207                 udelay(200);
8208
8209                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8210
8211                 /* Enable CPU source on CPU attached eDP */
8212                 if (has_cpu_edp) {
8213                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8214                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
8215                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8216                         } else
8217                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8218                 } else
8219                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8220
8221                 I915_WRITE(PCH_DREF_CONTROL, val);
8222                 POSTING_READ(PCH_DREF_CONTROL);
8223                 udelay(200);
8224         } else {
8225                 DRM_DEBUG_KMS("Disabling SSC entirely\n");
8226
8227                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8228
8229                 /* Turn off CPU output */
8230                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8231
8232                 I915_WRITE(PCH_DREF_CONTROL, val);
8233                 POSTING_READ(PCH_DREF_CONTROL);
8234                 udelay(200);
8235
8236                 /* Turn off the SSC source */
8237                 val &= ~DREF_SSC_SOURCE_MASK;
8238                 val |= DREF_SSC_SOURCE_DISABLE;
8239
8240                 /* Turn off SSC1 */
8241                 val &= ~DREF_SSC1_ENABLE;
8242
8243                 I915_WRITE(PCH_DREF_CONTROL, val);
8244                 POSTING_READ(PCH_DREF_CONTROL);
8245                 udelay(200);
8246         }
8247
8248         BUG_ON(val != final);
8249 }
8250
8251 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
8252 {
8253         uint32_t tmp;
8254
8255         tmp = I915_READ(SOUTH_CHICKEN2);
8256         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
8257         I915_WRITE(SOUTH_CHICKEN2, tmp);
8258
8259         if (wait_for_atomic_us(I915_READ(SOUTH_CHICKEN2) &
8260                                FDI_MPHY_IOSFSB_RESET_STATUS, 100))
8261                 DRM_ERROR("FDI mPHY reset assert timeout\n");
8262
8263         tmp = I915_READ(SOUTH_CHICKEN2);
8264         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
8265         I915_WRITE(SOUTH_CHICKEN2, tmp);
8266
8267         if (wait_for_atomic_us((I915_READ(SOUTH_CHICKEN2) &
8268                                 FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
8269                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
8270 }
8271
8272 /* WaMPhyProgramming:hsw */
8273 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
8274 {
8275         uint32_t tmp;
8276
8277         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
8278         tmp &= ~(0xFF << 24);
8279         tmp |= (0x12 << 24);
8280         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
8281
8282         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
8283         tmp |= (1 << 11);
8284         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
8285
8286         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
8287         tmp |= (1 << 11);
8288         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
8289
8290         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
8291         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8292         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
8293
8294         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
8295         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8296         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
8297
8298         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
8299         tmp &= ~(7 << 13);
8300         tmp |= (5 << 13);
8301         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
8302
8303         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
8304         tmp &= ~(7 << 13);
8305         tmp |= (5 << 13);
8306         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
8307
8308         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
8309         tmp &= ~0xFF;
8310         tmp |= 0x1C;
8311         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
8312
8313         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
8314         tmp &= ~0xFF;
8315         tmp |= 0x1C;
8316         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
8317
8318         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
8319         tmp &= ~(0xFF << 16);
8320         tmp |= (0x1C << 16);
8321         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
8322
8323         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
8324         tmp &= ~(0xFF << 16);
8325         tmp |= (0x1C << 16);
8326         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
8327
8328         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8329         tmp |= (1 << 27);
8330         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8331
8332         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8333         tmp |= (1 << 27);
8334         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8335
8336         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8337         tmp &= ~(0xF << 28);
8338         tmp |= (4 << 28);
8339         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8340
8341         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
8342         tmp &= ~(0xF << 28);
8343         tmp |= (4 << 28);
8344         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
8345 }
8346
8347 /* Implements 3 different sequences from BSpec chapter "Display iCLK
8348  * Programming" based on the parameters passed:
8349  * - Sequence to enable CLKOUT_DP
8350  * - Sequence to enable CLKOUT_DP without spread
8351  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
8352  */
8353 static void lpt_enable_clkout_dp(struct drm_device *dev, bool with_spread,
8354                                  bool with_fdi)
8355 {
8356         struct drm_i915_private *dev_priv = dev->dev_private;
8357         uint32_t reg, tmp;
8358
8359         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
8360                 with_spread = true;
8361         if (WARN(HAS_PCH_LPT_LP(dev) && with_fdi, "LP PCH doesn't have FDI\n"))
8362                 with_fdi = false;
8363
8364         mutex_lock(&dev_priv->sb_lock);
8365
8366         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8367         tmp &= ~SBI_SSCCTL_DISABLE;
8368         tmp |= SBI_SSCCTL_PATHALT;
8369         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8370
8371         udelay(24);
8372
8373         if (with_spread) {
8374                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8375                 tmp &= ~SBI_SSCCTL_PATHALT;
8376                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8377
8378                 if (with_fdi) {
8379                         lpt_reset_fdi_mphy(dev_priv);
8380                         lpt_program_fdi_mphy(dev_priv);
8381                 }
8382         }
8383
8384         reg = HAS_PCH_LPT_LP(dev) ? SBI_GEN0 : SBI_DBUFF0;
8385         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8386         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8387         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8388
8389         mutex_unlock(&dev_priv->sb_lock);
8390 }
8391
8392 /* Sequence to disable CLKOUT_DP */
8393 static void lpt_disable_clkout_dp(struct drm_device *dev)
8394 {
8395         struct drm_i915_private *dev_priv = dev->dev_private;
8396         uint32_t reg, tmp;
8397
8398         mutex_lock(&dev_priv->sb_lock);
8399
8400         reg = HAS_PCH_LPT_LP(dev) ? SBI_GEN0 : SBI_DBUFF0;
8401         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8402         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8403         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8404
8405         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8406         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8407                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8408                         tmp |= SBI_SSCCTL_PATHALT;
8409                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8410                         udelay(32);
8411                 }
8412                 tmp |= SBI_SSCCTL_DISABLE;
8413                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8414         }
8415
8416         mutex_unlock(&dev_priv->sb_lock);
8417 }
8418
8419 static void lpt_init_pch_refclk(struct drm_device *dev)
8420 {
8421         struct intel_encoder *encoder;
8422         bool has_vga = false;
8423
8424         for_each_intel_encoder(dev, encoder) {
8425                 switch (encoder->type) {
8426                 case INTEL_OUTPUT_ANALOG:
8427                         has_vga = true;
8428                         break;
8429                 default:
8430                         break;
8431                 }
8432         }
8433
8434         if (has_vga)
8435                 lpt_enable_clkout_dp(dev, true, true);
8436         else
8437                 lpt_disable_clkout_dp(dev);
8438 }
8439
8440 /*
8441  * Initialize reference clocks when the driver loads
8442  */
8443 void intel_init_pch_refclk(struct drm_device *dev)
8444 {
8445         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
8446                 ironlake_init_pch_refclk(dev);
8447         else if (HAS_PCH_LPT(dev))
8448                 lpt_init_pch_refclk(dev);
8449 }
8450
8451 static int ironlake_get_refclk(struct intel_crtc_state *crtc_state)
8452 {
8453         struct drm_device *dev = crtc_state->base.crtc->dev;
8454         struct drm_i915_private *dev_priv = dev->dev_private;
8455         struct drm_atomic_state *state = crtc_state->base.state;
8456         struct drm_connector *connector;
8457         struct drm_connector_state *connector_state;
8458         struct intel_encoder *encoder;
8459         int num_connectors = 0, i;
8460         bool is_lvds = false;
8461
8462         for_each_connector_in_state(state, connector, connector_state, i) {
8463                 if (connector_state->crtc != crtc_state->base.crtc)
8464                         continue;
8465
8466                 encoder = to_intel_encoder(connector_state->best_encoder);
8467
8468                 switch (encoder->type) {
8469                 case INTEL_OUTPUT_LVDS:
8470                         is_lvds = true;
8471                         break;
8472                 default:
8473                         break;
8474                 }
8475                 num_connectors++;
8476         }
8477
8478         if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2) {
8479                 DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8480                               dev_priv->vbt.lvds_ssc_freq);
8481                 return dev_priv->vbt.lvds_ssc_freq;
8482         }
8483
8484         return 120000;
8485 }
8486
8487 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
8488 {
8489         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
8490         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8491         int pipe = intel_crtc->pipe;
8492         uint32_t val;
8493
8494         val = 0;
8495
8496         switch (intel_crtc->config->pipe_bpp) {
8497         case 18:
8498                 val |= PIPECONF_6BPC;
8499                 break;
8500         case 24:
8501                 val |= PIPECONF_8BPC;
8502                 break;
8503         case 30:
8504                 val |= PIPECONF_10BPC;
8505                 break;
8506         case 36:
8507                 val |= PIPECONF_12BPC;
8508                 break;
8509         default:
8510                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8511                 BUG();
8512         }
8513
8514         if (intel_crtc->config->dither)
8515                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8516
8517         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8518                 val |= PIPECONF_INTERLACED_ILK;
8519         else
8520                 val |= PIPECONF_PROGRESSIVE;
8521
8522         if (intel_crtc->config->limited_color_range)
8523                 val |= PIPECONF_COLOR_RANGE_SELECT;
8524
8525         I915_WRITE(PIPECONF(pipe), val);
8526         POSTING_READ(PIPECONF(pipe));
8527 }
8528
8529 /*
8530  * Set up the pipe CSC unit.
8531  *
8532  * Currently only full range RGB to limited range RGB conversion
8533  * is supported, but eventually this should handle various
8534  * RGB<->YCbCr scenarios as well.
8535  */
8536 static void intel_set_pipe_csc(struct drm_crtc *crtc)
8537 {
8538         struct drm_device *dev = crtc->dev;
8539         struct drm_i915_private *dev_priv = dev->dev_private;
8540         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8541         int pipe = intel_crtc->pipe;
8542         uint16_t coeff = 0x7800; /* 1.0 */
8543
8544         /*
8545          * TODO: Check what kind of values actually come out of the pipe
8546          * with these coeff/postoff values and adjust to get the best
8547          * accuracy. Perhaps we even need to take the bpc value into
8548          * consideration.
8549          */
8550
8551         if (intel_crtc->config->limited_color_range)
8552                 coeff = ((235 - 16) * (1 << 12) / 255) & 0xff8; /* 0.xxx... */
8553
8554         /*
8555          * GY/GU and RY/RU should be the other way around according
8556          * to BSpec, but reality doesn't agree. Just set them up in
8557          * a way that results in the correct picture.
8558          */
8559         I915_WRITE(PIPE_CSC_COEFF_RY_GY(pipe), coeff << 16);
8560         I915_WRITE(PIPE_CSC_COEFF_BY(pipe), 0);
8561
8562         I915_WRITE(PIPE_CSC_COEFF_RU_GU(pipe), coeff);
8563         I915_WRITE(PIPE_CSC_COEFF_BU(pipe), 0);
8564
8565         I915_WRITE(PIPE_CSC_COEFF_RV_GV(pipe), 0);
8566         I915_WRITE(PIPE_CSC_COEFF_BV(pipe), coeff << 16);
8567
8568         I915_WRITE(PIPE_CSC_PREOFF_HI(pipe), 0);
8569         I915_WRITE(PIPE_CSC_PREOFF_ME(pipe), 0);
8570         I915_WRITE(PIPE_CSC_PREOFF_LO(pipe), 0);
8571
8572         if (INTEL_INFO(dev)->gen > 6) {
8573                 uint16_t postoff = 0;
8574
8575                 if (intel_crtc->config->limited_color_range)
8576                         postoff = (16 * (1 << 12) / 255) & 0x1fff;
8577
8578                 I915_WRITE(PIPE_CSC_POSTOFF_HI(pipe), postoff);
8579                 I915_WRITE(PIPE_CSC_POSTOFF_ME(pipe), postoff);
8580                 I915_WRITE(PIPE_CSC_POSTOFF_LO(pipe), postoff);
8581
8582                 I915_WRITE(PIPE_CSC_MODE(pipe), 0);
8583         } else {
8584                 uint32_t mode = CSC_MODE_YUV_TO_RGB;
8585
8586                 if (intel_crtc->config->limited_color_range)
8587                         mode |= CSC_BLACK_SCREEN_OFFSET;
8588
8589                 I915_WRITE(PIPE_CSC_MODE(pipe), mode);
8590         }
8591 }
8592
8593 static void haswell_set_pipeconf(struct drm_crtc *crtc)
8594 {
8595         struct drm_device *dev = crtc->dev;
8596         struct drm_i915_private *dev_priv = dev->dev_private;
8597         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8598         enum pipe pipe = intel_crtc->pipe;
8599         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8600         uint32_t val;
8601
8602         val = 0;
8603
8604         if (IS_HASWELL(dev) && intel_crtc->config->dither)
8605                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8606
8607         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8608                 val |= PIPECONF_INTERLACED_ILK;
8609         else
8610                 val |= PIPECONF_PROGRESSIVE;
8611
8612         I915_WRITE(PIPECONF(cpu_transcoder), val);
8613         POSTING_READ(PIPECONF(cpu_transcoder));
8614
8615         I915_WRITE(GAMMA_MODE(intel_crtc->pipe), GAMMA_MODE_MODE_8BIT);
8616         POSTING_READ(GAMMA_MODE(intel_crtc->pipe));
8617
8618         if (IS_BROADWELL(dev) || INTEL_INFO(dev)->gen >= 9) {
8619                 val = 0;
8620
8621                 switch (intel_crtc->config->pipe_bpp) {
8622                 case 18:
8623                         val |= PIPEMISC_DITHER_6_BPC;
8624                         break;
8625                 case 24:
8626                         val |= PIPEMISC_DITHER_8_BPC;
8627                         break;
8628                 case 30:
8629                         val |= PIPEMISC_DITHER_10_BPC;
8630                         break;
8631                 case 36:
8632                         val |= PIPEMISC_DITHER_12_BPC;
8633                         break;
8634                 default:
8635                         /* Case prevented by pipe_config_set_bpp. */
8636                         BUG();
8637                 }
8638
8639                 if (intel_crtc->config->dither)
8640                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8641
8642                 I915_WRITE(PIPEMISC(pipe), val);
8643         }
8644 }
8645
8646 static bool ironlake_compute_clocks(struct drm_crtc *crtc,
8647                                     struct intel_crtc_state *crtc_state,
8648                                     intel_clock_t *clock,
8649                                     bool *has_reduced_clock,
8650                                     intel_clock_t *reduced_clock)
8651 {
8652         struct drm_device *dev = crtc->dev;
8653         struct drm_i915_private *dev_priv = dev->dev_private;
8654         int refclk;
8655         const intel_limit_t *limit;
8656         bool ret;
8657
8658         refclk = ironlake_get_refclk(crtc_state);
8659
8660         /*
8661          * Returns a set of divisors for the desired target clock with the given
8662          * refclk, or FALSE.  The returned values represent the clock equation:
8663          * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
8664          */
8665         limit = intel_limit(crtc_state, refclk);
8666         ret = dev_priv->display.find_dpll(limit, crtc_state,
8667                                           crtc_state->port_clock,
8668                                           refclk, NULL, clock);
8669         if (!ret)
8670                 return false;
8671
8672         return true;
8673 }
8674
8675 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8676 {
8677         /*
8678          * Account for spread spectrum to avoid
8679          * oversubscribing the link. Max center spread
8680          * is 2.5%; use 5% for safety's sake.
8681          */
8682         u32 bps = target_clock * bpp * 21 / 20;
8683         return DIV_ROUND_UP(bps, link_bw * 8);
8684 }
8685
8686 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8687 {
8688         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8689 }
8690
8691 static uint32_t ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8692                                       struct intel_crtc_state *crtc_state,
8693                                       u32 *fp,
8694                                       intel_clock_t *reduced_clock, u32 *fp2)
8695 {
8696         struct drm_crtc *crtc = &intel_crtc->base;
8697         struct drm_device *dev = crtc->dev;
8698         struct drm_i915_private *dev_priv = dev->dev_private;
8699         struct drm_atomic_state *state = crtc_state->base.state;
8700         struct drm_connector *connector;
8701         struct drm_connector_state *connector_state;
8702         struct intel_encoder *encoder;
8703         uint32_t dpll;
8704         int factor, num_connectors = 0, i;
8705         bool is_lvds = false, is_sdvo = false;
8706
8707         for_each_connector_in_state(state, connector, connector_state, i) {
8708                 if (connector_state->crtc != crtc_state->base.crtc)
8709                         continue;
8710
8711                 encoder = to_intel_encoder(connector_state->best_encoder);
8712
8713                 switch (encoder->type) {
8714                 case INTEL_OUTPUT_LVDS:
8715                         is_lvds = true;
8716                         break;
8717                 case INTEL_OUTPUT_SDVO:
8718                 case INTEL_OUTPUT_HDMI:
8719                         is_sdvo = true;
8720                         break;
8721                 default:
8722                         break;
8723                 }
8724
8725                 num_connectors++;
8726         }
8727
8728         /* Enable autotuning of the PLL clock (if permissible) */
8729         factor = 21;
8730         if (is_lvds) {
8731                 if ((intel_panel_use_ssc(dev_priv) &&
8732                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8733                     (HAS_PCH_IBX(dev) && intel_is_dual_link_lvds(dev)))
8734                         factor = 25;
8735         } else if (crtc_state->sdvo_tv_clock)
8736                 factor = 20;
8737
8738         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8739                 *fp |= FP_CB_TUNE;
8740
8741         if (fp2 && (reduced_clock->m < factor * reduced_clock->n))
8742                 *fp2 |= FP_CB_TUNE;
8743
8744         dpll = 0;
8745
8746         if (is_lvds)
8747                 dpll |= DPLLB_MODE_LVDS;
8748         else
8749                 dpll |= DPLLB_MODE_DAC_SERIAL;
8750
8751         dpll |= (crtc_state->pixel_multiplier - 1)
8752                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8753
8754         if (is_sdvo)
8755                 dpll |= DPLL_SDVO_HIGH_SPEED;
8756         if (crtc_state->has_dp_encoder)
8757                 dpll |= DPLL_SDVO_HIGH_SPEED;
8758
8759         /* compute bitmask from p1 value */
8760         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8761         /* also FPA1 */
8762         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8763
8764         switch (crtc_state->dpll.p2) {
8765         case 5:
8766                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8767                 break;
8768         case 7:
8769                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8770                 break;
8771         case 10:
8772                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8773                 break;
8774         case 14:
8775                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8776                 break;
8777         }
8778
8779         if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2)
8780                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8781         else
8782                 dpll |= PLL_REF_INPUT_DREFCLK;
8783
8784         return dpll | DPLL_VCO_ENABLE;
8785 }
8786
8787 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
8788                                        struct intel_crtc_state *crtc_state)
8789 {
8790         struct drm_device *dev = crtc->base.dev;
8791         intel_clock_t clock, reduced_clock;
8792         u32 dpll = 0, fp = 0, fp2 = 0;
8793         bool ok, has_reduced_clock = false;
8794         bool is_lvds = false;
8795         struct intel_shared_dpll *pll;
8796
8797         memset(&crtc_state->dpll_hw_state, 0,
8798                sizeof(crtc_state->dpll_hw_state));
8799
8800         is_lvds = intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS);
8801
8802         WARN(!(HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev)),
8803              "Unexpected PCH type %d\n", INTEL_PCH_TYPE(dev));
8804
8805         ok = ironlake_compute_clocks(&crtc->base, crtc_state, &clock,
8806                                      &has_reduced_clock, &reduced_clock);
8807         if (!ok && !crtc_state->clock_set) {
8808                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8809                 return -EINVAL;
8810         }
8811         /* Compat-code for transition, will disappear. */
8812         if (!crtc_state->clock_set) {
8813                 crtc_state->dpll.n = clock.n;
8814                 crtc_state->dpll.m1 = clock.m1;
8815                 crtc_state->dpll.m2 = clock.m2;
8816                 crtc_state->dpll.p1 = clock.p1;
8817                 crtc_state->dpll.p2 = clock.p2;
8818         }
8819
8820         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
8821         if (crtc_state->has_pch_encoder) {
8822                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8823                 if (has_reduced_clock)
8824                         fp2 = i9xx_dpll_compute_fp(&reduced_clock);
8825
8826                 dpll = ironlake_compute_dpll(crtc, crtc_state,
8827                                              &fp, &reduced_clock,
8828                                              has_reduced_clock ? &fp2 : NULL);
8829
8830                 crtc_state->dpll_hw_state.dpll = dpll;
8831                 crtc_state->dpll_hw_state.fp0 = fp;
8832                 if (has_reduced_clock)
8833                         crtc_state->dpll_hw_state.fp1 = fp2;
8834                 else
8835                         crtc_state->dpll_hw_state.fp1 = fp;
8836
8837                 pll = intel_get_shared_dpll(crtc, crtc_state);
8838                 if (pll == NULL) {
8839                         DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
8840                                          pipe_name(crtc->pipe));
8841                         return -EINVAL;
8842                 }
8843         }
8844
8845         if (is_lvds && has_reduced_clock)
8846                 crtc->lowfreq_avail = true;
8847         else
8848                 crtc->lowfreq_avail = false;
8849
8850         return 0;
8851 }
8852
8853 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
8854                                          struct intel_link_m_n *m_n)
8855 {
8856         struct drm_device *dev = crtc->base.dev;
8857         struct drm_i915_private *dev_priv = dev->dev_private;
8858         enum pipe pipe = crtc->pipe;
8859
8860         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
8861         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
8862         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
8863                 & ~TU_SIZE_MASK;
8864         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
8865         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
8866                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8867 }
8868
8869 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
8870                                          enum transcoder transcoder,
8871                                          struct intel_link_m_n *m_n,
8872                                          struct intel_link_m_n *m2_n2)
8873 {
8874         struct drm_device *dev = crtc->base.dev;
8875         struct drm_i915_private *dev_priv = dev->dev_private;
8876         enum pipe pipe = crtc->pipe;
8877
8878         if (INTEL_INFO(dev)->gen >= 5) {
8879                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
8880                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
8881                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
8882                         & ~TU_SIZE_MASK;
8883                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
8884                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
8885                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8886                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
8887                  * gen < 8) and if DRRS is supported (to make sure the
8888                  * registers are not unnecessarily read).
8889                  */
8890                 if (m2_n2 && INTEL_INFO(dev)->gen < 8 &&
8891                         crtc->config->has_drrs) {
8892                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
8893                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
8894                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
8895                                         & ~TU_SIZE_MASK;
8896                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
8897                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
8898                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8899                 }
8900         } else {
8901                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
8902                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
8903                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
8904                         & ~TU_SIZE_MASK;
8905                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
8906                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
8907                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8908         }
8909 }
8910
8911 void intel_dp_get_m_n(struct intel_crtc *crtc,
8912                       struct intel_crtc_state *pipe_config)
8913 {
8914         if (pipe_config->has_pch_encoder)
8915                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
8916         else
8917                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8918                                              &pipe_config->dp_m_n,
8919                                              &pipe_config->dp_m2_n2);
8920 }
8921
8922 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
8923                                         struct intel_crtc_state *pipe_config)
8924 {
8925         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8926                                      &pipe_config->fdi_m_n, NULL);
8927 }
8928
8929 static void skylake_get_pfit_config(struct intel_crtc *crtc,
8930                                     struct intel_crtc_state *pipe_config)
8931 {
8932         struct drm_device *dev = crtc->base.dev;
8933         struct drm_i915_private *dev_priv = dev->dev_private;
8934         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
8935         uint32_t ps_ctrl = 0;
8936         int id = -1;
8937         int i;
8938
8939         /* find scaler attached to this pipe */
8940         for (i = 0; i < crtc->num_scalers; i++) {
8941                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
8942                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
8943                         id = i;
8944                         pipe_config->pch_pfit.enabled = true;
8945                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
8946                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
8947                         break;
8948                 }
8949         }
8950
8951         scaler_state->scaler_id = id;
8952         if (id >= 0) {
8953                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
8954         } else {
8955                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
8956         }
8957 }
8958
8959 static void
8960 skylake_get_initial_plane_config(struct intel_crtc *crtc,
8961                                  struct intel_initial_plane_config *plane_config)
8962 {
8963         struct drm_device *dev = crtc->base.dev;
8964         struct drm_i915_private *dev_priv = dev->dev_private;
8965         u32 val, base, offset, stride_mult, tiling;
8966         int pipe = crtc->pipe;
8967         int fourcc, pixel_format;
8968         unsigned int aligned_height;
8969         struct drm_framebuffer *fb;
8970         struct intel_framebuffer *intel_fb;
8971
8972         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8973         if (!intel_fb) {
8974                 DRM_DEBUG_KMS("failed to alloc fb\n");
8975                 return;
8976         }
8977
8978         fb = &intel_fb->base;
8979
8980         val = I915_READ(PLANE_CTL(pipe, 0));
8981         if (!(val & PLANE_CTL_ENABLE))
8982                 goto error;
8983
8984         pixel_format = val & PLANE_CTL_FORMAT_MASK;
8985         fourcc = skl_format_to_fourcc(pixel_format,
8986                                       val & PLANE_CTL_ORDER_RGBX,
8987                                       val & PLANE_CTL_ALPHA_MASK);
8988         fb->pixel_format = fourcc;
8989         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
8990
8991         tiling = val & PLANE_CTL_TILED_MASK;
8992         switch (tiling) {
8993         case PLANE_CTL_TILED_LINEAR:
8994                 fb->modifier[0] = DRM_FORMAT_MOD_NONE;
8995                 break;
8996         case PLANE_CTL_TILED_X:
8997                 plane_config->tiling = I915_TILING_X;
8998                 fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
8999                 break;
9000         case PLANE_CTL_TILED_Y:
9001                 fb->modifier[0] = I915_FORMAT_MOD_Y_TILED;
9002                 break;
9003         case PLANE_CTL_TILED_YF:
9004                 fb->modifier[0] = I915_FORMAT_MOD_Yf_TILED;
9005                 break;
9006         default:
9007                 MISSING_CASE(tiling);
9008                 goto error;
9009         }
9010
9011         base = I915_READ(PLANE_SURF(pipe, 0)) & 0xfffff000;
9012         plane_config->base = base;
9013
9014         offset = I915_READ(PLANE_OFFSET(pipe, 0));
9015
9016         val = I915_READ(PLANE_SIZE(pipe, 0));
9017         fb->height = ((val >> 16) & 0xfff) + 1;
9018         fb->width = ((val >> 0) & 0x1fff) + 1;
9019
9020         val = I915_READ(PLANE_STRIDE(pipe, 0));
9021         stride_mult = intel_fb_stride_alignment(dev, fb->modifier[0],
9022                                                 fb->pixel_format);
9023         fb->pitches[0] = (val & 0x3ff) * stride_mult;
9024
9025         aligned_height = intel_fb_align_height(dev, fb->height,
9026                                                fb->pixel_format,
9027                                                fb->modifier[0]);
9028
9029         plane_config->size = fb->pitches[0] * aligned_height;
9030
9031         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9032                       pipe_name(pipe), fb->width, fb->height,
9033                       fb->bits_per_pixel, base, fb->pitches[0],
9034                       plane_config->size);
9035
9036         plane_config->fb = intel_fb;
9037         return;
9038
9039 error:
9040         kfree(fb);
9041 }
9042
9043 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
9044                                      struct intel_crtc_state *pipe_config)
9045 {
9046         struct drm_device *dev = crtc->base.dev;
9047         struct drm_i915_private *dev_priv = dev->dev_private;
9048         uint32_t tmp;
9049
9050         tmp = I915_READ(PF_CTL(crtc->pipe));
9051
9052         if (tmp & PF_ENABLE) {
9053                 pipe_config->pch_pfit.enabled = true;
9054                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
9055                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
9056
9057                 /* We currently do not free assignements of panel fitters on
9058                  * ivb/hsw (since we don't use the higher upscaling modes which
9059                  * differentiates them) so just WARN about this case for now. */
9060                 if (IS_GEN7(dev)) {
9061                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
9062                                 PF_PIPE_SEL_IVB(crtc->pipe));
9063                 }
9064         }
9065 }
9066
9067 static void
9068 ironlake_get_initial_plane_config(struct intel_crtc *crtc,
9069                                   struct intel_initial_plane_config *plane_config)
9070 {
9071         struct drm_device *dev = crtc->base.dev;
9072         struct drm_i915_private *dev_priv = dev->dev_private;
9073         u32 val, base, offset;
9074         int pipe = crtc->pipe;
9075         int fourcc, pixel_format;
9076         unsigned int aligned_height;
9077         struct drm_framebuffer *fb;
9078         struct intel_framebuffer *intel_fb;
9079
9080         val = I915_READ(DSPCNTR(pipe));
9081         if (!(val & DISPLAY_PLANE_ENABLE))
9082                 return;
9083
9084         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9085         if (!intel_fb) {
9086                 DRM_DEBUG_KMS("failed to alloc fb\n");
9087                 return;
9088         }
9089
9090         fb = &intel_fb->base;
9091
9092         if (INTEL_INFO(dev)->gen >= 4) {
9093                 if (val & DISPPLANE_TILED) {
9094                         plane_config->tiling = I915_TILING_X;
9095                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9096                 }
9097         }
9098
9099         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
9100         fourcc = i9xx_format_to_fourcc(pixel_format);
9101         fb->pixel_format = fourcc;
9102         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9103
9104         base = I915_READ(DSPSURF(pipe)) & 0xfffff000;
9105         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
9106                 offset = I915_READ(DSPOFFSET(pipe));
9107         } else {
9108                 if (plane_config->tiling)
9109                         offset = I915_READ(DSPTILEOFF(pipe));
9110                 else
9111                         offset = I915_READ(DSPLINOFF(pipe));
9112         }
9113         plane_config->base = base;
9114
9115         val = I915_READ(PIPESRC(pipe));
9116         fb->width = ((val >> 16) & 0xfff) + 1;
9117         fb->height = ((val >> 0) & 0xfff) + 1;
9118
9119         val = I915_READ(DSPSTRIDE(pipe));
9120         fb->pitches[0] = val & 0xffffffc0;
9121
9122         aligned_height = intel_fb_align_height(dev, fb->height,
9123                                                fb->pixel_format,
9124                                                fb->modifier[0]);
9125
9126         plane_config->size = fb->pitches[0] * aligned_height;
9127
9128         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9129                       pipe_name(pipe), fb->width, fb->height,
9130                       fb->bits_per_pixel, base, fb->pitches[0],
9131                       plane_config->size);
9132
9133         plane_config->fb = intel_fb;
9134 }
9135
9136 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
9137                                      struct intel_crtc_state *pipe_config)
9138 {
9139         struct drm_device *dev = crtc->base.dev;
9140         struct drm_i915_private *dev_priv = dev->dev_private;
9141         uint32_t tmp;
9142
9143         if (!intel_display_power_is_enabled(dev_priv,
9144                                             POWER_DOMAIN_PIPE(crtc->pipe)))
9145                 return false;
9146
9147         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9148         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
9149
9150         tmp = I915_READ(PIPECONF(crtc->pipe));
9151         if (!(tmp & PIPECONF_ENABLE))
9152                 return false;
9153
9154         switch (tmp & PIPECONF_BPC_MASK) {
9155         case PIPECONF_6BPC:
9156                 pipe_config->pipe_bpp = 18;
9157                 break;
9158         case PIPECONF_8BPC:
9159                 pipe_config->pipe_bpp = 24;
9160                 break;
9161         case PIPECONF_10BPC:
9162                 pipe_config->pipe_bpp = 30;
9163                 break;
9164         case PIPECONF_12BPC:
9165                 pipe_config->pipe_bpp = 36;
9166                 break;
9167         default:
9168                 break;
9169         }
9170
9171         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
9172                 pipe_config->limited_color_range = true;
9173
9174         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
9175                 struct intel_shared_dpll *pll;
9176
9177                 pipe_config->has_pch_encoder = true;
9178
9179                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
9180                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9181                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9182
9183                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9184
9185                 if (HAS_PCH_IBX(dev_priv->dev)) {
9186                         pipe_config->shared_dpll =
9187                                 (enum intel_dpll_id) crtc->pipe;
9188                 } else {
9189                         tmp = I915_READ(PCH_DPLL_SEL);
9190                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
9191                                 pipe_config->shared_dpll = DPLL_ID_PCH_PLL_B;
9192                         else
9193                                 pipe_config->shared_dpll = DPLL_ID_PCH_PLL_A;
9194                 }
9195
9196                 pll = &dev_priv->shared_dplls[pipe_config->shared_dpll];
9197
9198                 WARN_ON(!pll->get_hw_state(dev_priv, pll,
9199                                            &pipe_config->dpll_hw_state));
9200
9201                 tmp = pipe_config->dpll_hw_state.dpll;
9202                 pipe_config->pixel_multiplier =
9203                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
9204                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
9205
9206                 ironlake_pch_clock_get(crtc, pipe_config);
9207         } else {
9208                 pipe_config->pixel_multiplier = 1;
9209         }
9210
9211         intel_get_pipe_timings(crtc, pipe_config);
9212
9213         ironlake_get_pfit_config(crtc, pipe_config);
9214
9215         return true;
9216 }
9217
9218 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
9219 {
9220         struct drm_device *dev = dev_priv->dev;
9221         struct intel_crtc *crtc;
9222
9223         for_each_intel_crtc(dev, crtc)
9224                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
9225                      pipe_name(crtc->pipe));
9226
9227         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_DRIVER), "Power well on\n");
9228         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
9229         I915_STATE_WARN(I915_READ(WRPLL_CTL1) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
9230         I915_STATE_WARN(I915_READ(WRPLL_CTL2) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
9231         I915_STATE_WARN(I915_READ(PCH_PP_STATUS) & PP_ON, "Panel power on\n");
9232         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
9233              "CPU PWM1 enabled\n");
9234         if (IS_HASWELL(dev))
9235                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
9236                      "CPU PWM2 enabled\n");
9237         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
9238              "PCH PWM1 enabled\n");
9239         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
9240              "Utility pin enabled\n");
9241         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
9242
9243         /*
9244          * In theory we can still leave IRQs enabled, as long as only the HPD
9245          * interrupts remain enabled. We used to check for that, but since it's
9246          * gen-specific and since we only disable LCPLL after we fully disable
9247          * the interrupts, the check below should be enough.
9248          */
9249         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
9250 }
9251
9252 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
9253 {
9254         struct drm_device *dev = dev_priv->dev;
9255
9256         if (IS_HASWELL(dev))
9257                 return I915_READ(D_COMP_HSW);
9258         else
9259                 return I915_READ(D_COMP_BDW);
9260 }
9261
9262 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
9263 {
9264         struct drm_device *dev = dev_priv->dev;
9265
9266         if (IS_HASWELL(dev)) {
9267                 mutex_lock(&dev_priv->rps.hw_lock);
9268                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
9269                                             val))
9270                         DRM_ERROR("Failed to write to D_COMP\n");
9271                 mutex_unlock(&dev_priv->rps.hw_lock);
9272         } else {
9273                 I915_WRITE(D_COMP_BDW, val);
9274                 POSTING_READ(D_COMP_BDW);
9275         }
9276 }
9277
9278 /*
9279  * This function implements pieces of two sequences from BSpec:
9280  * - Sequence for display software to disable LCPLL
9281  * - Sequence for display software to allow package C8+
9282  * The steps implemented here are just the steps that actually touch the LCPLL
9283  * register. Callers should take care of disabling all the display engine
9284  * functions, doing the mode unset, fixing interrupts, etc.
9285  */
9286 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
9287                               bool switch_to_fclk, bool allow_power_down)
9288 {
9289         uint32_t val;
9290
9291         assert_can_disable_lcpll(dev_priv);
9292
9293         val = I915_READ(LCPLL_CTL);
9294
9295         if (switch_to_fclk) {
9296                 val |= LCPLL_CD_SOURCE_FCLK;
9297                 I915_WRITE(LCPLL_CTL, val);
9298
9299                 if (wait_for_atomic_us(I915_READ(LCPLL_CTL) &
9300                                        LCPLL_CD_SOURCE_FCLK_DONE, 1))
9301                         DRM_ERROR("Switching to FCLK failed\n");
9302
9303                 val = I915_READ(LCPLL_CTL);
9304         }
9305
9306         val |= LCPLL_PLL_DISABLE;
9307         I915_WRITE(LCPLL_CTL, val);
9308         POSTING_READ(LCPLL_CTL);
9309
9310         if (wait_for((I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK) == 0, 1))
9311                 DRM_ERROR("LCPLL still locked\n");
9312
9313         val = hsw_read_dcomp(dev_priv);
9314         val |= D_COMP_COMP_DISABLE;
9315         hsw_write_dcomp(dev_priv, val);
9316         ndelay(100);
9317
9318         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
9319                      1))
9320                 DRM_ERROR("D_COMP RCOMP still in progress\n");
9321
9322         if (allow_power_down) {
9323                 val = I915_READ(LCPLL_CTL);
9324                 val |= LCPLL_POWER_DOWN_ALLOW;
9325                 I915_WRITE(LCPLL_CTL, val);
9326                 POSTING_READ(LCPLL_CTL);
9327         }
9328 }
9329
9330 /*
9331  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
9332  * source.
9333  */
9334 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
9335 {
9336         uint32_t val;
9337
9338         val = I915_READ(LCPLL_CTL);
9339
9340         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
9341                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
9342                 return;
9343
9344         /*
9345          * Make sure we're not on PC8 state before disabling PC8, otherwise
9346          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
9347          */
9348         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
9349
9350         if (val & LCPLL_POWER_DOWN_ALLOW) {
9351                 val &= ~LCPLL_POWER_DOWN_ALLOW;
9352                 I915_WRITE(LCPLL_CTL, val);
9353                 POSTING_READ(LCPLL_CTL);
9354         }
9355
9356         val = hsw_read_dcomp(dev_priv);
9357         val |= D_COMP_COMP_FORCE;
9358         val &= ~D_COMP_COMP_DISABLE;
9359         hsw_write_dcomp(dev_priv, val);
9360
9361         val = I915_READ(LCPLL_CTL);
9362         val &= ~LCPLL_PLL_DISABLE;
9363         I915_WRITE(LCPLL_CTL, val);
9364
9365         if (wait_for(I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK, 5))
9366                 DRM_ERROR("LCPLL not locked yet\n");
9367
9368         if (val & LCPLL_CD_SOURCE_FCLK) {
9369                 val = I915_READ(LCPLL_CTL);
9370                 val &= ~LCPLL_CD_SOURCE_FCLK;
9371                 I915_WRITE(LCPLL_CTL, val);
9372
9373                 if (wait_for_atomic_us((I915_READ(LCPLL_CTL) &
9374                                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9375                         DRM_ERROR("Switching back to LCPLL failed\n");
9376         }
9377
9378         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
9379         intel_update_cdclk(dev_priv->dev);
9380 }
9381
9382 /*
9383  * Package states C8 and deeper are really deep PC states that can only be
9384  * reached when all the devices on the system allow it, so even if the graphics
9385  * device allows PC8+, it doesn't mean the system will actually get to these
9386  * states. Our driver only allows PC8+ when going into runtime PM.
9387  *
9388  * The requirements for PC8+ are that all the outputs are disabled, the power
9389  * well is disabled and most interrupts are disabled, and these are also
9390  * requirements for runtime PM. When these conditions are met, we manually do
9391  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
9392  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
9393  * hang the machine.
9394  *
9395  * When we really reach PC8 or deeper states (not just when we allow it) we lose
9396  * the state of some registers, so when we come back from PC8+ we need to
9397  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
9398  * need to take care of the registers kept by RC6. Notice that this happens even
9399  * if we don't put the device in PCI D3 state (which is what currently happens
9400  * because of the runtime PM support).
9401  *
9402  * For more, read "Display Sequences for Package C8" on the hardware
9403  * documentation.
9404  */
9405 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
9406 {
9407         struct drm_device *dev = dev_priv->dev;
9408         uint32_t val;
9409
9410         DRM_DEBUG_KMS("Enabling package C8+\n");
9411
9412         if (HAS_PCH_LPT_LP(dev)) {
9413                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9414                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
9415                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9416         }
9417
9418         lpt_disable_clkout_dp(dev);
9419         hsw_disable_lcpll(dev_priv, true, true);
9420 }
9421
9422 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
9423 {
9424         struct drm_device *dev = dev_priv->dev;
9425         uint32_t val;
9426
9427         DRM_DEBUG_KMS("Disabling package C8+\n");
9428
9429         hsw_restore_lcpll(dev_priv);
9430         lpt_init_pch_refclk(dev);
9431
9432         if (HAS_PCH_LPT_LP(dev)) {
9433                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9434                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
9435                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9436         }
9437
9438         intel_prepare_ddi(dev);
9439 }
9440
9441 static void broxton_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9442 {
9443         struct drm_device *dev = old_state->dev;
9444         unsigned int req_cdclk = to_intel_atomic_state(old_state)->cdclk;
9445
9446         broxton_set_cdclk(dev, req_cdclk);
9447 }
9448
9449 /* compute the max rate for new configuration */
9450 static int ilk_max_pixel_rate(struct drm_atomic_state *state)
9451 {
9452         struct intel_crtc *intel_crtc;
9453         struct intel_crtc_state *crtc_state;
9454         int max_pixel_rate = 0;
9455
9456         for_each_intel_crtc(state->dev, intel_crtc) {
9457                 int pixel_rate;
9458
9459                 crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
9460                 if (IS_ERR(crtc_state))
9461                         return PTR_ERR(crtc_state);
9462
9463                 if (!crtc_state->base.enable)
9464                         continue;
9465
9466                 pixel_rate = ilk_pipe_pixel_rate(crtc_state);
9467
9468                 /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
9469                 if (IS_BROADWELL(state->dev) && crtc_state->ips_enabled)
9470                         pixel_rate = DIV_ROUND_UP(pixel_rate * 100, 95);
9471
9472                 max_pixel_rate = max(max_pixel_rate, pixel_rate);
9473         }
9474
9475         return max_pixel_rate;
9476 }
9477
9478 static void broadwell_set_cdclk(struct drm_device *dev, int cdclk)
9479 {
9480         struct drm_i915_private *dev_priv = dev->dev_private;
9481         uint32_t val, data;
9482         int ret;
9483
9484         if (WARN((I915_READ(LCPLL_CTL) &
9485                   (LCPLL_PLL_DISABLE | LCPLL_PLL_LOCK |
9486                    LCPLL_CD_CLOCK_DISABLE | LCPLL_ROOT_CD_CLOCK_DISABLE |
9487                    LCPLL_CD2X_CLOCK_DISABLE | LCPLL_POWER_DOWN_ALLOW |
9488                    LCPLL_CD_SOURCE_FCLK)) != LCPLL_PLL_LOCK,
9489                  "trying to change cdclk frequency with cdclk not enabled\n"))
9490                 return;
9491
9492         mutex_lock(&dev_priv->rps.hw_lock);
9493         ret = sandybridge_pcode_write(dev_priv,
9494                                       BDW_PCODE_DISPLAY_FREQ_CHANGE_REQ, 0x0);
9495         mutex_unlock(&dev_priv->rps.hw_lock);
9496         if (ret) {
9497                 DRM_ERROR("failed to inform pcode about cdclk change\n");
9498                 return;
9499         }
9500
9501         val = I915_READ(LCPLL_CTL);
9502         val |= LCPLL_CD_SOURCE_FCLK;
9503         I915_WRITE(LCPLL_CTL, val);
9504
9505         if (wait_for_atomic_us(I915_READ(LCPLL_CTL) &
9506                                LCPLL_CD_SOURCE_FCLK_DONE, 1))
9507                 DRM_ERROR("Switching to FCLK failed\n");
9508
9509         val = I915_READ(LCPLL_CTL);
9510         val &= ~LCPLL_CLK_FREQ_MASK;
9511
9512         switch (cdclk) {
9513         case 450000:
9514                 val |= LCPLL_CLK_FREQ_450;
9515                 data = 0;
9516                 break;
9517         case 540000:
9518                 val |= LCPLL_CLK_FREQ_54O_BDW;
9519                 data = 1;
9520                 break;
9521         case 337500:
9522                 val |= LCPLL_CLK_FREQ_337_5_BDW;
9523                 data = 2;
9524                 break;
9525         case 675000:
9526                 val |= LCPLL_CLK_FREQ_675_BDW;
9527                 data = 3;
9528                 break;
9529         default:
9530                 WARN(1, "invalid cdclk frequency\n");
9531                 return;
9532         }
9533
9534         I915_WRITE(LCPLL_CTL, val);
9535
9536         val = I915_READ(LCPLL_CTL);
9537         val &= ~LCPLL_CD_SOURCE_FCLK;
9538         I915_WRITE(LCPLL_CTL, val);
9539
9540         if (wait_for_atomic_us((I915_READ(LCPLL_CTL) &
9541                                 LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9542                 DRM_ERROR("Switching back to LCPLL failed\n");
9543
9544         mutex_lock(&dev_priv->rps.hw_lock);
9545         sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ, data);
9546         mutex_unlock(&dev_priv->rps.hw_lock);
9547
9548         intel_update_cdclk(dev);
9549
9550         WARN(cdclk != dev_priv->cdclk_freq,
9551              "cdclk requested %d kHz but got %d kHz\n",
9552              cdclk, dev_priv->cdclk_freq);
9553 }
9554
9555 static int broadwell_modeset_calc_cdclk(struct drm_atomic_state *state)
9556 {
9557         struct drm_i915_private *dev_priv = to_i915(state->dev);
9558         int max_pixclk = ilk_max_pixel_rate(state);
9559         int cdclk;
9560
9561         /*
9562          * FIXME should also account for plane ratio
9563          * once 64bpp pixel formats are supported.
9564          */
9565         if (max_pixclk > 540000)
9566                 cdclk = 675000;
9567         else if (max_pixclk > 450000)
9568                 cdclk = 540000;
9569         else if (max_pixclk > 337500)
9570                 cdclk = 450000;
9571         else
9572                 cdclk = 337500;
9573
9574         /*
9575          * FIXME move the cdclk caclulation to
9576          * compute_config() so we can fail gracegully.
9577          */
9578         if (cdclk > dev_priv->max_cdclk_freq) {
9579                 DRM_ERROR("requested cdclk (%d kHz) exceeds max (%d kHz)\n",
9580                           cdclk, dev_priv->max_cdclk_freq);
9581                 cdclk = dev_priv->max_cdclk_freq;
9582         }
9583
9584         to_intel_atomic_state(state)->cdclk = cdclk;
9585
9586         return 0;
9587 }
9588
9589 static void broadwell_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9590 {
9591         struct drm_device *dev = old_state->dev;
9592         unsigned int req_cdclk = to_intel_atomic_state(old_state)->cdclk;
9593
9594         broadwell_set_cdclk(dev, req_cdclk);
9595 }
9596
9597 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9598                                       struct intel_crtc_state *crtc_state)
9599 {
9600         if (!intel_ddi_pll_select(crtc, crtc_state))
9601                 return -EINVAL;
9602
9603         crtc->lowfreq_avail = false;
9604
9605         return 0;
9606 }
9607
9608 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9609                                 enum port port,
9610                                 struct intel_crtc_state *pipe_config)
9611 {
9612         switch (port) {
9613         case PORT_A:
9614                 pipe_config->ddi_pll_sel = SKL_DPLL0;
9615                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL1;
9616                 break;
9617         case PORT_B:
9618                 pipe_config->ddi_pll_sel = SKL_DPLL1;
9619                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL2;
9620                 break;
9621         case PORT_C:
9622                 pipe_config->ddi_pll_sel = SKL_DPLL2;
9623                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL3;
9624                 break;
9625         default:
9626                 DRM_ERROR("Incorrect port type\n");
9627         }
9628 }
9629
9630 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9631                                 enum port port,
9632                                 struct intel_crtc_state *pipe_config)
9633 {
9634         u32 temp, dpll_ctl1;
9635
9636         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9637         pipe_config->ddi_pll_sel = temp >> (port * 3 + 1);
9638
9639         switch (pipe_config->ddi_pll_sel) {
9640         case SKL_DPLL0:
9641                 /*
9642                  * On SKL the eDP DPLL (DPLL0 as we don't use SSC) is not part
9643                  * of the shared DPLL framework and thus needs to be read out
9644                  * separately
9645                  */
9646                 dpll_ctl1 = I915_READ(DPLL_CTRL1);
9647                 pipe_config->dpll_hw_state.ctrl1 = dpll_ctl1 & 0x3f;
9648                 break;
9649         case SKL_DPLL1:
9650                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL1;
9651                 break;
9652         case SKL_DPLL2:
9653                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL2;
9654                 break;
9655         case SKL_DPLL3:
9656                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL3;
9657                 break;
9658         }
9659 }
9660
9661 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9662                                 enum port port,
9663                                 struct intel_crtc_state *pipe_config)
9664 {
9665         pipe_config->ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9666
9667         switch (pipe_config->ddi_pll_sel) {
9668         case PORT_CLK_SEL_WRPLL1:
9669                 pipe_config->shared_dpll = DPLL_ID_WRPLL1;
9670                 break;
9671         case PORT_CLK_SEL_WRPLL2:
9672                 pipe_config->shared_dpll = DPLL_ID_WRPLL2;
9673                 break;
9674         }
9675 }
9676
9677 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9678                                        struct intel_crtc_state *pipe_config)
9679 {
9680         struct drm_device *dev = crtc->base.dev;
9681         struct drm_i915_private *dev_priv = dev->dev_private;
9682         struct intel_shared_dpll *pll;
9683         enum port port;
9684         uint32_t tmp;
9685
9686         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9687
9688         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9689
9690         if (IS_SKYLAKE(dev))
9691                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
9692         else if (IS_BROXTON(dev))
9693                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
9694         else
9695                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
9696
9697         if (pipe_config->shared_dpll >= 0) {
9698                 pll = &dev_priv->shared_dplls[pipe_config->shared_dpll];
9699
9700                 WARN_ON(!pll->get_hw_state(dev_priv, pll,
9701                                            &pipe_config->dpll_hw_state));
9702         }
9703
9704         /*
9705          * Haswell has only FDI/PCH transcoder A. It is which is connected to
9706          * DDI E. So just check whether this pipe is wired to DDI E and whether
9707          * the PCH transcoder is on.
9708          */
9709         if (INTEL_INFO(dev)->gen < 9 &&
9710             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
9711                 pipe_config->has_pch_encoder = true;
9712
9713                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
9714                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9715                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9716
9717                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9718         }
9719 }
9720
9721 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
9722                                     struct intel_crtc_state *pipe_config)
9723 {
9724         struct drm_device *dev = crtc->base.dev;
9725         struct drm_i915_private *dev_priv = dev->dev_private;
9726         enum intel_display_power_domain pfit_domain;
9727         uint32_t tmp;
9728
9729         if (!intel_display_power_is_enabled(dev_priv,
9730                                          POWER_DOMAIN_PIPE(crtc->pipe)))
9731                 return false;
9732
9733         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9734         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
9735
9736         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
9737         if (tmp & TRANS_DDI_FUNC_ENABLE) {
9738                 enum pipe trans_edp_pipe;
9739                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9740                 default:
9741                         WARN(1, "unknown pipe linked to edp transcoder\n");
9742                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9743                 case TRANS_DDI_EDP_INPUT_A_ON:
9744                         trans_edp_pipe = PIPE_A;
9745                         break;
9746                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
9747                         trans_edp_pipe = PIPE_B;
9748                         break;
9749                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
9750                         trans_edp_pipe = PIPE_C;
9751                         break;
9752                 }
9753
9754                 if (trans_edp_pipe == crtc->pipe)
9755                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
9756         }
9757
9758         if (!intel_display_power_is_enabled(dev_priv,
9759                         POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder)))
9760                 return false;
9761
9762         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
9763         if (!(tmp & PIPECONF_ENABLE))
9764                 return false;
9765
9766         haswell_get_ddi_port_state(crtc, pipe_config);
9767
9768         intel_get_pipe_timings(crtc, pipe_config);
9769
9770         if (INTEL_INFO(dev)->gen >= 9) {
9771                 skl_init_scalers(dev, crtc, pipe_config);
9772         }
9773
9774         pfit_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
9775
9776         if (INTEL_INFO(dev)->gen >= 9) {
9777                 pipe_config->scaler_state.scaler_id = -1;
9778                 pipe_config->scaler_state.scaler_users &= ~(1 << SKL_CRTC_INDEX);
9779         }
9780
9781         if (intel_display_power_is_enabled(dev_priv, pfit_domain)) {
9782                 if (INTEL_INFO(dev)->gen >= 9)
9783                         skylake_get_pfit_config(crtc, pipe_config);
9784                 else
9785                         ironlake_get_pfit_config(crtc, pipe_config);
9786         }
9787
9788         if (IS_HASWELL(dev))
9789                 pipe_config->ips_enabled = hsw_crtc_supports_ips(crtc) &&
9790                         (I915_READ(IPS_CTL) & IPS_ENABLE);
9791
9792         if (pipe_config->cpu_transcoder != TRANSCODER_EDP) {
9793                 pipe_config->pixel_multiplier =
9794                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
9795         } else {
9796                 pipe_config->pixel_multiplier = 1;
9797         }
9798
9799         return true;
9800 }
9801
9802 static void i845_update_cursor(struct drm_crtc *crtc, u32 base)
9803 {
9804         struct drm_device *dev = crtc->dev;
9805         struct drm_i915_private *dev_priv = dev->dev_private;
9806         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9807         uint32_t cntl = 0, size = 0;
9808
9809         if (base) {
9810                 unsigned int width = intel_crtc->base.cursor->state->crtc_w;
9811                 unsigned int height = intel_crtc->base.cursor->state->crtc_h;
9812                 unsigned int stride = roundup_pow_of_two(width) * 4;
9813
9814                 switch (stride) {
9815                 default:
9816                         WARN_ONCE(1, "Invalid cursor width/stride, width=%u, stride=%u\n",
9817                                   width, stride);
9818                         stride = 256;
9819                         /* fallthrough */
9820                 case 256:
9821                 case 512:
9822                 case 1024:
9823                 case 2048:
9824                         break;
9825                 }
9826
9827                 cntl |= CURSOR_ENABLE |
9828                         CURSOR_GAMMA_ENABLE |
9829                         CURSOR_FORMAT_ARGB |
9830                         CURSOR_STRIDE(stride);
9831
9832                 size = (height << 12) | width;
9833         }
9834
9835         if (intel_crtc->cursor_cntl != 0 &&
9836             (intel_crtc->cursor_base != base ||
9837              intel_crtc->cursor_size != size ||
9838              intel_crtc->cursor_cntl != cntl)) {
9839                 /* On these chipsets we can only modify the base/size/stride
9840                  * whilst the cursor is disabled.
9841                  */
9842                 I915_WRITE(_CURACNTR, 0);
9843                 POSTING_READ(_CURACNTR);
9844                 intel_crtc->cursor_cntl = 0;
9845         }
9846
9847         if (intel_crtc->cursor_base != base) {
9848                 I915_WRITE(_CURABASE, base);
9849                 intel_crtc->cursor_base = base;
9850         }
9851
9852         if (intel_crtc->cursor_size != size) {
9853                 I915_WRITE(CURSIZE, size);
9854                 intel_crtc->cursor_size = size;
9855         }
9856
9857         if (intel_crtc->cursor_cntl != cntl) {
9858                 I915_WRITE(_CURACNTR, cntl);
9859                 POSTING_READ(_CURACNTR);
9860                 intel_crtc->cursor_cntl = cntl;
9861         }
9862 }
9863
9864 static void i9xx_update_cursor(struct drm_crtc *crtc, u32 base)
9865 {
9866         struct drm_device *dev = crtc->dev;
9867         struct drm_i915_private *dev_priv = dev->dev_private;
9868         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9869         int pipe = intel_crtc->pipe;
9870         uint32_t cntl;
9871
9872         cntl = 0;
9873         if (base) {
9874                 cntl = MCURSOR_GAMMA_ENABLE;
9875                 switch (intel_crtc->base.cursor->state->crtc_w) {
9876                         case 64:
9877                                 cntl |= CURSOR_MODE_64_ARGB_AX;
9878                                 break;
9879                         case 128:
9880                                 cntl |= CURSOR_MODE_128_ARGB_AX;
9881                                 break;
9882                         case 256:
9883                                 cntl |= CURSOR_MODE_256_ARGB_AX;
9884                                 break;
9885                         default:
9886                                 MISSING_CASE(intel_crtc->base.cursor->state->crtc_w);
9887                                 return;
9888                 }
9889                 cntl |= pipe << 28; /* Connect to correct pipe */
9890
9891                 if (IS_HASWELL(dev) || IS_BROADWELL(dev))
9892                         cntl |= CURSOR_PIPE_CSC_ENABLE;
9893         }
9894
9895         if (crtc->cursor->state->rotation == BIT(DRM_ROTATE_180))
9896                 cntl |= CURSOR_ROTATE_180;
9897
9898         if (intel_crtc->cursor_cntl != cntl) {
9899                 I915_WRITE(CURCNTR(pipe), cntl);
9900                 POSTING_READ(CURCNTR(pipe));
9901                 intel_crtc->cursor_cntl = cntl;
9902         }
9903
9904         /* and commit changes on next vblank */
9905         I915_WRITE(CURBASE(pipe), base);
9906         POSTING_READ(CURBASE(pipe));
9907
9908         intel_crtc->cursor_base = base;
9909 }
9910
9911 /* If no-part of the cursor is visible on the framebuffer, then the GPU may hang... */
9912 static void intel_crtc_update_cursor(struct drm_crtc *crtc,
9913                                      bool on)
9914 {
9915         struct drm_device *dev = crtc->dev;
9916         struct drm_i915_private *dev_priv = dev->dev_private;
9917         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9918         int pipe = intel_crtc->pipe;
9919         int x = crtc->cursor_x;
9920         int y = crtc->cursor_y;
9921         u32 base = 0, pos = 0;
9922
9923         if (on)
9924                 base = intel_crtc->cursor_addr;
9925
9926         if (x >= intel_crtc->config->pipe_src_w)
9927                 base = 0;
9928
9929         if (y >= intel_crtc->config->pipe_src_h)
9930                 base = 0;
9931
9932         if (x < 0) {
9933                 if (x + intel_crtc->base.cursor->state->crtc_w <= 0)
9934                         base = 0;
9935
9936                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
9937                 x = -x;
9938         }
9939         pos |= x << CURSOR_X_SHIFT;
9940
9941         if (y < 0) {
9942                 if (y + intel_crtc->base.cursor->state->crtc_h <= 0)
9943                         base = 0;
9944
9945                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
9946                 y = -y;
9947         }
9948         pos |= y << CURSOR_Y_SHIFT;
9949
9950         if (base == 0 && intel_crtc->cursor_base == 0)
9951                 return;
9952
9953         I915_WRITE(CURPOS(pipe), pos);
9954
9955         /* ILK+ do this automagically */
9956         if (HAS_GMCH_DISPLAY(dev) &&
9957             crtc->cursor->state->rotation == BIT(DRM_ROTATE_180)) {
9958                 base += (intel_crtc->base.cursor->state->crtc_h *
9959                         intel_crtc->base.cursor->state->crtc_w - 1) * 4;
9960         }
9961
9962         if (IS_845G(dev) || IS_I865G(dev))
9963                 i845_update_cursor(crtc, base);
9964         else
9965                 i9xx_update_cursor(crtc, base);
9966 }
9967
9968 static bool cursor_size_ok(struct drm_device *dev,
9969                            uint32_t width, uint32_t height)
9970 {
9971         if (width == 0 || height == 0)
9972                 return false;
9973
9974         /*
9975          * 845g/865g are special in that they are only limited by
9976          * the width of their cursors, the height is arbitrary up to
9977          * the precision of the register. Everything else requires
9978          * square cursors, limited to a few power-of-two sizes.
9979          */
9980         if (IS_845G(dev) || IS_I865G(dev)) {
9981                 if ((width & 63) != 0)
9982                         return false;
9983
9984                 if (width > (IS_845G(dev) ? 64 : 512))
9985                         return false;
9986
9987                 if (height > 1023)
9988                         return false;
9989         } else {
9990                 switch (width | height) {
9991                 case 256:
9992                 case 128:
9993                         if (IS_GEN2(dev))
9994                                 return false;
9995                 case 64:
9996                         break;
9997                 default:
9998                         return false;
9999                 }
10000         }
10001
10002         return true;
10003 }
10004
10005 static void intel_crtc_gamma_set(struct drm_crtc *crtc, u16 *red, u16 *green,
10006                                  u16 *blue, uint32_t start, uint32_t size)
10007 {
10008         int end = (start + size > 256) ? 256 : start + size, i;
10009         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10010
10011         for (i = start; i < end; i++) {
10012                 intel_crtc->lut_r[i] = red[i] >> 8;
10013                 intel_crtc->lut_g[i] = green[i] >> 8;
10014                 intel_crtc->lut_b[i] = blue[i] >> 8;
10015         }
10016
10017         intel_crtc_load_lut(crtc);
10018 }
10019
10020 /* VESA 640x480x72Hz mode to set on the pipe */
10021 static struct drm_display_mode load_detect_mode = {
10022         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10023                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10024 };
10025
10026 struct drm_framebuffer *
10027 __intel_framebuffer_create(struct drm_device *dev,
10028                            struct drm_mode_fb_cmd2 *mode_cmd,
10029                            struct drm_i915_gem_object *obj)
10030 {
10031         struct intel_framebuffer *intel_fb;
10032         int ret;
10033
10034         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10035         if (!intel_fb) {
10036                 drm_gem_object_unreference(&obj->base);
10037                 return ERR_PTR(-ENOMEM);
10038         }
10039
10040         ret = intel_framebuffer_init(dev, intel_fb, mode_cmd, obj);
10041         if (ret)
10042                 goto err;
10043
10044         return &intel_fb->base;
10045 err:
10046         drm_gem_object_unreference(&obj->base);
10047         kfree(intel_fb);
10048
10049         return ERR_PTR(ret);
10050 }
10051
10052 static struct drm_framebuffer *
10053 intel_framebuffer_create(struct drm_device *dev,
10054                          struct drm_mode_fb_cmd2 *mode_cmd,
10055                          struct drm_i915_gem_object *obj)
10056 {
10057         struct drm_framebuffer *fb;
10058         int ret;
10059
10060         ret = i915_mutex_lock_interruptible(dev);
10061         if (ret)
10062                 return ERR_PTR(ret);
10063         fb = __intel_framebuffer_create(dev, mode_cmd, obj);
10064         mutex_unlock(&dev->struct_mutex);
10065
10066         return fb;
10067 }
10068
10069 static u32
10070 intel_framebuffer_pitch_for_width(int width, int bpp)
10071 {
10072         u32 pitch = DIV_ROUND_UP(width * bpp, 8);
10073         return ALIGN(pitch, 64);
10074 }
10075
10076 static u32
10077 intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
10078 {
10079         u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
10080         return PAGE_ALIGN(pitch * mode->vdisplay);
10081 }
10082
10083 static struct drm_framebuffer *
10084 intel_framebuffer_create_for_mode(struct drm_device *dev,
10085                                   struct drm_display_mode *mode,
10086                                   int depth, int bpp)
10087 {
10088         struct drm_i915_gem_object *obj;
10089         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
10090
10091         obj = i915_gem_alloc_object(dev,
10092                                     intel_framebuffer_size_for_mode(mode, bpp));
10093         if (obj == NULL)
10094                 return ERR_PTR(-ENOMEM);
10095
10096         mode_cmd.width = mode->hdisplay;
10097         mode_cmd.height = mode->vdisplay;
10098         mode_cmd.pitches[0] = intel_framebuffer_pitch_for_width(mode_cmd.width,
10099                                                                 bpp);
10100         mode_cmd.pixel_format = drm_mode_legacy_fb_format(bpp, depth);
10101
10102         return intel_framebuffer_create(dev, &mode_cmd, obj);
10103 }
10104
10105 static struct drm_framebuffer *
10106 mode_fits_in_fbdev(struct drm_device *dev,
10107                    struct drm_display_mode *mode)
10108 {
10109 #ifdef CONFIG_DRM_FBDEV_EMULATION
10110         struct drm_i915_private *dev_priv = dev->dev_private;
10111         struct drm_i915_gem_object *obj;
10112         struct drm_framebuffer *fb;
10113
10114         if (!dev_priv->fbdev)
10115                 return NULL;
10116
10117         if (!dev_priv->fbdev->fb)
10118                 return NULL;
10119
10120         obj = dev_priv->fbdev->fb->obj;
10121         BUG_ON(!obj);
10122
10123         fb = &dev_priv->fbdev->fb->base;
10124         if (fb->pitches[0] < intel_framebuffer_pitch_for_width(mode->hdisplay,
10125                                                                fb->bits_per_pixel))
10126                 return NULL;
10127
10128         if (obj->base.size < mode->vdisplay * fb->pitches[0])
10129                 return NULL;
10130
10131         return fb;
10132 #else
10133         return NULL;
10134 #endif
10135 }
10136
10137 static int intel_modeset_setup_plane_state(struct drm_atomic_state *state,
10138                                            struct drm_crtc *crtc,
10139                                            struct drm_display_mode *mode,
10140                                            struct drm_framebuffer *fb,
10141                                            int x, int y)
10142 {
10143         struct drm_plane_state *plane_state;
10144         int hdisplay, vdisplay;
10145         int ret;
10146
10147         plane_state = drm_atomic_get_plane_state(state, crtc->primary);
10148         if (IS_ERR(plane_state))
10149                 return PTR_ERR(plane_state);
10150
10151         if (mode)
10152                 drm_crtc_get_hv_timing(mode, &hdisplay, &vdisplay);
10153         else
10154                 hdisplay = vdisplay = 0;
10155
10156         ret = drm_atomic_set_crtc_for_plane(plane_state, fb ? crtc : NULL);
10157         if (ret)
10158                 return ret;
10159         drm_atomic_set_fb_for_plane(plane_state, fb);
10160         plane_state->crtc_x = 0;
10161         plane_state->crtc_y = 0;
10162         plane_state->crtc_w = hdisplay;
10163         plane_state->crtc_h = vdisplay;
10164         plane_state->src_x = x << 16;
10165         plane_state->src_y = y << 16;
10166         plane_state->src_w = hdisplay << 16;
10167         plane_state->src_h = vdisplay << 16;
10168
10169         return 0;
10170 }
10171
10172 bool intel_get_load_detect_pipe(struct drm_connector *connector,
10173                                 struct drm_display_mode *mode,
10174                                 struct intel_load_detect_pipe *old,
10175                                 struct drm_modeset_acquire_ctx *ctx)
10176 {
10177         struct intel_crtc *intel_crtc;
10178         struct intel_encoder *intel_encoder =
10179                 intel_attached_encoder(connector);
10180         struct drm_crtc *possible_crtc;
10181         struct drm_encoder *encoder = &intel_encoder->base;
10182         struct drm_crtc *crtc = NULL;
10183         struct drm_device *dev = encoder->dev;
10184         struct drm_framebuffer *fb;
10185         struct drm_mode_config *config = &dev->mode_config;
10186         struct drm_atomic_state *state = NULL;
10187         struct drm_connector_state *connector_state;
10188         struct intel_crtc_state *crtc_state;
10189         int ret, i = -1;
10190
10191         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10192                       connector->base.id, connector->name,
10193                       encoder->base.id, encoder->name);
10194
10195 retry:
10196         ret = drm_modeset_lock(&config->connection_mutex, ctx);
10197         if (ret)
10198                 goto fail;
10199
10200         /*
10201          * Algorithm gets a little messy:
10202          *
10203          *   - if the connector already has an assigned crtc, use it (but make
10204          *     sure it's on first)
10205          *
10206          *   - try to find the first unused crtc that can drive this connector,
10207          *     and use that if we find one
10208          */
10209
10210         /* See if we already have a CRTC for this connector */
10211         if (encoder->crtc) {
10212                 crtc = encoder->crtc;
10213
10214                 ret = drm_modeset_lock(&crtc->mutex, ctx);
10215                 if (ret)
10216                         goto fail;
10217                 ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
10218                 if (ret)
10219                         goto fail;
10220
10221                 old->dpms_mode = connector->dpms;
10222                 old->load_detect_temp = false;
10223
10224                 /* Make sure the crtc and connector are running */
10225                 if (connector->dpms != DRM_MODE_DPMS_ON)
10226                         connector->funcs->dpms(connector, DRM_MODE_DPMS_ON);
10227
10228                 return true;
10229         }
10230
10231         /* Find an unused one (if possible) */
10232         for_each_crtc(dev, possible_crtc) {
10233                 i++;
10234                 if (!(encoder->possible_crtcs & (1 << i)))
10235                         continue;
10236                 if (possible_crtc->state->enable)
10237                         continue;
10238
10239                 crtc = possible_crtc;
10240                 break;
10241         }
10242
10243         /*
10244          * If we didn't find an unused CRTC, don't use any.
10245          */
10246         if (!crtc) {
10247                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
10248                 goto fail;
10249         }
10250
10251         ret = drm_modeset_lock(&crtc->mutex, ctx);
10252         if (ret)
10253                 goto fail;
10254         ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
10255         if (ret)
10256                 goto fail;
10257
10258         intel_crtc = to_intel_crtc(crtc);
10259         old->dpms_mode = connector->dpms;
10260         old->load_detect_temp = true;
10261         old->release_fb = NULL;
10262
10263         state = drm_atomic_state_alloc(dev);
10264         if (!state)
10265                 return false;
10266
10267         state->acquire_ctx = ctx;
10268
10269         connector_state = drm_atomic_get_connector_state(state, connector);
10270         if (IS_ERR(connector_state)) {
10271                 ret = PTR_ERR(connector_state);
10272                 goto fail;
10273         }
10274
10275         connector_state->crtc = crtc;
10276         connector_state->best_encoder = &intel_encoder->base;
10277
10278         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10279         if (IS_ERR(crtc_state)) {
10280                 ret = PTR_ERR(crtc_state);
10281                 goto fail;
10282         }
10283
10284         crtc_state->base.active = crtc_state->base.enable = true;
10285
10286         if (!mode)
10287                 mode = &load_detect_mode;
10288
10289         /* We need a framebuffer large enough to accommodate all accesses
10290          * that the plane may generate whilst we perform load detection.
10291          * We can not rely on the fbcon either being present (we get called
10292          * during its initialisation to detect all boot displays, or it may
10293          * not even exist) or that it is large enough to satisfy the
10294          * requested mode.
10295          */
10296         fb = mode_fits_in_fbdev(dev, mode);
10297         if (fb == NULL) {
10298                 DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
10299                 fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
10300                 old->release_fb = fb;
10301         } else
10302                 DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
10303         if (IS_ERR(fb)) {
10304                 DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
10305                 goto fail;
10306         }
10307
10308         ret = intel_modeset_setup_plane_state(state, crtc, mode, fb, 0, 0);
10309         if (ret)
10310                 goto fail;
10311
10312         drm_mode_copy(&crtc_state->base.mode, mode);
10313
10314         if (drm_atomic_commit(state)) {
10315                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
10316                 if (old->release_fb)
10317                         old->release_fb->funcs->destroy(old->release_fb);
10318                 goto fail;
10319         }
10320         crtc->primary->crtc = crtc;
10321
10322         /* let the connector get through one full cycle before testing */
10323         intel_wait_for_vblank(dev, intel_crtc->pipe);
10324         return true;
10325
10326 fail:
10327         drm_atomic_state_free(state);
10328         state = NULL;
10329
10330         if (ret == -EDEADLK) {
10331                 drm_modeset_backoff(ctx);
10332                 goto retry;
10333         }
10334
10335         return false;
10336 }
10337
10338 void intel_release_load_detect_pipe(struct drm_connector *connector,
10339                                     struct intel_load_detect_pipe *old,
10340                                     struct drm_modeset_acquire_ctx *ctx)
10341 {
10342         struct drm_device *dev = connector->dev;
10343         struct intel_encoder *intel_encoder =
10344                 intel_attached_encoder(connector);
10345         struct drm_encoder *encoder = &intel_encoder->base;
10346         struct drm_crtc *crtc = encoder->crtc;
10347         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10348         struct drm_atomic_state *state;
10349         struct drm_connector_state *connector_state;
10350         struct intel_crtc_state *crtc_state;
10351         int ret;
10352
10353         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10354                       connector->base.id, connector->name,
10355                       encoder->base.id, encoder->name);
10356
10357         if (old->load_detect_temp) {
10358                 state = drm_atomic_state_alloc(dev);
10359                 if (!state)
10360                         goto fail;
10361
10362                 state->acquire_ctx = ctx;
10363
10364                 connector_state = drm_atomic_get_connector_state(state, connector);
10365                 if (IS_ERR(connector_state))
10366                         goto fail;
10367
10368                 crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10369                 if (IS_ERR(crtc_state))
10370                         goto fail;
10371
10372                 connector_state->best_encoder = NULL;
10373                 connector_state->crtc = NULL;
10374
10375                 crtc_state->base.enable = crtc_state->base.active = false;
10376
10377                 ret = intel_modeset_setup_plane_state(state, crtc, NULL, NULL,
10378                                                       0, 0);
10379                 if (ret)
10380                         goto fail;
10381
10382                 ret = drm_atomic_commit(state);
10383                 if (ret)
10384                         goto fail;
10385
10386                 if (old->release_fb) {
10387                         drm_framebuffer_unregister_private(old->release_fb);
10388                         drm_framebuffer_unreference(old->release_fb);
10389                 }
10390
10391                 return;
10392         }
10393
10394         /* Switch crtc and encoder back off if necessary */
10395         if (old->dpms_mode != DRM_MODE_DPMS_ON)
10396                 connector->funcs->dpms(connector, old->dpms_mode);
10397
10398         return;
10399 fail:
10400         DRM_DEBUG_KMS("Couldn't release load detect pipe.\n");
10401         drm_atomic_state_free(state);
10402 }
10403
10404 static int i9xx_pll_refclk(struct drm_device *dev,
10405                            const struct intel_crtc_state *pipe_config)
10406 {
10407         struct drm_i915_private *dev_priv = dev->dev_private;
10408         u32 dpll = pipe_config->dpll_hw_state.dpll;
10409
10410         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10411                 return dev_priv->vbt.lvds_ssc_freq;
10412         else if (HAS_PCH_SPLIT(dev))
10413                 return 120000;
10414         else if (!IS_GEN2(dev))
10415                 return 96000;
10416         else
10417                 return 48000;
10418 }
10419
10420 /* Returns the clock of the currently programmed mode of the given pipe. */
10421 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
10422                                 struct intel_crtc_state *pipe_config)
10423 {
10424         struct drm_device *dev = crtc->base.dev;
10425         struct drm_i915_private *dev_priv = dev->dev_private;
10426         int pipe = pipe_config->cpu_transcoder;
10427         u32 dpll = pipe_config->dpll_hw_state.dpll;
10428         u32 fp;
10429         intel_clock_t clock;
10430         int port_clock;
10431         int refclk = i9xx_pll_refclk(dev, pipe_config);
10432
10433         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10434                 fp = pipe_config->dpll_hw_state.fp0;
10435         else
10436                 fp = pipe_config->dpll_hw_state.fp1;
10437
10438         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10439         if (IS_PINEVIEW(dev)) {
10440                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10441                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10442         } else {
10443                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10444                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10445         }
10446
10447         if (!IS_GEN2(dev)) {
10448                 if (IS_PINEVIEW(dev))
10449                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10450                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10451                 else
10452                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10453                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10454
10455                 switch (dpll & DPLL_MODE_MASK) {
10456                 case DPLLB_MODE_DAC_SERIAL:
10457                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10458                                 5 : 10;
10459                         break;
10460                 case DPLLB_MODE_LVDS:
10461                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10462                                 7 : 14;
10463                         break;
10464                 default:
10465                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10466                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10467                         return;
10468                 }
10469
10470                 if (IS_PINEVIEW(dev))
10471                         port_clock = pnv_calc_dpll_params(refclk, &clock);
10472                 else
10473                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
10474         } else {
10475                 u32 lvds = IS_I830(dev) ? 0 : I915_READ(LVDS);
10476                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10477
10478                 if (is_lvds) {
10479                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10480                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10481
10482                         if (lvds & LVDS_CLKB_POWER_UP)
10483                                 clock.p2 = 7;
10484                         else
10485                                 clock.p2 = 14;
10486                 } else {
10487                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10488                                 clock.p1 = 2;
10489                         else {
10490                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10491                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10492                         }
10493                         if (dpll & PLL_P2_DIVIDE_BY_4)
10494                                 clock.p2 = 4;
10495                         else
10496                                 clock.p2 = 2;
10497                 }
10498
10499                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10500         }
10501
10502         /*
10503          * This value includes pixel_multiplier. We will use
10504          * port_clock to compute adjusted_mode.crtc_clock in the
10505          * encoder's get_config() function.
10506          */
10507         pipe_config->port_clock = port_clock;
10508 }
10509
10510 int intel_dotclock_calculate(int link_freq,
10511                              const struct intel_link_m_n *m_n)
10512 {
10513         /*
10514          * The calculation for the data clock is:
10515          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10516          * But we want to avoid losing precison if possible, so:
10517          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10518          *
10519          * and the link clock is simpler:
10520          * link_clock = (m * link_clock) / n
10521          */
10522
10523         if (!m_n->link_n)
10524                 return 0;
10525
10526         return div_u64((u64)m_n->link_m * link_freq, m_n->link_n);
10527 }
10528
10529 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10530                                    struct intel_crtc_state *pipe_config)
10531 {
10532         struct drm_device *dev = crtc->base.dev;
10533
10534         /* read out port_clock from the DPLL */
10535         i9xx_crtc_clock_get(crtc, pipe_config);
10536
10537         /*
10538          * This value does not include pixel_multiplier.
10539          * We will check that port_clock and adjusted_mode.crtc_clock
10540          * agree once we know their relationship in the encoder's
10541          * get_config() function.
10542          */
10543         pipe_config->base.adjusted_mode.crtc_clock =
10544                 intel_dotclock_calculate(intel_fdi_link_freq(dev) * 10000,
10545                                          &pipe_config->fdi_m_n);
10546 }
10547
10548 /** Returns the currently programmed mode of the given pipe. */
10549 struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
10550                                              struct drm_crtc *crtc)
10551 {
10552         struct drm_i915_private *dev_priv = dev->dev_private;
10553         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10554         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
10555         struct drm_display_mode *mode;
10556         struct intel_crtc_state pipe_config;
10557         int htot = I915_READ(HTOTAL(cpu_transcoder));
10558         int hsync = I915_READ(HSYNC(cpu_transcoder));
10559         int vtot = I915_READ(VTOTAL(cpu_transcoder));
10560         int vsync = I915_READ(VSYNC(cpu_transcoder));
10561         enum pipe pipe = intel_crtc->pipe;
10562
10563         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10564         if (!mode)
10565                 return NULL;
10566
10567         /*
10568          * Construct a pipe_config sufficient for getting the clock info
10569          * back out of crtc_clock_get.
10570          *
10571          * Note, if LVDS ever uses a non-1 pixel multiplier, we'll need
10572          * to use a real value here instead.
10573          */
10574         pipe_config.cpu_transcoder = (enum transcoder) pipe;
10575         pipe_config.pixel_multiplier = 1;
10576         pipe_config.dpll_hw_state.dpll = I915_READ(DPLL(pipe));
10577         pipe_config.dpll_hw_state.fp0 = I915_READ(FP0(pipe));
10578         pipe_config.dpll_hw_state.fp1 = I915_READ(FP1(pipe));
10579         i9xx_crtc_clock_get(intel_crtc, &pipe_config);
10580
10581         mode->clock = pipe_config.port_clock / pipe_config.pixel_multiplier;
10582         mode->hdisplay = (htot & 0xffff) + 1;
10583         mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
10584         mode->hsync_start = (hsync & 0xffff) + 1;
10585         mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
10586         mode->vdisplay = (vtot & 0xffff) + 1;
10587         mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
10588         mode->vsync_start = (vsync & 0xffff) + 1;
10589         mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
10590
10591         drm_mode_set_name(mode);
10592
10593         return mode;
10594 }
10595
10596 void intel_mark_busy(struct drm_device *dev)
10597 {
10598         struct drm_i915_private *dev_priv = dev->dev_private;
10599
10600         if (dev_priv->mm.busy)
10601                 return;
10602
10603         intel_runtime_pm_get(dev_priv);
10604         i915_update_gfx_val(dev_priv);
10605         if (INTEL_INFO(dev)->gen >= 6)
10606                 gen6_rps_busy(dev_priv);
10607         dev_priv->mm.busy = true;
10608 }
10609
10610 void intel_mark_idle(struct drm_device *dev)
10611 {
10612         struct drm_i915_private *dev_priv = dev->dev_private;
10613
10614         if (!dev_priv->mm.busy)
10615                 return;
10616
10617         dev_priv->mm.busy = false;
10618
10619         if (INTEL_INFO(dev)->gen >= 6)
10620                 gen6_rps_idle(dev->dev_private);
10621
10622         intel_runtime_pm_put(dev_priv);
10623 }
10624
10625 static void intel_crtc_destroy(struct drm_crtc *crtc)
10626 {
10627         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10628         struct drm_device *dev = crtc->dev;
10629         struct intel_unpin_work *work;
10630
10631         spin_lock_irq(&dev->event_lock);
10632         work = intel_crtc->unpin_work;
10633         intel_crtc->unpin_work = NULL;
10634         spin_unlock_irq(&dev->event_lock);
10635
10636         if (work) {
10637                 cancel_work_sync(&work->work);
10638                 kfree(work);
10639         }
10640
10641         drm_crtc_cleanup(crtc);
10642
10643         kfree(intel_crtc);
10644 }
10645
10646 static void intel_unpin_work_fn(struct work_struct *__work)
10647 {
10648         struct intel_unpin_work *work =
10649                 container_of(__work, struct intel_unpin_work, work);
10650         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
10651         struct drm_device *dev = crtc->base.dev;
10652         struct drm_plane *primary = crtc->base.primary;
10653
10654         mutex_lock(&dev->struct_mutex);
10655         intel_unpin_fb_obj(work->old_fb, primary->state);
10656         drm_gem_object_unreference(&work->pending_flip_obj->base);
10657
10658         if (work->flip_queued_req)
10659                 i915_gem_request_assign(&work->flip_queued_req, NULL);
10660         mutex_unlock(&dev->struct_mutex);
10661
10662         intel_frontbuffer_flip_complete(dev, to_intel_plane(primary)->frontbuffer_bit);
10663         drm_framebuffer_unreference(work->old_fb);
10664
10665         BUG_ON(atomic_read(&crtc->unpin_work_count) == 0);
10666         atomic_dec(&crtc->unpin_work_count);
10667
10668         kfree(work);
10669 }
10670
10671 static void do_intel_finish_page_flip(struct drm_device *dev,
10672                                       struct drm_crtc *crtc)
10673 {
10674         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10675         struct intel_unpin_work *work;
10676         unsigned long flags;
10677
10678         /* Ignore early vblank irqs */
10679         if (intel_crtc == NULL)
10680                 return;
10681
10682         /*
10683          * This is called both by irq handlers and the reset code (to complete
10684          * lost pageflips) so needs the full irqsave spinlocks.
10685          */
10686         spin_lock_irqsave(&dev->event_lock, flags);
10687         work = intel_crtc->unpin_work;
10688
10689         /* Ensure we don't miss a work->pending update ... */
10690         smp_rmb();
10691
10692         if (work == NULL || atomic_read(&work->pending) < INTEL_FLIP_COMPLETE) {
10693                 spin_unlock_irqrestore(&dev->event_lock, flags);
10694                 return;
10695         }
10696
10697         page_flip_completed(intel_crtc);
10698
10699         spin_unlock_irqrestore(&dev->event_lock, flags);
10700 }
10701
10702 void intel_finish_page_flip(struct drm_device *dev, int pipe)
10703 {
10704         struct drm_i915_private *dev_priv = dev->dev_private;
10705         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
10706
10707         do_intel_finish_page_flip(dev, crtc);
10708 }
10709
10710 void intel_finish_page_flip_plane(struct drm_device *dev, int plane)
10711 {
10712         struct drm_i915_private *dev_priv = dev->dev_private;
10713         struct drm_crtc *crtc = dev_priv->plane_to_crtc_mapping[plane];
10714
10715         do_intel_finish_page_flip(dev, crtc);
10716 }
10717
10718 /* Is 'a' after or equal to 'b'? */
10719 static bool g4x_flip_count_after_eq(u32 a, u32 b)
10720 {
10721         return !((a - b) & 0x80000000);
10722 }
10723
10724 static bool page_flip_finished(struct intel_crtc *crtc)
10725 {
10726         struct drm_device *dev = crtc->base.dev;
10727         struct drm_i915_private *dev_priv = dev->dev_private;
10728
10729         if (i915_reset_in_progress(&dev_priv->gpu_error) ||
10730             crtc->reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
10731                 return true;
10732
10733         /*
10734          * The relevant registers doen't exist on pre-ctg.
10735          * As the flip done interrupt doesn't trigger for mmio
10736          * flips on gmch platforms, a flip count check isn't
10737          * really needed there. But since ctg has the registers,
10738          * include it in the check anyway.
10739          */
10740         if (INTEL_INFO(dev)->gen < 5 && !IS_G4X(dev))
10741                 return true;
10742
10743         /*
10744          * A DSPSURFLIVE check isn't enough in case the mmio and CS flips
10745          * used the same base address. In that case the mmio flip might
10746          * have completed, but the CS hasn't even executed the flip yet.
10747          *
10748          * A flip count check isn't enough as the CS might have updated
10749          * the base address just after start of vblank, but before we
10750          * managed to process the interrupt. This means we'd complete the
10751          * CS flip too soon.
10752          *
10753          * Combining both checks should get us a good enough result. It may
10754          * still happen that the CS flip has been executed, but has not
10755          * yet actually completed. But in case the base address is the same
10756          * anyway, we don't really care.
10757          */
10758         return (I915_READ(DSPSURFLIVE(crtc->plane)) & ~0xfff) ==
10759                 crtc->unpin_work->gtt_offset &&
10760                 g4x_flip_count_after_eq(I915_READ(PIPE_FLIPCOUNT_GM45(crtc->pipe)),
10761                                     crtc->unpin_work->flip_count);
10762 }
10763
10764 void intel_prepare_page_flip(struct drm_device *dev, int plane)
10765 {
10766         struct drm_i915_private *dev_priv = dev->dev_private;
10767         struct intel_crtc *intel_crtc =
10768                 to_intel_crtc(dev_priv->plane_to_crtc_mapping[plane]);
10769         unsigned long flags;
10770
10771
10772         /*
10773          * This is called both by irq handlers and the reset code (to complete
10774          * lost pageflips) so needs the full irqsave spinlocks.
10775          *
10776          * NB: An MMIO update of the plane base pointer will also
10777          * generate a page-flip completion irq, i.e. every modeset
10778          * is also accompanied by a spurious intel_prepare_page_flip().
10779          */
10780         spin_lock_irqsave(&dev->event_lock, flags);
10781         if (intel_crtc->unpin_work && page_flip_finished(intel_crtc))
10782                 atomic_inc_not_zero(&intel_crtc->unpin_work->pending);
10783         spin_unlock_irqrestore(&dev->event_lock, flags);
10784 }
10785
10786 static inline void intel_mark_page_flip_active(struct intel_crtc *intel_crtc)
10787 {
10788         /* Ensure that the work item is consistent when activating it ... */
10789         smp_wmb();
10790         atomic_set(&intel_crtc->unpin_work->pending, INTEL_FLIP_PENDING);
10791         /* and that it is marked active as soon as the irq could fire. */
10792         smp_wmb();
10793 }
10794
10795 static int intel_gen2_queue_flip(struct drm_device *dev,
10796                                  struct drm_crtc *crtc,
10797                                  struct drm_framebuffer *fb,
10798                                  struct drm_i915_gem_object *obj,
10799                                  struct drm_i915_gem_request *req,
10800                                  uint32_t flags)
10801 {
10802         struct intel_engine_cs *ring = req->ring;
10803         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10804         u32 flip_mask;
10805         int ret;
10806
10807         ret = intel_ring_begin(req, 6);
10808         if (ret)
10809                 return ret;
10810
10811         /* Can't queue multiple flips, so wait for the previous
10812          * one to finish before executing the next.
10813          */
10814         if (intel_crtc->plane)
10815                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
10816         else
10817                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
10818         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
10819         intel_ring_emit(ring, MI_NOOP);
10820         intel_ring_emit(ring, MI_DISPLAY_FLIP |
10821                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
10822         intel_ring_emit(ring, fb->pitches[0]);
10823         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
10824         intel_ring_emit(ring, 0); /* aux display base address, unused */
10825
10826         intel_mark_page_flip_active(intel_crtc);
10827         return 0;
10828 }
10829
10830 static int intel_gen3_queue_flip(struct drm_device *dev,
10831                                  struct drm_crtc *crtc,
10832                                  struct drm_framebuffer *fb,
10833                                  struct drm_i915_gem_object *obj,
10834                                  struct drm_i915_gem_request *req,
10835                                  uint32_t flags)
10836 {
10837         struct intel_engine_cs *ring = req->ring;
10838         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10839         u32 flip_mask;
10840         int ret;
10841
10842         ret = intel_ring_begin(req, 6);
10843         if (ret)
10844                 return ret;
10845
10846         if (intel_crtc->plane)
10847                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
10848         else
10849                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
10850         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
10851         intel_ring_emit(ring, MI_NOOP);
10852         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 |
10853                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
10854         intel_ring_emit(ring, fb->pitches[0]);
10855         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
10856         intel_ring_emit(ring, MI_NOOP);
10857
10858         intel_mark_page_flip_active(intel_crtc);
10859         return 0;
10860 }
10861
10862 static int intel_gen4_queue_flip(struct drm_device *dev,
10863                                  struct drm_crtc *crtc,
10864                                  struct drm_framebuffer *fb,
10865                                  struct drm_i915_gem_object *obj,
10866                                  struct drm_i915_gem_request *req,
10867                                  uint32_t flags)
10868 {
10869         struct intel_engine_cs *ring = req->ring;
10870         struct drm_i915_private *dev_priv = dev->dev_private;
10871         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10872         uint32_t pf, pipesrc;
10873         int ret;
10874
10875         ret = intel_ring_begin(req, 4);
10876         if (ret)
10877                 return ret;
10878
10879         /* i965+ uses the linear or tiled offsets from the
10880          * Display Registers (which do not change across a page-flip)
10881          * so we need only reprogram the base address.
10882          */
10883         intel_ring_emit(ring, MI_DISPLAY_FLIP |
10884                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
10885         intel_ring_emit(ring, fb->pitches[0]);
10886         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset |
10887                         obj->tiling_mode);
10888
10889         /* XXX Enabling the panel-fitter across page-flip is so far
10890          * untested on non-native modes, so ignore it for now.
10891          * pf = I915_READ(pipe == 0 ? PFA_CTL_1 : PFB_CTL_1) & PF_ENABLE;
10892          */
10893         pf = 0;
10894         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
10895         intel_ring_emit(ring, pf | pipesrc);
10896
10897         intel_mark_page_flip_active(intel_crtc);
10898         return 0;
10899 }
10900
10901 static int intel_gen6_queue_flip(struct drm_device *dev,
10902                                  struct drm_crtc *crtc,
10903                                  struct drm_framebuffer *fb,
10904                                  struct drm_i915_gem_object *obj,
10905                                  struct drm_i915_gem_request *req,
10906                                  uint32_t flags)
10907 {
10908         struct intel_engine_cs *ring = req->ring;
10909         struct drm_i915_private *dev_priv = dev->dev_private;
10910         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10911         uint32_t pf, pipesrc;
10912         int ret;
10913
10914         ret = intel_ring_begin(req, 4);
10915         if (ret)
10916                 return ret;
10917
10918         intel_ring_emit(ring, MI_DISPLAY_FLIP |
10919                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
10920         intel_ring_emit(ring, fb->pitches[0] | obj->tiling_mode);
10921         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
10922
10923         /* Contrary to the suggestions in the documentation,
10924          * "Enable Panel Fitter" does not seem to be required when page
10925          * flipping with a non-native mode, and worse causes a normal
10926          * modeset to fail.
10927          * pf = I915_READ(PF_CTL(intel_crtc->pipe)) & PF_ENABLE;
10928          */
10929         pf = 0;
10930         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
10931         intel_ring_emit(ring, pf | pipesrc);
10932
10933         intel_mark_page_flip_active(intel_crtc);
10934         return 0;
10935 }
10936
10937 static int intel_gen7_queue_flip(struct drm_device *dev,
10938                                  struct drm_crtc *crtc,
10939                                  struct drm_framebuffer *fb,
10940                                  struct drm_i915_gem_object *obj,
10941                                  struct drm_i915_gem_request *req,
10942                                  uint32_t flags)
10943 {
10944         struct intel_engine_cs *ring = req->ring;
10945         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10946         uint32_t plane_bit = 0;
10947         int len, ret;
10948
10949         switch (intel_crtc->plane) {
10950         case PLANE_A:
10951                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_A;
10952                 break;
10953         case PLANE_B:
10954                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_B;
10955                 break;
10956         case PLANE_C:
10957                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_C;
10958                 break;
10959         default:
10960                 WARN_ONCE(1, "unknown plane in flip command\n");
10961                 return -ENODEV;
10962         }
10963
10964         len = 4;
10965         if (ring->id == RCS) {
10966                 len += 6;
10967                 /*
10968                  * On Gen 8, SRM is now taking an extra dword to accommodate
10969                  * 48bits addresses, and we need a NOOP for the batch size to
10970                  * stay even.
10971                  */
10972                 if (IS_GEN8(dev))
10973                         len += 2;
10974         }
10975
10976         /*
10977          * BSpec MI_DISPLAY_FLIP for IVB:
10978          * "The full packet must be contained within the same cache line."
10979          *
10980          * Currently the LRI+SRM+MI_DISPLAY_FLIP all fit within the same
10981          * cacheline, if we ever start emitting more commands before
10982          * the MI_DISPLAY_FLIP we may need to first emit everything else,
10983          * then do the cacheline alignment, and finally emit the
10984          * MI_DISPLAY_FLIP.
10985          */
10986         ret = intel_ring_cacheline_align(req);
10987         if (ret)
10988                 return ret;
10989
10990         ret = intel_ring_begin(req, len);
10991         if (ret)
10992                 return ret;
10993
10994         /* Unmask the flip-done completion message. Note that the bspec says that
10995          * we should do this for both the BCS and RCS, and that we must not unmask
10996          * more than one flip event at any time (or ensure that one flip message
10997          * can be sent by waiting for flip-done prior to queueing new flips).
10998          * Experimentation says that BCS works despite DERRMR masking all
10999          * flip-done completion events and that unmasking all planes at once
11000          * for the RCS also doesn't appear to drop events. Setting the DERRMR
11001          * to zero does lead to lockups within MI_DISPLAY_FLIP.
11002          */
11003         if (ring->id == RCS) {
11004                 intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
11005                 intel_ring_emit(ring, DERRMR);
11006                 intel_ring_emit(ring, ~(DERRMR_PIPEA_PRI_FLIP_DONE |
11007                                         DERRMR_PIPEB_PRI_FLIP_DONE |
11008                                         DERRMR_PIPEC_PRI_FLIP_DONE));
11009                 if (IS_GEN8(dev))
11010                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM_GEN8 |
11011                                               MI_SRM_LRM_GLOBAL_GTT);
11012                 else
11013                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM |
11014                                               MI_SRM_LRM_GLOBAL_GTT);
11015                 intel_ring_emit(ring, DERRMR);
11016                 intel_ring_emit(ring, ring->scratch.gtt_offset + 256);
11017                 if (IS_GEN8(dev)) {
11018                         intel_ring_emit(ring, 0);
11019                         intel_ring_emit(ring, MI_NOOP);
11020                 }
11021         }
11022
11023         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 | plane_bit);
11024         intel_ring_emit(ring, (fb->pitches[0] | obj->tiling_mode));
11025         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
11026         intel_ring_emit(ring, (MI_NOOP));
11027
11028         intel_mark_page_flip_active(intel_crtc);
11029         return 0;
11030 }
11031
11032 static bool use_mmio_flip(struct intel_engine_cs *ring,
11033                           struct drm_i915_gem_object *obj)
11034 {
11035         /*
11036          * This is not being used for older platforms, because
11037          * non-availability of flip done interrupt forces us to use
11038          * CS flips. Older platforms derive flip done using some clever
11039          * tricks involving the flip_pending status bits and vblank irqs.
11040          * So using MMIO flips there would disrupt this mechanism.
11041          */
11042
11043         if (ring == NULL)
11044                 return true;
11045
11046         if (INTEL_INFO(ring->dev)->gen < 5)
11047                 return false;
11048
11049         if (i915.use_mmio_flip < 0)
11050                 return false;
11051         else if (i915.use_mmio_flip > 0)
11052                 return true;
11053         else if (i915.enable_execlists)
11054                 return true;
11055         else
11056                 return ring != i915_gem_request_get_ring(obj->last_write_req);
11057 }
11058
11059 static void skl_do_mmio_flip(struct intel_crtc *intel_crtc)
11060 {
11061         struct drm_device *dev = intel_crtc->base.dev;
11062         struct drm_i915_private *dev_priv = dev->dev_private;
11063         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
11064         const enum pipe pipe = intel_crtc->pipe;
11065         u32 ctl, stride;
11066
11067         ctl = I915_READ(PLANE_CTL(pipe, 0));
11068         ctl &= ~PLANE_CTL_TILED_MASK;
11069         switch (fb->modifier[0]) {
11070         case DRM_FORMAT_MOD_NONE:
11071                 break;
11072         case I915_FORMAT_MOD_X_TILED:
11073                 ctl |= PLANE_CTL_TILED_X;
11074                 break;
11075         case I915_FORMAT_MOD_Y_TILED:
11076                 ctl |= PLANE_CTL_TILED_Y;
11077                 break;
11078         case I915_FORMAT_MOD_Yf_TILED:
11079                 ctl |= PLANE_CTL_TILED_YF;
11080                 break;
11081         default:
11082                 MISSING_CASE(fb->modifier[0]);
11083         }
11084
11085         /*
11086          * The stride is either expressed as a multiple of 64 bytes chunks for
11087          * linear buffers or in number of tiles for tiled buffers.
11088          */
11089         stride = fb->pitches[0] /
11090                  intel_fb_stride_alignment(dev, fb->modifier[0],
11091                                            fb->pixel_format);
11092
11093         /*
11094          * Both PLANE_CTL and PLANE_STRIDE are not updated on vblank but on
11095          * PLANE_SURF updates, the update is then guaranteed to be atomic.
11096          */
11097         I915_WRITE(PLANE_CTL(pipe, 0), ctl);
11098         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
11099
11100         I915_WRITE(PLANE_SURF(pipe, 0), intel_crtc->unpin_work->gtt_offset);
11101         POSTING_READ(PLANE_SURF(pipe, 0));
11102 }
11103
11104 static void ilk_do_mmio_flip(struct intel_crtc *intel_crtc)
11105 {
11106         struct drm_device *dev = intel_crtc->base.dev;
11107         struct drm_i915_private *dev_priv = dev->dev_private;
11108         struct intel_framebuffer *intel_fb =
11109                 to_intel_framebuffer(intel_crtc->base.primary->fb);
11110         struct drm_i915_gem_object *obj = intel_fb->obj;
11111         u32 dspcntr;
11112         u32 reg;
11113
11114         reg = DSPCNTR(intel_crtc->plane);
11115         dspcntr = I915_READ(reg);
11116
11117         if (obj->tiling_mode != I915_TILING_NONE)
11118                 dspcntr |= DISPPLANE_TILED;
11119         else
11120                 dspcntr &= ~DISPPLANE_TILED;
11121
11122         I915_WRITE(reg, dspcntr);
11123
11124         I915_WRITE(DSPSURF(intel_crtc->plane),
11125                    intel_crtc->unpin_work->gtt_offset);
11126         POSTING_READ(DSPSURF(intel_crtc->plane));
11127
11128 }
11129
11130 /*
11131  * XXX: This is the temporary way to update the plane registers until we get
11132  * around to using the usual plane update functions for MMIO flips
11133  */
11134 static void intel_do_mmio_flip(struct intel_crtc *intel_crtc)
11135 {
11136         struct drm_device *dev = intel_crtc->base.dev;
11137
11138         intel_mark_page_flip_active(intel_crtc);
11139
11140         intel_pipe_update_start(intel_crtc);
11141
11142         if (INTEL_INFO(dev)->gen >= 9)
11143                 skl_do_mmio_flip(intel_crtc);
11144         else
11145                 /* use_mmio_flip() retricts MMIO flips to ilk+ */
11146                 ilk_do_mmio_flip(intel_crtc);
11147
11148         intel_pipe_update_end(intel_crtc);
11149 }
11150
11151 static void intel_mmio_flip_work_func(struct work_struct *work)
11152 {
11153         struct intel_mmio_flip *mmio_flip =
11154                 container_of(work, struct intel_mmio_flip, work);
11155
11156         if (mmio_flip->req)
11157                 WARN_ON(__i915_wait_request(mmio_flip->req,
11158                                             mmio_flip->crtc->reset_counter,
11159                                             false, NULL,
11160                                             &mmio_flip->i915->rps.mmioflips));
11161
11162         intel_do_mmio_flip(mmio_flip->crtc);
11163
11164         i915_gem_request_unreference__unlocked(mmio_flip->req);
11165         kfree(mmio_flip);
11166 }
11167
11168 static int intel_queue_mmio_flip(struct drm_device *dev,
11169                                  struct drm_crtc *crtc,
11170                                  struct drm_framebuffer *fb,
11171                                  struct drm_i915_gem_object *obj,
11172                                  struct intel_engine_cs *ring,
11173                                  uint32_t flags)
11174 {
11175         struct intel_mmio_flip *mmio_flip;
11176
11177         mmio_flip = kmalloc(sizeof(*mmio_flip), GFP_KERNEL);
11178         if (mmio_flip == NULL)
11179                 return -ENOMEM;
11180
11181         mmio_flip->i915 = to_i915(dev);
11182         mmio_flip->req = i915_gem_request_reference(obj->last_write_req);
11183         mmio_flip->crtc = to_intel_crtc(crtc);
11184
11185         INIT_WORK(&mmio_flip->work, intel_mmio_flip_work_func);
11186         schedule_work(&mmio_flip->work);
11187
11188         return 0;
11189 }
11190
11191 static int intel_default_queue_flip(struct drm_device *dev,
11192                                     struct drm_crtc *crtc,
11193                                     struct drm_framebuffer *fb,
11194                                     struct drm_i915_gem_object *obj,
11195                                     struct drm_i915_gem_request *req,
11196                                     uint32_t flags)
11197 {
11198         return -ENODEV;
11199 }
11200
11201 static bool __intel_pageflip_stall_check(struct drm_device *dev,
11202                                          struct drm_crtc *crtc)
11203 {
11204         struct drm_i915_private *dev_priv = dev->dev_private;
11205         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11206         struct intel_unpin_work *work = intel_crtc->unpin_work;
11207         u32 addr;
11208
11209         if (atomic_read(&work->pending) >= INTEL_FLIP_COMPLETE)
11210                 return true;
11211
11212         if (atomic_read(&work->pending) < INTEL_FLIP_PENDING)
11213                 return false;
11214
11215         if (!work->enable_stall_check)
11216                 return false;
11217
11218         if (work->flip_ready_vblank == 0) {
11219                 if (work->flip_queued_req &&
11220                     !i915_gem_request_completed(work->flip_queued_req, true))
11221                         return false;
11222
11223                 work->flip_ready_vblank = drm_crtc_vblank_count(crtc);
11224         }
11225
11226         if (drm_crtc_vblank_count(crtc) - work->flip_ready_vblank < 3)
11227                 return false;
11228
11229         /* Potential stall - if we see that the flip has happened,
11230          * assume a missed interrupt. */
11231         if (INTEL_INFO(dev)->gen >= 4)
11232                 addr = I915_HI_DISPBASE(I915_READ(DSPSURF(intel_crtc->plane)));
11233         else
11234                 addr = I915_READ(DSPADDR(intel_crtc->plane));
11235
11236         /* There is a potential issue here with a false positive after a flip
11237          * to the same address. We could address this by checking for a
11238          * non-incrementing frame counter.
11239          */
11240         return addr == work->gtt_offset;
11241 }
11242
11243 void intel_check_page_flip(struct drm_device *dev, int pipe)
11244 {
11245         struct drm_i915_private *dev_priv = dev->dev_private;
11246         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11247         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11248         struct intel_unpin_work *work;
11249
11250         WARN_ON(!in_interrupt());
11251
11252         if (crtc == NULL)
11253                 return;
11254
11255         spin_lock(&dev->event_lock);
11256         work = intel_crtc->unpin_work;
11257         if (work != NULL && __intel_pageflip_stall_check(dev, crtc)) {
11258                 WARN_ONCE(1, "Kicking stuck page flip: queued at %d, now %d\n",
11259                          work->flip_queued_vblank, drm_vblank_count(dev, pipe));
11260                 page_flip_completed(intel_crtc);
11261                 work = NULL;
11262         }
11263         if (work != NULL &&
11264             drm_vblank_count(dev, pipe) - work->flip_queued_vblank > 1)
11265                 intel_queue_rps_boost_for_request(dev, work->flip_queued_req);
11266         spin_unlock(&dev->event_lock);
11267 }
11268
11269 static int intel_crtc_page_flip(struct drm_crtc *crtc,
11270                                 struct drm_framebuffer *fb,
11271                                 struct drm_pending_vblank_event *event,
11272                                 uint32_t page_flip_flags)
11273 {
11274         struct drm_device *dev = crtc->dev;
11275         struct drm_i915_private *dev_priv = dev->dev_private;
11276         struct drm_framebuffer *old_fb = crtc->primary->fb;
11277         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
11278         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11279         struct drm_plane *primary = crtc->primary;
11280         enum pipe pipe = intel_crtc->pipe;
11281         struct intel_unpin_work *work;
11282         struct intel_engine_cs *ring;
11283         bool mmio_flip;
11284         struct drm_i915_gem_request *request = NULL;
11285         int ret;
11286
11287         /*
11288          * drm_mode_page_flip_ioctl() should already catch this, but double
11289          * check to be safe.  In the future we may enable pageflipping from
11290          * a disabled primary plane.
11291          */
11292         if (WARN_ON(intel_fb_obj(old_fb) == NULL))
11293                 return -EBUSY;
11294
11295         /* Can't change pixel format via MI display flips. */
11296         if (fb->pixel_format != crtc->primary->fb->pixel_format)
11297                 return -EINVAL;
11298
11299         /*
11300          * TILEOFF/LINOFF registers can't be changed via MI display flips.
11301          * Note that pitch changes could also affect these register.
11302          */
11303         if (INTEL_INFO(dev)->gen > 3 &&
11304             (fb->offsets[0] != crtc->primary->fb->offsets[0] ||
11305              fb->pitches[0] != crtc->primary->fb->pitches[0]))
11306                 return -EINVAL;
11307
11308         if (i915_terminally_wedged(&dev_priv->gpu_error))
11309                 goto out_hang;
11310
11311         work = kzalloc(sizeof(*work), GFP_KERNEL);
11312         if (work == NULL)
11313                 return -ENOMEM;
11314
11315         work->event = event;
11316         work->crtc = crtc;
11317         work->old_fb = old_fb;
11318         INIT_WORK(&work->work, intel_unpin_work_fn);
11319
11320         ret = drm_crtc_vblank_get(crtc);
11321         if (ret)
11322                 goto free_work;
11323
11324         /* We borrow the event spin lock for protecting unpin_work */
11325         spin_lock_irq(&dev->event_lock);
11326         if (intel_crtc->unpin_work) {
11327                 /* Before declaring the flip queue wedged, check if
11328                  * the hardware completed the operation behind our backs.
11329                  */
11330                 if (__intel_pageflip_stall_check(dev, crtc)) {
11331                         DRM_DEBUG_DRIVER("flip queue: previous flip completed, continuing\n");
11332                         page_flip_completed(intel_crtc);
11333                 } else {
11334                         DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
11335                         spin_unlock_irq(&dev->event_lock);
11336
11337                         drm_crtc_vblank_put(crtc);
11338                         kfree(work);
11339                         return -EBUSY;
11340                 }
11341         }
11342         intel_crtc->unpin_work = work;
11343         spin_unlock_irq(&dev->event_lock);
11344
11345         if (atomic_read(&intel_crtc->unpin_work_count) >= 2)
11346                 flush_workqueue(dev_priv->wq);
11347
11348         /* Reference the objects for the scheduled work. */
11349         drm_framebuffer_reference(work->old_fb);
11350         drm_gem_object_reference(&obj->base);
11351
11352         crtc->primary->fb = fb;
11353         update_state_fb(crtc->primary);
11354
11355         work->pending_flip_obj = obj;
11356
11357         ret = i915_mutex_lock_interruptible(dev);
11358         if (ret)
11359                 goto cleanup;
11360
11361         atomic_inc(&intel_crtc->unpin_work_count);
11362         intel_crtc->reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
11363
11364         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
11365                 work->flip_count = I915_READ(PIPE_FLIPCOUNT_GM45(pipe)) + 1;
11366
11367         if (IS_VALLEYVIEW(dev)) {
11368                 ring = &dev_priv->ring[BCS];
11369                 if (obj->tiling_mode != intel_fb_obj(work->old_fb)->tiling_mode)
11370                         /* vlv: DISPLAY_FLIP fails to change tiling */
11371                         ring = NULL;
11372         } else if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev)) {
11373                 ring = &dev_priv->ring[BCS];
11374         } else if (INTEL_INFO(dev)->gen >= 7) {
11375                 ring = i915_gem_request_get_ring(obj->last_write_req);
11376                 if (ring == NULL || ring->id != RCS)
11377                         ring = &dev_priv->ring[BCS];
11378         } else {
11379                 ring = &dev_priv->ring[RCS];
11380         }
11381
11382         mmio_flip = use_mmio_flip(ring, obj);
11383
11384         /* When using CS flips, we want to emit semaphores between rings.
11385          * However, when using mmio flips we will create a task to do the
11386          * synchronisation, so all we want here is to pin the framebuffer
11387          * into the display plane and skip any waits.
11388          */
11389         ret = intel_pin_and_fence_fb_obj(crtc->primary, fb,
11390                                          crtc->primary->state,
11391                                          mmio_flip ? i915_gem_request_get_ring(obj->last_write_req) : ring, &request);
11392         if (ret)
11393                 goto cleanup_pending;
11394
11395         work->gtt_offset = intel_plane_obj_offset(to_intel_plane(primary), obj)
11396                                                   + intel_crtc->dspaddr_offset;
11397
11398         if (mmio_flip) {
11399                 ret = intel_queue_mmio_flip(dev, crtc, fb, obj, ring,
11400                                             page_flip_flags);
11401                 if (ret)
11402                         goto cleanup_unpin;
11403
11404                 i915_gem_request_assign(&work->flip_queued_req,
11405                                         obj->last_write_req);
11406         } else {
11407                 if (!request) {
11408                         ret = i915_gem_request_alloc(ring, ring->default_context, &request);
11409                         if (ret)
11410                                 goto cleanup_unpin;
11411                 }
11412
11413                 ret = dev_priv->display.queue_flip(dev, crtc, fb, obj, request,
11414                                                    page_flip_flags);
11415                 if (ret)
11416                         goto cleanup_unpin;
11417
11418                 i915_gem_request_assign(&work->flip_queued_req, request);
11419         }
11420
11421         if (request)
11422                 i915_add_request_no_flush(request);
11423
11424         work->flip_queued_vblank = drm_crtc_vblank_count(crtc);
11425         work->enable_stall_check = true;
11426
11427         i915_gem_track_fb(intel_fb_obj(work->old_fb), obj,
11428                           to_intel_plane(primary)->frontbuffer_bit);
11429         mutex_unlock(&dev->struct_mutex);
11430
11431         intel_fbc_disable_crtc(intel_crtc);
11432         intel_frontbuffer_flip_prepare(dev,
11433                                        to_intel_plane(primary)->frontbuffer_bit);
11434
11435         trace_i915_flip_request(intel_crtc->plane, obj);
11436
11437         return 0;
11438
11439 cleanup_unpin:
11440         intel_unpin_fb_obj(fb, crtc->primary->state);
11441 cleanup_pending:
11442         if (request)
11443                 i915_gem_request_cancel(request);
11444         atomic_dec(&intel_crtc->unpin_work_count);
11445         mutex_unlock(&dev->struct_mutex);
11446 cleanup:
11447         crtc->primary->fb = old_fb;
11448         update_state_fb(crtc->primary);
11449
11450         drm_gem_object_unreference_unlocked(&obj->base);
11451         drm_framebuffer_unreference(work->old_fb);
11452
11453         spin_lock_irq(&dev->event_lock);
11454         intel_crtc->unpin_work = NULL;
11455         spin_unlock_irq(&dev->event_lock);
11456
11457         drm_crtc_vblank_put(crtc);
11458 free_work:
11459         kfree(work);
11460
11461         if (ret == -EIO) {
11462                 struct drm_atomic_state *state;
11463                 struct drm_plane_state *plane_state;
11464
11465 out_hang:
11466                 state = drm_atomic_state_alloc(dev);
11467                 if (!state)
11468                         return -ENOMEM;
11469                 state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
11470
11471 retry:
11472                 plane_state = drm_atomic_get_plane_state(state, primary);
11473                 ret = PTR_ERR_OR_ZERO(plane_state);
11474                 if (!ret) {
11475                         drm_atomic_set_fb_for_plane(plane_state, fb);
11476
11477                         ret = drm_atomic_set_crtc_for_plane(plane_state, crtc);
11478                         if (!ret)
11479                                 ret = drm_atomic_commit(state);
11480                 }
11481
11482                 if (ret == -EDEADLK) {
11483                         drm_modeset_backoff(state->acquire_ctx);
11484                         drm_atomic_state_clear(state);
11485                         goto retry;
11486                 }
11487
11488                 if (ret)
11489                         drm_atomic_state_free(state);
11490
11491                 if (ret == 0 && event) {
11492                         spin_lock_irq(&dev->event_lock);
11493                         drm_send_vblank_event(dev, pipe, event);
11494                         spin_unlock_irq(&dev->event_lock);
11495                 }
11496         }
11497         return ret;
11498 }
11499
11500
11501 /**
11502  * intel_wm_need_update - Check whether watermarks need updating
11503  * @plane: drm plane
11504  * @state: new plane state
11505  *
11506  * Check current plane state versus the new one to determine whether
11507  * watermarks need to be recalculated.
11508  *
11509  * Returns true or false.
11510  */
11511 static bool intel_wm_need_update(struct drm_plane *plane,
11512                                  struct drm_plane_state *state)
11513 {
11514         /* Update watermarks on tiling changes. */
11515         if (!plane->state->fb || !state->fb ||
11516             plane->state->fb->modifier[0] != state->fb->modifier[0] ||
11517             plane->state->rotation != state->rotation)
11518                 return true;
11519
11520         if (plane->state->crtc_w != state->crtc_w)
11521                 return true;
11522
11523         return false;
11524 }
11525
11526 int intel_plane_atomic_calc_changes(struct drm_crtc_state *crtc_state,
11527                                     struct drm_plane_state *plane_state)
11528 {
11529         struct drm_crtc *crtc = crtc_state->crtc;
11530         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11531         struct drm_plane *plane = plane_state->plane;
11532         struct drm_device *dev = crtc->dev;
11533         struct drm_i915_private *dev_priv = dev->dev_private;
11534         struct intel_plane_state *old_plane_state =
11535                 to_intel_plane_state(plane->state);
11536         int idx = intel_crtc->base.base.id, ret;
11537         int i = drm_plane_index(plane);
11538         bool mode_changed = needs_modeset(crtc_state);
11539         bool was_crtc_enabled = crtc->state->active;
11540         bool is_crtc_enabled = crtc_state->active;
11541
11542         bool turn_off, turn_on, visible, was_visible;
11543         struct drm_framebuffer *fb = plane_state->fb;
11544
11545         if (crtc_state && INTEL_INFO(dev)->gen >= 9 &&
11546             plane->type != DRM_PLANE_TYPE_CURSOR) {
11547                 ret = skl_update_scaler_plane(
11548                         to_intel_crtc_state(crtc_state),
11549                         to_intel_plane_state(plane_state));
11550                 if (ret)
11551                         return ret;
11552         }
11553
11554         /*
11555          * Disabling a plane is always okay; we just need to update
11556          * fb tracking in a special way since cleanup_fb() won't
11557          * get called by the plane helpers.
11558          */
11559         if (old_plane_state->base.fb && !fb)
11560                 intel_crtc->atomic.disabled_planes |= 1 << i;
11561
11562         was_visible = old_plane_state->visible;
11563         visible = to_intel_plane_state(plane_state)->visible;
11564
11565         if (!was_crtc_enabled && WARN_ON(was_visible))
11566                 was_visible = false;
11567
11568         if (!is_crtc_enabled && WARN_ON(visible))
11569                 visible = false;
11570
11571         if (!was_visible && !visible)
11572                 return 0;
11573
11574         turn_off = was_visible && (!visible || mode_changed);
11575         turn_on = visible && (!was_visible || mode_changed);
11576
11577         DRM_DEBUG_ATOMIC("[CRTC:%i] has [PLANE:%i] with fb %i\n", idx,
11578                          plane->base.id, fb ? fb->base.id : -1);
11579
11580         DRM_DEBUG_ATOMIC("[PLANE:%i] visible %i -> %i, off %i, on %i, ms %i\n",
11581                          plane->base.id, was_visible, visible,
11582                          turn_off, turn_on, mode_changed);
11583
11584         if (turn_on) {
11585                 intel_crtc->atomic.update_wm_pre = true;
11586                 /* must disable cxsr around plane enable/disable */
11587                 if (plane->type != DRM_PLANE_TYPE_CURSOR) {
11588                         intel_crtc->atomic.disable_cxsr = true;
11589                         /* to potentially re-enable cxsr */
11590                         intel_crtc->atomic.wait_vblank = true;
11591                         intel_crtc->atomic.update_wm_post = true;
11592                 }
11593         } else if (turn_off) {
11594                 intel_crtc->atomic.update_wm_post = true;
11595                 /* must disable cxsr around plane enable/disable */
11596                 if (plane->type != DRM_PLANE_TYPE_CURSOR) {
11597                         if (is_crtc_enabled)
11598                                 intel_crtc->atomic.wait_vblank = true;
11599                         intel_crtc->atomic.disable_cxsr = true;
11600                 }
11601         } else if (intel_wm_need_update(plane, plane_state)) {
11602                 intel_crtc->atomic.update_wm_pre = true;
11603         }
11604
11605         if (visible || was_visible)
11606                 intel_crtc->atomic.fb_bits |=
11607                         to_intel_plane(plane)->frontbuffer_bit;
11608
11609         switch (plane->type) {
11610         case DRM_PLANE_TYPE_PRIMARY:
11611                 intel_crtc->atomic.wait_for_flips = true;
11612                 intel_crtc->atomic.pre_disable_primary = turn_off;
11613                 intel_crtc->atomic.post_enable_primary = turn_on;
11614
11615                 if (turn_off) {
11616                         /*
11617                          * FIXME: Actually if we will still have any other
11618                          * plane enabled on the pipe we could let IPS enabled
11619                          * still, but for now lets consider that when we make
11620                          * primary invisible by setting DSPCNTR to 0 on
11621                          * update_primary_plane function IPS needs to be
11622                          * disable.
11623                          */
11624                         intel_crtc->atomic.disable_ips = true;
11625
11626                         intel_crtc->atomic.disable_fbc = true;
11627                 }
11628
11629                 /*
11630                  * FBC does not work on some platforms for rotated
11631                  * planes, so disable it when rotation is not 0 and
11632                  * update it when rotation is set back to 0.
11633                  *
11634                  * FIXME: This is redundant with the fbc update done in
11635                  * the primary plane enable function except that that
11636                  * one is done too late. We eventually need to unify
11637                  * this.
11638                  */
11639
11640                 if (visible &&
11641                     INTEL_INFO(dev)->gen <= 4 && !IS_G4X(dev) &&
11642                     dev_priv->fbc.crtc == intel_crtc &&
11643                     plane_state->rotation != BIT(DRM_ROTATE_0))
11644                         intel_crtc->atomic.disable_fbc = true;
11645
11646                 /*
11647                  * BDW signals flip done immediately if the plane
11648                  * is disabled, even if the plane enable is already
11649                  * armed to occur at the next vblank :(
11650                  */
11651                 if (turn_on && IS_BROADWELL(dev))
11652                         intel_crtc->atomic.wait_vblank = true;
11653
11654                 intel_crtc->atomic.update_fbc |= visible || mode_changed;
11655                 break;
11656         case DRM_PLANE_TYPE_CURSOR:
11657                 break;
11658         case DRM_PLANE_TYPE_OVERLAY:
11659                 if (turn_off && !mode_changed) {
11660                         intel_crtc->atomic.wait_vblank = true;
11661                         intel_crtc->atomic.update_sprite_watermarks |=
11662                                 1 << i;
11663                 }
11664         }
11665         return 0;
11666 }
11667
11668 static bool encoders_cloneable(const struct intel_encoder *a,
11669                                const struct intel_encoder *b)
11670 {
11671         /* masks could be asymmetric, so check both ways */
11672         return a == b || (a->cloneable & (1 << b->type) &&
11673                           b->cloneable & (1 << a->type));
11674 }
11675
11676 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
11677                                          struct intel_crtc *crtc,
11678                                          struct intel_encoder *encoder)
11679 {
11680         struct intel_encoder *source_encoder;
11681         struct drm_connector *connector;
11682         struct drm_connector_state *connector_state;
11683         int i;
11684
11685         for_each_connector_in_state(state, connector, connector_state, i) {
11686                 if (connector_state->crtc != &crtc->base)
11687                         continue;
11688
11689                 source_encoder =
11690                         to_intel_encoder(connector_state->best_encoder);
11691                 if (!encoders_cloneable(encoder, source_encoder))
11692                         return false;
11693         }
11694
11695         return true;
11696 }
11697
11698 static bool check_encoder_cloning(struct drm_atomic_state *state,
11699                                   struct intel_crtc *crtc)
11700 {
11701         struct intel_encoder *encoder;
11702         struct drm_connector *connector;
11703         struct drm_connector_state *connector_state;
11704         int i;
11705
11706         for_each_connector_in_state(state, connector, connector_state, i) {
11707                 if (connector_state->crtc != &crtc->base)
11708                         continue;
11709
11710                 encoder = to_intel_encoder(connector_state->best_encoder);
11711                 if (!check_single_encoder_cloning(state, crtc, encoder))
11712                         return false;
11713         }
11714
11715         return true;
11716 }
11717
11718 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
11719                                    struct drm_crtc_state *crtc_state)
11720 {
11721         struct drm_device *dev = crtc->dev;
11722         struct drm_i915_private *dev_priv = dev->dev_private;
11723         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11724         struct intel_crtc_state *pipe_config =
11725                 to_intel_crtc_state(crtc_state);
11726         struct drm_atomic_state *state = crtc_state->state;
11727         int ret;
11728         bool mode_changed = needs_modeset(crtc_state);
11729
11730         if (mode_changed && !check_encoder_cloning(state, intel_crtc)) {
11731                 DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
11732                 return -EINVAL;
11733         }
11734
11735         if (mode_changed && !crtc_state->active)
11736                 intel_crtc->atomic.update_wm_post = true;
11737
11738         if (mode_changed && crtc_state->enable &&
11739             dev_priv->display.crtc_compute_clock &&
11740             !WARN_ON(pipe_config->shared_dpll != DPLL_ID_PRIVATE)) {
11741                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
11742                                                            pipe_config);
11743                 if (ret)
11744                         return ret;
11745         }
11746
11747         ret = 0;
11748         if (INTEL_INFO(dev)->gen >= 9) {
11749                 if (mode_changed)
11750                         ret = skl_update_scaler_crtc(pipe_config);
11751
11752                 if (!ret)
11753                         ret = intel_atomic_setup_scalers(dev, intel_crtc,
11754                                                          pipe_config);
11755         }
11756
11757         return ret;
11758 }
11759
11760 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
11761         .mode_set_base_atomic = intel_pipe_set_base_atomic,
11762         .load_lut = intel_crtc_load_lut,
11763         .atomic_begin = intel_begin_crtc_commit,
11764         .atomic_flush = intel_finish_crtc_commit,
11765         .atomic_check = intel_crtc_atomic_check,
11766 };
11767
11768 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
11769 {
11770         struct intel_connector *connector;
11771
11772         for_each_intel_connector(dev, connector) {
11773                 if (connector->base.encoder) {
11774                         connector->base.state->best_encoder =
11775                                 connector->base.encoder;
11776                         connector->base.state->crtc =
11777                                 connector->base.encoder->crtc;
11778                 } else {
11779                         connector->base.state->best_encoder = NULL;
11780                         connector->base.state->crtc = NULL;
11781                 }
11782         }
11783 }
11784
11785 static void
11786 connected_sink_compute_bpp(struct intel_connector *connector,
11787                            struct intel_crtc_state *pipe_config)
11788 {
11789         int bpp = pipe_config->pipe_bpp;
11790
11791         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
11792                 connector->base.base.id,
11793                 connector->base.name);
11794
11795         /* Don't use an invalid EDID bpc value */
11796         if (connector->base.display_info.bpc &&
11797             connector->base.display_info.bpc * 3 < bpp) {
11798                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
11799                               bpp, connector->base.display_info.bpc*3);
11800                 pipe_config->pipe_bpp = connector->base.display_info.bpc*3;
11801         }
11802
11803         /* Clamp bpp to 8 on screens without EDID 1.4 */
11804         if (connector->base.display_info.bpc == 0 && bpp > 24) {
11805                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
11806                               bpp);
11807                 pipe_config->pipe_bpp = 24;
11808         }
11809 }
11810
11811 static int
11812 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
11813                           struct intel_crtc_state *pipe_config)
11814 {
11815         struct drm_device *dev = crtc->base.dev;
11816         struct drm_atomic_state *state;
11817         struct drm_connector *connector;
11818         struct drm_connector_state *connector_state;
11819         int bpp, i;
11820
11821         if ((IS_G4X(dev) || IS_VALLEYVIEW(dev)))
11822                 bpp = 10*3;
11823         else if (INTEL_INFO(dev)->gen >= 5)
11824                 bpp = 12*3;
11825         else
11826                 bpp = 8*3;
11827
11828
11829         pipe_config->pipe_bpp = bpp;
11830
11831         state = pipe_config->base.state;
11832
11833         /* Clamp display bpp to EDID value */
11834         for_each_connector_in_state(state, connector, connector_state, i) {
11835                 if (connector_state->crtc != &crtc->base)
11836                         continue;
11837
11838                 connected_sink_compute_bpp(to_intel_connector(connector),
11839                                            pipe_config);
11840         }
11841
11842         return bpp;
11843 }
11844
11845 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
11846 {
11847         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
11848                         "type: 0x%x flags: 0x%x\n",
11849                 mode->crtc_clock,
11850                 mode->crtc_hdisplay, mode->crtc_hsync_start,
11851                 mode->crtc_hsync_end, mode->crtc_htotal,
11852                 mode->crtc_vdisplay, mode->crtc_vsync_start,
11853                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
11854 }
11855
11856 static void intel_dump_pipe_config(struct intel_crtc *crtc,
11857                                    struct intel_crtc_state *pipe_config,
11858                                    const char *context)
11859 {
11860         struct drm_device *dev = crtc->base.dev;
11861         struct drm_plane *plane;
11862         struct intel_plane *intel_plane;
11863         struct intel_plane_state *state;
11864         struct drm_framebuffer *fb;
11865
11866         DRM_DEBUG_KMS("[CRTC:%d]%s config %p for pipe %c\n", crtc->base.base.id,
11867                       context, pipe_config, pipe_name(crtc->pipe));
11868
11869         DRM_DEBUG_KMS("cpu_transcoder: %c\n", transcoder_name(pipe_config->cpu_transcoder));
11870         DRM_DEBUG_KMS("pipe bpp: %i, dithering: %i\n",
11871                       pipe_config->pipe_bpp, pipe_config->dither);
11872         DRM_DEBUG_KMS("fdi/pch: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
11873                       pipe_config->has_pch_encoder,
11874                       pipe_config->fdi_lanes,
11875                       pipe_config->fdi_m_n.gmch_m, pipe_config->fdi_m_n.gmch_n,
11876                       pipe_config->fdi_m_n.link_m, pipe_config->fdi_m_n.link_n,
11877                       pipe_config->fdi_m_n.tu);
11878         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
11879                       pipe_config->has_dp_encoder,
11880                       pipe_config->lane_count,
11881                       pipe_config->dp_m_n.gmch_m, pipe_config->dp_m_n.gmch_n,
11882                       pipe_config->dp_m_n.link_m, pipe_config->dp_m_n.link_n,
11883                       pipe_config->dp_m_n.tu);
11884
11885         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m2: %u, gmch_n2: %u, link_m2: %u, link_n2: %u, tu2: %u\n",
11886                       pipe_config->has_dp_encoder,
11887                       pipe_config->lane_count,
11888                       pipe_config->dp_m2_n2.gmch_m,
11889                       pipe_config->dp_m2_n2.gmch_n,
11890                       pipe_config->dp_m2_n2.link_m,
11891                       pipe_config->dp_m2_n2.link_n,
11892                       pipe_config->dp_m2_n2.tu);
11893
11894         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
11895                       pipe_config->has_audio,
11896                       pipe_config->has_infoframe);
11897
11898         DRM_DEBUG_KMS("requested mode:\n");
11899         drm_mode_debug_printmodeline(&pipe_config->base.mode);
11900         DRM_DEBUG_KMS("adjusted mode:\n");
11901         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
11902         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
11903         DRM_DEBUG_KMS("port clock: %d\n", pipe_config->port_clock);
11904         DRM_DEBUG_KMS("pipe src size: %dx%d\n",
11905                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
11906         DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
11907                       crtc->num_scalers,
11908                       pipe_config->scaler_state.scaler_users,
11909                       pipe_config->scaler_state.scaler_id);
11910         DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
11911                       pipe_config->gmch_pfit.control,
11912                       pipe_config->gmch_pfit.pgm_ratios,
11913                       pipe_config->gmch_pfit.lvds_border_bits);
11914         DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
11915                       pipe_config->pch_pfit.pos,
11916                       pipe_config->pch_pfit.size,
11917                       pipe_config->pch_pfit.enabled ? "enabled" : "disabled");
11918         DRM_DEBUG_KMS("ips: %i\n", pipe_config->ips_enabled);
11919         DRM_DEBUG_KMS("double wide: %i\n", pipe_config->double_wide);
11920
11921         if (IS_BROXTON(dev)) {
11922                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: ebb0: 0x%x, ebb4: 0x%x,"
11923                               "pll0: 0x%x, pll1: 0x%x, pll2: 0x%x, pll3: 0x%x, "
11924                               "pll6: 0x%x, pll8: 0x%x, pll9: 0x%x, pll10: 0x%x, pcsdw12: 0x%x\n",
11925                               pipe_config->ddi_pll_sel,
11926                               pipe_config->dpll_hw_state.ebb0,
11927                               pipe_config->dpll_hw_state.ebb4,
11928                               pipe_config->dpll_hw_state.pll0,
11929                               pipe_config->dpll_hw_state.pll1,
11930                               pipe_config->dpll_hw_state.pll2,
11931                               pipe_config->dpll_hw_state.pll3,
11932                               pipe_config->dpll_hw_state.pll6,
11933                               pipe_config->dpll_hw_state.pll8,
11934                               pipe_config->dpll_hw_state.pll9,
11935                               pipe_config->dpll_hw_state.pll10,
11936                               pipe_config->dpll_hw_state.pcsdw12);
11937         } else if (IS_SKYLAKE(dev)) {
11938                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: "
11939                               "ctrl1: 0x%x, cfgcr1: 0x%x, cfgcr2: 0x%x\n",
11940                               pipe_config->ddi_pll_sel,
11941                               pipe_config->dpll_hw_state.ctrl1,
11942                               pipe_config->dpll_hw_state.cfgcr1,
11943                               pipe_config->dpll_hw_state.cfgcr2);
11944         } else if (HAS_DDI(dev)) {
11945                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: wrpll: 0x%x\n",
11946                               pipe_config->ddi_pll_sel,
11947                               pipe_config->dpll_hw_state.wrpll);
11948         } else {
11949                 DRM_DEBUG_KMS("dpll_hw_state: dpll: 0x%x, dpll_md: 0x%x, "
11950                               "fp0: 0x%x, fp1: 0x%x\n",
11951                               pipe_config->dpll_hw_state.dpll,
11952                               pipe_config->dpll_hw_state.dpll_md,
11953                               pipe_config->dpll_hw_state.fp0,
11954                               pipe_config->dpll_hw_state.fp1);
11955         }
11956
11957         DRM_DEBUG_KMS("planes on this crtc\n");
11958         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
11959                 intel_plane = to_intel_plane(plane);
11960                 if (intel_plane->pipe != crtc->pipe)
11961                         continue;
11962
11963                 state = to_intel_plane_state(plane->state);
11964                 fb = state->base.fb;
11965                 if (!fb) {
11966                         DRM_DEBUG_KMS("%s PLANE:%d plane: %u.%u idx: %d "
11967                                 "disabled, scaler_id = %d\n",
11968                                 plane->type == DRM_PLANE_TYPE_CURSOR ? "CURSOR" : "STANDARD",
11969                                 plane->base.id, intel_plane->pipe,
11970                                 (crtc->base.primary == plane) ? 0 : intel_plane->plane + 1,
11971                                 drm_plane_index(plane), state->scaler_id);
11972                         continue;
11973                 }
11974
11975                 DRM_DEBUG_KMS("%s PLANE:%d plane: %u.%u idx: %d enabled",
11976                         plane->type == DRM_PLANE_TYPE_CURSOR ? "CURSOR" : "STANDARD",
11977                         plane->base.id, intel_plane->pipe,
11978                         crtc->base.primary == plane ? 0 : intel_plane->plane + 1,
11979                         drm_plane_index(plane));
11980                 DRM_DEBUG_KMS("\tFB:%d, fb = %ux%u format = 0x%x",
11981                         fb->base.id, fb->width, fb->height, fb->pixel_format);
11982                 DRM_DEBUG_KMS("\tscaler:%d src (%u, %u) %ux%u dst (%u, %u) %ux%u\n",
11983                         state->scaler_id,
11984                         state->src.x1 >> 16, state->src.y1 >> 16,
11985                         drm_rect_width(&state->src) >> 16,
11986                         drm_rect_height(&state->src) >> 16,
11987                         state->dst.x1, state->dst.y1,
11988                         drm_rect_width(&state->dst), drm_rect_height(&state->dst));
11989         }
11990 }
11991
11992 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
11993 {
11994         struct drm_device *dev = state->dev;
11995         struct intel_encoder *encoder;
11996         struct drm_connector *connector;
11997         struct drm_connector_state *connector_state;
11998         unsigned int used_ports = 0;
11999         int i;
12000
12001         /*
12002          * Walk the connector list instead of the encoder
12003          * list to detect the problem on ddi platforms
12004          * where there's just one encoder per digital port.
12005          */
12006         for_each_connector_in_state(state, connector, connector_state, i) {
12007                 if (!connector_state->best_encoder)
12008                         continue;
12009
12010                 encoder = to_intel_encoder(connector_state->best_encoder);
12011
12012                 WARN_ON(!connector_state->crtc);
12013
12014                 switch (encoder->type) {
12015                         unsigned int port_mask;
12016                 case INTEL_OUTPUT_UNKNOWN:
12017                         if (WARN_ON(!HAS_DDI(dev)))
12018                                 break;
12019                 case INTEL_OUTPUT_DISPLAYPORT:
12020                 case INTEL_OUTPUT_HDMI:
12021                 case INTEL_OUTPUT_EDP:
12022                         port_mask = 1 << enc_to_dig_port(&encoder->base)->port;
12023
12024                         /* the same port mustn't appear more than once */
12025                         if (used_ports & port_mask)
12026                                 return false;
12027
12028                         used_ports |= port_mask;
12029                 default:
12030                         break;
12031                 }
12032         }
12033
12034         return true;
12035 }
12036
12037 static void
12038 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
12039 {
12040         struct drm_crtc_state tmp_state;
12041         struct intel_crtc_scaler_state scaler_state;
12042         struct intel_dpll_hw_state dpll_hw_state;
12043         enum intel_dpll_id shared_dpll;
12044         uint32_t ddi_pll_sel;
12045         bool force_thru;
12046
12047         /* FIXME: before the switch to atomic started, a new pipe_config was
12048          * kzalloc'd. Code that depends on any field being zero should be
12049          * fixed, so that the crtc_state can be safely duplicated. For now,
12050          * only fields that are know to not cause problems are preserved. */
12051
12052         tmp_state = crtc_state->base;
12053         scaler_state = crtc_state->scaler_state;
12054         shared_dpll = crtc_state->shared_dpll;
12055         dpll_hw_state = crtc_state->dpll_hw_state;
12056         ddi_pll_sel = crtc_state->ddi_pll_sel;
12057         force_thru = crtc_state->pch_pfit.force_thru;
12058
12059         memset(crtc_state, 0, sizeof *crtc_state);
12060
12061         crtc_state->base = tmp_state;
12062         crtc_state->scaler_state = scaler_state;
12063         crtc_state->shared_dpll = shared_dpll;
12064         crtc_state->dpll_hw_state = dpll_hw_state;
12065         crtc_state->ddi_pll_sel = ddi_pll_sel;
12066         crtc_state->pch_pfit.force_thru = force_thru;
12067 }
12068
12069 static int
12070 intel_modeset_pipe_config(struct drm_crtc *crtc,
12071                           struct intel_crtc_state *pipe_config)
12072 {
12073         struct drm_atomic_state *state = pipe_config->base.state;
12074         struct intel_encoder *encoder;
12075         struct drm_connector *connector;
12076         struct drm_connector_state *connector_state;
12077         int base_bpp, ret = -EINVAL;
12078         int i;
12079         bool retry = true;
12080
12081         clear_intel_crtc_state(pipe_config);
12082
12083         pipe_config->cpu_transcoder =
12084                 (enum transcoder) to_intel_crtc(crtc)->pipe;
12085
12086         /*
12087          * Sanitize sync polarity flags based on requested ones. If neither
12088          * positive or negative polarity is requested, treat this as meaning
12089          * negative polarity.
12090          */
12091         if (!(pipe_config->base.adjusted_mode.flags &
12092               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
12093                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
12094
12095         if (!(pipe_config->base.adjusted_mode.flags &
12096               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
12097                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
12098
12099         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
12100                                              pipe_config);
12101         if (base_bpp < 0)
12102                 goto fail;
12103
12104         /*
12105          * Determine the real pipe dimensions. Note that stereo modes can
12106          * increase the actual pipe size due to the frame doubling and
12107          * insertion of additional space for blanks between the frame. This
12108          * is stored in the crtc timings. We use the requested mode to do this
12109          * computation to clearly distinguish it from the adjusted mode, which
12110          * can be changed by the connectors in the below retry loop.
12111          */
12112         drm_crtc_get_hv_timing(&pipe_config->base.mode,
12113                                &pipe_config->pipe_src_w,
12114                                &pipe_config->pipe_src_h);
12115
12116 encoder_retry:
12117         /* Ensure the port clock defaults are reset when retrying. */
12118         pipe_config->port_clock = 0;
12119         pipe_config->pixel_multiplier = 1;
12120
12121         /* Fill in default crtc timings, allow encoders to overwrite them. */
12122         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
12123                               CRTC_STEREO_DOUBLE);
12124
12125         /* Pass our mode to the connectors and the CRTC to give them a chance to
12126          * adjust it according to limitations or connector properties, and also
12127          * a chance to reject the mode entirely.
12128          */
12129         for_each_connector_in_state(state, connector, connector_state, i) {
12130                 if (connector_state->crtc != crtc)
12131                         continue;
12132
12133                 encoder = to_intel_encoder(connector_state->best_encoder);
12134
12135                 if (!(encoder->compute_config(encoder, pipe_config))) {
12136                         DRM_DEBUG_KMS("Encoder config failure\n");
12137                         goto fail;
12138                 }
12139         }
12140
12141         /* Set default port clock if not overwritten by the encoder. Needs to be
12142          * done afterwards in case the encoder adjusts the mode. */
12143         if (!pipe_config->port_clock)
12144                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
12145                         * pipe_config->pixel_multiplier;
12146
12147         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
12148         if (ret < 0) {
12149                 DRM_DEBUG_KMS("CRTC fixup failed\n");
12150                 goto fail;
12151         }
12152
12153         if (ret == RETRY) {
12154                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
12155                         ret = -EINVAL;
12156                         goto fail;
12157                 }
12158
12159                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
12160                 retry = false;
12161                 goto encoder_retry;
12162         }
12163
12164         /* Dithering seems to not pass-through bits correctly when it should, so
12165          * only enable it on 6bpc panels. */
12166         pipe_config->dither = pipe_config->pipe_bpp == 6*3;
12167         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
12168                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
12169
12170 fail:
12171         return ret;
12172 }
12173
12174 static void
12175 intel_modeset_update_crtc_state(struct drm_atomic_state *state)
12176 {
12177         struct drm_crtc *crtc;
12178         struct drm_crtc_state *crtc_state;
12179         int i;
12180
12181         /* Double check state. */
12182         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12183                 to_intel_crtc(crtc)->config = to_intel_crtc_state(crtc->state);
12184
12185                 /* Update hwmode for vblank functions */
12186                 if (crtc->state->active)
12187                         crtc->hwmode = crtc->state->adjusted_mode;
12188                 else
12189                         crtc->hwmode.crtc_clock = 0;
12190         }
12191 }
12192
12193 static bool intel_fuzzy_clock_check(int clock1, int clock2)
12194 {
12195         int diff;
12196
12197         if (clock1 == clock2)
12198                 return true;
12199
12200         if (!clock1 || !clock2)
12201                 return false;
12202
12203         diff = abs(clock1 - clock2);
12204
12205         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
12206                 return true;
12207
12208         return false;
12209 }
12210
12211 #define for_each_intel_crtc_masked(dev, mask, intel_crtc) \
12212         list_for_each_entry((intel_crtc), \
12213                             &(dev)->mode_config.crtc_list, \
12214                             base.head) \
12215                 if (mask & (1 <<(intel_crtc)->pipe))
12216
12217
12218 static bool
12219 intel_compare_m_n(unsigned int m, unsigned int n,
12220                   unsigned int m2, unsigned int n2,
12221                   bool exact)
12222 {
12223         if (m == m2 && n == n2)
12224                 return true;
12225
12226         if (exact || !m || !n || !m2 || !n2)
12227                 return false;
12228
12229         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
12230
12231         if (m > m2) {
12232                 while (m > m2) {
12233                         m2 <<= 1;
12234                         n2 <<= 1;
12235                 }
12236         } else if (m < m2) {
12237                 while (m < m2) {
12238                         m <<= 1;
12239                         n <<= 1;
12240                 }
12241         }
12242
12243         return m == m2 && n == n2;
12244 }
12245
12246 static bool
12247 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
12248                        struct intel_link_m_n *m2_n2,
12249                        bool adjust)
12250 {
12251         if (m_n->tu == m2_n2->tu &&
12252             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
12253                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
12254             intel_compare_m_n(m_n->link_m, m_n->link_n,
12255                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
12256                 if (adjust)
12257                         *m2_n2 = *m_n;
12258
12259                 return true;
12260         }
12261
12262         return false;
12263 }
12264
12265 static bool
12266 intel_pipe_config_compare(struct drm_device *dev,
12267                           struct intel_crtc_state *current_config,
12268                           struct intel_crtc_state *pipe_config,
12269                           bool adjust)
12270 {
12271         bool ret = true;
12272
12273 #define INTEL_ERR_OR_DBG_KMS(fmt, ...) \
12274         do { \
12275                 if (!adjust) \
12276                         DRM_ERROR(fmt, ##__VA_ARGS__); \
12277                 else \
12278                         DRM_DEBUG_KMS(fmt, ##__VA_ARGS__); \
12279         } while (0)
12280
12281 #define PIPE_CONF_CHECK_X(name) \
12282         if (current_config->name != pipe_config->name) { \
12283                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12284                           "(expected 0x%08x, found 0x%08x)\n", \
12285                           current_config->name, \
12286                           pipe_config->name); \
12287                 ret = false; \
12288         }
12289
12290 #define PIPE_CONF_CHECK_I(name) \
12291         if (current_config->name != pipe_config->name) { \
12292                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12293                           "(expected %i, found %i)\n", \
12294                           current_config->name, \
12295                           pipe_config->name); \
12296                 ret = false; \
12297         }
12298
12299 #define PIPE_CONF_CHECK_M_N(name) \
12300         if (!intel_compare_link_m_n(&current_config->name, \
12301                                     &pipe_config->name,\
12302                                     adjust)) { \
12303                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12304                           "(expected tu %i gmch %i/%i link %i/%i, " \
12305                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12306                           current_config->name.tu, \
12307                           current_config->name.gmch_m, \
12308                           current_config->name.gmch_n, \
12309                           current_config->name.link_m, \
12310                           current_config->name.link_n, \
12311                           pipe_config->name.tu, \
12312                           pipe_config->name.gmch_m, \
12313                           pipe_config->name.gmch_n, \
12314                           pipe_config->name.link_m, \
12315                           pipe_config->name.link_n); \
12316                 ret = false; \
12317         }
12318
12319 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) \
12320         if (!intel_compare_link_m_n(&current_config->name, \
12321                                     &pipe_config->name, adjust) && \
12322             !intel_compare_link_m_n(&current_config->alt_name, \
12323                                     &pipe_config->name, adjust)) { \
12324                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12325                           "(expected tu %i gmch %i/%i link %i/%i, " \
12326                           "or tu %i gmch %i/%i link %i/%i, " \
12327                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12328                           current_config->name.tu, \
12329                           current_config->name.gmch_m, \
12330                           current_config->name.gmch_n, \
12331                           current_config->name.link_m, \
12332                           current_config->name.link_n, \
12333                           current_config->alt_name.tu, \
12334                           current_config->alt_name.gmch_m, \
12335                           current_config->alt_name.gmch_n, \
12336                           current_config->alt_name.link_m, \
12337                           current_config->alt_name.link_n, \
12338                           pipe_config->name.tu, \
12339                           pipe_config->name.gmch_m, \
12340                           pipe_config->name.gmch_n, \
12341                           pipe_config->name.link_m, \
12342                           pipe_config->name.link_n); \
12343                 ret = false; \
12344         }
12345
12346 /* This is required for BDW+ where there is only one set of registers for
12347  * switching between high and low RR.
12348  * This macro can be used whenever a comparison has to be made between one
12349  * hw state and multiple sw state variables.
12350  */
12351 #define PIPE_CONF_CHECK_I_ALT(name, alt_name) \
12352         if ((current_config->name != pipe_config->name) && \
12353                 (current_config->alt_name != pipe_config->name)) { \
12354                         INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12355                                   "(expected %i or %i, found %i)\n", \
12356                                   current_config->name, \
12357                                   current_config->alt_name, \
12358                                   pipe_config->name); \
12359                         ret = false; \
12360         }
12361
12362 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
12363         if ((current_config->name ^ pipe_config->name) & (mask)) { \
12364                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name "(" #mask ") " \
12365                           "(expected %i, found %i)\n", \
12366                           current_config->name & (mask), \
12367                           pipe_config->name & (mask)); \
12368                 ret = false; \
12369         }
12370
12371 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
12372         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
12373                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12374                           "(expected %i, found %i)\n", \
12375                           current_config->name, \
12376                           pipe_config->name); \
12377                 ret = false; \
12378         }
12379
12380 #define PIPE_CONF_QUIRK(quirk)  \
12381         ((current_config->quirks | pipe_config->quirks) & (quirk))
12382
12383         PIPE_CONF_CHECK_I(cpu_transcoder);
12384
12385         PIPE_CONF_CHECK_I(has_pch_encoder);
12386         PIPE_CONF_CHECK_I(fdi_lanes);
12387         PIPE_CONF_CHECK_M_N(fdi_m_n);
12388
12389         PIPE_CONF_CHECK_I(has_dp_encoder);
12390         PIPE_CONF_CHECK_I(lane_count);
12391
12392         if (INTEL_INFO(dev)->gen < 8) {
12393                 PIPE_CONF_CHECK_M_N(dp_m_n);
12394
12395                 PIPE_CONF_CHECK_I(has_drrs);
12396                 if (current_config->has_drrs)
12397                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
12398         } else
12399                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
12400
12401         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
12402         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
12403         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
12404         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
12405         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
12406         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
12407
12408         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
12409         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
12410         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
12411         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
12412         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
12413         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
12414
12415         PIPE_CONF_CHECK_I(pixel_multiplier);
12416         PIPE_CONF_CHECK_I(has_hdmi_sink);
12417         if ((INTEL_INFO(dev)->gen < 8 && !IS_HASWELL(dev)) ||
12418             IS_VALLEYVIEW(dev))
12419                 PIPE_CONF_CHECK_I(limited_color_range);
12420         PIPE_CONF_CHECK_I(has_infoframe);
12421
12422         PIPE_CONF_CHECK_I(has_audio);
12423
12424         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12425                               DRM_MODE_FLAG_INTERLACE);
12426
12427         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
12428                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12429                                       DRM_MODE_FLAG_PHSYNC);
12430                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12431                                       DRM_MODE_FLAG_NHSYNC);
12432                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12433                                       DRM_MODE_FLAG_PVSYNC);
12434                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12435                                       DRM_MODE_FLAG_NVSYNC);
12436         }
12437
12438         PIPE_CONF_CHECK_I(pipe_src_w);
12439         PIPE_CONF_CHECK_I(pipe_src_h);
12440
12441         PIPE_CONF_CHECK_X(gmch_pfit.control);
12442         /* pfit ratios are autocomputed by the hw on gen4+ */
12443         if (INTEL_INFO(dev)->gen < 4)
12444                 PIPE_CONF_CHECK_I(gmch_pfit.pgm_ratios);
12445         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
12446
12447         PIPE_CONF_CHECK_I(pch_pfit.enabled);
12448         if (current_config->pch_pfit.enabled) {
12449                 PIPE_CONF_CHECK_X(pch_pfit.pos);
12450                 PIPE_CONF_CHECK_X(pch_pfit.size);
12451         }
12452
12453         PIPE_CONF_CHECK_I(scaler_state.scaler_id);
12454
12455         /* BDW+ don't expose a synchronous way to read the state */
12456         if (IS_HASWELL(dev))
12457                 PIPE_CONF_CHECK_I(ips_enabled);
12458
12459         PIPE_CONF_CHECK_I(double_wide);
12460
12461         PIPE_CONF_CHECK_X(ddi_pll_sel);
12462
12463         PIPE_CONF_CHECK_I(shared_dpll);
12464         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
12465         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
12466         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
12467         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
12468         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
12469         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
12470         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
12471         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
12472
12473         if (IS_G4X(dev) || INTEL_INFO(dev)->gen >= 5)
12474                 PIPE_CONF_CHECK_I(pipe_bpp);
12475
12476         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
12477         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
12478
12479 #undef PIPE_CONF_CHECK_X
12480 #undef PIPE_CONF_CHECK_I
12481 #undef PIPE_CONF_CHECK_I_ALT
12482 #undef PIPE_CONF_CHECK_FLAGS
12483 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
12484 #undef PIPE_CONF_QUIRK
12485 #undef INTEL_ERR_OR_DBG_KMS
12486
12487         return ret;
12488 }
12489
12490 static void check_wm_state(struct drm_device *dev)
12491 {
12492         struct drm_i915_private *dev_priv = dev->dev_private;
12493         struct skl_ddb_allocation hw_ddb, *sw_ddb;
12494         struct intel_crtc *intel_crtc;
12495         int plane;
12496
12497         if (INTEL_INFO(dev)->gen < 9)
12498                 return;
12499
12500         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
12501         sw_ddb = &dev_priv->wm.skl_hw.ddb;
12502
12503         for_each_intel_crtc(dev, intel_crtc) {
12504                 struct skl_ddb_entry *hw_entry, *sw_entry;
12505                 const enum pipe pipe = intel_crtc->pipe;
12506
12507                 if (!intel_crtc->active)
12508                         continue;
12509
12510                 /* planes */
12511                 for_each_plane(dev_priv, pipe, plane) {
12512                         hw_entry = &hw_ddb.plane[pipe][plane];
12513                         sw_entry = &sw_ddb->plane[pipe][plane];
12514
12515                         if (skl_ddb_entry_equal(hw_entry, sw_entry))
12516                                 continue;
12517
12518                         DRM_ERROR("mismatch in DDB state pipe %c plane %d "
12519                                   "(expected (%u,%u), found (%u,%u))\n",
12520                                   pipe_name(pipe), plane + 1,
12521                                   sw_entry->start, sw_entry->end,
12522                                   hw_entry->start, hw_entry->end);
12523                 }
12524
12525                 /* cursor */
12526                 hw_entry = &hw_ddb.cursor[pipe];
12527                 sw_entry = &sw_ddb->cursor[pipe];
12528
12529                 if (skl_ddb_entry_equal(hw_entry, sw_entry))
12530                         continue;
12531
12532                 DRM_ERROR("mismatch in DDB state pipe %c cursor "
12533                           "(expected (%u,%u), found (%u,%u))\n",
12534                           pipe_name(pipe),
12535                           sw_entry->start, sw_entry->end,
12536                           hw_entry->start, hw_entry->end);
12537         }
12538 }
12539
12540 static void
12541 check_connector_state(struct drm_device *dev,
12542                       struct drm_atomic_state *old_state)
12543 {
12544         struct drm_connector_state *old_conn_state;
12545         struct drm_connector *connector;
12546         int i;
12547
12548         for_each_connector_in_state(old_state, connector, old_conn_state, i) {
12549                 struct drm_encoder *encoder = connector->encoder;
12550                 struct drm_connector_state *state = connector->state;
12551
12552                 /* This also checks the encoder/connector hw state with the
12553                  * ->get_hw_state callbacks. */
12554                 intel_connector_check_state(to_intel_connector(connector));
12555
12556                 I915_STATE_WARN(state->best_encoder != encoder,
12557                      "connector's atomic encoder doesn't match legacy encoder\n");
12558         }
12559 }
12560
12561 static void
12562 check_encoder_state(struct drm_device *dev)
12563 {
12564         struct intel_encoder *encoder;
12565         struct intel_connector *connector;
12566
12567         for_each_intel_encoder(dev, encoder) {
12568                 bool enabled = false;
12569                 enum pipe pipe;
12570
12571                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
12572                               encoder->base.base.id,
12573                               encoder->base.name);
12574
12575                 for_each_intel_connector(dev, connector) {
12576                         if (connector->base.state->best_encoder != &encoder->base)
12577                                 continue;
12578                         enabled = true;
12579
12580                         I915_STATE_WARN(connector->base.state->crtc !=
12581                                         encoder->base.crtc,
12582                              "connector's crtc doesn't match encoder crtc\n");
12583                 }
12584
12585                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
12586                      "encoder's enabled state mismatch "
12587                      "(expected %i, found %i)\n",
12588                      !!encoder->base.crtc, enabled);
12589
12590                 if (!encoder->base.crtc) {
12591                         bool active;
12592
12593                         active = encoder->get_hw_state(encoder, &pipe);
12594                         I915_STATE_WARN(active,
12595                              "encoder detached but still enabled on pipe %c.\n",
12596                              pipe_name(pipe));
12597                 }
12598         }
12599 }
12600
12601 static void
12602 check_crtc_state(struct drm_device *dev, struct drm_atomic_state *old_state)
12603 {
12604         struct drm_i915_private *dev_priv = dev->dev_private;
12605         struct intel_encoder *encoder;
12606         struct drm_crtc_state *old_crtc_state;
12607         struct drm_crtc *crtc;
12608         int i;
12609
12610         for_each_crtc_in_state(old_state, crtc, old_crtc_state, i) {
12611                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12612                 struct intel_crtc_state *pipe_config, *sw_config;
12613                 bool active;
12614
12615                 if (!needs_modeset(crtc->state))
12616                         continue;
12617
12618                 __drm_atomic_helper_crtc_destroy_state(crtc, old_crtc_state);
12619                 pipe_config = to_intel_crtc_state(old_crtc_state);
12620                 memset(pipe_config, 0, sizeof(*pipe_config));
12621                 pipe_config->base.crtc = crtc;
12622                 pipe_config->base.state = old_state;
12623
12624                 DRM_DEBUG_KMS("[CRTC:%d]\n",
12625                               crtc->base.id);
12626
12627                 active = dev_priv->display.get_pipe_config(intel_crtc,
12628                                                            pipe_config);
12629
12630                 /* hw state is inconsistent with the pipe quirk */
12631                 if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
12632                     (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
12633                         active = crtc->state->active;
12634
12635                 I915_STATE_WARN(crtc->state->active != active,
12636                      "crtc active state doesn't match with hw state "
12637                      "(expected %i, found %i)\n", crtc->state->active, active);
12638
12639                 I915_STATE_WARN(intel_crtc->active != crtc->state->active,
12640                      "transitional active state does not match atomic hw state "
12641                      "(expected %i, found %i)\n", crtc->state->active, intel_crtc->active);
12642
12643                 for_each_encoder_on_crtc(dev, crtc, encoder) {
12644                         enum pipe pipe;
12645
12646                         active = encoder->get_hw_state(encoder, &pipe);
12647                         I915_STATE_WARN(active != crtc->state->active,
12648                                 "[ENCODER:%i] active %i with crtc active %i\n",
12649                                 encoder->base.base.id, active, crtc->state->active);
12650
12651                         I915_STATE_WARN(active && intel_crtc->pipe != pipe,
12652                                         "Encoder connected to wrong pipe %c\n",
12653                                         pipe_name(pipe));
12654
12655                         if (active)
12656                                 encoder->get_config(encoder, pipe_config);
12657                 }
12658
12659                 if (!crtc->state->active)
12660                         continue;
12661
12662                 sw_config = to_intel_crtc_state(crtc->state);
12663                 if (!intel_pipe_config_compare(dev, sw_config,
12664                                                pipe_config, false)) {
12665                         I915_STATE_WARN(1, "pipe state doesn't match!\n");
12666                         intel_dump_pipe_config(intel_crtc, pipe_config,
12667                                                "[hw state]");
12668                         intel_dump_pipe_config(intel_crtc, sw_config,
12669                                                "[sw state]");
12670                 }
12671         }
12672 }
12673
12674 static void
12675 check_shared_dpll_state(struct drm_device *dev)
12676 {
12677         struct drm_i915_private *dev_priv = dev->dev_private;
12678         struct intel_crtc *crtc;
12679         struct intel_dpll_hw_state dpll_hw_state;
12680         int i;
12681
12682         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
12683                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
12684                 int enabled_crtcs = 0, active_crtcs = 0;
12685                 bool active;
12686
12687                 memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
12688
12689                 DRM_DEBUG_KMS("%s\n", pll->name);
12690
12691                 active = pll->get_hw_state(dev_priv, pll, &dpll_hw_state);
12692
12693                 I915_STATE_WARN(pll->active > hweight32(pll->config.crtc_mask),
12694                      "more active pll users than references: %i vs %i\n",
12695                      pll->active, hweight32(pll->config.crtc_mask));
12696                 I915_STATE_WARN(pll->active && !pll->on,
12697                      "pll in active use but not on in sw tracking\n");
12698                 I915_STATE_WARN(pll->on && !pll->active,
12699                      "pll in on but not on in use in sw tracking\n");
12700                 I915_STATE_WARN(pll->on != active,
12701                      "pll on state mismatch (expected %i, found %i)\n",
12702                      pll->on, active);
12703
12704                 for_each_intel_crtc(dev, crtc) {
12705                         if (crtc->base.state->enable && intel_crtc_to_shared_dpll(crtc) == pll)
12706                                 enabled_crtcs++;
12707                         if (crtc->active && intel_crtc_to_shared_dpll(crtc) == pll)
12708                                 active_crtcs++;
12709                 }
12710                 I915_STATE_WARN(pll->active != active_crtcs,
12711                      "pll active crtcs mismatch (expected %i, found %i)\n",
12712                      pll->active, active_crtcs);
12713                 I915_STATE_WARN(hweight32(pll->config.crtc_mask) != enabled_crtcs,
12714                      "pll enabled crtcs mismatch (expected %i, found %i)\n",
12715                      hweight32(pll->config.crtc_mask), enabled_crtcs);
12716
12717                 I915_STATE_WARN(pll->on && memcmp(&pll->config.hw_state, &dpll_hw_state,
12718                                        sizeof(dpll_hw_state)),
12719                      "pll hw state mismatch\n");
12720         }
12721 }
12722
12723 static void
12724 intel_modeset_check_state(struct drm_device *dev,
12725                           struct drm_atomic_state *old_state)
12726 {
12727         check_wm_state(dev);
12728         check_connector_state(dev, old_state);
12729         check_encoder_state(dev);
12730         check_crtc_state(dev, old_state);
12731         check_shared_dpll_state(dev);
12732 }
12733
12734 void ironlake_check_encoder_dotclock(const struct intel_crtc_state *pipe_config,
12735                                      int dotclock)
12736 {
12737         /*
12738          * FDI already provided one idea for the dotclock.
12739          * Yell if the encoder disagrees.
12740          */
12741         WARN(!intel_fuzzy_clock_check(pipe_config->base.adjusted_mode.crtc_clock, dotclock),
12742              "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
12743              pipe_config->base.adjusted_mode.crtc_clock, dotclock);
12744 }
12745
12746 static void update_scanline_offset(struct intel_crtc *crtc)
12747 {
12748         struct drm_device *dev = crtc->base.dev;
12749
12750         /*
12751          * The scanline counter increments at the leading edge of hsync.
12752          *
12753          * On most platforms it starts counting from vtotal-1 on the
12754          * first active line. That means the scanline counter value is
12755          * always one less than what we would expect. Ie. just after
12756          * start of vblank, which also occurs at start of hsync (on the
12757          * last active line), the scanline counter will read vblank_start-1.
12758          *
12759          * On gen2 the scanline counter starts counting from 1 instead
12760          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
12761          * to keep the value positive), instead of adding one.
12762          *
12763          * On HSW+ the behaviour of the scanline counter depends on the output
12764          * type. For DP ports it behaves like most other platforms, but on HDMI
12765          * there's an extra 1 line difference. So we need to add two instead of
12766          * one to the value.
12767          */
12768         if (IS_GEN2(dev)) {
12769                 const struct drm_display_mode *mode = &crtc->config->base.adjusted_mode;
12770                 int vtotal;
12771
12772                 vtotal = mode->crtc_vtotal;
12773                 if (mode->flags & DRM_MODE_FLAG_INTERLACE)
12774                         vtotal /= 2;
12775
12776                 crtc->scanline_offset = vtotal - 1;
12777         } else if (HAS_DDI(dev) &&
12778                    intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI)) {
12779                 crtc->scanline_offset = 2;
12780         } else
12781                 crtc->scanline_offset = 1;
12782 }
12783
12784 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
12785 {
12786         struct drm_device *dev = state->dev;
12787         struct drm_i915_private *dev_priv = to_i915(dev);
12788         struct intel_shared_dpll_config *shared_dpll = NULL;
12789         struct intel_crtc *intel_crtc;
12790         struct intel_crtc_state *intel_crtc_state;
12791         struct drm_crtc *crtc;
12792         struct drm_crtc_state *crtc_state;
12793         int i;
12794
12795         if (!dev_priv->display.crtc_compute_clock)
12796                 return;
12797
12798         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12799                 int dpll;
12800
12801                 intel_crtc = to_intel_crtc(crtc);
12802                 intel_crtc_state = to_intel_crtc_state(crtc_state);
12803                 dpll = intel_crtc_state->shared_dpll;
12804
12805                 if (!needs_modeset(crtc_state) || dpll == DPLL_ID_PRIVATE)
12806                         continue;
12807
12808                 intel_crtc_state->shared_dpll = DPLL_ID_PRIVATE;
12809
12810                 if (!shared_dpll)
12811                         shared_dpll = intel_atomic_get_shared_dpll_state(state);
12812
12813                 shared_dpll[dpll].crtc_mask &= ~(1 << intel_crtc->pipe);
12814         }
12815 }
12816
12817 /*
12818  * This implements the workaround described in the "notes" section of the mode
12819  * set sequence documentation. When going from no pipes or single pipe to
12820  * multiple pipes, and planes are enabled after the pipe, we need to wait at
12821  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
12822  */
12823 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
12824 {
12825         struct drm_crtc_state *crtc_state;
12826         struct intel_crtc *intel_crtc;
12827         struct drm_crtc *crtc;
12828         struct intel_crtc_state *first_crtc_state = NULL;
12829         struct intel_crtc_state *other_crtc_state = NULL;
12830         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
12831         int i;
12832
12833         /* look at all crtc's that are going to be enabled in during modeset */
12834         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12835                 intel_crtc = to_intel_crtc(crtc);
12836
12837                 if (!crtc_state->active || !needs_modeset(crtc_state))
12838                         continue;
12839
12840                 if (first_crtc_state) {
12841                         other_crtc_state = to_intel_crtc_state(crtc_state);
12842                         break;
12843                 } else {
12844                         first_crtc_state = to_intel_crtc_state(crtc_state);
12845                         first_pipe = intel_crtc->pipe;
12846                 }
12847         }
12848
12849         /* No workaround needed? */
12850         if (!first_crtc_state)
12851                 return 0;
12852
12853         /* w/a possibly needed, check how many crtc's are already enabled. */
12854         for_each_intel_crtc(state->dev, intel_crtc) {
12855                 struct intel_crtc_state *pipe_config;
12856
12857                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
12858                 if (IS_ERR(pipe_config))
12859                         return PTR_ERR(pipe_config);
12860
12861                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
12862
12863                 if (!pipe_config->base.active ||
12864                     needs_modeset(&pipe_config->base))
12865                         continue;
12866
12867                 /* 2 or more enabled crtcs means no need for w/a */
12868                 if (enabled_pipe != INVALID_PIPE)
12869                         return 0;
12870
12871                 enabled_pipe = intel_crtc->pipe;
12872         }
12873
12874         if (enabled_pipe != INVALID_PIPE)
12875                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
12876         else if (other_crtc_state)
12877                 other_crtc_state->hsw_workaround_pipe = first_pipe;
12878
12879         return 0;
12880 }
12881
12882 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
12883 {
12884         struct drm_crtc *crtc;
12885         struct drm_crtc_state *crtc_state;
12886         int ret = 0;
12887
12888         /* add all active pipes to the state */
12889         for_each_crtc(state->dev, crtc) {
12890                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
12891                 if (IS_ERR(crtc_state))
12892                         return PTR_ERR(crtc_state);
12893
12894                 if (!crtc_state->active || needs_modeset(crtc_state))
12895                         continue;
12896
12897                 crtc_state->mode_changed = true;
12898
12899                 ret = drm_atomic_add_affected_connectors(state, crtc);
12900                 if (ret)
12901                         break;
12902
12903                 ret = drm_atomic_add_affected_planes(state, crtc);
12904                 if (ret)
12905                         break;
12906         }
12907
12908         return ret;
12909 }
12910
12911
12912 static int intel_modeset_checks(struct drm_atomic_state *state)
12913 {
12914         struct drm_device *dev = state->dev;
12915         struct drm_i915_private *dev_priv = dev->dev_private;
12916         int ret;
12917
12918         if (!check_digital_port_conflicts(state)) {
12919                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
12920                 return -EINVAL;
12921         }
12922
12923         /*
12924          * See if the config requires any additional preparation, e.g.
12925          * to adjust global state with pipes off.  We need to do this
12926          * here so we can get the modeset_pipe updated config for the new
12927          * mode set on this crtc.  For other crtcs we need to use the
12928          * adjusted_mode bits in the crtc directly.
12929          */
12930         if (dev_priv->display.modeset_calc_cdclk) {
12931                 unsigned int cdclk;
12932
12933                 ret = dev_priv->display.modeset_calc_cdclk(state);
12934
12935                 cdclk = to_intel_atomic_state(state)->cdclk;
12936                 if (!ret && cdclk != dev_priv->cdclk_freq)
12937                         ret = intel_modeset_all_pipes(state);
12938
12939                 if (ret < 0)
12940                         return ret;
12941         } else
12942                 to_intel_atomic_state(state)->cdclk = dev_priv->cdclk_freq;
12943
12944         intel_modeset_clear_plls(state);
12945
12946         if (IS_HASWELL(dev))
12947                 return haswell_mode_set_planes_workaround(state);
12948
12949         return 0;
12950 }
12951
12952 /**
12953  * intel_atomic_check - validate state object
12954  * @dev: drm device
12955  * @state: state to validate
12956  */
12957 static int intel_atomic_check(struct drm_device *dev,
12958                               struct drm_atomic_state *state)
12959 {
12960         struct drm_crtc *crtc;
12961         struct drm_crtc_state *crtc_state;
12962         int ret, i;
12963         bool any_ms = false;
12964
12965         ret = drm_atomic_helper_check_modeset(dev, state);
12966         if (ret)
12967                 return ret;
12968
12969         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12970                 struct intel_crtc_state *pipe_config =
12971                         to_intel_crtc_state(crtc_state);
12972
12973                 /* Catch I915_MODE_FLAG_INHERITED */
12974                 if (crtc_state->mode.private_flags != crtc->state->mode.private_flags)
12975                         crtc_state->mode_changed = true;
12976
12977                 if (!crtc_state->enable) {
12978                         if (needs_modeset(crtc_state))
12979                                 any_ms = true;
12980                         continue;
12981                 }
12982
12983                 if (!needs_modeset(crtc_state))
12984                         continue;
12985
12986                 /* FIXME: For only active_changed we shouldn't need to do any
12987                  * state recomputation at all. */
12988
12989                 ret = drm_atomic_add_affected_connectors(state, crtc);
12990                 if (ret)
12991                         return ret;
12992
12993                 ret = intel_modeset_pipe_config(crtc, pipe_config);
12994                 if (ret)
12995                         return ret;
12996
12997                 if (i915.fastboot &&
12998                     intel_pipe_config_compare(state->dev,
12999                                         to_intel_crtc_state(crtc->state),
13000                                         pipe_config, true)) {
13001                         crtc_state->mode_changed = false;
13002                 }
13003
13004                 if (needs_modeset(crtc_state)) {
13005                         any_ms = true;
13006
13007                         ret = drm_atomic_add_affected_planes(state, crtc);
13008                         if (ret)
13009                                 return ret;
13010                 }
13011
13012                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
13013                                        needs_modeset(crtc_state) ?
13014                                        "[modeset]" : "[fastset]");
13015         }
13016
13017         if (any_ms) {
13018                 ret = intel_modeset_checks(state);
13019
13020                 if (ret)
13021                         return ret;
13022         } else
13023                 to_intel_atomic_state(state)->cdclk =
13024                         to_i915(state->dev)->cdclk_freq;
13025
13026         return drm_atomic_helper_check_planes(state->dev, state);
13027 }
13028
13029 /**
13030  * intel_atomic_commit - commit validated state object
13031  * @dev: DRM device
13032  * @state: the top-level driver state object
13033  * @async: asynchronous commit
13034  *
13035  * This function commits a top-level state object that has been validated
13036  * with drm_atomic_helper_check().
13037  *
13038  * FIXME:  Atomic modeset support for i915 is not yet complete.  At the moment
13039  * we can only handle plane-related operations and do not yet support
13040  * asynchronous commit.
13041  *
13042  * RETURNS
13043  * Zero for success or -errno.
13044  */
13045 static int intel_atomic_commit(struct drm_device *dev,
13046                                struct drm_atomic_state *state,
13047                                bool async)
13048 {
13049         struct drm_i915_private *dev_priv = dev->dev_private;
13050         struct drm_crtc *crtc;
13051         struct drm_crtc_state *crtc_state;
13052         int ret = 0;
13053         int i;
13054         bool any_ms = false;
13055
13056         if (async) {
13057                 DRM_DEBUG_KMS("i915 does not yet support async commit\n");
13058                 return -EINVAL;
13059         }
13060
13061         ret = drm_atomic_helper_prepare_planes(dev, state);
13062         if (ret)
13063                 return ret;
13064
13065         drm_atomic_helper_swap_state(dev, state);
13066
13067         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13068                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13069
13070                 if (!needs_modeset(crtc->state))
13071                         continue;
13072
13073                 any_ms = true;
13074                 intel_pre_plane_update(intel_crtc);
13075
13076                 if (crtc_state->active) {
13077                         intel_crtc_disable_planes(crtc, crtc_state->plane_mask);
13078                         dev_priv->display.crtc_disable(crtc);
13079                         intel_crtc->active = false;
13080                         intel_disable_shared_dpll(intel_crtc);
13081                 }
13082         }
13083
13084         /* Only after disabling all output pipelines that will be changed can we
13085          * update the the output configuration. */
13086         intel_modeset_update_crtc_state(state);
13087
13088         if (any_ms) {
13089                 intel_shared_dpll_commit(state);
13090
13091                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
13092                 modeset_update_crtc_power_domains(state);
13093         }
13094
13095         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
13096         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13097                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13098                 bool modeset = needs_modeset(crtc->state);
13099
13100                 if (modeset && crtc->state->active) {
13101                         update_scanline_offset(to_intel_crtc(crtc));
13102                         dev_priv->display.crtc_enable(crtc);
13103                 }
13104
13105                 if (!modeset)
13106                         intel_pre_plane_update(intel_crtc);
13107
13108                 drm_atomic_helper_commit_planes_on_crtc(crtc_state);
13109                 intel_post_plane_update(intel_crtc);
13110         }
13111
13112         /* FIXME: add subpixel order */
13113
13114         drm_atomic_helper_wait_for_vblanks(dev, state);
13115         drm_atomic_helper_cleanup_planes(dev, state);
13116
13117         if (any_ms)
13118                 intel_modeset_check_state(dev, state);
13119
13120         drm_atomic_state_free(state);
13121
13122         return 0;
13123 }
13124
13125 void intel_crtc_restore_mode(struct drm_crtc *crtc)
13126 {
13127         struct drm_device *dev = crtc->dev;
13128         struct drm_atomic_state *state;
13129         struct drm_crtc_state *crtc_state;
13130         int ret;
13131
13132         state = drm_atomic_state_alloc(dev);
13133         if (!state) {
13134                 DRM_DEBUG_KMS("[CRTC:%d] crtc restore failed, out of memory",
13135                               crtc->base.id);
13136                 return;
13137         }
13138
13139         state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
13140
13141 retry:
13142         crtc_state = drm_atomic_get_crtc_state(state, crtc);
13143         ret = PTR_ERR_OR_ZERO(crtc_state);
13144         if (!ret) {
13145                 if (!crtc_state->active)
13146                         goto out;
13147
13148                 crtc_state->mode_changed = true;
13149                 ret = drm_atomic_commit(state);
13150         }
13151
13152         if (ret == -EDEADLK) {
13153                 drm_atomic_state_clear(state);
13154                 drm_modeset_backoff(state->acquire_ctx);
13155                 goto retry;
13156         }
13157
13158         if (ret)
13159 out:
13160                 drm_atomic_state_free(state);
13161 }
13162
13163 #undef for_each_intel_crtc_masked
13164
13165 static const struct drm_crtc_funcs intel_crtc_funcs = {
13166         .gamma_set = intel_crtc_gamma_set,
13167         .set_config = drm_atomic_helper_set_config,
13168         .destroy = intel_crtc_destroy,
13169         .page_flip = intel_crtc_page_flip,
13170         .atomic_duplicate_state = intel_crtc_duplicate_state,
13171         .atomic_destroy_state = intel_crtc_destroy_state,
13172 };
13173
13174 static bool ibx_pch_dpll_get_hw_state(struct drm_i915_private *dev_priv,
13175                                       struct intel_shared_dpll *pll,
13176                                       struct intel_dpll_hw_state *hw_state)
13177 {
13178         uint32_t val;
13179
13180         if (!intel_display_power_is_enabled(dev_priv, POWER_DOMAIN_PLLS))
13181                 return false;
13182
13183         val = I915_READ(PCH_DPLL(pll->id));
13184         hw_state->dpll = val;
13185         hw_state->fp0 = I915_READ(PCH_FP0(pll->id));
13186         hw_state->fp1 = I915_READ(PCH_FP1(pll->id));
13187
13188         return val & DPLL_VCO_ENABLE;
13189 }
13190
13191 static void ibx_pch_dpll_mode_set(struct drm_i915_private *dev_priv,
13192                                   struct intel_shared_dpll *pll)
13193 {
13194         I915_WRITE(PCH_FP0(pll->id), pll->config.hw_state.fp0);
13195         I915_WRITE(PCH_FP1(pll->id), pll->config.hw_state.fp1);
13196 }
13197
13198 static void ibx_pch_dpll_enable(struct drm_i915_private *dev_priv,
13199                                 struct intel_shared_dpll *pll)
13200 {
13201         /* PCH refclock must be enabled first */
13202         ibx_assert_pch_refclk_enabled(dev_priv);
13203
13204         I915_WRITE(PCH_DPLL(pll->id), pll->config.hw_state.dpll);
13205
13206         /* Wait for the clocks to stabilize. */
13207         POSTING_READ(PCH_DPLL(pll->id));
13208         udelay(150);
13209
13210         /* The pixel multiplier can only be updated once the
13211          * DPLL is enabled and the clocks are stable.
13212          *
13213          * So write it again.
13214          */
13215         I915_WRITE(PCH_DPLL(pll->id), pll->config.hw_state.dpll);
13216         POSTING_READ(PCH_DPLL(pll->id));
13217         udelay(200);
13218 }
13219
13220 static void ibx_pch_dpll_disable(struct drm_i915_private *dev_priv,
13221                                  struct intel_shared_dpll *pll)
13222 {
13223         struct drm_device *dev = dev_priv->dev;
13224         struct intel_crtc *crtc;
13225
13226         /* Make sure no transcoder isn't still depending on us. */
13227         for_each_intel_crtc(dev, crtc) {
13228                 if (intel_crtc_to_shared_dpll(crtc) == pll)
13229                         assert_pch_transcoder_disabled(dev_priv, crtc->pipe);
13230         }
13231
13232         I915_WRITE(PCH_DPLL(pll->id), 0);
13233         POSTING_READ(PCH_DPLL(pll->id));
13234         udelay(200);
13235 }
13236
13237 static char *ibx_pch_dpll_names[] = {
13238         "PCH DPLL A",
13239         "PCH DPLL B",
13240 };
13241
13242 static void ibx_pch_dpll_init(struct drm_device *dev)
13243 {
13244         struct drm_i915_private *dev_priv = dev->dev_private;
13245         int i;
13246
13247         dev_priv->num_shared_dpll = 2;
13248
13249         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
13250                 dev_priv->shared_dplls[i].id = i;
13251                 dev_priv->shared_dplls[i].name = ibx_pch_dpll_names[i];
13252                 dev_priv->shared_dplls[i].mode_set = ibx_pch_dpll_mode_set;
13253                 dev_priv->shared_dplls[i].enable = ibx_pch_dpll_enable;
13254                 dev_priv->shared_dplls[i].disable = ibx_pch_dpll_disable;
13255                 dev_priv->shared_dplls[i].get_hw_state =
13256                         ibx_pch_dpll_get_hw_state;
13257         }
13258 }
13259
13260 static void intel_shared_dpll_init(struct drm_device *dev)
13261 {
13262         struct drm_i915_private *dev_priv = dev->dev_private;
13263
13264         intel_update_cdclk(dev);
13265
13266         if (HAS_DDI(dev))
13267                 intel_ddi_pll_init(dev);
13268         else if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
13269                 ibx_pch_dpll_init(dev);
13270         else
13271                 dev_priv->num_shared_dpll = 0;
13272
13273         BUG_ON(dev_priv->num_shared_dpll > I915_NUM_PLLS);
13274 }
13275
13276 /**
13277  * intel_prepare_plane_fb - Prepare fb for usage on plane
13278  * @plane: drm plane to prepare for
13279  * @fb: framebuffer to prepare for presentation
13280  *
13281  * Prepares a framebuffer for usage on a display plane.  Generally this
13282  * involves pinning the underlying object and updating the frontbuffer tracking
13283  * bits.  Some older platforms need special physical address handling for
13284  * cursor planes.
13285  *
13286  * Returns 0 on success, negative error code on failure.
13287  */
13288 int
13289 intel_prepare_plane_fb(struct drm_plane *plane,
13290                        struct drm_framebuffer *fb,
13291                        const struct drm_plane_state *new_state)
13292 {
13293         struct drm_device *dev = plane->dev;
13294         struct intel_plane *intel_plane = to_intel_plane(plane);
13295         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13296         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->fb);
13297         int ret = 0;
13298
13299         if (!obj)
13300                 return 0;
13301
13302         mutex_lock(&dev->struct_mutex);
13303
13304         if (plane->type == DRM_PLANE_TYPE_CURSOR &&
13305             INTEL_INFO(dev)->cursor_needs_physical) {
13306                 int align = IS_I830(dev) ? 16 * 1024 : 256;
13307                 ret = i915_gem_object_attach_phys(obj, align);
13308                 if (ret)
13309                         DRM_DEBUG_KMS("failed to attach phys object\n");
13310         } else {
13311                 ret = intel_pin_and_fence_fb_obj(plane, fb, new_state, NULL, NULL);
13312         }
13313
13314         if (ret == 0)
13315                 i915_gem_track_fb(old_obj, obj, intel_plane->frontbuffer_bit);
13316
13317         mutex_unlock(&dev->struct_mutex);
13318
13319         return ret;
13320 }
13321
13322 /**
13323  * intel_cleanup_plane_fb - Cleans up an fb after plane use
13324  * @plane: drm plane to clean up for
13325  * @fb: old framebuffer that was on plane
13326  *
13327  * Cleans up a framebuffer that has just been removed from a plane.
13328  */
13329 void
13330 intel_cleanup_plane_fb(struct drm_plane *plane,
13331                        struct drm_framebuffer *fb,
13332                        const struct drm_plane_state *old_state)
13333 {
13334         struct drm_device *dev = plane->dev;
13335         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13336
13337         if (WARN_ON(!obj))
13338                 return;
13339
13340         if (plane->type != DRM_PLANE_TYPE_CURSOR ||
13341             !INTEL_INFO(dev)->cursor_needs_physical) {
13342                 mutex_lock(&dev->struct_mutex);
13343                 intel_unpin_fb_obj(fb, old_state);
13344                 mutex_unlock(&dev->struct_mutex);
13345         }
13346 }
13347
13348 int
13349 skl_max_scale(struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state)
13350 {
13351         int max_scale;
13352         struct drm_device *dev;
13353         struct drm_i915_private *dev_priv;
13354         int crtc_clock, cdclk;
13355
13356         if (!intel_crtc || !crtc_state)
13357                 return DRM_PLANE_HELPER_NO_SCALING;
13358
13359         dev = intel_crtc->base.dev;
13360         dev_priv = dev->dev_private;
13361         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
13362         cdclk = to_intel_atomic_state(crtc_state->base.state)->cdclk;
13363
13364         if (!crtc_clock || !cdclk)
13365                 return DRM_PLANE_HELPER_NO_SCALING;
13366
13367         /*
13368          * skl max scale is lower of:
13369          *    close to 3 but not 3, -1 is for that purpose
13370          *            or
13371          *    cdclk/crtc_clock
13372          */
13373         max_scale = min((1 << 16) * 3 - 1, (1 << 8) * ((cdclk << 8) / crtc_clock));
13374
13375         return max_scale;
13376 }
13377
13378 static int
13379 intel_check_primary_plane(struct drm_plane *plane,
13380                           struct intel_crtc_state *crtc_state,
13381                           struct intel_plane_state *state)
13382 {
13383         struct drm_crtc *crtc = state->base.crtc;
13384         struct drm_framebuffer *fb = state->base.fb;
13385         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
13386         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
13387         bool can_position = false;
13388
13389         /* use scaler when colorkey is not required */
13390         if (INTEL_INFO(plane->dev)->gen >= 9 &&
13391             state->ckey.flags == I915_SET_COLORKEY_NONE) {
13392                 min_scale = 1;
13393                 max_scale = skl_max_scale(to_intel_crtc(crtc), crtc_state);
13394                 can_position = true;
13395         }
13396
13397         return drm_plane_helper_check_update(plane, crtc, fb, &state->src,
13398                                              &state->dst, &state->clip,
13399                                              min_scale, max_scale,
13400                                              can_position, true,
13401                                              &state->visible);
13402 }
13403
13404 static void
13405 intel_commit_primary_plane(struct drm_plane *plane,
13406                            struct intel_plane_state *state)
13407 {
13408         struct drm_crtc *crtc = state->base.crtc;
13409         struct drm_framebuffer *fb = state->base.fb;
13410         struct drm_device *dev = plane->dev;
13411         struct drm_i915_private *dev_priv = dev->dev_private;
13412         struct intel_crtc *intel_crtc;
13413         struct drm_rect *src = &state->src;
13414
13415         crtc = crtc ? crtc : plane->crtc;
13416         intel_crtc = to_intel_crtc(crtc);
13417
13418         plane->fb = fb;
13419         crtc->x = src->x1 >> 16;
13420         crtc->y = src->y1 >> 16;
13421
13422         if (!crtc->state->active)
13423                 return;
13424
13425         if (state->visible)
13426                 /* FIXME: kill this fastboot hack */
13427                 intel_update_pipe_size(intel_crtc);
13428
13429         dev_priv->display.update_primary_plane(crtc, fb,
13430                                                state->src.x1 >> 16,
13431                                                state->src.y1 >> 16);
13432 }
13433
13434 static void
13435 intel_disable_primary_plane(struct drm_plane *plane,
13436                             struct drm_crtc *crtc)
13437 {
13438         struct drm_device *dev = plane->dev;
13439         struct drm_i915_private *dev_priv = dev->dev_private;
13440
13441         dev_priv->display.update_primary_plane(crtc, NULL, 0, 0);
13442 }
13443
13444 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
13445                                     struct drm_crtc_state *old_crtc_state)
13446 {
13447         struct drm_device *dev = crtc->dev;
13448         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13449
13450         if (intel_crtc->atomic.update_wm_pre)
13451                 intel_update_watermarks(crtc);
13452
13453         /* Perform vblank evasion around commit operation */
13454         if (crtc->state->active)
13455                 intel_pipe_update_start(intel_crtc);
13456
13457         if (!needs_modeset(crtc->state) && INTEL_INFO(dev)->gen >= 9)
13458                 skl_detach_scalers(intel_crtc);
13459 }
13460
13461 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
13462                                      struct drm_crtc_state *old_crtc_state)
13463 {
13464         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13465
13466         if (crtc->state->active)
13467                 intel_pipe_update_end(intel_crtc);
13468 }
13469
13470 /**
13471  * intel_plane_destroy - destroy a plane
13472  * @plane: plane to destroy
13473  *
13474  * Common destruction function for all types of planes (primary, cursor,
13475  * sprite).
13476  */
13477 void intel_plane_destroy(struct drm_plane *plane)
13478 {
13479         struct intel_plane *intel_plane = to_intel_plane(plane);
13480         drm_plane_cleanup(plane);
13481         kfree(intel_plane);
13482 }
13483
13484 const struct drm_plane_funcs intel_plane_funcs = {
13485         .update_plane = drm_atomic_helper_update_plane,
13486         .disable_plane = drm_atomic_helper_disable_plane,
13487         .destroy = intel_plane_destroy,
13488         .set_property = drm_atomic_helper_plane_set_property,
13489         .atomic_get_property = intel_plane_atomic_get_property,
13490         .atomic_set_property = intel_plane_atomic_set_property,
13491         .atomic_duplicate_state = intel_plane_duplicate_state,
13492         .atomic_destroy_state = intel_plane_destroy_state,
13493
13494 };
13495
13496 static struct drm_plane *intel_primary_plane_create(struct drm_device *dev,
13497                                                     int pipe)
13498 {
13499         struct intel_plane *primary;
13500         struct intel_plane_state *state;
13501         const uint32_t *intel_primary_formats;
13502         unsigned int num_formats;
13503
13504         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
13505         if (primary == NULL)
13506                 return NULL;
13507
13508         state = intel_create_plane_state(&primary->base);
13509         if (!state) {
13510                 kfree(primary);
13511                 return NULL;
13512         }
13513         primary->base.state = &state->base;
13514
13515         primary->can_scale = false;
13516         primary->max_downscale = 1;
13517         if (INTEL_INFO(dev)->gen >= 9) {
13518                 primary->can_scale = true;
13519                 state->scaler_id = -1;
13520         }
13521         primary->pipe = pipe;
13522         primary->plane = pipe;
13523         primary->frontbuffer_bit = INTEL_FRONTBUFFER_PRIMARY(pipe);
13524         primary->check_plane = intel_check_primary_plane;
13525         primary->commit_plane = intel_commit_primary_plane;
13526         primary->disable_plane = intel_disable_primary_plane;
13527         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4)
13528                 primary->plane = !pipe;
13529
13530         if (INTEL_INFO(dev)->gen >= 9) {
13531                 intel_primary_formats = skl_primary_formats;
13532                 num_formats = ARRAY_SIZE(skl_primary_formats);
13533         } else if (INTEL_INFO(dev)->gen >= 4) {
13534                 intel_primary_formats = i965_primary_formats;
13535                 num_formats = ARRAY_SIZE(i965_primary_formats);
13536         } else {
13537                 intel_primary_formats = i8xx_primary_formats;
13538                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
13539         }
13540
13541         drm_universal_plane_init(dev, &primary->base, 0,
13542                                  &intel_plane_funcs,
13543                                  intel_primary_formats, num_formats,
13544                                  DRM_PLANE_TYPE_PRIMARY);
13545
13546         if (INTEL_INFO(dev)->gen >= 4)
13547                 intel_create_rotation_property(dev, primary);
13548
13549         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
13550
13551         return &primary->base;
13552 }
13553
13554 void intel_create_rotation_property(struct drm_device *dev, struct intel_plane *plane)
13555 {
13556         if (!dev->mode_config.rotation_property) {
13557                 unsigned long flags = BIT(DRM_ROTATE_0) |
13558                         BIT(DRM_ROTATE_180);
13559
13560                 if (INTEL_INFO(dev)->gen >= 9)
13561                         flags |= BIT(DRM_ROTATE_90) | BIT(DRM_ROTATE_270);
13562
13563                 dev->mode_config.rotation_property =
13564                         drm_mode_create_rotation_property(dev, flags);
13565         }
13566         if (dev->mode_config.rotation_property)
13567                 drm_object_attach_property(&plane->base.base,
13568                                 dev->mode_config.rotation_property,
13569                                 plane->base.state->rotation);
13570 }
13571
13572 static int
13573 intel_check_cursor_plane(struct drm_plane *plane,
13574                          struct intel_crtc_state *crtc_state,
13575                          struct intel_plane_state *state)
13576 {
13577         struct drm_crtc *crtc = crtc_state->base.crtc;
13578         struct drm_framebuffer *fb = state->base.fb;
13579         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13580         unsigned stride;
13581         int ret;
13582
13583         ret = drm_plane_helper_check_update(plane, crtc, fb, &state->src,
13584                                             &state->dst, &state->clip,
13585                                             DRM_PLANE_HELPER_NO_SCALING,
13586                                             DRM_PLANE_HELPER_NO_SCALING,
13587                                             true, true, &state->visible);
13588         if (ret)
13589                 return ret;
13590
13591         /* if we want to turn off the cursor ignore width and height */
13592         if (!obj)
13593                 return 0;
13594
13595         /* Check for which cursor types we support */
13596         if (!cursor_size_ok(plane->dev, state->base.crtc_w, state->base.crtc_h)) {
13597                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
13598                           state->base.crtc_w, state->base.crtc_h);
13599                 return -EINVAL;
13600         }
13601
13602         stride = roundup_pow_of_two(state->base.crtc_w) * 4;
13603         if (obj->base.size < stride * state->base.crtc_h) {
13604                 DRM_DEBUG_KMS("buffer is too small\n");
13605                 return -ENOMEM;
13606         }
13607
13608         if (fb->modifier[0] != DRM_FORMAT_MOD_NONE) {
13609                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
13610                 return -EINVAL;
13611         }
13612
13613         return 0;
13614 }
13615
13616 static void
13617 intel_disable_cursor_plane(struct drm_plane *plane,
13618                            struct drm_crtc *crtc)
13619 {
13620         intel_crtc_update_cursor(crtc, false);
13621 }
13622
13623 static void
13624 intel_commit_cursor_plane(struct drm_plane *plane,
13625                           struct intel_plane_state *state)
13626 {
13627         struct drm_crtc *crtc = state->base.crtc;
13628         struct drm_device *dev = plane->dev;
13629         struct intel_crtc *intel_crtc;
13630         struct drm_i915_gem_object *obj = intel_fb_obj(state->base.fb);
13631         uint32_t addr;
13632
13633         crtc = crtc ? crtc : plane->crtc;
13634         intel_crtc = to_intel_crtc(crtc);
13635
13636         plane->fb = state->base.fb;
13637         crtc->cursor_x = state->base.crtc_x;
13638         crtc->cursor_y = state->base.crtc_y;
13639
13640         if (intel_crtc->cursor_bo == obj)
13641                 goto update;
13642
13643         if (!obj)
13644                 addr = 0;
13645         else if (!INTEL_INFO(dev)->cursor_needs_physical)
13646                 addr = i915_gem_obj_ggtt_offset(obj);
13647         else
13648                 addr = obj->phys_handle->busaddr;
13649
13650         intel_crtc->cursor_addr = addr;
13651         intel_crtc->cursor_bo = obj;
13652
13653 update:
13654         if (crtc->state->active)
13655                 intel_crtc_update_cursor(crtc, state->visible);
13656 }
13657
13658 static struct drm_plane *intel_cursor_plane_create(struct drm_device *dev,
13659                                                    int pipe)
13660 {
13661         struct intel_plane *cursor;
13662         struct intel_plane_state *state;
13663
13664         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
13665         if (cursor == NULL)
13666                 return NULL;
13667
13668         state = intel_create_plane_state(&cursor->base);
13669         if (!state) {
13670                 kfree(cursor);
13671                 return NULL;
13672         }
13673         cursor->base.state = &state->base;
13674
13675         cursor->can_scale = false;
13676         cursor->max_downscale = 1;
13677         cursor->pipe = pipe;
13678         cursor->plane = pipe;
13679         cursor->frontbuffer_bit = INTEL_FRONTBUFFER_CURSOR(pipe);
13680         cursor->check_plane = intel_check_cursor_plane;
13681         cursor->commit_plane = intel_commit_cursor_plane;
13682         cursor->disable_plane = intel_disable_cursor_plane;
13683
13684         drm_universal_plane_init(dev, &cursor->base, 0,
13685                                  &intel_plane_funcs,
13686                                  intel_cursor_formats,
13687                                  ARRAY_SIZE(intel_cursor_formats),
13688                                  DRM_PLANE_TYPE_CURSOR);
13689
13690         if (INTEL_INFO(dev)->gen >= 4) {
13691                 if (!dev->mode_config.rotation_property)
13692                         dev->mode_config.rotation_property =
13693                                 drm_mode_create_rotation_property(dev,
13694                                                         BIT(DRM_ROTATE_0) |
13695                                                         BIT(DRM_ROTATE_180));
13696                 if (dev->mode_config.rotation_property)
13697                         drm_object_attach_property(&cursor->base.base,
13698                                 dev->mode_config.rotation_property,
13699                                 state->base.rotation);
13700         }
13701
13702         if (INTEL_INFO(dev)->gen >=9)
13703                 state->scaler_id = -1;
13704
13705         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
13706
13707         return &cursor->base;
13708 }
13709
13710 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
13711         struct intel_crtc_state *crtc_state)
13712 {
13713         int i;
13714         struct intel_scaler *intel_scaler;
13715         struct intel_crtc_scaler_state *scaler_state = &crtc_state->scaler_state;
13716
13717         for (i = 0; i < intel_crtc->num_scalers; i++) {
13718                 intel_scaler = &scaler_state->scalers[i];
13719                 intel_scaler->in_use = 0;
13720                 intel_scaler->mode = PS_SCALER_MODE_DYN;
13721         }
13722
13723         scaler_state->scaler_id = -1;
13724 }
13725
13726 static void intel_crtc_init(struct drm_device *dev, int pipe)
13727 {
13728         struct drm_i915_private *dev_priv = dev->dev_private;
13729         struct intel_crtc *intel_crtc;
13730         struct intel_crtc_state *crtc_state = NULL;
13731         struct drm_plane *primary = NULL;
13732         struct drm_plane *cursor = NULL;
13733         int i, ret;
13734
13735         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
13736         if (intel_crtc == NULL)
13737                 return;
13738
13739         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
13740         if (!crtc_state)
13741                 goto fail;
13742         intel_crtc->config = crtc_state;
13743         intel_crtc->base.state = &crtc_state->base;
13744         crtc_state->base.crtc = &intel_crtc->base;
13745
13746         /* initialize shared scalers */
13747         if (INTEL_INFO(dev)->gen >= 9) {
13748                 if (pipe == PIPE_C)
13749                         intel_crtc->num_scalers = 1;
13750                 else
13751                         intel_crtc->num_scalers = SKL_NUM_SCALERS;
13752
13753                 skl_init_scalers(dev, intel_crtc, crtc_state);
13754         }
13755
13756         primary = intel_primary_plane_create(dev, pipe);
13757         if (!primary)
13758                 goto fail;
13759
13760         cursor = intel_cursor_plane_create(dev, pipe);
13761         if (!cursor)
13762                 goto fail;
13763
13764         ret = drm_crtc_init_with_planes(dev, &intel_crtc->base, primary,
13765                                         cursor, &intel_crtc_funcs);
13766         if (ret)
13767                 goto fail;
13768
13769         drm_mode_crtc_set_gamma_size(&intel_crtc->base, 256);
13770         for (i = 0; i < 256; i++) {
13771                 intel_crtc->lut_r[i] = i;
13772                 intel_crtc->lut_g[i] = i;
13773                 intel_crtc->lut_b[i] = i;
13774         }
13775
13776         /*
13777          * On gen2/3 only plane A can do fbc, but the panel fitter and lvds port
13778          * is hooked to pipe B. Hence we want plane A feeding pipe B.
13779          */
13780         intel_crtc->pipe = pipe;
13781         intel_crtc->plane = pipe;
13782         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4) {
13783                 DRM_DEBUG_KMS("swapping pipes & planes for FBC\n");
13784                 intel_crtc->plane = !pipe;
13785         }
13786
13787         intel_crtc->cursor_base = ~0;
13788         intel_crtc->cursor_cntl = ~0;
13789         intel_crtc->cursor_size = ~0;
13790
13791         intel_crtc->wm.cxsr_allowed = true;
13792
13793         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
13794                dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
13795         dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = &intel_crtc->base;
13796         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = &intel_crtc->base;
13797
13798         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
13799
13800         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
13801         return;
13802
13803 fail:
13804         if (primary)
13805                 drm_plane_cleanup(primary);
13806         if (cursor)
13807                 drm_plane_cleanup(cursor);
13808         kfree(crtc_state);
13809         kfree(intel_crtc);
13810 }
13811
13812 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
13813 {
13814         struct drm_encoder *encoder = connector->base.encoder;
13815         struct drm_device *dev = connector->base.dev;
13816
13817         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
13818
13819         if (!encoder || WARN_ON(!encoder->crtc))
13820                 return INVALID_PIPE;
13821
13822         return to_intel_crtc(encoder->crtc)->pipe;
13823 }
13824
13825 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
13826                                 struct drm_file *file)
13827 {
13828         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
13829         struct drm_crtc *drmmode_crtc;
13830         struct intel_crtc *crtc;
13831
13832         drmmode_crtc = drm_crtc_find(dev, pipe_from_crtc_id->crtc_id);
13833
13834         if (!drmmode_crtc) {
13835                 DRM_ERROR("no such CRTC id\n");
13836                 return -ENOENT;
13837         }
13838
13839         crtc = to_intel_crtc(drmmode_crtc);
13840         pipe_from_crtc_id->pipe = crtc->pipe;
13841
13842         return 0;
13843 }
13844
13845 static int intel_encoder_clones(struct intel_encoder *encoder)
13846 {
13847         struct drm_device *dev = encoder->base.dev;
13848         struct intel_encoder *source_encoder;
13849         int index_mask = 0;
13850         int entry = 0;
13851
13852         for_each_intel_encoder(dev, source_encoder) {
13853                 if (encoders_cloneable(encoder, source_encoder))
13854                         index_mask |= (1 << entry);
13855
13856                 entry++;
13857         }
13858
13859         return index_mask;
13860 }
13861
13862 static bool has_edp_a(struct drm_device *dev)
13863 {
13864         struct drm_i915_private *dev_priv = dev->dev_private;
13865
13866         if (!IS_MOBILE(dev))
13867                 return false;
13868
13869         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
13870                 return false;
13871
13872         if (IS_GEN5(dev) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
13873                 return false;
13874
13875         return true;
13876 }
13877
13878 static bool intel_crt_present(struct drm_device *dev)
13879 {
13880         struct drm_i915_private *dev_priv = dev->dev_private;
13881
13882         if (INTEL_INFO(dev)->gen >= 9)
13883                 return false;
13884
13885         if (IS_HSW_ULT(dev) || IS_BDW_ULT(dev))
13886                 return false;
13887
13888         if (IS_CHERRYVIEW(dev))
13889                 return false;
13890
13891         if (IS_VALLEYVIEW(dev) && !dev_priv->vbt.int_crt_support)
13892                 return false;
13893
13894         return true;
13895 }
13896
13897 static void intel_setup_outputs(struct drm_device *dev)
13898 {
13899         struct drm_i915_private *dev_priv = dev->dev_private;
13900         struct intel_encoder *encoder;
13901         bool dpd_is_edp = false;
13902
13903         intel_lvds_init(dev);
13904
13905         if (intel_crt_present(dev))
13906                 intel_crt_init(dev);
13907
13908         if (IS_BROXTON(dev)) {
13909                 /*
13910                  * FIXME: Broxton doesn't support port detection via the
13911                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
13912                  * detect the ports.
13913                  */
13914                 intel_ddi_init(dev, PORT_A);
13915                 intel_ddi_init(dev, PORT_B);
13916                 intel_ddi_init(dev, PORT_C);
13917         } else if (HAS_DDI(dev)) {
13918                 int found;
13919
13920                 /*
13921                  * Haswell uses DDI functions to detect digital outputs.
13922                  * On SKL pre-D0 the strap isn't connected, so we assume
13923                  * it's there.
13924                  */
13925                 found = I915_READ(DDI_BUF_CTL_A) & DDI_INIT_DISPLAY_DETECTED;
13926                 /* WaIgnoreDDIAStrap: skl */
13927                 if (found || IS_SKYLAKE(dev))
13928                         intel_ddi_init(dev, PORT_A);
13929
13930                 /* DDI B, C and D detection is indicated by the SFUSE_STRAP
13931                  * register */
13932                 found = I915_READ(SFUSE_STRAP);
13933
13934                 if (found & SFUSE_STRAP_DDIB_DETECTED)
13935                         intel_ddi_init(dev, PORT_B);
13936                 if (found & SFUSE_STRAP_DDIC_DETECTED)
13937                         intel_ddi_init(dev, PORT_C);
13938                 if (found & SFUSE_STRAP_DDID_DETECTED)
13939                         intel_ddi_init(dev, PORT_D);
13940                 /*
13941                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
13942                  */
13943                 if (IS_SKYLAKE(dev) &&
13944                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
13945                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
13946                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
13947                         intel_ddi_init(dev, PORT_E);
13948
13949         } else if (HAS_PCH_SPLIT(dev)) {
13950                 int found;
13951                 dpd_is_edp = intel_dp_is_edp(dev, PORT_D);
13952
13953                 if (has_edp_a(dev))
13954                         intel_dp_init(dev, DP_A, PORT_A);
13955
13956                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
13957                         /* PCH SDVOB multiplex with HDMIB */
13958                         found = intel_sdvo_init(dev, PCH_SDVOB, true);
13959                         if (!found)
13960                                 intel_hdmi_init(dev, PCH_HDMIB, PORT_B);
13961                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
13962                                 intel_dp_init(dev, PCH_DP_B, PORT_B);
13963                 }
13964
13965                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
13966                         intel_hdmi_init(dev, PCH_HDMIC, PORT_C);
13967
13968                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
13969                         intel_hdmi_init(dev, PCH_HDMID, PORT_D);
13970
13971                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
13972                         intel_dp_init(dev, PCH_DP_C, PORT_C);
13973
13974                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
13975                         intel_dp_init(dev, PCH_DP_D, PORT_D);
13976         } else if (IS_VALLEYVIEW(dev)) {
13977                 /*
13978                  * The DP_DETECTED bit is the latched state of the DDC
13979                  * SDA pin at boot. However since eDP doesn't require DDC
13980                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
13981                  * eDP ports may have been muxed to an alternate function.
13982                  * Thus we can't rely on the DP_DETECTED bit alone to detect
13983                  * eDP ports. Consult the VBT as well as DP_DETECTED to
13984                  * detect eDP ports.
13985                  */
13986                 if (I915_READ(VLV_DISPLAY_BASE + GEN4_HDMIB) & SDVO_DETECTED &&
13987                     !intel_dp_is_edp(dev, PORT_B))
13988                         intel_hdmi_init(dev, VLV_DISPLAY_BASE + GEN4_HDMIB,
13989                                         PORT_B);
13990                 if (I915_READ(VLV_DISPLAY_BASE + DP_B) & DP_DETECTED ||
13991                     intel_dp_is_edp(dev, PORT_B))
13992                         intel_dp_init(dev, VLV_DISPLAY_BASE + DP_B, PORT_B);
13993
13994                 if (I915_READ(VLV_DISPLAY_BASE + GEN4_HDMIC) & SDVO_DETECTED &&
13995                     !intel_dp_is_edp(dev, PORT_C))
13996                         intel_hdmi_init(dev, VLV_DISPLAY_BASE + GEN4_HDMIC,
13997                                         PORT_C);
13998                 if (I915_READ(VLV_DISPLAY_BASE + DP_C) & DP_DETECTED ||
13999                     intel_dp_is_edp(dev, PORT_C))
14000                         intel_dp_init(dev, VLV_DISPLAY_BASE + DP_C, PORT_C);
14001
14002                 if (IS_CHERRYVIEW(dev)) {
14003                         if (I915_READ(VLV_DISPLAY_BASE + CHV_HDMID) & SDVO_DETECTED)
14004                                 intel_hdmi_init(dev, VLV_DISPLAY_BASE + CHV_HDMID,
14005                                                 PORT_D);
14006                         /* eDP not supported on port D, so don't check VBT */
14007                         if (I915_READ(VLV_DISPLAY_BASE + DP_D) & DP_DETECTED)
14008                                 intel_dp_init(dev, VLV_DISPLAY_BASE + DP_D, PORT_D);
14009                 }
14010
14011                 intel_dsi_init(dev);
14012         } else if (!IS_GEN2(dev) && !IS_PINEVIEW(dev)) {
14013                 bool found = false;
14014
14015                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14016                         DRM_DEBUG_KMS("probing SDVOB\n");
14017                         found = intel_sdvo_init(dev, GEN3_SDVOB, true);
14018                         if (!found && IS_G4X(dev)) {
14019                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
14020                                 intel_hdmi_init(dev, GEN4_HDMIB, PORT_B);
14021                         }
14022
14023                         if (!found && IS_G4X(dev))
14024                                 intel_dp_init(dev, DP_B, PORT_B);
14025                 }
14026
14027                 /* Before G4X SDVOC doesn't have its own detect register */
14028
14029                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14030                         DRM_DEBUG_KMS("probing SDVOC\n");
14031                         found = intel_sdvo_init(dev, GEN3_SDVOC, false);
14032                 }
14033
14034                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
14035
14036                         if (IS_G4X(dev)) {
14037                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
14038                                 intel_hdmi_init(dev, GEN4_HDMIC, PORT_C);
14039                         }
14040                         if (IS_G4X(dev))
14041                                 intel_dp_init(dev, DP_C, PORT_C);
14042                 }
14043
14044                 if (IS_G4X(dev) &&
14045                     (I915_READ(DP_D) & DP_DETECTED))
14046                         intel_dp_init(dev, DP_D, PORT_D);
14047         } else if (IS_GEN2(dev))
14048                 intel_dvo_init(dev);
14049
14050         if (SUPPORTS_TV(dev))
14051                 intel_tv_init(dev);
14052
14053         intel_psr_init(dev);
14054
14055         for_each_intel_encoder(dev, encoder) {
14056                 encoder->base.possible_crtcs = encoder->crtc_mask;
14057                 encoder->base.possible_clones =
14058                         intel_encoder_clones(encoder);
14059         }
14060
14061         intel_init_pch_refclk(dev);
14062
14063         drm_helper_move_panel_connectors_to_head(dev);
14064 }
14065
14066 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
14067 {
14068         struct drm_device *dev = fb->dev;
14069         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14070
14071         drm_framebuffer_cleanup(fb);
14072         mutex_lock(&dev->struct_mutex);
14073         WARN_ON(!intel_fb->obj->framebuffer_references--);
14074         drm_gem_object_unreference(&intel_fb->obj->base);
14075         mutex_unlock(&dev->struct_mutex);
14076         kfree(intel_fb);
14077 }
14078
14079 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
14080                                                 struct drm_file *file,
14081                                                 unsigned int *handle)
14082 {
14083         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14084         struct drm_i915_gem_object *obj = intel_fb->obj;
14085
14086         return drm_gem_handle_create(file, &obj->base, handle);
14087 }
14088
14089 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
14090                                         struct drm_file *file,
14091                                         unsigned flags, unsigned color,
14092                                         struct drm_clip_rect *clips,
14093                                         unsigned num_clips)
14094 {
14095         struct drm_device *dev = fb->dev;
14096         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14097         struct drm_i915_gem_object *obj = intel_fb->obj;
14098
14099         mutex_lock(&dev->struct_mutex);
14100         intel_fb_obj_flush(obj, false, ORIGIN_DIRTYFB);
14101         mutex_unlock(&dev->struct_mutex);
14102
14103         return 0;
14104 }
14105
14106 static const struct drm_framebuffer_funcs intel_fb_funcs = {
14107         .destroy = intel_user_framebuffer_destroy,
14108         .create_handle = intel_user_framebuffer_create_handle,
14109         .dirty = intel_user_framebuffer_dirty,
14110 };
14111
14112 static
14113 u32 intel_fb_pitch_limit(struct drm_device *dev, uint64_t fb_modifier,
14114                          uint32_t pixel_format)
14115 {
14116         u32 gen = INTEL_INFO(dev)->gen;
14117
14118         if (gen >= 9) {
14119                 /* "The stride in bytes must not exceed the of the size of 8K
14120                  *  pixels and 32K bytes."
14121                  */
14122                  return min(8192*drm_format_plane_cpp(pixel_format, 0), 32768);
14123         } else if (gen >= 5 && !IS_VALLEYVIEW(dev)) {
14124                 return 32*1024;
14125         } else if (gen >= 4) {
14126                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14127                         return 16*1024;
14128                 else
14129                         return 32*1024;
14130         } else if (gen >= 3) {
14131                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14132                         return 8*1024;
14133                 else
14134                         return 16*1024;
14135         } else {
14136                 /* XXX DSPC is limited to 4k tiled */
14137                 return 8*1024;
14138         }
14139 }
14140
14141 static int intel_framebuffer_init(struct drm_device *dev,
14142                                   struct intel_framebuffer *intel_fb,
14143                                   struct drm_mode_fb_cmd2 *mode_cmd,
14144                                   struct drm_i915_gem_object *obj)
14145 {
14146         unsigned int aligned_height;
14147         int ret;
14148         u32 pitch_limit, stride_alignment;
14149
14150         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
14151
14152         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
14153                 /* Enforce that fb modifier and tiling mode match, but only for
14154                  * X-tiled. This is needed for FBC. */
14155                 if (!!(obj->tiling_mode == I915_TILING_X) !=
14156                     !!(mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED)) {
14157                         DRM_DEBUG("tiling_mode doesn't match fb modifier\n");
14158                         return -EINVAL;
14159                 }
14160         } else {
14161                 if (obj->tiling_mode == I915_TILING_X)
14162                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
14163                 else if (obj->tiling_mode == I915_TILING_Y) {
14164                         DRM_DEBUG("No Y tiling for legacy addfb\n");
14165                         return -EINVAL;
14166                 }
14167         }
14168
14169         /* Passed in modifier sanity checking. */
14170         switch (mode_cmd->modifier[0]) {
14171         case I915_FORMAT_MOD_Y_TILED:
14172         case I915_FORMAT_MOD_Yf_TILED:
14173                 if (INTEL_INFO(dev)->gen < 9) {
14174                         DRM_DEBUG("Unsupported tiling 0x%llx!\n",
14175                                   mode_cmd->modifier[0]);
14176                         return -EINVAL;
14177                 }
14178         case DRM_FORMAT_MOD_NONE:
14179         case I915_FORMAT_MOD_X_TILED:
14180                 break;
14181         default:
14182                 DRM_DEBUG("Unsupported fb modifier 0x%llx!\n",
14183                           mode_cmd->modifier[0]);
14184                 return -EINVAL;
14185         }
14186
14187         stride_alignment = intel_fb_stride_alignment(dev, mode_cmd->modifier[0],
14188                                                      mode_cmd->pixel_format);
14189         if (mode_cmd->pitches[0] & (stride_alignment - 1)) {
14190                 DRM_DEBUG("pitch (%d) must be at least %u byte aligned\n",
14191                           mode_cmd->pitches[0], stride_alignment);
14192                 return -EINVAL;
14193         }
14194
14195         pitch_limit = intel_fb_pitch_limit(dev, mode_cmd->modifier[0],
14196                                            mode_cmd->pixel_format);
14197         if (mode_cmd->pitches[0] > pitch_limit) {
14198                 DRM_DEBUG("%s pitch (%u) must be at less than %d\n",
14199                           mode_cmd->modifier[0] != DRM_FORMAT_MOD_NONE ?
14200                           "tiled" : "linear",
14201                           mode_cmd->pitches[0], pitch_limit);
14202                 return -EINVAL;
14203         }
14204
14205         if (mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED &&
14206             mode_cmd->pitches[0] != obj->stride) {
14207                 DRM_DEBUG("pitch (%d) must match tiling stride (%d)\n",
14208                           mode_cmd->pitches[0], obj->stride);
14209                 return -EINVAL;
14210         }
14211
14212         /* Reject formats not supported by any plane early. */
14213         switch (mode_cmd->pixel_format) {
14214         case DRM_FORMAT_C8:
14215         case DRM_FORMAT_RGB565:
14216         case DRM_FORMAT_XRGB8888:
14217         case DRM_FORMAT_ARGB8888:
14218                 break;
14219         case DRM_FORMAT_XRGB1555:
14220                 if (INTEL_INFO(dev)->gen > 3) {
14221                         DRM_DEBUG("unsupported pixel format: %s\n",
14222                                   drm_get_format_name(mode_cmd->pixel_format));
14223                         return -EINVAL;
14224                 }
14225                 break;
14226         case DRM_FORMAT_ABGR8888:
14227                 if (!IS_VALLEYVIEW(dev) && INTEL_INFO(dev)->gen < 9) {
14228                         DRM_DEBUG("unsupported pixel format: %s\n",
14229                                   drm_get_format_name(mode_cmd->pixel_format));
14230                         return -EINVAL;
14231                 }
14232                 break;
14233         case DRM_FORMAT_XBGR8888:
14234         case DRM_FORMAT_XRGB2101010:
14235         case DRM_FORMAT_XBGR2101010:
14236                 if (INTEL_INFO(dev)->gen < 4) {
14237                         DRM_DEBUG("unsupported pixel format: %s\n",
14238                                   drm_get_format_name(mode_cmd->pixel_format));
14239                         return -EINVAL;
14240                 }
14241                 break;
14242         case DRM_FORMAT_ABGR2101010:
14243                 if (!IS_VALLEYVIEW(dev)) {
14244                         DRM_DEBUG("unsupported pixel format: %s\n",
14245                                   drm_get_format_name(mode_cmd->pixel_format));
14246                         return -EINVAL;
14247                 }
14248                 break;
14249         case DRM_FORMAT_YUYV:
14250         case DRM_FORMAT_UYVY:
14251         case DRM_FORMAT_YVYU:
14252         case DRM_FORMAT_VYUY:
14253                 if (INTEL_INFO(dev)->gen < 5) {
14254                         DRM_DEBUG("unsupported pixel format: %s\n",
14255                                   drm_get_format_name(mode_cmd->pixel_format));
14256                         return -EINVAL;
14257                 }
14258                 break;
14259         default:
14260                 DRM_DEBUG("unsupported pixel format: %s\n",
14261                           drm_get_format_name(mode_cmd->pixel_format));
14262                 return -EINVAL;
14263         }
14264
14265         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14266         if (mode_cmd->offsets[0] != 0)
14267                 return -EINVAL;
14268
14269         aligned_height = intel_fb_align_height(dev, mode_cmd->height,
14270                                                mode_cmd->pixel_format,
14271                                                mode_cmd->modifier[0]);
14272         /* FIXME drm helper for size checks (especially planar formats)? */
14273         if (obj->base.size < aligned_height * mode_cmd->pitches[0])
14274                 return -EINVAL;
14275
14276         drm_helper_mode_fill_fb_struct(&intel_fb->base, mode_cmd);
14277         intel_fb->obj = obj;
14278         intel_fb->obj->framebuffer_references++;
14279
14280         ret = drm_framebuffer_init(dev, &intel_fb->base, &intel_fb_funcs);
14281         if (ret) {
14282                 DRM_ERROR("framebuffer init failed %d\n", ret);
14283                 return ret;
14284         }
14285
14286         return 0;
14287 }
14288
14289 static struct drm_framebuffer *
14290 intel_user_framebuffer_create(struct drm_device *dev,
14291                               struct drm_file *filp,
14292                               struct drm_mode_fb_cmd2 *mode_cmd)
14293 {
14294         struct drm_i915_gem_object *obj;
14295
14296         obj = to_intel_bo(drm_gem_object_lookup(dev, filp,
14297                                                 mode_cmd->handles[0]));
14298         if (&obj->base == NULL)
14299                 return ERR_PTR(-ENOENT);
14300
14301         return intel_framebuffer_create(dev, mode_cmd, obj);
14302 }
14303
14304 #ifndef CONFIG_DRM_FBDEV_EMULATION
14305 static inline void intel_fbdev_output_poll_changed(struct drm_device *dev)
14306 {
14307 }
14308 #endif
14309
14310 static const struct drm_mode_config_funcs intel_mode_funcs = {
14311         .fb_create = intel_user_framebuffer_create,
14312         .output_poll_changed = intel_fbdev_output_poll_changed,
14313         .atomic_check = intel_atomic_check,
14314         .atomic_commit = intel_atomic_commit,
14315         .atomic_state_alloc = intel_atomic_state_alloc,
14316         .atomic_state_clear = intel_atomic_state_clear,
14317 };
14318
14319 /* Set up chip specific display functions */
14320 static void intel_init_display(struct drm_device *dev)
14321 {
14322         struct drm_i915_private *dev_priv = dev->dev_private;
14323
14324         if (HAS_PCH_SPLIT(dev) || IS_G4X(dev))
14325                 dev_priv->display.find_dpll = g4x_find_best_dpll;
14326         else if (IS_CHERRYVIEW(dev))
14327                 dev_priv->display.find_dpll = chv_find_best_dpll;
14328         else if (IS_VALLEYVIEW(dev))
14329                 dev_priv->display.find_dpll = vlv_find_best_dpll;
14330         else if (IS_PINEVIEW(dev))
14331                 dev_priv->display.find_dpll = pnv_find_best_dpll;
14332         else
14333                 dev_priv->display.find_dpll = i9xx_find_best_dpll;
14334
14335         if (INTEL_INFO(dev)->gen >= 9) {
14336                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14337                 dev_priv->display.get_initial_plane_config =
14338                         skylake_get_initial_plane_config;
14339                 dev_priv->display.crtc_compute_clock =
14340                         haswell_crtc_compute_clock;
14341                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14342                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14343                 dev_priv->display.update_primary_plane =
14344                         skylake_update_primary_plane;
14345         } else if (HAS_DDI(dev)) {
14346                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14347                 dev_priv->display.get_initial_plane_config =
14348                         ironlake_get_initial_plane_config;
14349                 dev_priv->display.crtc_compute_clock =
14350                         haswell_crtc_compute_clock;
14351                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14352                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14353                 dev_priv->display.update_primary_plane =
14354                         ironlake_update_primary_plane;
14355         } else if (HAS_PCH_SPLIT(dev)) {
14356                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
14357                 dev_priv->display.get_initial_plane_config =
14358                         ironlake_get_initial_plane_config;
14359                 dev_priv->display.crtc_compute_clock =
14360                         ironlake_crtc_compute_clock;
14361                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
14362                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
14363                 dev_priv->display.update_primary_plane =
14364                         ironlake_update_primary_plane;
14365         } else if (IS_VALLEYVIEW(dev)) {
14366                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14367                 dev_priv->display.get_initial_plane_config =
14368                         i9xx_get_initial_plane_config;
14369                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14370                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14371                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14372                 dev_priv->display.update_primary_plane =
14373                         i9xx_update_primary_plane;
14374         } else {
14375                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14376                 dev_priv->display.get_initial_plane_config =
14377                         i9xx_get_initial_plane_config;
14378                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14379                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14380                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14381                 dev_priv->display.update_primary_plane =
14382                         i9xx_update_primary_plane;
14383         }
14384
14385         /* Returns the core display clock speed */
14386         if (IS_SKYLAKE(dev))
14387                 dev_priv->display.get_display_clock_speed =
14388                         skylake_get_display_clock_speed;
14389         else if (IS_BROXTON(dev))
14390                 dev_priv->display.get_display_clock_speed =
14391                         broxton_get_display_clock_speed;
14392         else if (IS_BROADWELL(dev))
14393                 dev_priv->display.get_display_clock_speed =
14394                         broadwell_get_display_clock_speed;
14395         else if (IS_HASWELL(dev))
14396                 dev_priv->display.get_display_clock_speed =
14397                         haswell_get_display_clock_speed;
14398         else if (IS_VALLEYVIEW(dev))
14399                 dev_priv->display.get_display_clock_speed =
14400                         valleyview_get_display_clock_speed;
14401         else if (IS_GEN5(dev))
14402                 dev_priv->display.get_display_clock_speed =
14403                         ilk_get_display_clock_speed;
14404         else if (IS_I945G(dev) || IS_BROADWATER(dev) ||
14405                  IS_GEN6(dev) || IS_IVYBRIDGE(dev))
14406                 dev_priv->display.get_display_clock_speed =
14407                         i945_get_display_clock_speed;
14408         else if (IS_GM45(dev))
14409                 dev_priv->display.get_display_clock_speed =
14410                         gm45_get_display_clock_speed;
14411         else if (IS_CRESTLINE(dev))
14412                 dev_priv->display.get_display_clock_speed =
14413                         i965gm_get_display_clock_speed;
14414         else if (IS_PINEVIEW(dev))
14415                 dev_priv->display.get_display_clock_speed =
14416                         pnv_get_display_clock_speed;
14417         else if (IS_G33(dev) || IS_G4X(dev))
14418                 dev_priv->display.get_display_clock_speed =
14419                         g33_get_display_clock_speed;
14420         else if (IS_I915G(dev))
14421                 dev_priv->display.get_display_clock_speed =
14422                         i915_get_display_clock_speed;
14423         else if (IS_I945GM(dev) || IS_845G(dev))
14424                 dev_priv->display.get_display_clock_speed =
14425                         i9xx_misc_get_display_clock_speed;
14426         else if (IS_PINEVIEW(dev))
14427                 dev_priv->display.get_display_clock_speed =
14428                         pnv_get_display_clock_speed;
14429         else if (IS_I915GM(dev))
14430                 dev_priv->display.get_display_clock_speed =
14431                         i915gm_get_display_clock_speed;
14432         else if (IS_I865G(dev))
14433                 dev_priv->display.get_display_clock_speed =
14434                         i865_get_display_clock_speed;
14435         else if (IS_I85X(dev))
14436                 dev_priv->display.get_display_clock_speed =
14437                         i85x_get_display_clock_speed;
14438         else { /* 830 */
14439                 WARN(!IS_I830(dev), "Unknown platform. Assuming 133 MHz CDCLK\n");
14440                 dev_priv->display.get_display_clock_speed =
14441                         i830_get_display_clock_speed;
14442         }
14443
14444         if (IS_GEN5(dev)) {
14445                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
14446         } else if (IS_GEN6(dev)) {
14447                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
14448         } else if (IS_IVYBRIDGE(dev)) {
14449                 /* FIXME: detect B0+ stepping and use auto training */
14450                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
14451         } else if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
14452                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
14453                 if (IS_BROADWELL(dev)) {
14454                         dev_priv->display.modeset_commit_cdclk =
14455                                 broadwell_modeset_commit_cdclk;
14456                         dev_priv->display.modeset_calc_cdclk =
14457                                 broadwell_modeset_calc_cdclk;
14458                 }
14459         } else if (IS_VALLEYVIEW(dev)) {
14460                 dev_priv->display.modeset_commit_cdclk =
14461                         valleyview_modeset_commit_cdclk;
14462                 dev_priv->display.modeset_calc_cdclk =
14463                         valleyview_modeset_calc_cdclk;
14464         } else if (IS_BROXTON(dev)) {
14465                 dev_priv->display.modeset_commit_cdclk =
14466                         broxton_modeset_commit_cdclk;
14467                 dev_priv->display.modeset_calc_cdclk =
14468                         broxton_modeset_calc_cdclk;
14469         }
14470
14471         switch (INTEL_INFO(dev)->gen) {
14472         case 2:
14473                 dev_priv->display.queue_flip = intel_gen2_queue_flip;
14474                 break;
14475
14476         case 3:
14477                 dev_priv->display.queue_flip = intel_gen3_queue_flip;
14478                 break;
14479
14480         case 4:
14481         case 5:
14482                 dev_priv->display.queue_flip = intel_gen4_queue_flip;
14483                 break;
14484
14485         case 6:
14486                 dev_priv->display.queue_flip = intel_gen6_queue_flip;
14487                 break;
14488         case 7:
14489         case 8: /* FIXME(BDW): Check that the gen8 RCS flip works. */
14490                 dev_priv->display.queue_flip = intel_gen7_queue_flip;
14491                 break;
14492         case 9:
14493                 /* Drop through - unsupported since execlist only. */
14494         default:
14495                 /* Default just returns -ENODEV to indicate unsupported */
14496                 dev_priv->display.queue_flip = intel_default_queue_flip;
14497         }
14498
14499         intel_panel_init_backlight_funcs(dev);
14500
14501         mutex_init(&dev_priv->pps_mutex);
14502 }
14503
14504 /*
14505  * Some BIOSes insist on assuming the GPU's pipe A is enabled at suspend,
14506  * resume, or other times.  This quirk makes sure that's the case for
14507  * affected systems.
14508  */
14509 static void quirk_pipea_force(struct drm_device *dev)
14510 {
14511         struct drm_i915_private *dev_priv = dev->dev_private;
14512
14513         dev_priv->quirks |= QUIRK_PIPEA_FORCE;
14514         DRM_INFO("applying pipe a force quirk\n");
14515 }
14516
14517 static void quirk_pipeb_force(struct drm_device *dev)
14518 {
14519         struct drm_i915_private *dev_priv = dev->dev_private;
14520
14521         dev_priv->quirks |= QUIRK_PIPEB_FORCE;
14522         DRM_INFO("applying pipe b force quirk\n");
14523 }
14524
14525 /*
14526  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
14527  */
14528 static void quirk_ssc_force_disable(struct drm_device *dev)
14529 {
14530         struct drm_i915_private *dev_priv = dev->dev_private;
14531         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
14532         DRM_INFO("applying lvds SSC disable quirk\n");
14533 }
14534
14535 /*
14536  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
14537  * brightness value
14538  */
14539 static void quirk_invert_brightness(struct drm_device *dev)
14540 {
14541         struct drm_i915_private *dev_priv = dev->dev_private;
14542         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
14543         DRM_INFO("applying inverted panel brightness quirk\n");
14544 }
14545
14546 /* Some VBT's incorrectly indicate no backlight is present */
14547 static void quirk_backlight_present(struct drm_device *dev)
14548 {
14549         struct drm_i915_private *dev_priv = dev->dev_private;
14550         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
14551         DRM_INFO("applying backlight present quirk\n");
14552 }
14553
14554 struct intel_quirk {
14555         int device;
14556         int subsystem_vendor;
14557         int subsystem_device;
14558         void (*hook)(struct drm_device *dev);
14559 };
14560
14561 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
14562 struct intel_dmi_quirk {
14563         void (*hook)(struct drm_device *dev);
14564         const struct dmi_system_id (*dmi_id_list)[];
14565 };
14566
14567 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
14568 {
14569         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
14570         return 1;
14571 }
14572
14573 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
14574         {
14575                 .dmi_id_list = &(const struct dmi_system_id[]) {
14576                         {
14577                                 .callback = intel_dmi_reverse_brightness,
14578                                 .ident = "NCR Corporation",
14579                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
14580                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
14581                                 },
14582                         },
14583                         { }  /* terminating entry */
14584                 },
14585                 .hook = quirk_invert_brightness,
14586         },
14587 };
14588
14589 static struct intel_quirk intel_quirks[] = {
14590         /* Toshiba Protege R-205, S-209 needs pipe A force quirk */
14591         { 0x2592, 0x1179, 0x0001, quirk_pipea_force },
14592
14593         /* ThinkPad T60 needs pipe A force quirk (bug #16494) */
14594         { 0x2782, 0x17aa, 0x201a, quirk_pipea_force },
14595
14596         /* 830 needs to leave pipe A & dpll A up */
14597         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipea_force },
14598
14599         /* 830 needs to leave pipe B & dpll B up */
14600         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipeb_force },
14601
14602         /* Lenovo U160 cannot use SSC on LVDS */
14603         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
14604
14605         /* Sony Vaio Y cannot use SSC on LVDS */
14606         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
14607
14608         /* Acer Aspire 5734Z must invert backlight brightness */
14609         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
14610
14611         /* Acer/eMachines G725 */
14612         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
14613
14614         /* Acer/eMachines e725 */
14615         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
14616
14617         /* Acer/Packard Bell NCL20 */
14618         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
14619
14620         /* Acer Aspire 4736Z */
14621         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
14622
14623         /* Acer Aspire 5336 */
14624         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
14625
14626         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
14627         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
14628
14629         /* Acer C720 Chromebook (Core i3 4005U) */
14630         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
14631
14632         /* Apple Macbook 2,1 (Core 2 T7400) */
14633         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
14634
14635         /* Toshiba CB35 Chromebook (Celeron 2955U) */
14636         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
14637
14638         /* HP Chromebook 14 (Celeron 2955U) */
14639         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
14640
14641         /* Dell Chromebook 11 */
14642         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
14643 };
14644
14645 static void intel_init_quirks(struct drm_device *dev)
14646 {
14647         struct pci_dev *d = dev->pdev;
14648         int i;
14649
14650         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
14651                 struct intel_quirk *q = &intel_quirks[i];
14652
14653                 if (d->device == q->device &&
14654                     (d->subsystem_vendor == q->subsystem_vendor ||
14655                      q->subsystem_vendor == PCI_ANY_ID) &&
14656                     (d->subsystem_device == q->subsystem_device ||
14657                      q->subsystem_device == PCI_ANY_ID))
14658                         q->hook(dev);
14659         }
14660         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
14661                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
14662                         intel_dmi_quirks[i].hook(dev);
14663         }
14664 }
14665
14666 /* Disable the VGA plane that we never use */
14667 static void i915_disable_vga(struct drm_device *dev)
14668 {
14669         struct drm_i915_private *dev_priv = dev->dev_private;
14670         u8 sr1;
14671         u32 vga_reg = i915_vgacntrl_reg(dev);
14672
14673         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
14674         vga_get_uninterruptible(dev->pdev, VGA_RSRC_LEGACY_IO);
14675         outb(SR01, VGA_SR_INDEX);
14676         sr1 = inb(VGA_SR_DATA);
14677         outb(sr1 | 1<<5, VGA_SR_DATA);
14678         vga_put(dev->pdev, VGA_RSRC_LEGACY_IO);
14679         udelay(300);
14680
14681         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
14682         POSTING_READ(vga_reg);
14683 }
14684
14685 void intel_modeset_init_hw(struct drm_device *dev)
14686 {
14687         intel_update_cdclk(dev);
14688         intel_prepare_ddi(dev);
14689         intel_init_clock_gating(dev);
14690         intel_enable_gt_powersave(dev);
14691 }
14692
14693 void intel_modeset_init(struct drm_device *dev)
14694 {
14695         struct drm_i915_private *dev_priv = dev->dev_private;
14696         int sprite, ret;
14697         enum pipe pipe;
14698         struct intel_crtc *crtc;
14699
14700         drm_mode_config_init(dev);
14701
14702         dev->mode_config.min_width = 0;
14703         dev->mode_config.min_height = 0;
14704
14705         dev->mode_config.preferred_depth = 24;
14706         dev->mode_config.prefer_shadow = 1;
14707
14708         dev->mode_config.allow_fb_modifiers = true;
14709
14710         dev->mode_config.funcs = &intel_mode_funcs;
14711
14712         intel_init_quirks(dev);
14713
14714         intel_init_pm(dev);
14715
14716         if (INTEL_INFO(dev)->num_pipes == 0)
14717                 return;
14718
14719         /*
14720          * There may be no VBT; and if the BIOS enabled SSC we can
14721          * just keep using it to avoid unnecessary flicker.  Whereas if the
14722          * BIOS isn't using it, don't assume it will work even if the VBT
14723          * indicates as much.
14724          */
14725         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev)) {
14726                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
14727                                             DREF_SSC1_ENABLE);
14728
14729                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
14730                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
14731                                      bios_lvds_use_ssc ? "en" : "dis",
14732                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
14733                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
14734                 }
14735         }
14736
14737         intel_init_display(dev);
14738         intel_init_audio(dev);
14739
14740         if (IS_GEN2(dev)) {
14741                 dev->mode_config.max_width = 2048;
14742                 dev->mode_config.max_height = 2048;
14743         } else if (IS_GEN3(dev)) {
14744                 dev->mode_config.max_width = 4096;
14745                 dev->mode_config.max_height = 4096;
14746         } else {
14747                 dev->mode_config.max_width = 8192;
14748                 dev->mode_config.max_height = 8192;
14749         }
14750
14751         if (IS_845G(dev) || IS_I865G(dev)) {
14752                 dev->mode_config.cursor_width = IS_845G(dev) ? 64 : 512;
14753                 dev->mode_config.cursor_height = 1023;
14754         } else if (IS_GEN2(dev)) {
14755                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
14756                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
14757         } else {
14758                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
14759                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
14760         }
14761
14762         dev->mode_config.fb_base = dev_priv->gtt.mappable_base;
14763
14764         DRM_DEBUG_KMS("%d display pipe%s available.\n",
14765                       INTEL_INFO(dev)->num_pipes,
14766                       INTEL_INFO(dev)->num_pipes > 1 ? "s" : "");
14767
14768         for_each_pipe(dev_priv, pipe) {
14769                 intel_crtc_init(dev, pipe);
14770                 for_each_sprite(dev_priv, pipe, sprite) {
14771                         ret = intel_plane_init(dev, pipe, sprite);
14772                         if (ret)
14773                                 DRM_DEBUG_KMS("pipe %c sprite %c init failed: %d\n",
14774                                               pipe_name(pipe), sprite_name(pipe, sprite), ret);
14775                 }
14776         }
14777
14778         intel_shared_dpll_init(dev);
14779
14780         /* Just disable it once at startup */
14781         i915_disable_vga(dev);
14782         intel_setup_outputs(dev);
14783
14784         /* Just in case the BIOS is doing something questionable. */
14785         intel_fbc_disable(dev_priv);
14786
14787         drm_modeset_lock_all(dev);
14788         intel_modeset_setup_hw_state(dev);
14789         drm_modeset_unlock_all(dev);
14790
14791         for_each_intel_crtc(dev, crtc) {
14792                 struct intel_initial_plane_config plane_config = {};
14793
14794                 if (!crtc->active)
14795                         continue;
14796
14797                 /*
14798                  * Note that reserving the BIOS fb up front prevents us
14799                  * from stuffing other stolen allocations like the ring
14800                  * on top.  This prevents some ugliness at boot time, and
14801                  * can even allow for smooth boot transitions if the BIOS
14802                  * fb is large enough for the active pipe configuration.
14803                  */
14804                 dev_priv->display.get_initial_plane_config(crtc,
14805                                                            &plane_config);
14806
14807                 /*
14808                  * If the fb is shared between multiple heads, we'll
14809                  * just get the first one.
14810                  */
14811                 intel_find_initial_plane_obj(crtc, &plane_config);
14812         }
14813 }
14814
14815 static void intel_enable_pipe_a(struct drm_device *dev)
14816 {
14817         struct intel_connector *connector;
14818         struct drm_connector *crt = NULL;
14819         struct intel_load_detect_pipe load_detect_temp;
14820         struct drm_modeset_acquire_ctx *ctx = dev->mode_config.acquire_ctx;
14821
14822         /* We can't just switch on the pipe A, we need to set things up with a
14823          * proper mode and output configuration. As a gross hack, enable pipe A
14824          * by enabling the load detect pipe once. */
14825         for_each_intel_connector(dev, connector) {
14826                 if (connector->encoder->type == INTEL_OUTPUT_ANALOG) {
14827                         crt = &connector->base;
14828                         break;
14829                 }
14830         }
14831
14832         if (!crt)
14833                 return;
14834
14835         if (intel_get_load_detect_pipe(crt, NULL, &load_detect_temp, ctx))
14836                 intel_release_load_detect_pipe(crt, &load_detect_temp, ctx);
14837 }
14838
14839 static bool
14840 intel_check_plane_mapping(struct intel_crtc *crtc)
14841 {
14842         struct drm_device *dev = crtc->base.dev;
14843         struct drm_i915_private *dev_priv = dev->dev_private;
14844         u32 reg, val;
14845
14846         if (INTEL_INFO(dev)->num_pipes == 1)
14847                 return true;
14848
14849         reg = DSPCNTR(!crtc->plane);
14850         val = I915_READ(reg);
14851
14852         if ((val & DISPLAY_PLANE_ENABLE) &&
14853             (!!(val & DISPPLANE_SEL_PIPE_MASK) == crtc->pipe))
14854                 return false;
14855
14856         return true;
14857 }
14858
14859 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
14860 {
14861         struct drm_device *dev = crtc->base.dev;
14862         struct intel_encoder *encoder;
14863
14864         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
14865                 return true;
14866
14867         return false;
14868 }
14869
14870 static void intel_sanitize_crtc(struct intel_crtc *crtc)
14871 {
14872         struct drm_device *dev = crtc->base.dev;
14873         struct drm_i915_private *dev_priv = dev->dev_private;
14874         u32 reg;
14875
14876         /* Clear any frame start delays used for debugging left by the BIOS */
14877         reg = PIPECONF(crtc->config->cpu_transcoder);
14878         I915_WRITE(reg, I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
14879
14880         /* restore vblank interrupts to correct state */
14881         drm_crtc_vblank_reset(&crtc->base);
14882         if (crtc->active) {
14883                 drm_calc_timestamping_constants(&crtc->base, &crtc->base.hwmode);
14884                 update_scanline_offset(crtc);
14885                 drm_crtc_vblank_on(&crtc->base);
14886         }
14887
14888         /* We need to sanitize the plane -> pipe mapping first because this will
14889          * disable the crtc (and hence change the state) if it is wrong. Note
14890          * that gen4+ has a fixed plane -> pipe mapping.  */
14891         if (INTEL_INFO(dev)->gen < 4 && !intel_check_plane_mapping(crtc)) {
14892                 bool plane;
14893
14894                 DRM_DEBUG_KMS("[CRTC:%d] wrong plane connection detected!\n",
14895                               crtc->base.base.id);
14896
14897                 /* Pipe has the wrong plane attached and the plane is active.
14898                  * Temporarily change the plane mapping and disable everything
14899                  * ...  */
14900                 plane = crtc->plane;
14901                 to_intel_plane_state(crtc->base.primary->state)->visible = true;
14902                 crtc->plane = !plane;
14903                 intel_crtc_disable_noatomic(&crtc->base);
14904                 crtc->plane = plane;
14905         }
14906
14907         if (dev_priv->quirks & QUIRK_PIPEA_FORCE &&
14908             crtc->pipe == PIPE_A && !crtc->active) {
14909                 /* BIOS forgot to enable pipe A, this mostly happens after
14910                  * resume. Force-enable the pipe to fix this, the update_dpms
14911                  * call below we restore the pipe to the right state, but leave
14912                  * the required bits on. */
14913                 intel_enable_pipe_a(dev);
14914         }
14915
14916         /* Adjust the state of the output pipe according to whether we
14917          * have active connectors/encoders. */
14918         if (!intel_crtc_has_encoders(crtc))
14919                 intel_crtc_disable_noatomic(&crtc->base);
14920
14921         if (crtc->active != crtc->base.state->active) {
14922                 struct intel_encoder *encoder;
14923
14924                 /* This can happen either due to bugs in the get_hw_state
14925                  * functions or because of calls to intel_crtc_disable_noatomic,
14926                  * or because the pipe is force-enabled due to the
14927                  * pipe A quirk. */
14928                 DRM_DEBUG_KMS("[CRTC:%d] hw state adjusted, was %s, now %s\n",
14929                               crtc->base.base.id,
14930                               crtc->base.state->enable ? "enabled" : "disabled",
14931                               crtc->active ? "enabled" : "disabled");
14932
14933                 WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, NULL) < 0);
14934                 crtc->base.state->active = crtc->active;
14935                 crtc->base.enabled = crtc->active;
14936
14937                 /* Because we only establish the connector -> encoder ->
14938                  * crtc links if something is active, this means the
14939                  * crtc is now deactivated. Break the links. connector
14940                  * -> encoder links are only establish when things are
14941                  *  actually up, hence no need to break them. */
14942                 WARN_ON(crtc->active);
14943
14944                 for_each_encoder_on_crtc(dev, &crtc->base, encoder)
14945                         encoder->base.crtc = NULL;
14946         }
14947
14948         if (crtc->active || HAS_GMCH_DISPLAY(dev)) {
14949                 /*
14950                  * We start out with underrun reporting disabled to avoid races.
14951                  * For correct bookkeeping mark this on active crtcs.
14952                  *
14953                  * Also on gmch platforms we dont have any hardware bits to
14954                  * disable the underrun reporting. Which means we need to start
14955                  * out with underrun reporting disabled also on inactive pipes,
14956                  * since otherwise we'll complain about the garbage we read when
14957                  * e.g. coming up after runtime pm.
14958                  *
14959                  * No protection against concurrent access is required - at
14960                  * worst a fifo underrun happens which also sets this to false.
14961                  */
14962                 crtc->cpu_fifo_underrun_disabled = true;
14963                 crtc->pch_fifo_underrun_disabled = true;
14964         }
14965 }
14966
14967 static void intel_sanitize_encoder(struct intel_encoder *encoder)
14968 {
14969         struct intel_connector *connector;
14970         struct drm_device *dev = encoder->base.dev;
14971         bool active = false;
14972
14973         /* We need to check both for a crtc link (meaning that the
14974          * encoder is active and trying to read from a pipe) and the
14975          * pipe itself being active. */
14976         bool has_active_crtc = encoder->base.crtc &&
14977                 to_intel_crtc(encoder->base.crtc)->active;
14978
14979         for_each_intel_connector(dev, connector) {
14980                 if (connector->base.encoder != &encoder->base)
14981                         continue;
14982
14983                 active = true;
14984                 break;
14985         }
14986
14987         if (active && !has_active_crtc) {
14988                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
14989                               encoder->base.base.id,
14990                               encoder->base.name);
14991
14992                 /* Connector is active, but has no active pipe. This is
14993                  * fallout from our resume register restoring. Disable
14994                  * the encoder manually again. */
14995                 if (encoder->base.crtc) {
14996                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
14997                                       encoder->base.base.id,
14998                                       encoder->base.name);
14999                         encoder->disable(encoder);
15000                         if (encoder->post_disable)
15001                                 encoder->post_disable(encoder);
15002                 }
15003                 encoder->base.crtc = NULL;
15004
15005                 /* Inconsistent output/port/pipe state happens presumably due to
15006                  * a bug in one of the get_hw_state functions. Or someplace else
15007                  * in our code, like the register restore mess on resume. Clamp
15008                  * things to off as a safer default. */
15009                 for_each_intel_connector(dev, connector) {
15010                         if (connector->encoder != encoder)
15011                                 continue;
15012                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15013                         connector->base.encoder = NULL;
15014                 }
15015         }
15016         /* Enabled encoders without active connectors will be fixed in
15017          * the crtc fixup. */
15018 }
15019
15020 void i915_redisable_vga_power_on(struct drm_device *dev)
15021 {
15022         struct drm_i915_private *dev_priv = dev->dev_private;
15023         u32 vga_reg = i915_vgacntrl_reg(dev);
15024
15025         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
15026                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
15027                 i915_disable_vga(dev);
15028         }
15029 }
15030
15031 void i915_redisable_vga(struct drm_device *dev)
15032 {
15033         struct drm_i915_private *dev_priv = dev->dev_private;
15034
15035         /* This function can be called both from intel_modeset_setup_hw_state or
15036          * at a very early point in our resume sequence, where the power well
15037          * structures are not yet restored. Since this function is at a very
15038          * paranoid "someone might have enabled VGA while we were not looking"
15039          * level, just check if the power well is enabled instead of trying to
15040          * follow the "don't touch the power well if we don't need it" policy
15041          * the rest of the driver uses. */
15042         if (!intel_display_power_is_enabled(dev_priv, POWER_DOMAIN_VGA))
15043                 return;
15044
15045         i915_redisable_vga_power_on(dev);
15046 }
15047
15048 static bool primary_get_hw_state(struct intel_crtc *crtc)
15049 {
15050         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
15051
15052         return !!(I915_READ(DSPCNTR(crtc->plane)) & DISPLAY_PLANE_ENABLE);
15053 }
15054
15055 static void readout_plane_state(struct intel_crtc *crtc,
15056                                 struct intel_crtc_state *crtc_state)
15057 {
15058         struct intel_plane *p;
15059         struct intel_plane_state *plane_state;
15060         bool active = crtc_state->base.active;
15061
15062         for_each_intel_plane(crtc->base.dev, p) {
15063                 if (crtc->pipe != p->pipe)
15064                         continue;
15065
15066                 plane_state = to_intel_plane_state(p->base.state);
15067
15068                 if (p->base.type == DRM_PLANE_TYPE_PRIMARY)
15069                         plane_state->visible = primary_get_hw_state(crtc);
15070                 else {
15071                         if (active)
15072                                 p->disable_plane(&p->base, &crtc->base);
15073
15074                         plane_state->visible = false;
15075                 }
15076         }
15077 }
15078
15079 static void intel_modeset_readout_hw_state(struct drm_device *dev)
15080 {
15081         struct drm_i915_private *dev_priv = dev->dev_private;
15082         enum pipe pipe;
15083         struct intel_crtc *crtc;
15084         struct intel_encoder *encoder;
15085         struct intel_connector *connector;
15086         int i;
15087
15088         for_each_intel_crtc(dev, crtc) {
15089                 __drm_atomic_helper_crtc_destroy_state(&crtc->base, crtc->base.state);
15090                 memset(crtc->config, 0, sizeof(*crtc->config));
15091                 crtc->config->base.crtc = &crtc->base;
15092
15093                 crtc->active = dev_priv->display.get_pipe_config(crtc,
15094                                                                  crtc->config);
15095
15096                 crtc->base.state->active = crtc->active;
15097                 crtc->base.enabled = crtc->active;
15098
15099                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
15100                 if (crtc->base.state->active) {
15101                         intel_mode_from_pipe_config(&crtc->base.mode, crtc->config);
15102                         intel_mode_from_pipe_config(&crtc->base.state->adjusted_mode, crtc->config);
15103                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
15104
15105                         /*
15106                          * The initial mode needs to be set in order to keep
15107                          * the atomic core happy. It wants a valid mode if the
15108                          * crtc's enabled, so we do the above call.
15109                          *
15110                          * At this point some state updated by the connectors
15111                          * in their ->detect() callback has not run yet, so
15112                          * no recalculation can be done yet.
15113                          *
15114                          * Even if we could do a recalculation and modeset
15115                          * right now it would cause a double modeset if
15116                          * fbdev or userspace chooses a different initial mode.
15117                          *
15118                          * If that happens, someone indicated they wanted a
15119                          * mode change, which means it's safe to do a full
15120                          * recalculation.
15121                          */
15122                         crtc->base.state->mode.private_flags = I915_MODE_FLAG_INHERITED;
15123                 }
15124
15125                 crtc->base.hwmode = crtc->config->base.adjusted_mode;
15126                 readout_plane_state(crtc, to_intel_crtc_state(crtc->base.state));
15127
15128                 DRM_DEBUG_KMS("[CRTC:%d] hw state readout: %s\n",
15129                               crtc->base.base.id,
15130                               crtc->active ? "enabled" : "disabled");
15131         }
15132
15133         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15134                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15135
15136                 pll->on = pll->get_hw_state(dev_priv, pll,
15137                                             &pll->config.hw_state);
15138                 pll->active = 0;
15139                 pll->config.crtc_mask = 0;
15140                 for_each_intel_crtc(dev, crtc) {
15141                         if (crtc->active && intel_crtc_to_shared_dpll(crtc) == pll) {
15142                                 pll->active++;
15143                                 pll->config.crtc_mask |= 1 << crtc->pipe;
15144                         }
15145                 }
15146
15147                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15148                               pll->name, pll->config.crtc_mask, pll->on);
15149
15150                 if (pll->config.crtc_mask)
15151                         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
15152         }
15153
15154         for_each_intel_encoder(dev, encoder) {
15155                 pipe = 0;
15156
15157                 if (encoder->get_hw_state(encoder, &pipe)) {
15158                         crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
15159                         encoder->base.crtc = &crtc->base;
15160                         encoder->get_config(encoder, crtc->config);
15161                 } else {
15162                         encoder->base.crtc = NULL;
15163                 }
15164
15165                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
15166                               encoder->base.base.id,
15167                               encoder->base.name,
15168                               encoder->base.crtc ? "enabled" : "disabled",
15169                               pipe_name(pipe));
15170         }
15171
15172         for_each_intel_connector(dev, connector) {
15173                 if (connector->get_hw_state(connector)) {
15174                         connector->base.dpms = DRM_MODE_DPMS_ON;
15175                         connector->base.encoder = &connector->encoder->base;
15176                 } else {
15177                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15178                         connector->base.encoder = NULL;
15179                 }
15180                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
15181                               connector->base.base.id,
15182                               connector->base.name,
15183                               connector->base.encoder ? "enabled" : "disabled");
15184         }
15185 }
15186
15187 /* Scan out the current hw modeset state,
15188  * and sanitizes it to the current state
15189  */
15190 static void
15191 intel_modeset_setup_hw_state(struct drm_device *dev)
15192 {
15193         struct drm_i915_private *dev_priv = dev->dev_private;
15194         enum pipe pipe;
15195         struct intel_crtc *crtc;
15196         struct intel_encoder *encoder;
15197         int i;
15198
15199         intel_modeset_readout_hw_state(dev);
15200
15201         /* HW state is read out, now we need to sanitize this mess. */
15202         for_each_intel_encoder(dev, encoder) {
15203                 intel_sanitize_encoder(encoder);
15204         }
15205
15206         for_each_pipe(dev_priv, pipe) {
15207                 crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
15208                 intel_sanitize_crtc(crtc);
15209                 intel_dump_pipe_config(crtc, crtc->config,
15210                                        "[setup_hw_state]");
15211         }
15212
15213         intel_modeset_update_connector_atomic_state(dev);
15214
15215         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15216                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15217
15218                 if (!pll->on || pll->active)
15219                         continue;
15220
15221                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
15222
15223                 pll->disable(dev_priv, pll);
15224                 pll->on = false;
15225         }
15226
15227         if (IS_VALLEYVIEW(dev))
15228                 vlv_wm_get_hw_state(dev);
15229         else if (IS_GEN9(dev))
15230                 skl_wm_get_hw_state(dev);
15231         else if (HAS_PCH_SPLIT(dev))
15232                 ilk_wm_get_hw_state(dev);
15233
15234         for_each_intel_crtc(dev, crtc) {
15235                 unsigned long put_domains;
15236
15237                 put_domains = modeset_get_crtc_power_domains(&crtc->base);
15238                 if (WARN_ON(put_domains))
15239                         modeset_put_power_domains(dev_priv, put_domains);
15240         }
15241         intel_display_set_init_power(dev_priv, false);
15242 }
15243
15244 void intel_display_resume(struct drm_device *dev)
15245 {
15246         struct drm_atomic_state *state = drm_atomic_state_alloc(dev);
15247         struct intel_connector *conn;
15248         struct intel_plane *plane;
15249         struct drm_crtc *crtc;
15250         int ret;
15251
15252         if (!state)
15253                 return;
15254
15255         state->acquire_ctx = dev->mode_config.acquire_ctx;
15256
15257         /* preserve complete old state, including dpll */
15258         intel_atomic_get_shared_dpll_state(state);
15259
15260         for_each_crtc(dev, crtc) {
15261                 struct drm_crtc_state *crtc_state =
15262                         drm_atomic_get_crtc_state(state, crtc);
15263
15264                 ret = PTR_ERR_OR_ZERO(crtc_state);
15265                 if (ret)
15266                         goto err;
15267
15268                 /* force a restore */
15269                 crtc_state->mode_changed = true;
15270         }
15271
15272         for_each_intel_plane(dev, plane) {
15273                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_plane_state(state, &plane->base));
15274                 if (ret)
15275                         goto err;
15276         }
15277
15278         for_each_intel_connector(dev, conn) {
15279                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(state, &conn->base));
15280                 if (ret)
15281                         goto err;
15282         }
15283
15284         intel_modeset_setup_hw_state(dev);
15285
15286         i915_redisable_vga(dev);
15287         ret = drm_atomic_commit(state);
15288         if (!ret)
15289                 return;
15290
15291 err:
15292         DRM_ERROR("Restoring old state failed with %i\n", ret);
15293         drm_atomic_state_free(state);
15294 }
15295
15296 void intel_modeset_gem_init(struct drm_device *dev)
15297 {
15298         struct drm_crtc *c;
15299         struct drm_i915_gem_object *obj;
15300         int ret;
15301
15302         mutex_lock(&dev->struct_mutex);
15303         intel_init_gt_powersave(dev);
15304         mutex_unlock(&dev->struct_mutex);
15305
15306         intel_modeset_init_hw(dev);
15307
15308         intel_setup_overlay(dev);
15309
15310         /*
15311          * Make sure any fbs we allocated at startup are properly
15312          * pinned & fenced.  When we do the allocation it's too early
15313          * for this.
15314          */
15315         for_each_crtc(dev, c) {
15316                 obj = intel_fb_obj(c->primary->fb);
15317                 if (obj == NULL)
15318                         continue;
15319
15320                 mutex_lock(&dev->struct_mutex);
15321                 ret = intel_pin_and_fence_fb_obj(c->primary,
15322                                                  c->primary->fb,
15323                                                  c->primary->state,
15324                                                  NULL, NULL);
15325                 mutex_unlock(&dev->struct_mutex);
15326                 if (ret) {
15327                         DRM_ERROR("failed to pin boot fb on pipe %d\n",
15328                                   to_intel_crtc(c)->pipe);
15329                         drm_framebuffer_unreference(c->primary->fb);
15330                         c->primary->fb = NULL;
15331                         c->primary->crtc = c->primary->state->crtc = NULL;
15332                         update_state_fb(c->primary);
15333                         c->state->plane_mask &= ~(1 << drm_plane_index(c->primary));
15334                 }
15335         }
15336
15337         intel_backlight_register(dev);
15338 }
15339
15340 void intel_connector_unregister(struct intel_connector *intel_connector)
15341 {
15342         struct drm_connector *connector = &intel_connector->base;
15343
15344         intel_panel_destroy_backlight(connector);
15345         drm_connector_unregister(connector);
15346 }
15347
15348 void intel_modeset_cleanup(struct drm_device *dev)
15349 {
15350         struct drm_i915_private *dev_priv = dev->dev_private;
15351         struct drm_connector *connector;
15352
15353         intel_disable_gt_powersave(dev);
15354
15355         intel_backlight_unregister(dev);
15356
15357         /*
15358          * Interrupts and polling as the first thing to avoid creating havoc.
15359          * Too much stuff here (turning of connectors, ...) would
15360          * experience fancy races otherwise.
15361          */
15362         intel_irq_uninstall(dev_priv);
15363
15364         /*
15365          * Due to the hpd irq storm handling the hotplug work can re-arm the
15366          * poll handlers. Hence disable polling after hpd handling is shut down.
15367          */
15368         drm_kms_helper_poll_fini(dev);
15369
15370         intel_unregister_dsm_handler();
15371
15372         intel_fbc_disable(dev_priv);
15373
15374         /* flush any delayed tasks or pending work */
15375         flush_scheduled_work();
15376
15377         /* destroy the backlight and sysfs files before encoders/connectors */
15378         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
15379                 struct intel_connector *intel_connector;
15380
15381                 intel_connector = to_intel_connector(connector);
15382                 intel_connector->unregister(intel_connector);
15383         }
15384
15385         drm_mode_config_cleanup(dev);
15386
15387         intel_cleanup_overlay(dev);
15388
15389         mutex_lock(&dev->struct_mutex);
15390         intel_cleanup_gt_powersave(dev);
15391         mutex_unlock(&dev->struct_mutex);
15392 }
15393
15394 /*
15395  * Return which encoder is currently attached for connector.
15396  */
15397 struct drm_encoder *intel_best_encoder(struct drm_connector *connector)
15398 {
15399         return &intel_attached_encoder(connector)->base;
15400 }
15401
15402 void intel_connector_attach_encoder(struct intel_connector *connector,
15403                                     struct intel_encoder *encoder)
15404 {
15405         connector->encoder = encoder;
15406         drm_mode_connector_attach_encoder(&connector->base,
15407                                           &encoder->base);
15408 }
15409
15410 /*
15411  * set vga decode state - true == enable VGA decode
15412  */
15413 int intel_modeset_vga_set_state(struct drm_device *dev, bool state)
15414 {
15415         struct drm_i915_private *dev_priv = dev->dev_private;
15416         unsigned reg = INTEL_INFO(dev)->gen >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
15417         u16 gmch_ctrl;
15418
15419         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
15420                 DRM_ERROR("failed to read control word\n");
15421                 return -EIO;
15422         }
15423
15424         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
15425                 return 0;
15426
15427         if (state)
15428                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
15429         else
15430                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
15431
15432         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
15433                 DRM_ERROR("failed to write control word\n");
15434                 return -EIO;
15435         }
15436
15437         return 0;
15438 }
15439
15440 struct intel_display_error_state {
15441
15442         u32 power_well_driver;
15443
15444         int num_transcoders;
15445
15446         struct intel_cursor_error_state {
15447                 u32 control;
15448                 u32 position;
15449                 u32 base;
15450                 u32 size;
15451         } cursor[I915_MAX_PIPES];
15452
15453         struct intel_pipe_error_state {
15454                 bool power_domain_on;
15455                 u32 source;
15456                 u32 stat;
15457         } pipe[I915_MAX_PIPES];
15458
15459         struct intel_plane_error_state {
15460                 u32 control;
15461                 u32 stride;
15462                 u32 size;
15463                 u32 pos;
15464                 u32 addr;
15465                 u32 surface;
15466                 u32 tile_offset;
15467         } plane[I915_MAX_PIPES];
15468
15469         struct intel_transcoder_error_state {
15470                 bool power_domain_on;
15471                 enum transcoder cpu_transcoder;
15472
15473                 u32 conf;
15474
15475                 u32 htotal;
15476                 u32 hblank;
15477                 u32 hsync;
15478                 u32 vtotal;
15479                 u32 vblank;
15480                 u32 vsync;
15481         } transcoder[4];
15482 };
15483
15484 struct intel_display_error_state *
15485 intel_display_capture_error_state(struct drm_device *dev)
15486 {
15487         struct drm_i915_private *dev_priv = dev->dev_private;
15488         struct intel_display_error_state *error;
15489         int transcoders[] = {
15490                 TRANSCODER_A,
15491                 TRANSCODER_B,
15492                 TRANSCODER_C,
15493                 TRANSCODER_EDP,
15494         };
15495         int i;
15496
15497         if (INTEL_INFO(dev)->num_pipes == 0)
15498                 return NULL;
15499
15500         error = kzalloc(sizeof(*error), GFP_ATOMIC);
15501         if (error == NULL)
15502                 return NULL;
15503
15504         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
15505                 error->power_well_driver = I915_READ(HSW_PWR_WELL_DRIVER);
15506
15507         for_each_pipe(dev_priv, i) {
15508                 error->pipe[i].power_domain_on =
15509                         __intel_display_power_is_enabled(dev_priv,
15510                                                          POWER_DOMAIN_PIPE(i));
15511                 if (!error->pipe[i].power_domain_on)
15512                         continue;
15513
15514                 error->cursor[i].control = I915_READ(CURCNTR(i));
15515                 error->cursor[i].position = I915_READ(CURPOS(i));
15516                 error->cursor[i].base = I915_READ(CURBASE(i));
15517
15518                 error->plane[i].control = I915_READ(DSPCNTR(i));
15519                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
15520                 if (INTEL_INFO(dev)->gen <= 3) {
15521                         error->plane[i].size = I915_READ(DSPSIZE(i));
15522                         error->plane[i].pos = I915_READ(DSPPOS(i));
15523                 }
15524                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
15525                         error->plane[i].addr = I915_READ(DSPADDR(i));
15526                 if (INTEL_INFO(dev)->gen >= 4) {
15527                         error->plane[i].surface = I915_READ(DSPSURF(i));
15528                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
15529                 }
15530
15531                 error->pipe[i].source = I915_READ(PIPESRC(i));
15532
15533                 if (HAS_GMCH_DISPLAY(dev))
15534                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
15535         }
15536
15537         error->num_transcoders = INTEL_INFO(dev)->num_pipes;
15538         if (HAS_DDI(dev_priv->dev))
15539                 error->num_transcoders++; /* Account for eDP. */
15540
15541         for (i = 0; i < error->num_transcoders; i++) {
15542                 enum transcoder cpu_transcoder = transcoders[i];
15543
15544                 error->transcoder[i].power_domain_on =
15545                         __intel_display_power_is_enabled(dev_priv,
15546                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
15547                 if (!error->transcoder[i].power_domain_on)
15548                         continue;
15549
15550                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
15551
15552                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
15553                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
15554                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
15555                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
15556                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
15557                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
15558                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
15559         }
15560
15561         return error;
15562 }
15563
15564 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
15565
15566 void
15567 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
15568                                 struct drm_device *dev,
15569                                 struct intel_display_error_state *error)
15570 {
15571         struct drm_i915_private *dev_priv = dev->dev_private;
15572         int i;
15573
15574         if (!error)
15575                 return;
15576
15577         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev)->num_pipes);
15578         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
15579                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
15580                            error->power_well_driver);
15581         for_each_pipe(dev_priv, i) {
15582                 err_printf(m, "Pipe [%d]:\n", i);
15583                 err_printf(m, "  Power: %s\n",
15584                            error->pipe[i].power_domain_on ? "on" : "off");
15585                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
15586                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
15587
15588                 err_printf(m, "Plane [%d]:\n", i);
15589                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
15590                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
15591                 if (INTEL_INFO(dev)->gen <= 3) {
15592                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
15593                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
15594                 }
15595                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
15596                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
15597                 if (INTEL_INFO(dev)->gen >= 4) {
15598                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
15599                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
15600                 }
15601
15602                 err_printf(m, "Cursor [%d]:\n", i);
15603                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
15604                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
15605                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
15606         }
15607
15608         for (i = 0; i < error->num_transcoders; i++) {
15609                 err_printf(m, "CPU transcoder: %c\n",
15610                            transcoder_name(error->transcoder[i].cpu_transcoder));
15611                 err_printf(m, "  Power: %s\n",
15612                            error->transcoder[i].power_domain_on ? "on" : "off");
15613                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
15614                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
15615                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
15616                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
15617                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
15618                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
15619                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
15620         }
15621 }
15622
15623 void intel_modeset_preclose(struct drm_device *dev, struct drm_file *file)
15624 {
15625         struct intel_crtc *crtc;
15626
15627         for_each_intel_crtc(dev, crtc) {
15628                 struct intel_unpin_work *work;
15629
15630                 spin_lock_irq(&dev->event_lock);
15631
15632                 work = crtc->unpin_work;
15633
15634                 if (work && work->event &&
15635                     work->event->base.file_priv == file) {
15636                         kfree(work->event);
15637                         work->event = NULL;
15638                 }
15639
15640                 spin_unlock_irq(&dev->event_lock);
15641         }
15642 }