Merge tag 'drm-intel-next-2015-09-11' of git://anongit.freedesktop.org/drm-intel...
[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 intel_encoder *encoder = connector->encoder;
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 || encoder->type == INTEL_OUTPUT_DP_MST)
6292                         return;
6293
6294                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6295                         "atomic encoder doesn't match attached encoder\n");
6296
6297                 I915_STATE_WARN(conn_state->crtc != encoder->base.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         struct drm_plane_state *cursor_state = crtc->cursor->state;
9920         int x = cursor_state->crtc_x;
9921         int y = cursor_state->crtc_y;
9922         u32 base = 0, pos = 0;
9923
9924         if (on)
9925                 base = intel_crtc->cursor_addr;
9926
9927         if (x >= intel_crtc->config->pipe_src_w)
9928                 base = 0;
9929
9930         if (y >= intel_crtc->config->pipe_src_h)
9931                 base = 0;
9932
9933         if (x < 0) {
9934                 if (x + cursor_state->crtc_w <= 0)
9935                         base = 0;
9936
9937                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
9938                 x = -x;
9939         }
9940         pos |= x << CURSOR_X_SHIFT;
9941
9942         if (y < 0) {
9943                 if (y + cursor_state->crtc_h <= 0)
9944                         base = 0;
9945
9946                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
9947                 y = -y;
9948         }
9949         pos |= y << CURSOR_Y_SHIFT;
9950
9951         if (base == 0 && intel_crtc->cursor_base == 0)
9952                 return;
9953
9954         I915_WRITE(CURPOS(pipe), pos);
9955
9956         /* ILK+ do this automagically */
9957         if (HAS_GMCH_DISPLAY(dev) &&
9958             crtc->cursor->state->rotation == BIT(DRM_ROTATE_180)) {
9959                 base += (cursor_state->crtc_h *
9960                          cursor_state->crtc_w - 1) * 4;
9961         }
9962
9963         if (IS_845G(dev) || IS_I865G(dev))
9964                 i845_update_cursor(crtc, base);
9965         else
9966                 i9xx_update_cursor(crtc, base);
9967 }
9968
9969 static bool cursor_size_ok(struct drm_device *dev,
9970                            uint32_t width, uint32_t height)
9971 {
9972         if (width == 0 || height == 0)
9973                 return false;
9974
9975         /*
9976          * 845g/865g are special in that they are only limited by
9977          * the width of their cursors, the height is arbitrary up to
9978          * the precision of the register. Everything else requires
9979          * square cursors, limited to a few power-of-two sizes.
9980          */
9981         if (IS_845G(dev) || IS_I865G(dev)) {
9982                 if ((width & 63) != 0)
9983                         return false;
9984
9985                 if (width > (IS_845G(dev) ? 64 : 512))
9986                         return false;
9987
9988                 if (height > 1023)
9989                         return false;
9990         } else {
9991                 switch (width | height) {
9992                 case 256:
9993                 case 128:
9994                         if (IS_GEN2(dev))
9995                                 return false;
9996                 case 64:
9997                         break;
9998                 default:
9999                         return false;
10000                 }
10001         }
10002
10003         return true;
10004 }
10005
10006 static void intel_crtc_gamma_set(struct drm_crtc *crtc, u16 *red, u16 *green,
10007                                  u16 *blue, uint32_t start, uint32_t size)
10008 {
10009         int end = (start + size > 256) ? 256 : start + size, i;
10010         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10011
10012         for (i = start; i < end; i++) {
10013                 intel_crtc->lut_r[i] = red[i] >> 8;
10014                 intel_crtc->lut_g[i] = green[i] >> 8;
10015                 intel_crtc->lut_b[i] = blue[i] >> 8;
10016         }
10017
10018         intel_crtc_load_lut(crtc);
10019 }
10020
10021 /* VESA 640x480x72Hz mode to set on the pipe */
10022 static struct drm_display_mode load_detect_mode = {
10023         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10024                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10025 };
10026
10027 struct drm_framebuffer *
10028 __intel_framebuffer_create(struct drm_device *dev,
10029                            struct drm_mode_fb_cmd2 *mode_cmd,
10030                            struct drm_i915_gem_object *obj)
10031 {
10032         struct intel_framebuffer *intel_fb;
10033         int ret;
10034
10035         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10036         if (!intel_fb) {
10037                 drm_gem_object_unreference(&obj->base);
10038                 return ERR_PTR(-ENOMEM);
10039         }
10040
10041         ret = intel_framebuffer_init(dev, intel_fb, mode_cmd, obj);
10042         if (ret)
10043                 goto err;
10044
10045         return &intel_fb->base;
10046 err:
10047         drm_gem_object_unreference(&obj->base);
10048         kfree(intel_fb);
10049
10050         return ERR_PTR(ret);
10051 }
10052
10053 static struct drm_framebuffer *
10054 intel_framebuffer_create(struct drm_device *dev,
10055                          struct drm_mode_fb_cmd2 *mode_cmd,
10056                          struct drm_i915_gem_object *obj)
10057 {
10058         struct drm_framebuffer *fb;
10059         int ret;
10060
10061         ret = i915_mutex_lock_interruptible(dev);
10062         if (ret)
10063                 return ERR_PTR(ret);
10064         fb = __intel_framebuffer_create(dev, mode_cmd, obj);
10065         mutex_unlock(&dev->struct_mutex);
10066
10067         return fb;
10068 }
10069
10070 static u32
10071 intel_framebuffer_pitch_for_width(int width, int bpp)
10072 {
10073         u32 pitch = DIV_ROUND_UP(width * bpp, 8);
10074         return ALIGN(pitch, 64);
10075 }
10076
10077 static u32
10078 intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
10079 {
10080         u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
10081         return PAGE_ALIGN(pitch * mode->vdisplay);
10082 }
10083
10084 static struct drm_framebuffer *
10085 intel_framebuffer_create_for_mode(struct drm_device *dev,
10086                                   struct drm_display_mode *mode,
10087                                   int depth, int bpp)
10088 {
10089         struct drm_i915_gem_object *obj;
10090         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
10091
10092         obj = i915_gem_alloc_object(dev,
10093                                     intel_framebuffer_size_for_mode(mode, bpp));
10094         if (obj == NULL)
10095                 return ERR_PTR(-ENOMEM);
10096
10097         mode_cmd.width = mode->hdisplay;
10098         mode_cmd.height = mode->vdisplay;
10099         mode_cmd.pitches[0] = intel_framebuffer_pitch_for_width(mode_cmd.width,
10100                                                                 bpp);
10101         mode_cmd.pixel_format = drm_mode_legacy_fb_format(bpp, depth);
10102
10103         return intel_framebuffer_create(dev, &mode_cmd, obj);
10104 }
10105
10106 static struct drm_framebuffer *
10107 mode_fits_in_fbdev(struct drm_device *dev,
10108                    struct drm_display_mode *mode)
10109 {
10110 #ifdef CONFIG_DRM_FBDEV_EMULATION
10111         struct drm_i915_private *dev_priv = dev->dev_private;
10112         struct drm_i915_gem_object *obj;
10113         struct drm_framebuffer *fb;
10114
10115         if (!dev_priv->fbdev)
10116                 return NULL;
10117
10118         if (!dev_priv->fbdev->fb)
10119                 return NULL;
10120
10121         obj = dev_priv->fbdev->fb->obj;
10122         BUG_ON(!obj);
10123
10124         fb = &dev_priv->fbdev->fb->base;
10125         if (fb->pitches[0] < intel_framebuffer_pitch_for_width(mode->hdisplay,
10126                                                                fb->bits_per_pixel))
10127                 return NULL;
10128
10129         if (obj->base.size < mode->vdisplay * fb->pitches[0])
10130                 return NULL;
10131
10132         return fb;
10133 #else
10134         return NULL;
10135 #endif
10136 }
10137
10138 static int intel_modeset_setup_plane_state(struct drm_atomic_state *state,
10139                                            struct drm_crtc *crtc,
10140                                            struct drm_display_mode *mode,
10141                                            struct drm_framebuffer *fb,
10142                                            int x, int y)
10143 {
10144         struct drm_plane_state *plane_state;
10145         int hdisplay, vdisplay;
10146         int ret;
10147
10148         plane_state = drm_atomic_get_plane_state(state, crtc->primary);
10149         if (IS_ERR(plane_state))
10150                 return PTR_ERR(plane_state);
10151
10152         if (mode)
10153                 drm_crtc_get_hv_timing(mode, &hdisplay, &vdisplay);
10154         else
10155                 hdisplay = vdisplay = 0;
10156
10157         ret = drm_atomic_set_crtc_for_plane(plane_state, fb ? crtc : NULL);
10158         if (ret)
10159                 return ret;
10160         drm_atomic_set_fb_for_plane(plane_state, fb);
10161         plane_state->crtc_x = 0;
10162         plane_state->crtc_y = 0;
10163         plane_state->crtc_w = hdisplay;
10164         plane_state->crtc_h = vdisplay;
10165         plane_state->src_x = x << 16;
10166         plane_state->src_y = y << 16;
10167         plane_state->src_w = hdisplay << 16;
10168         plane_state->src_h = vdisplay << 16;
10169
10170         return 0;
10171 }
10172
10173 bool intel_get_load_detect_pipe(struct drm_connector *connector,
10174                                 struct drm_display_mode *mode,
10175                                 struct intel_load_detect_pipe *old,
10176                                 struct drm_modeset_acquire_ctx *ctx)
10177 {
10178         struct intel_crtc *intel_crtc;
10179         struct intel_encoder *intel_encoder =
10180                 intel_attached_encoder(connector);
10181         struct drm_crtc *possible_crtc;
10182         struct drm_encoder *encoder = &intel_encoder->base;
10183         struct drm_crtc *crtc = NULL;
10184         struct drm_device *dev = encoder->dev;
10185         struct drm_framebuffer *fb;
10186         struct drm_mode_config *config = &dev->mode_config;
10187         struct drm_atomic_state *state = NULL;
10188         struct drm_connector_state *connector_state;
10189         struct intel_crtc_state *crtc_state;
10190         int ret, i = -1;
10191
10192         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10193                       connector->base.id, connector->name,
10194                       encoder->base.id, encoder->name);
10195
10196 retry:
10197         ret = drm_modeset_lock(&config->connection_mutex, ctx);
10198         if (ret)
10199                 goto fail;
10200
10201         /*
10202          * Algorithm gets a little messy:
10203          *
10204          *   - if the connector already has an assigned crtc, use it (but make
10205          *     sure it's on first)
10206          *
10207          *   - try to find the first unused crtc that can drive this connector,
10208          *     and use that if we find one
10209          */
10210
10211         /* See if we already have a CRTC for this connector */
10212         if (encoder->crtc) {
10213                 crtc = encoder->crtc;
10214
10215                 ret = drm_modeset_lock(&crtc->mutex, ctx);
10216                 if (ret)
10217                         goto fail;
10218                 ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
10219                 if (ret)
10220                         goto fail;
10221
10222                 old->dpms_mode = connector->dpms;
10223                 old->load_detect_temp = false;
10224
10225                 /* Make sure the crtc and connector are running */
10226                 if (connector->dpms != DRM_MODE_DPMS_ON)
10227                         connector->funcs->dpms(connector, DRM_MODE_DPMS_ON);
10228
10229                 return true;
10230         }
10231
10232         /* Find an unused one (if possible) */
10233         for_each_crtc(dev, possible_crtc) {
10234                 i++;
10235                 if (!(encoder->possible_crtcs & (1 << i)))
10236                         continue;
10237                 if (possible_crtc->state->enable)
10238                         continue;
10239
10240                 crtc = possible_crtc;
10241                 break;
10242         }
10243
10244         /*
10245          * If we didn't find an unused CRTC, don't use any.
10246          */
10247         if (!crtc) {
10248                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
10249                 goto fail;
10250         }
10251
10252         ret = drm_modeset_lock(&crtc->mutex, ctx);
10253         if (ret)
10254                 goto fail;
10255         ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
10256         if (ret)
10257                 goto fail;
10258
10259         intel_crtc = to_intel_crtc(crtc);
10260         old->dpms_mode = connector->dpms;
10261         old->load_detect_temp = true;
10262         old->release_fb = NULL;
10263
10264         state = drm_atomic_state_alloc(dev);
10265         if (!state)
10266                 return false;
10267
10268         state->acquire_ctx = ctx;
10269
10270         connector_state = drm_atomic_get_connector_state(state, connector);
10271         if (IS_ERR(connector_state)) {
10272                 ret = PTR_ERR(connector_state);
10273                 goto fail;
10274         }
10275
10276         connector_state->crtc = crtc;
10277         connector_state->best_encoder = &intel_encoder->base;
10278
10279         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10280         if (IS_ERR(crtc_state)) {
10281                 ret = PTR_ERR(crtc_state);
10282                 goto fail;
10283         }
10284
10285         crtc_state->base.active = crtc_state->base.enable = true;
10286
10287         if (!mode)
10288                 mode = &load_detect_mode;
10289
10290         /* We need a framebuffer large enough to accommodate all accesses
10291          * that the plane may generate whilst we perform load detection.
10292          * We can not rely on the fbcon either being present (we get called
10293          * during its initialisation to detect all boot displays, or it may
10294          * not even exist) or that it is large enough to satisfy the
10295          * requested mode.
10296          */
10297         fb = mode_fits_in_fbdev(dev, mode);
10298         if (fb == NULL) {
10299                 DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
10300                 fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
10301                 old->release_fb = fb;
10302         } else
10303                 DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
10304         if (IS_ERR(fb)) {
10305                 DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
10306                 goto fail;
10307         }
10308
10309         ret = intel_modeset_setup_plane_state(state, crtc, mode, fb, 0, 0);
10310         if (ret)
10311                 goto fail;
10312
10313         drm_mode_copy(&crtc_state->base.mode, mode);
10314
10315         if (drm_atomic_commit(state)) {
10316                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
10317                 if (old->release_fb)
10318                         old->release_fb->funcs->destroy(old->release_fb);
10319                 goto fail;
10320         }
10321         crtc->primary->crtc = crtc;
10322
10323         /* let the connector get through one full cycle before testing */
10324         intel_wait_for_vblank(dev, intel_crtc->pipe);
10325         return true;
10326
10327 fail:
10328         drm_atomic_state_free(state);
10329         state = NULL;
10330
10331         if (ret == -EDEADLK) {
10332                 drm_modeset_backoff(ctx);
10333                 goto retry;
10334         }
10335
10336         return false;
10337 }
10338
10339 void intel_release_load_detect_pipe(struct drm_connector *connector,
10340                                     struct intel_load_detect_pipe *old,
10341                                     struct drm_modeset_acquire_ctx *ctx)
10342 {
10343         struct drm_device *dev = connector->dev;
10344         struct intel_encoder *intel_encoder =
10345                 intel_attached_encoder(connector);
10346         struct drm_encoder *encoder = &intel_encoder->base;
10347         struct drm_crtc *crtc = encoder->crtc;
10348         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10349         struct drm_atomic_state *state;
10350         struct drm_connector_state *connector_state;
10351         struct intel_crtc_state *crtc_state;
10352         int ret;
10353
10354         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10355                       connector->base.id, connector->name,
10356                       encoder->base.id, encoder->name);
10357
10358         if (old->load_detect_temp) {
10359                 state = drm_atomic_state_alloc(dev);
10360                 if (!state)
10361                         goto fail;
10362
10363                 state->acquire_ctx = ctx;
10364
10365                 connector_state = drm_atomic_get_connector_state(state, connector);
10366                 if (IS_ERR(connector_state))
10367                         goto fail;
10368
10369                 crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10370                 if (IS_ERR(crtc_state))
10371                         goto fail;
10372
10373                 connector_state->best_encoder = NULL;
10374                 connector_state->crtc = NULL;
10375
10376                 crtc_state->base.enable = crtc_state->base.active = false;
10377
10378                 ret = intel_modeset_setup_plane_state(state, crtc, NULL, NULL,
10379                                                       0, 0);
10380                 if (ret)
10381                         goto fail;
10382
10383                 ret = drm_atomic_commit(state);
10384                 if (ret)
10385                         goto fail;
10386
10387                 if (old->release_fb) {
10388                         drm_framebuffer_unregister_private(old->release_fb);
10389                         drm_framebuffer_unreference(old->release_fb);
10390                 }
10391
10392                 return;
10393         }
10394
10395         /* Switch crtc and encoder back off if necessary */
10396         if (old->dpms_mode != DRM_MODE_DPMS_ON)
10397                 connector->funcs->dpms(connector, old->dpms_mode);
10398
10399         return;
10400 fail:
10401         DRM_DEBUG_KMS("Couldn't release load detect pipe.\n");
10402         drm_atomic_state_free(state);
10403 }
10404
10405 static int i9xx_pll_refclk(struct drm_device *dev,
10406                            const struct intel_crtc_state *pipe_config)
10407 {
10408         struct drm_i915_private *dev_priv = dev->dev_private;
10409         u32 dpll = pipe_config->dpll_hw_state.dpll;
10410
10411         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10412                 return dev_priv->vbt.lvds_ssc_freq;
10413         else if (HAS_PCH_SPLIT(dev))
10414                 return 120000;
10415         else if (!IS_GEN2(dev))
10416                 return 96000;
10417         else
10418                 return 48000;
10419 }
10420
10421 /* Returns the clock of the currently programmed mode of the given pipe. */
10422 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
10423                                 struct intel_crtc_state *pipe_config)
10424 {
10425         struct drm_device *dev = crtc->base.dev;
10426         struct drm_i915_private *dev_priv = dev->dev_private;
10427         int pipe = pipe_config->cpu_transcoder;
10428         u32 dpll = pipe_config->dpll_hw_state.dpll;
10429         u32 fp;
10430         intel_clock_t clock;
10431         int port_clock;
10432         int refclk = i9xx_pll_refclk(dev, pipe_config);
10433
10434         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10435                 fp = pipe_config->dpll_hw_state.fp0;
10436         else
10437                 fp = pipe_config->dpll_hw_state.fp1;
10438
10439         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10440         if (IS_PINEVIEW(dev)) {
10441                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10442                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10443         } else {
10444                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10445                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10446         }
10447
10448         if (!IS_GEN2(dev)) {
10449                 if (IS_PINEVIEW(dev))
10450                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10451                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10452                 else
10453                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10454                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10455
10456                 switch (dpll & DPLL_MODE_MASK) {
10457                 case DPLLB_MODE_DAC_SERIAL:
10458                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10459                                 5 : 10;
10460                         break;
10461                 case DPLLB_MODE_LVDS:
10462                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10463                                 7 : 14;
10464                         break;
10465                 default:
10466                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10467                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10468                         return;
10469                 }
10470
10471                 if (IS_PINEVIEW(dev))
10472                         port_clock = pnv_calc_dpll_params(refclk, &clock);
10473                 else
10474                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
10475         } else {
10476                 u32 lvds = IS_I830(dev) ? 0 : I915_READ(LVDS);
10477                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10478
10479                 if (is_lvds) {
10480                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10481                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10482
10483                         if (lvds & LVDS_CLKB_POWER_UP)
10484                                 clock.p2 = 7;
10485                         else
10486                                 clock.p2 = 14;
10487                 } else {
10488                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10489                                 clock.p1 = 2;
10490                         else {
10491                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10492                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10493                         }
10494                         if (dpll & PLL_P2_DIVIDE_BY_4)
10495                                 clock.p2 = 4;
10496                         else
10497                                 clock.p2 = 2;
10498                 }
10499
10500                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10501         }
10502
10503         /*
10504          * This value includes pixel_multiplier. We will use
10505          * port_clock to compute adjusted_mode.crtc_clock in the
10506          * encoder's get_config() function.
10507          */
10508         pipe_config->port_clock = port_clock;
10509 }
10510
10511 int intel_dotclock_calculate(int link_freq,
10512                              const struct intel_link_m_n *m_n)
10513 {
10514         /*
10515          * The calculation for the data clock is:
10516          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10517          * But we want to avoid losing precison if possible, so:
10518          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10519          *
10520          * and the link clock is simpler:
10521          * link_clock = (m * link_clock) / n
10522          */
10523
10524         if (!m_n->link_n)
10525                 return 0;
10526
10527         return div_u64((u64)m_n->link_m * link_freq, m_n->link_n);
10528 }
10529
10530 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10531                                    struct intel_crtc_state *pipe_config)
10532 {
10533         struct drm_device *dev = crtc->base.dev;
10534
10535         /* read out port_clock from the DPLL */
10536         i9xx_crtc_clock_get(crtc, pipe_config);
10537
10538         /*
10539          * This value does not include pixel_multiplier.
10540          * We will check that port_clock and adjusted_mode.crtc_clock
10541          * agree once we know their relationship in the encoder's
10542          * get_config() function.
10543          */
10544         pipe_config->base.adjusted_mode.crtc_clock =
10545                 intel_dotclock_calculate(intel_fdi_link_freq(dev) * 10000,
10546                                          &pipe_config->fdi_m_n);
10547 }
10548
10549 /** Returns the currently programmed mode of the given pipe. */
10550 struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
10551                                              struct drm_crtc *crtc)
10552 {
10553         struct drm_i915_private *dev_priv = dev->dev_private;
10554         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10555         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
10556         struct drm_display_mode *mode;
10557         struct intel_crtc_state pipe_config;
10558         int htot = I915_READ(HTOTAL(cpu_transcoder));
10559         int hsync = I915_READ(HSYNC(cpu_transcoder));
10560         int vtot = I915_READ(VTOTAL(cpu_transcoder));
10561         int vsync = I915_READ(VSYNC(cpu_transcoder));
10562         enum pipe pipe = intel_crtc->pipe;
10563
10564         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10565         if (!mode)
10566                 return NULL;
10567
10568         /*
10569          * Construct a pipe_config sufficient for getting the clock info
10570          * back out of crtc_clock_get.
10571          *
10572          * Note, if LVDS ever uses a non-1 pixel multiplier, we'll need
10573          * to use a real value here instead.
10574          */
10575         pipe_config.cpu_transcoder = (enum transcoder) pipe;
10576         pipe_config.pixel_multiplier = 1;
10577         pipe_config.dpll_hw_state.dpll = I915_READ(DPLL(pipe));
10578         pipe_config.dpll_hw_state.fp0 = I915_READ(FP0(pipe));
10579         pipe_config.dpll_hw_state.fp1 = I915_READ(FP1(pipe));
10580         i9xx_crtc_clock_get(intel_crtc, &pipe_config);
10581
10582         mode->clock = pipe_config.port_clock / pipe_config.pixel_multiplier;
10583         mode->hdisplay = (htot & 0xffff) + 1;
10584         mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
10585         mode->hsync_start = (hsync & 0xffff) + 1;
10586         mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
10587         mode->vdisplay = (vtot & 0xffff) + 1;
10588         mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
10589         mode->vsync_start = (vsync & 0xffff) + 1;
10590         mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
10591
10592         drm_mode_set_name(mode);
10593
10594         return mode;
10595 }
10596
10597 void intel_mark_busy(struct drm_device *dev)
10598 {
10599         struct drm_i915_private *dev_priv = dev->dev_private;
10600
10601         if (dev_priv->mm.busy)
10602                 return;
10603
10604         intel_runtime_pm_get(dev_priv);
10605         i915_update_gfx_val(dev_priv);
10606         if (INTEL_INFO(dev)->gen >= 6)
10607                 gen6_rps_busy(dev_priv);
10608         dev_priv->mm.busy = true;
10609 }
10610
10611 void intel_mark_idle(struct drm_device *dev)
10612 {
10613         struct drm_i915_private *dev_priv = dev->dev_private;
10614
10615         if (!dev_priv->mm.busy)
10616                 return;
10617
10618         dev_priv->mm.busy = false;
10619
10620         if (INTEL_INFO(dev)->gen >= 6)
10621                 gen6_rps_idle(dev->dev_private);
10622
10623         intel_runtime_pm_put(dev_priv);
10624 }
10625
10626 static void intel_crtc_destroy(struct drm_crtc *crtc)
10627 {
10628         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10629         struct drm_device *dev = crtc->dev;
10630         struct intel_unpin_work *work;
10631
10632         spin_lock_irq(&dev->event_lock);
10633         work = intel_crtc->unpin_work;
10634         intel_crtc->unpin_work = NULL;
10635         spin_unlock_irq(&dev->event_lock);
10636
10637         if (work) {
10638                 cancel_work_sync(&work->work);
10639                 kfree(work);
10640         }
10641
10642         drm_crtc_cleanup(crtc);
10643
10644         kfree(intel_crtc);
10645 }
10646
10647 static void intel_unpin_work_fn(struct work_struct *__work)
10648 {
10649         struct intel_unpin_work *work =
10650                 container_of(__work, struct intel_unpin_work, work);
10651         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
10652         struct drm_device *dev = crtc->base.dev;
10653         struct drm_plane *primary = crtc->base.primary;
10654
10655         mutex_lock(&dev->struct_mutex);
10656         intel_unpin_fb_obj(work->old_fb, primary->state);
10657         drm_gem_object_unreference(&work->pending_flip_obj->base);
10658
10659         if (work->flip_queued_req)
10660                 i915_gem_request_assign(&work->flip_queued_req, NULL);
10661         mutex_unlock(&dev->struct_mutex);
10662
10663         intel_frontbuffer_flip_complete(dev, to_intel_plane(primary)->frontbuffer_bit);
10664         drm_framebuffer_unreference(work->old_fb);
10665
10666         BUG_ON(atomic_read(&crtc->unpin_work_count) == 0);
10667         atomic_dec(&crtc->unpin_work_count);
10668
10669         kfree(work);
10670 }
10671
10672 static void do_intel_finish_page_flip(struct drm_device *dev,
10673                                       struct drm_crtc *crtc)
10674 {
10675         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10676         struct intel_unpin_work *work;
10677         unsigned long flags;
10678
10679         /* Ignore early vblank irqs */
10680         if (intel_crtc == NULL)
10681                 return;
10682
10683         /*
10684          * This is called both by irq handlers and the reset code (to complete
10685          * lost pageflips) so needs the full irqsave spinlocks.
10686          */
10687         spin_lock_irqsave(&dev->event_lock, flags);
10688         work = intel_crtc->unpin_work;
10689
10690         /* Ensure we don't miss a work->pending update ... */
10691         smp_rmb();
10692
10693         if (work == NULL || atomic_read(&work->pending) < INTEL_FLIP_COMPLETE) {
10694                 spin_unlock_irqrestore(&dev->event_lock, flags);
10695                 return;
10696         }
10697
10698         page_flip_completed(intel_crtc);
10699
10700         spin_unlock_irqrestore(&dev->event_lock, flags);
10701 }
10702
10703 void intel_finish_page_flip(struct drm_device *dev, int pipe)
10704 {
10705         struct drm_i915_private *dev_priv = dev->dev_private;
10706         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
10707
10708         do_intel_finish_page_flip(dev, crtc);
10709 }
10710
10711 void intel_finish_page_flip_plane(struct drm_device *dev, int plane)
10712 {
10713         struct drm_i915_private *dev_priv = dev->dev_private;
10714         struct drm_crtc *crtc = dev_priv->plane_to_crtc_mapping[plane];
10715
10716         do_intel_finish_page_flip(dev, crtc);
10717 }
10718
10719 /* Is 'a' after or equal to 'b'? */
10720 static bool g4x_flip_count_after_eq(u32 a, u32 b)
10721 {
10722         return !((a - b) & 0x80000000);
10723 }
10724
10725 static bool page_flip_finished(struct intel_crtc *crtc)
10726 {
10727         struct drm_device *dev = crtc->base.dev;
10728         struct drm_i915_private *dev_priv = dev->dev_private;
10729
10730         if (i915_reset_in_progress(&dev_priv->gpu_error) ||
10731             crtc->reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
10732                 return true;
10733
10734         /*
10735          * The relevant registers doen't exist on pre-ctg.
10736          * As the flip done interrupt doesn't trigger for mmio
10737          * flips on gmch platforms, a flip count check isn't
10738          * really needed there. But since ctg has the registers,
10739          * include it in the check anyway.
10740          */
10741         if (INTEL_INFO(dev)->gen < 5 && !IS_G4X(dev))
10742                 return true;
10743
10744         /*
10745          * A DSPSURFLIVE check isn't enough in case the mmio and CS flips
10746          * used the same base address. In that case the mmio flip might
10747          * have completed, but the CS hasn't even executed the flip yet.
10748          *
10749          * A flip count check isn't enough as the CS might have updated
10750          * the base address just after start of vblank, but before we
10751          * managed to process the interrupt. This means we'd complete the
10752          * CS flip too soon.
10753          *
10754          * Combining both checks should get us a good enough result. It may
10755          * still happen that the CS flip has been executed, but has not
10756          * yet actually completed. But in case the base address is the same
10757          * anyway, we don't really care.
10758          */
10759         return (I915_READ(DSPSURFLIVE(crtc->plane)) & ~0xfff) ==
10760                 crtc->unpin_work->gtt_offset &&
10761                 g4x_flip_count_after_eq(I915_READ(PIPE_FLIPCOUNT_GM45(crtc->pipe)),
10762                                     crtc->unpin_work->flip_count);
10763 }
10764
10765 void intel_prepare_page_flip(struct drm_device *dev, int plane)
10766 {
10767         struct drm_i915_private *dev_priv = dev->dev_private;
10768         struct intel_crtc *intel_crtc =
10769                 to_intel_crtc(dev_priv->plane_to_crtc_mapping[plane]);
10770         unsigned long flags;
10771
10772
10773         /*
10774          * This is called both by irq handlers and the reset code (to complete
10775          * lost pageflips) so needs the full irqsave spinlocks.
10776          *
10777          * NB: An MMIO update of the plane base pointer will also
10778          * generate a page-flip completion irq, i.e. every modeset
10779          * is also accompanied by a spurious intel_prepare_page_flip().
10780          */
10781         spin_lock_irqsave(&dev->event_lock, flags);
10782         if (intel_crtc->unpin_work && page_flip_finished(intel_crtc))
10783                 atomic_inc_not_zero(&intel_crtc->unpin_work->pending);
10784         spin_unlock_irqrestore(&dev->event_lock, flags);
10785 }
10786
10787 static inline void intel_mark_page_flip_active(struct intel_crtc *intel_crtc)
10788 {
10789         /* Ensure that the work item is consistent when activating it ... */
10790         smp_wmb();
10791         atomic_set(&intel_crtc->unpin_work->pending, INTEL_FLIP_PENDING);
10792         /* and that it is marked active as soon as the irq could fire. */
10793         smp_wmb();
10794 }
10795
10796 static int intel_gen2_queue_flip(struct drm_device *dev,
10797                                  struct drm_crtc *crtc,
10798                                  struct drm_framebuffer *fb,
10799                                  struct drm_i915_gem_object *obj,
10800                                  struct drm_i915_gem_request *req,
10801                                  uint32_t flags)
10802 {
10803         struct intel_engine_cs *ring = req->ring;
10804         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10805         u32 flip_mask;
10806         int ret;
10807
10808         ret = intel_ring_begin(req, 6);
10809         if (ret)
10810                 return ret;
10811
10812         /* Can't queue multiple flips, so wait for the previous
10813          * one to finish before executing the next.
10814          */
10815         if (intel_crtc->plane)
10816                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
10817         else
10818                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
10819         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
10820         intel_ring_emit(ring, MI_NOOP);
10821         intel_ring_emit(ring, MI_DISPLAY_FLIP |
10822                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
10823         intel_ring_emit(ring, fb->pitches[0]);
10824         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
10825         intel_ring_emit(ring, 0); /* aux display base address, unused */
10826
10827         intel_mark_page_flip_active(intel_crtc);
10828         return 0;
10829 }
10830
10831 static int intel_gen3_queue_flip(struct drm_device *dev,
10832                                  struct drm_crtc *crtc,
10833                                  struct drm_framebuffer *fb,
10834                                  struct drm_i915_gem_object *obj,
10835                                  struct drm_i915_gem_request *req,
10836                                  uint32_t flags)
10837 {
10838         struct intel_engine_cs *ring = req->ring;
10839         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10840         u32 flip_mask;
10841         int ret;
10842
10843         ret = intel_ring_begin(req, 6);
10844         if (ret)
10845                 return ret;
10846
10847         if (intel_crtc->plane)
10848                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
10849         else
10850                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
10851         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
10852         intel_ring_emit(ring, MI_NOOP);
10853         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 |
10854                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
10855         intel_ring_emit(ring, fb->pitches[0]);
10856         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
10857         intel_ring_emit(ring, MI_NOOP);
10858
10859         intel_mark_page_flip_active(intel_crtc);
10860         return 0;
10861 }
10862
10863 static int intel_gen4_queue_flip(struct drm_device *dev,
10864                                  struct drm_crtc *crtc,
10865                                  struct drm_framebuffer *fb,
10866                                  struct drm_i915_gem_object *obj,
10867                                  struct drm_i915_gem_request *req,
10868                                  uint32_t flags)
10869 {
10870         struct intel_engine_cs *ring = req->ring;
10871         struct drm_i915_private *dev_priv = dev->dev_private;
10872         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10873         uint32_t pf, pipesrc;
10874         int ret;
10875
10876         ret = intel_ring_begin(req, 4);
10877         if (ret)
10878                 return ret;
10879
10880         /* i965+ uses the linear or tiled offsets from the
10881          * Display Registers (which do not change across a page-flip)
10882          * so we need only reprogram the base address.
10883          */
10884         intel_ring_emit(ring, MI_DISPLAY_FLIP |
10885                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
10886         intel_ring_emit(ring, fb->pitches[0]);
10887         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset |
10888                         obj->tiling_mode);
10889
10890         /* XXX Enabling the panel-fitter across page-flip is so far
10891          * untested on non-native modes, so ignore it for now.
10892          * pf = I915_READ(pipe == 0 ? PFA_CTL_1 : PFB_CTL_1) & PF_ENABLE;
10893          */
10894         pf = 0;
10895         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
10896         intel_ring_emit(ring, pf | pipesrc);
10897
10898         intel_mark_page_flip_active(intel_crtc);
10899         return 0;
10900 }
10901
10902 static int intel_gen6_queue_flip(struct drm_device *dev,
10903                                  struct drm_crtc *crtc,
10904                                  struct drm_framebuffer *fb,
10905                                  struct drm_i915_gem_object *obj,
10906                                  struct drm_i915_gem_request *req,
10907                                  uint32_t flags)
10908 {
10909         struct intel_engine_cs *ring = req->ring;
10910         struct drm_i915_private *dev_priv = dev->dev_private;
10911         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10912         uint32_t pf, pipesrc;
10913         int ret;
10914
10915         ret = intel_ring_begin(req, 4);
10916         if (ret)
10917                 return ret;
10918
10919         intel_ring_emit(ring, MI_DISPLAY_FLIP |
10920                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
10921         intel_ring_emit(ring, fb->pitches[0] | obj->tiling_mode);
10922         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
10923
10924         /* Contrary to the suggestions in the documentation,
10925          * "Enable Panel Fitter" does not seem to be required when page
10926          * flipping with a non-native mode, and worse causes a normal
10927          * modeset to fail.
10928          * pf = I915_READ(PF_CTL(intel_crtc->pipe)) & PF_ENABLE;
10929          */
10930         pf = 0;
10931         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
10932         intel_ring_emit(ring, pf | pipesrc);
10933
10934         intel_mark_page_flip_active(intel_crtc);
10935         return 0;
10936 }
10937
10938 static int intel_gen7_queue_flip(struct drm_device *dev,
10939                                  struct drm_crtc *crtc,
10940                                  struct drm_framebuffer *fb,
10941                                  struct drm_i915_gem_object *obj,
10942                                  struct drm_i915_gem_request *req,
10943                                  uint32_t flags)
10944 {
10945         struct intel_engine_cs *ring = req->ring;
10946         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10947         uint32_t plane_bit = 0;
10948         int len, ret;
10949
10950         switch (intel_crtc->plane) {
10951         case PLANE_A:
10952                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_A;
10953                 break;
10954         case PLANE_B:
10955                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_B;
10956                 break;
10957         case PLANE_C:
10958                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_C;
10959                 break;
10960         default:
10961                 WARN_ONCE(1, "unknown plane in flip command\n");
10962                 return -ENODEV;
10963         }
10964
10965         len = 4;
10966         if (ring->id == RCS) {
10967                 len += 6;
10968                 /*
10969                  * On Gen 8, SRM is now taking an extra dword to accommodate
10970                  * 48bits addresses, and we need a NOOP for the batch size to
10971                  * stay even.
10972                  */
10973                 if (IS_GEN8(dev))
10974                         len += 2;
10975         }
10976
10977         /*
10978          * BSpec MI_DISPLAY_FLIP for IVB:
10979          * "The full packet must be contained within the same cache line."
10980          *
10981          * Currently the LRI+SRM+MI_DISPLAY_FLIP all fit within the same
10982          * cacheline, if we ever start emitting more commands before
10983          * the MI_DISPLAY_FLIP we may need to first emit everything else,
10984          * then do the cacheline alignment, and finally emit the
10985          * MI_DISPLAY_FLIP.
10986          */
10987         ret = intel_ring_cacheline_align(req);
10988         if (ret)
10989                 return ret;
10990
10991         ret = intel_ring_begin(req, len);
10992         if (ret)
10993                 return ret;
10994
10995         /* Unmask the flip-done completion message. Note that the bspec says that
10996          * we should do this for both the BCS and RCS, and that we must not unmask
10997          * more than one flip event at any time (or ensure that one flip message
10998          * can be sent by waiting for flip-done prior to queueing new flips).
10999          * Experimentation says that BCS works despite DERRMR masking all
11000          * flip-done completion events and that unmasking all planes at once
11001          * for the RCS also doesn't appear to drop events. Setting the DERRMR
11002          * to zero does lead to lockups within MI_DISPLAY_FLIP.
11003          */
11004         if (ring->id == RCS) {
11005                 intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
11006                 intel_ring_emit(ring, DERRMR);
11007                 intel_ring_emit(ring, ~(DERRMR_PIPEA_PRI_FLIP_DONE |
11008                                         DERRMR_PIPEB_PRI_FLIP_DONE |
11009                                         DERRMR_PIPEC_PRI_FLIP_DONE));
11010                 if (IS_GEN8(dev))
11011                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM_GEN8 |
11012                                               MI_SRM_LRM_GLOBAL_GTT);
11013                 else
11014                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM |
11015                                               MI_SRM_LRM_GLOBAL_GTT);
11016                 intel_ring_emit(ring, DERRMR);
11017                 intel_ring_emit(ring, ring->scratch.gtt_offset + 256);
11018                 if (IS_GEN8(dev)) {
11019                         intel_ring_emit(ring, 0);
11020                         intel_ring_emit(ring, MI_NOOP);
11021                 }
11022         }
11023
11024         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 | plane_bit);
11025         intel_ring_emit(ring, (fb->pitches[0] | obj->tiling_mode));
11026         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
11027         intel_ring_emit(ring, (MI_NOOP));
11028
11029         intel_mark_page_flip_active(intel_crtc);
11030         return 0;
11031 }
11032
11033 static bool use_mmio_flip(struct intel_engine_cs *ring,
11034                           struct drm_i915_gem_object *obj)
11035 {
11036         /*
11037          * This is not being used for older platforms, because
11038          * non-availability of flip done interrupt forces us to use
11039          * CS flips. Older platforms derive flip done using some clever
11040          * tricks involving the flip_pending status bits and vblank irqs.
11041          * So using MMIO flips there would disrupt this mechanism.
11042          */
11043
11044         if (ring == NULL)
11045                 return true;
11046
11047         if (INTEL_INFO(ring->dev)->gen < 5)
11048                 return false;
11049
11050         if (i915.use_mmio_flip < 0)
11051                 return false;
11052         else if (i915.use_mmio_flip > 0)
11053                 return true;
11054         else if (i915.enable_execlists)
11055                 return true;
11056         else
11057                 return ring != i915_gem_request_get_ring(obj->last_write_req);
11058 }
11059
11060 static void skl_do_mmio_flip(struct intel_crtc *intel_crtc)
11061 {
11062         struct drm_device *dev = intel_crtc->base.dev;
11063         struct drm_i915_private *dev_priv = dev->dev_private;
11064         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
11065         const enum pipe pipe = intel_crtc->pipe;
11066         u32 ctl, stride;
11067
11068         ctl = I915_READ(PLANE_CTL(pipe, 0));
11069         ctl &= ~PLANE_CTL_TILED_MASK;
11070         switch (fb->modifier[0]) {
11071         case DRM_FORMAT_MOD_NONE:
11072                 break;
11073         case I915_FORMAT_MOD_X_TILED:
11074                 ctl |= PLANE_CTL_TILED_X;
11075                 break;
11076         case I915_FORMAT_MOD_Y_TILED:
11077                 ctl |= PLANE_CTL_TILED_Y;
11078                 break;
11079         case I915_FORMAT_MOD_Yf_TILED:
11080                 ctl |= PLANE_CTL_TILED_YF;
11081                 break;
11082         default:
11083                 MISSING_CASE(fb->modifier[0]);
11084         }
11085
11086         /*
11087          * The stride is either expressed as a multiple of 64 bytes chunks for
11088          * linear buffers or in number of tiles for tiled buffers.
11089          */
11090         stride = fb->pitches[0] /
11091                  intel_fb_stride_alignment(dev, fb->modifier[0],
11092                                            fb->pixel_format);
11093
11094         /*
11095          * Both PLANE_CTL and PLANE_STRIDE are not updated on vblank but on
11096          * PLANE_SURF updates, the update is then guaranteed to be atomic.
11097          */
11098         I915_WRITE(PLANE_CTL(pipe, 0), ctl);
11099         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
11100
11101         I915_WRITE(PLANE_SURF(pipe, 0), intel_crtc->unpin_work->gtt_offset);
11102         POSTING_READ(PLANE_SURF(pipe, 0));
11103 }
11104
11105 static void ilk_do_mmio_flip(struct intel_crtc *intel_crtc)
11106 {
11107         struct drm_device *dev = intel_crtc->base.dev;
11108         struct drm_i915_private *dev_priv = dev->dev_private;
11109         struct intel_framebuffer *intel_fb =
11110                 to_intel_framebuffer(intel_crtc->base.primary->fb);
11111         struct drm_i915_gem_object *obj = intel_fb->obj;
11112         u32 dspcntr;
11113         u32 reg;
11114
11115         reg = DSPCNTR(intel_crtc->plane);
11116         dspcntr = I915_READ(reg);
11117
11118         if (obj->tiling_mode != I915_TILING_NONE)
11119                 dspcntr |= DISPPLANE_TILED;
11120         else
11121                 dspcntr &= ~DISPPLANE_TILED;
11122
11123         I915_WRITE(reg, dspcntr);
11124
11125         I915_WRITE(DSPSURF(intel_crtc->plane),
11126                    intel_crtc->unpin_work->gtt_offset);
11127         POSTING_READ(DSPSURF(intel_crtc->plane));
11128
11129 }
11130
11131 /*
11132  * XXX: This is the temporary way to update the plane registers until we get
11133  * around to using the usual plane update functions for MMIO flips
11134  */
11135 static void intel_do_mmio_flip(struct intel_crtc *intel_crtc)
11136 {
11137         struct drm_device *dev = intel_crtc->base.dev;
11138
11139         intel_mark_page_flip_active(intel_crtc);
11140
11141         intel_pipe_update_start(intel_crtc);
11142
11143         if (INTEL_INFO(dev)->gen >= 9)
11144                 skl_do_mmio_flip(intel_crtc);
11145         else
11146                 /* use_mmio_flip() retricts MMIO flips to ilk+ */
11147                 ilk_do_mmio_flip(intel_crtc);
11148
11149         intel_pipe_update_end(intel_crtc);
11150 }
11151
11152 static void intel_mmio_flip_work_func(struct work_struct *work)
11153 {
11154         struct intel_mmio_flip *mmio_flip =
11155                 container_of(work, struct intel_mmio_flip, work);
11156
11157         if (mmio_flip->req)
11158                 WARN_ON(__i915_wait_request(mmio_flip->req,
11159                                             mmio_flip->crtc->reset_counter,
11160                                             false, NULL,
11161                                             &mmio_flip->i915->rps.mmioflips));
11162
11163         intel_do_mmio_flip(mmio_flip->crtc);
11164
11165         i915_gem_request_unreference__unlocked(mmio_flip->req);
11166         kfree(mmio_flip);
11167 }
11168
11169 static int intel_queue_mmio_flip(struct drm_device *dev,
11170                                  struct drm_crtc *crtc,
11171                                  struct drm_framebuffer *fb,
11172                                  struct drm_i915_gem_object *obj,
11173                                  struct intel_engine_cs *ring,
11174                                  uint32_t flags)
11175 {
11176         struct intel_mmio_flip *mmio_flip;
11177
11178         mmio_flip = kmalloc(sizeof(*mmio_flip), GFP_KERNEL);
11179         if (mmio_flip == NULL)
11180                 return -ENOMEM;
11181
11182         mmio_flip->i915 = to_i915(dev);
11183         mmio_flip->req = i915_gem_request_reference(obj->last_write_req);
11184         mmio_flip->crtc = to_intel_crtc(crtc);
11185
11186         INIT_WORK(&mmio_flip->work, intel_mmio_flip_work_func);
11187         schedule_work(&mmio_flip->work);
11188
11189         return 0;
11190 }
11191
11192 static int intel_default_queue_flip(struct drm_device *dev,
11193                                     struct drm_crtc *crtc,
11194                                     struct drm_framebuffer *fb,
11195                                     struct drm_i915_gem_object *obj,
11196                                     struct drm_i915_gem_request *req,
11197                                     uint32_t flags)
11198 {
11199         return -ENODEV;
11200 }
11201
11202 static bool __intel_pageflip_stall_check(struct drm_device *dev,
11203                                          struct drm_crtc *crtc)
11204 {
11205         struct drm_i915_private *dev_priv = dev->dev_private;
11206         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11207         struct intel_unpin_work *work = intel_crtc->unpin_work;
11208         u32 addr;
11209
11210         if (atomic_read(&work->pending) >= INTEL_FLIP_COMPLETE)
11211                 return true;
11212
11213         if (atomic_read(&work->pending) < INTEL_FLIP_PENDING)
11214                 return false;
11215
11216         if (!work->enable_stall_check)
11217                 return false;
11218
11219         if (work->flip_ready_vblank == 0) {
11220                 if (work->flip_queued_req &&
11221                     !i915_gem_request_completed(work->flip_queued_req, true))
11222                         return false;
11223
11224                 work->flip_ready_vblank = drm_crtc_vblank_count(crtc);
11225         }
11226
11227         if (drm_crtc_vblank_count(crtc) - work->flip_ready_vblank < 3)
11228                 return false;
11229
11230         /* Potential stall - if we see that the flip has happened,
11231          * assume a missed interrupt. */
11232         if (INTEL_INFO(dev)->gen >= 4)
11233                 addr = I915_HI_DISPBASE(I915_READ(DSPSURF(intel_crtc->plane)));
11234         else
11235                 addr = I915_READ(DSPADDR(intel_crtc->plane));
11236
11237         /* There is a potential issue here with a false positive after a flip
11238          * to the same address. We could address this by checking for a
11239          * non-incrementing frame counter.
11240          */
11241         return addr == work->gtt_offset;
11242 }
11243
11244 void intel_check_page_flip(struct drm_device *dev, int pipe)
11245 {
11246         struct drm_i915_private *dev_priv = dev->dev_private;
11247         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11248         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11249         struct intel_unpin_work *work;
11250
11251         WARN_ON(!in_interrupt());
11252
11253         if (crtc == NULL)
11254                 return;
11255
11256         spin_lock(&dev->event_lock);
11257         work = intel_crtc->unpin_work;
11258         if (work != NULL && __intel_pageflip_stall_check(dev, crtc)) {
11259                 WARN_ONCE(1, "Kicking stuck page flip: queued at %d, now %d\n",
11260                          work->flip_queued_vblank, drm_vblank_count(dev, pipe));
11261                 page_flip_completed(intel_crtc);
11262                 work = NULL;
11263         }
11264         if (work != NULL &&
11265             drm_vblank_count(dev, pipe) - work->flip_queued_vblank > 1)
11266                 intel_queue_rps_boost_for_request(dev, work->flip_queued_req);
11267         spin_unlock(&dev->event_lock);
11268 }
11269
11270 static int intel_crtc_page_flip(struct drm_crtc *crtc,
11271                                 struct drm_framebuffer *fb,
11272                                 struct drm_pending_vblank_event *event,
11273                                 uint32_t page_flip_flags)
11274 {
11275         struct drm_device *dev = crtc->dev;
11276         struct drm_i915_private *dev_priv = dev->dev_private;
11277         struct drm_framebuffer *old_fb = crtc->primary->fb;
11278         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
11279         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11280         struct drm_plane *primary = crtc->primary;
11281         enum pipe pipe = intel_crtc->pipe;
11282         struct intel_unpin_work *work;
11283         struct intel_engine_cs *ring;
11284         bool mmio_flip;
11285         struct drm_i915_gem_request *request = NULL;
11286         int ret;
11287
11288         /*
11289          * drm_mode_page_flip_ioctl() should already catch this, but double
11290          * check to be safe.  In the future we may enable pageflipping from
11291          * a disabled primary plane.
11292          */
11293         if (WARN_ON(intel_fb_obj(old_fb) == NULL))
11294                 return -EBUSY;
11295
11296         /* Can't change pixel format via MI display flips. */
11297         if (fb->pixel_format != crtc->primary->fb->pixel_format)
11298                 return -EINVAL;
11299
11300         /*
11301          * TILEOFF/LINOFF registers can't be changed via MI display flips.
11302          * Note that pitch changes could also affect these register.
11303          */
11304         if (INTEL_INFO(dev)->gen > 3 &&
11305             (fb->offsets[0] != crtc->primary->fb->offsets[0] ||
11306              fb->pitches[0] != crtc->primary->fb->pitches[0]))
11307                 return -EINVAL;
11308
11309         if (i915_terminally_wedged(&dev_priv->gpu_error))
11310                 goto out_hang;
11311
11312         work = kzalloc(sizeof(*work), GFP_KERNEL);
11313         if (work == NULL)
11314                 return -ENOMEM;
11315
11316         work->event = event;
11317         work->crtc = crtc;
11318         work->old_fb = old_fb;
11319         INIT_WORK(&work->work, intel_unpin_work_fn);
11320
11321         ret = drm_crtc_vblank_get(crtc);
11322         if (ret)
11323                 goto free_work;
11324
11325         /* We borrow the event spin lock for protecting unpin_work */
11326         spin_lock_irq(&dev->event_lock);
11327         if (intel_crtc->unpin_work) {
11328                 /* Before declaring the flip queue wedged, check if
11329                  * the hardware completed the operation behind our backs.
11330                  */
11331                 if (__intel_pageflip_stall_check(dev, crtc)) {
11332                         DRM_DEBUG_DRIVER("flip queue: previous flip completed, continuing\n");
11333                         page_flip_completed(intel_crtc);
11334                 } else {
11335                         DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
11336                         spin_unlock_irq(&dev->event_lock);
11337
11338                         drm_crtc_vblank_put(crtc);
11339                         kfree(work);
11340                         return -EBUSY;
11341                 }
11342         }
11343         intel_crtc->unpin_work = work;
11344         spin_unlock_irq(&dev->event_lock);
11345
11346         if (atomic_read(&intel_crtc->unpin_work_count) >= 2)
11347                 flush_workqueue(dev_priv->wq);
11348
11349         /* Reference the objects for the scheduled work. */
11350         drm_framebuffer_reference(work->old_fb);
11351         drm_gem_object_reference(&obj->base);
11352
11353         crtc->primary->fb = fb;
11354         update_state_fb(crtc->primary);
11355
11356         work->pending_flip_obj = obj;
11357
11358         ret = i915_mutex_lock_interruptible(dev);
11359         if (ret)
11360                 goto cleanup;
11361
11362         atomic_inc(&intel_crtc->unpin_work_count);
11363         intel_crtc->reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
11364
11365         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
11366                 work->flip_count = I915_READ(PIPE_FLIPCOUNT_GM45(pipe)) + 1;
11367
11368         if (IS_VALLEYVIEW(dev)) {
11369                 ring = &dev_priv->ring[BCS];
11370                 if (obj->tiling_mode != intel_fb_obj(work->old_fb)->tiling_mode)
11371                         /* vlv: DISPLAY_FLIP fails to change tiling */
11372                         ring = NULL;
11373         } else if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev)) {
11374                 ring = &dev_priv->ring[BCS];
11375         } else if (INTEL_INFO(dev)->gen >= 7) {
11376                 ring = i915_gem_request_get_ring(obj->last_write_req);
11377                 if (ring == NULL || ring->id != RCS)
11378                         ring = &dev_priv->ring[BCS];
11379         } else {
11380                 ring = &dev_priv->ring[RCS];
11381         }
11382
11383         mmio_flip = use_mmio_flip(ring, obj);
11384
11385         /* When using CS flips, we want to emit semaphores between rings.
11386          * However, when using mmio flips we will create a task to do the
11387          * synchronisation, so all we want here is to pin the framebuffer
11388          * into the display plane and skip any waits.
11389          */
11390         ret = intel_pin_and_fence_fb_obj(crtc->primary, fb,
11391                                          crtc->primary->state,
11392                                          mmio_flip ? i915_gem_request_get_ring(obj->last_write_req) : ring, &request);
11393         if (ret)
11394                 goto cleanup_pending;
11395
11396         work->gtt_offset = intel_plane_obj_offset(to_intel_plane(primary), obj)
11397                                                   + intel_crtc->dspaddr_offset;
11398
11399         if (mmio_flip) {
11400                 ret = intel_queue_mmio_flip(dev, crtc, fb, obj, ring,
11401                                             page_flip_flags);
11402                 if (ret)
11403                         goto cleanup_unpin;
11404
11405                 i915_gem_request_assign(&work->flip_queued_req,
11406                                         obj->last_write_req);
11407         } else {
11408                 if (!request) {
11409                         ret = i915_gem_request_alloc(ring, ring->default_context, &request);
11410                         if (ret)
11411                                 goto cleanup_unpin;
11412                 }
11413
11414                 ret = dev_priv->display.queue_flip(dev, crtc, fb, obj, request,
11415                                                    page_flip_flags);
11416                 if (ret)
11417                         goto cleanup_unpin;
11418
11419                 i915_gem_request_assign(&work->flip_queued_req, request);
11420         }
11421
11422         if (request)
11423                 i915_add_request_no_flush(request);
11424
11425         work->flip_queued_vblank = drm_crtc_vblank_count(crtc);
11426         work->enable_stall_check = true;
11427
11428         i915_gem_track_fb(intel_fb_obj(work->old_fb), obj,
11429                           to_intel_plane(primary)->frontbuffer_bit);
11430         mutex_unlock(&dev->struct_mutex);
11431
11432         intel_fbc_disable_crtc(intel_crtc);
11433         intel_frontbuffer_flip_prepare(dev,
11434                                        to_intel_plane(primary)->frontbuffer_bit);
11435
11436         trace_i915_flip_request(intel_crtc->plane, obj);
11437
11438         return 0;
11439
11440 cleanup_unpin:
11441         intel_unpin_fb_obj(fb, crtc->primary->state);
11442 cleanup_pending:
11443         if (request)
11444                 i915_gem_request_cancel(request);
11445         atomic_dec(&intel_crtc->unpin_work_count);
11446         mutex_unlock(&dev->struct_mutex);
11447 cleanup:
11448         crtc->primary->fb = old_fb;
11449         update_state_fb(crtc->primary);
11450
11451         drm_gem_object_unreference_unlocked(&obj->base);
11452         drm_framebuffer_unreference(work->old_fb);
11453
11454         spin_lock_irq(&dev->event_lock);
11455         intel_crtc->unpin_work = NULL;
11456         spin_unlock_irq(&dev->event_lock);
11457
11458         drm_crtc_vblank_put(crtc);
11459 free_work:
11460         kfree(work);
11461
11462         if (ret == -EIO) {
11463                 struct drm_atomic_state *state;
11464                 struct drm_plane_state *plane_state;
11465
11466 out_hang:
11467                 state = drm_atomic_state_alloc(dev);
11468                 if (!state)
11469                         return -ENOMEM;
11470                 state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
11471
11472 retry:
11473                 plane_state = drm_atomic_get_plane_state(state, primary);
11474                 ret = PTR_ERR_OR_ZERO(plane_state);
11475                 if (!ret) {
11476                         drm_atomic_set_fb_for_plane(plane_state, fb);
11477
11478                         ret = drm_atomic_set_crtc_for_plane(plane_state, crtc);
11479                         if (!ret)
11480                                 ret = drm_atomic_commit(state);
11481                 }
11482
11483                 if (ret == -EDEADLK) {
11484                         drm_modeset_backoff(state->acquire_ctx);
11485                         drm_atomic_state_clear(state);
11486                         goto retry;
11487                 }
11488
11489                 if (ret)
11490                         drm_atomic_state_free(state);
11491
11492                 if (ret == 0 && event) {
11493                         spin_lock_irq(&dev->event_lock);
11494                         drm_send_vblank_event(dev, pipe, event);
11495                         spin_unlock_irq(&dev->event_lock);
11496                 }
11497         }
11498         return ret;
11499 }
11500
11501
11502 /**
11503  * intel_wm_need_update - Check whether watermarks need updating
11504  * @plane: drm plane
11505  * @state: new plane state
11506  *
11507  * Check current plane state versus the new one to determine whether
11508  * watermarks need to be recalculated.
11509  *
11510  * Returns true or false.
11511  */
11512 static bool intel_wm_need_update(struct drm_plane *plane,
11513                                  struct drm_plane_state *state)
11514 {
11515         /* Update watermarks on tiling changes. */
11516         if (!plane->state->fb || !state->fb ||
11517             plane->state->fb->modifier[0] != state->fb->modifier[0] ||
11518             plane->state->rotation != state->rotation)
11519                 return true;
11520
11521         if (plane->state->crtc_w != state->crtc_w)
11522                 return true;
11523
11524         return false;
11525 }
11526
11527 int intel_plane_atomic_calc_changes(struct drm_crtc_state *crtc_state,
11528                                     struct drm_plane_state *plane_state)
11529 {
11530         struct drm_crtc *crtc = crtc_state->crtc;
11531         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11532         struct drm_plane *plane = plane_state->plane;
11533         struct drm_device *dev = crtc->dev;
11534         struct drm_i915_private *dev_priv = dev->dev_private;
11535         struct intel_plane_state *old_plane_state =
11536                 to_intel_plane_state(plane->state);
11537         int idx = intel_crtc->base.base.id, ret;
11538         int i = drm_plane_index(plane);
11539         bool mode_changed = needs_modeset(crtc_state);
11540         bool was_crtc_enabled = crtc->state->active;
11541         bool is_crtc_enabled = crtc_state->active;
11542
11543         bool turn_off, turn_on, visible, was_visible;
11544         struct drm_framebuffer *fb = plane_state->fb;
11545
11546         if (crtc_state && INTEL_INFO(dev)->gen >= 9 &&
11547             plane->type != DRM_PLANE_TYPE_CURSOR) {
11548                 ret = skl_update_scaler_plane(
11549                         to_intel_crtc_state(crtc_state),
11550                         to_intel_plane_state(plane_state));
11551                 if (ret)
11552                         return ret;
11553         }
11554
11555         /*
11556          * Disabling a plane is always okay; we just need to update
11557          * fb tracking in a special way since cleanup_fb() won't
11558          * get called by the plane helpers.
11559          */
11560         if (old_plane_state->base.fb && !fb)
11561                 intel_crtc->atomic.disabled_planes |= 1 << i;
11562
11563         was_visible = old_plane_state->visible;
11564         visible = to_intel_plane_state(plane_state)->visible;
11565
11566         if (!was_crtc_enabled && WARN_ON(was_visible))
11567                 was_visible = false;
11568
11569         if (!is_crtc_enabled && WARN_ON(visible))
11570                 visible = false;
11571
11572         if (!was_visible && !visible)
11573                 return 0;
11574
11575         turn_off = was_visible && (!visible || mode_changed);
11576         turn_on = visible && (!was_visible || mode_changed);
11577
11578         DRM_DEBUG_ATOMIC("[CRTC:%i] has [PLANE:%i] with fb %i\n", idx,
11579                          plane->base.id, fb ? fb->base.id : -1);
11580
11581         DRM_DEBUG_ATOMIC("[PLANE:%i] visible %i -> %i, off %i, on %i, ms %i\n",
11582                          plane->base.id, was_visible, visible,
11583                          turn_off, turn_on, mode_changed);
11584
11585         if (turn_on) {
11586                 intel_crtc->atomic.update_wm_pre = true;
11587                 /* must disable cxsr around plane enable/disable */
11588                 if (plane->type != DRM_PLANE_TYPE_CURSOR) {
11589                         intel_crtc->atomic.disable_cxsr = true;
11590                         /* to potentially re-enable cxsr */
11591                         intel_crtc->atomic.wait_vblank = true;
11592                         intel_crtc->atomic.update_wm_post = true;
11593                 }
11594         } else if (turn_off) {
11595                 intel_crtc->atomic.update_wm_post = true;
11596                 /* must disable cxsr around plane enable/disable */
11597                 if (plane->type != DRM_PLANE_TYPE_CURSOR) {
11598                         if (is_crtc_enabled)
11599                                 intel_crtc->atomic.wait_vblank = true;
11600                         intel_crtc->atomic.disable_cxsr = true;
11601                 }
11602         } else if (intel_wm_need_update(plane, plane_state)) {
11603                 intel_crtc->atomic.update_wm_pre = true;
11604         }
11605
11606         if (visible || was_visible)
11607                 intel_crtc->atomic.fb_bits |=
11608                         to_intel_plane(plane)->frontbuffer_bit;
11609
11610         switch (plane->type) {
11611         case DRM_PLANE_TYPE_PRIMARY:
11612                 intel_crtc->atomic.wait_for_flips = true;
11613                 intel_crtc->atomic.pre_disable_primary = turn_off;
11614                 intel_crtc->atomic.post_enable_primary = turn_on;
11615
11616                 if (turn_off) {
11617                         /*
11618                          * FIXME: Actually if we will still have any other
11619                          * plane enabled on the pipe we could let IPS enabled
11620                          * still, but for now lets consider that when we make
11621                          * primary invisible by setting DSPCNTR to 0 on
11622                          * update_primary_plane function IPS needs to be
11623                          * disable.
11624                          */
11625                         intel_crtc->atomic.disable_ips = true;
11626
11627                         intel_crtc->atomic.disable_fbc = true;
11628                 }
11629
11630                 /*
11631                  * FBC does not work on some platforms for rotated
11632                  * planes, so disable it when rotation is not 0 and
11633                  * update it when rotation is set back to 0.
11634                  *
11635                  * FIXME: This is redundant with the fbc update done in
11636                  * the primary plane enable function except that that
11637                  * one is done too late. We eventually need to unify
11638                  * this.
11639                  */
11640
11641                 if (visible &&
11642                     INTEL_INFO(dev)->gen <= 4 && !IS_G4X(dev) &&
11643                     dev_priv->fbc.crtc == intel_crtc &&
11644                     plane_state->rotation != BIT(DRM_ROTATE_0))
11645                         intel_crtc->atomic.disable_fbc = true;
11646
11647                 /*
11648                  * BDW signals flip done immediately if the plane
11649                  * is disabled, even if the plane enable is already
11650                  * armed to occur at the next vblank :(
11651                  */
11652                 if (turn_on && IS_BROADWELL(dev))
11653                         intel_crtc->atomic.wait_vblank = true;
11654
11655                 intel_crtc->atomic.update_fbc |= visible || mode_changed;
11656                 break;
11657         case DRM_PLANE_TYPE_CURSOR:
11658                 break;
11659         case DRM_PLANE_TYPE_OVERLAY:
11660                 if (turn_off && !mode_changed) {
11661                         intel_crtc->atomic.wait_vblank = true;
11662                         intel_crtc->atomic.update_sprite_watermarks |=
11663                                 1 << i;
11664                 }
11665         }
11666         return 0;
11667 }
11668
11669 static bool encoders_cloneable(const struct intel_encoder *a,
11670                                const struct intel_encoder *b)
11671 {
11672         /* masks could be asymmetric, so check both ways */
11673         return a == b || (a->cloneable & (1 << b->type) &&
11674                           b->cloneable & (1 << a->type));
11675 }
11676
11677 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
11678                                          struct intel_crtc *crtc,
11679                                          struct intel_encoder *encoder)
11680 {
11681         struct intel_encoder *source_encoder;
11682         struct drm_connector *connector;
11683         struct drm_connector_state *connector_state;
11684         int i;
11685
11686         for_each_connector_in_state(state, connector, connector_state, i) {
11687                 if (connector_state->crtc != &crtc->base)
11688                         continue;
11689
11690                 source_encoder =
11691                         to_intel_encoder(connector_state->best_encoder);
11692                 if (!encoders_cloneable(encoder, source_encoder))
11693                         return false;
11694         }
11695
11696         return true;
11697 }
11698
11699 static bool check_encoder_cloning(struct drm_atomic_state *state,
11700                                   struct intel_crtc *crtc)
11701 {
11702         struct intel_encoder *encoder;
11703         struct drm_connector *connector;
11704         struct drm_connector_state *connector_state;
11705         int i;
11706
11707         for_each_connector_in_state(state, connector, connector_state, i) {
11708                 if (connector_state->crtc != &crtc->base)
11709                         continue;
11710
11711                 encoder = to_intel_encoder(connector_state->best_encoder);
11712                 if (!check_single_encoder_cloning(state, crtc, encoder))
11713                         return false;
11714         }
11715
11716         return true;
11717 }
11718
11719 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
11720                                    struct drm_crtc_state *crtc_state)
11721 {
11722         struct drm_device *dev = crtc->dev;
11723         struct drm_i915_private *dev_priv = dev->dev_private;
11724         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11725         struct intel_crtc_state *pipe_config =
11726                 to_intel_crtc_state(crtc_state);
11727         struct drm_atomic_state *state = crtc_state->state;
11728         int ret;
11729         bool mode_changed = needs_modeset(crtc_state);
11730
11731         if (mode_changed && !check_encoder_cloning(state, intel_crtc)) {
11732                 DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
11733                 return -EINVAL;
11734         }
11735
11736         if (mode_changed && !crtc_state->active)
11737                 intel_crtc->atomic.update_wm_post = true;
11738
11739         if (mode_changed && crtc_state->enable &&
11740             dev_priv->display.crtc_compute_clock &&
11741             !WARN_ON(pipe_config->shared_dpll != DPLL_ID_PRIVATE)) {
11742                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
11743                                                            pipe_config);
11744                 if (ret)
11745                         return ret;
11746         }
11747
11748         ret = 0;
11749         if (INTEL_INFO(dev)->gen >= 9) {
11750                 if (mode_changed)
11751                         ret = skl_update_scaler_crtc(pipe_config);
11752
11753                 if (!ret)
11754                         ret = intel_atomic_setup_scalers(dev, intel_crtc,
11755                                                          pipe_config);
11756         }
11757
11758         return ret;
11759 }
11760
11761 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
11762         .mode_set_base_atomic = intel_pipe_set_base_atomic,
11763         .load_lut = intel_crtc_load_lut,
11764         .atomic_begin = intel_begin_crtc_commit,
11765         .atomic_flush = intel_finish_crtc_commit,
11766         .atomic_check = intel_crtc_atomic_check,
11767 };
11768
11769 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
11770 {
11771         struct intel_connector *connector;
11772
11773         for_each_intel_connector(dev, connector) {
11774                 if (connector->base.encoder) {
11775                         connector->base.state->best_encoder =
11776                                 connector->base.encoder;
11777                         connector->base.state->crtc =
11778                                 connector->base.encoder->crtc;
11779                 } else {
11780                         connector->base.state->best_encoder = NULL;
11781                         connector->base.state->crtc = NULL;
11782                 }
11783         }
11784 }
11785
11786 static void
11787 connected_sink_compute_bpp(struct intel_connector *connector,
11788                            struct intel_crtc_state *pipe_config)
11789 {
11790         int bpp = pipe_config->pipe_bpp;
11791
11792         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
11793                 connector->base.base.id,
11794                 connector->base.name);
11795
11796         /* Don't use an invalid EDID bpc value */
11797         if (connector->base.display_info.bpc &&
11798             connector->base.display_info.bpc * 3 < bpp) {
11799                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
11800                               bpp, connector->base.display_info.bpc*3);
11801                 pipe_config->pipe_bpp = connector->base.display_info.bpc*3;
11802         }
11803
11804         /* Clamp bpp to 8 on screens without EDID 1.4 */
11805         if (connector->base.display_info.bpc == 0 && bpp > 24) {
11806                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
11807                               bpp);
11808                 pipe_config->pipe_bpp = 24;
11809         }
11810 }
11811
11812 static int
11813 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
11814                           struct intel_crtc_state *pipe_config)
11815 {
11816         struct drm_device *dev = crtc->base.dev;
11817         struct drm_atomic_state *state;
11818         struct drm_connector *connector;
11819         struct drm_connector_state *connector_state;
11820         int bpp, i;
11821
11822         if ((IS_G4X(dev) || IS_VALLEYVIEW(dev)))
11823                 bpp = 10*3;
11824         else if (INTEL_INFO(dev)->gen >= 5)
11825                 bpp = 12*3;
11826         else
11827                 bpp = 8*3;
11828
11829
11830         pipe_config->pipe_bpp = bpp;
11831
11832         state = pipe_config->base.state;
11833
11834         /* Clamp display bpp to EDID value */
11835         for_each_connector_in_state(state, connector, connector_state, i) {
11836                 if (connector_state->crtc != &crtc->base)
11837                         continue;
11838
11839                 connected_sink_compute_bpp(to_intel_connector(connector),
11840                                            pipe_config);
11841         }
11842
11843         return bpp;
11844 }
11845
11846 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
11847 {
11848         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
11849                         "type: 0x%x flags: 0x%x\n",
11850                 mode->crtc_clock,
11851                 mode->crtc_hdisplay, mode->crtc_hsync_start,
11852                 mode->crtc_hsync_end, mode->crtc_htotal,
11853                 mode->crtc_vdisplay, mode->crtc_vsync_start,
11854                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
11855 }
11856
11857 static void intel_dump_pipe_config(struct intel_crtc *crtc,
11858                                    struct intel_crtc_state *pipe_config,
11859                                    const char *context)
11860 {
11861         struct drm_device *dev = crtc->base.dev;
11862         struct drm_plane *plane;
11863         struct intel_plane *intel_plane;
11864         struct intel_plane_state *state;
11865         struct drm_framebuffer *fb;
11866
11867         DRM_DEBUG_KMS("[CRTC:%d]%s config %p for pipe %c\n", crtc->base.base.id,
11868                       context, pipe_config, pipe_name(crtc->pipe));
11869
11870         DRM_DEBUG_KMS("cpu_transcoder: %c\n", transcoder_name(pipe_config->cpu_transcoder));
11871         DRM_DEBUG_KMS("pipe bpp: %i, dithering: %i\n",
11872                       pipe_config->pipe_bpp, pipe_config->dither);
11873         DRM_DEBUG_KMS("fdi/pch: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
11874                       pipe_config->has_pch_encoder,
11875                       pipe_config->fdi_lanes,
11876                       pipe_config->fdi_m_n.gmch_m, pipe_config->fdi_m_n.gmch_n,
11877                       pipe_config->fdi_m_n.link_m, pipe_config->fdi_m_n.link_n,
11878                       pipe_config->fdi_m_n.tu);
11879         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
11880                       pipe_config->has_dp_encoder,
11881                       pipe_config->lane_count,
11882                       pipe_config->dp_m_n.gmch_m, pipe_config->dp_m_n.gmch_n,
11883                       pipe_config->dp_m_n.link_m, pipe_config->dp_m_n.link_n,
11884                       pipe_config->dp_m_n.tu);
11885
11886         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m2: %u, gmch_n2: %u, link_m2: %u, link_n2: %u, tu2: %u\n",
11887                       pipe_config->has_dp_encoder,
11888                       pipe_config->lane_count,
11889                       pipe_config->dp_m2_n2.gmch_m,
11890                       pipe_config->dp_m2_n2.gmch_n,
11891                       pipe_config->dp_m2_n2.link_m,
11892                       pipe_config->dp_m2_n2.link_n,
11893                       pipe_config->dp_m2_n2.tu);
11894
11895         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
11896                       pipe_config->has_audio,
11897                       pipe_config->has_infoframe);
11898
11899         DRM_DEBUG_KMS("requested mode:\n");
11900         drm_mode_debug_printmodeline(&pipe_config->base.mode);
11901         DRM_DEBUG_KMS("adjusted mode:\n");
11902         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
11903         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
11904         DRM_DEBUG_KMS("port clock: %d\n", pipe_config->port_clock);
11905         DRM_DEBUG_KMS("pipe src size: %dx%d\n",
11906                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
11907         DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
11908                       crtc->num_scalers,
11909                       pipe_config->scaler_state.scaler_users,
11910                       pipe_config->scaler_state.scaler_id);
11911         DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
11912                       pipe_config->gmch_pfit.control,
11913                       pipe_config->gmch_pfit.pgm_ratios,
11914                       pipe_config->gmch_pfit.lvds_border_bits);
11915         DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
11916                       pipe_config->pch_pfit.pos,
11917                       pipe_config->pch_pfit.size,
11918                       pipe_config->pch_pfit.enabled ? "enabled" : "disabled");
11919         DRM_DEBUG_KMS("ips: %i\n", pipe_config->ips_enabled);
11920         DRM_DEBUG_KMS("double wide: %i\n", pipe_config->double_wide);
11921
11922         if (IS_BROXTON(dev)) {
11923                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: ebb0: 0x%x, ebb4: 0x%x,"
11924                               "pll0: 0x%x, pll1: 0x%x, pll2: 0x%x, pll3: 0x%x, "
11925                               "pll6: 0x%x, pll8: 0x%x, pll9: 0x%x, pll10: 0x%x, pcsdw12: 0x%x\n",
11926                               pipe_config->ddi_pll_sel,
11927                               pipe_config->dpll_hw_state.ebb0,
11928                               pipe_config->dpll_hw_state.ebb4,
11929                               pipe_config->dpll_hw_state.pll0,
11930                               pipe_config->dpll_hw_state.pll1,
11931                               pipe_config->dpll_hw_state.pll2,
11932                               pipe_config->dpll_hw_state.pll3,
11933                               pipe_config->dpll_hw_state.pll6,
11934                               pipe_config->dpll_hw_state.pll8,
11935                               pipe_config->dpll_hw_state.pll9,
11936                               pipe_config->dpll_hw_state.pll10,
11937                               pipe_config->dpll_hw_state.pcsdw12);
11938         } else if (IS_SKYLAKE(dev)) {
11939                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: "
11940                               "ctrl1: 0x%x, cfgcr1: 0x%x, cfgcr2: 0x%x\n",
11941                               pipe_config->ddi_pll_sel,
11942                               pipe_config->dpll_hw_state.ctrl1,
11943                               pipe_config->dpll_hw_state.cfgcr1,
11944                               pipe_config->dpll_hw_state.cfgcr2);
11945         } else if (HAS_DDI(dev)) {
11946                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: wrpll: 0x%x\n",
11947                               pipe_config->ddi_pll_sel,
11948                               pipe_config->dpll_hw_state.wrpll);
11949         } else {
11950                 DRM_DEBUG_KMS("dpll_hw_state: dpll: 0x%x, dpll_md: 0x%x, "
11951                               "fp0: 0x%x, fp1: 0x%x\n",
11952                               pipe_config->dpll_hw_state.dpll,
11953                               pipe_config->dpll_hw_state.dpll_md,
11954                               pipe_config->dpll_hw_state.fp0,
11955                               pipe_config->dpll_hw_state.fp1);
11956         }
11957
11958         DRM_DEBUG_KMS("planes on this crtc\n");
11959         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
11960                 intel_plane = to_intel_plane(plane);
11961                 if (intel_plane->pipe != crtc->pipe)
11962                         continue;
11963
11964                 state = to_intel_plane_state(plane->state);
11965                 fb = state->base.fb;
11966                 if (!fb) {
11967                         DRM_DEBUG_KMS("%s PLANE:%d plane: %u.%u idx: %d "
11968                                 "disabled, scaler_id = %d\n",
11969                                 plane->type == DRM_PLANE_TYPE_CURSOR ? "CURSOR" : "STANDARD",
11970                                 plane->base.id, intel_plane->pipe,
11971                                 (crtc->base.primary == plane) ? 0 : intel_plane->plane + 1,
11972                                 drm_plane_index(plane), state->scaler_id);
11973                         continue;
11974                 }
11975
11976                 DRM_DEBUG_KMS("%s PLANE:%d plane: %u.%u idx: %d enabled",
11977                         plane->type == DRM_PLANE_TYPE_CURSOR ? "CURSOR" : "STANDARD",
11978                         plane->base.id, intel_plane->pipe,
11979                         crtc->base.primary == plane ? 0 : intel_plane->plane + 1,
11980                         drm_plane_index(plane));
11981                 DRM_DEBUG_KMS("\tFB:%d, fb = %ux%u format = 0x%x",
11982                         fb->base.id, fb->width, fb->height, fb->pixel_format);
11983                 DRM_DEBUG_KMS("\tscaler:%d src (%u, %u) %ux%u dst (%u, %u) %ux%u\n",
11984                         state->scaler_id,
11985                         state->src.x1 >> 16, state->src.y1 >> 16,
11986                         drm_rect_width(&state->src) >> 16,
11987                         drm_rect_height(&state->src) >> 16,
11988                         state->dst.x1, state->dst.y1,
11989                         drm_rect_width(&state->dst), drm_rect_height(&state->dst));
11990         }
11991 }
11992
11993 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
11994 {
11995         struct drm_device *dev = state->dev;
11996         struct intel_encoder *encoder;
11997         struct drm_connector *connector;
11998         struct drm_connector_state *connector_state;
11999         unsigned int used_ports = 0;
12000         int i;
12001
12002         /*
12003          * Walk the connector list instead of the encoder
12004          * list to detect the problem on ddi platforms
12005          * where there's just one encoder per digital port.
12006          */
12007         for_each_connector_in_state(state, connector, connector_state, i) {
12008                 if (!connector_state->best_encoder)
12009                         continue;
12010
12011                 encoder = to_intel_encoder(connector_state->best_encoder);
12012
12013                 WARN_ON(!connector_state->crtc);
12014
12015                 switch (encoder->type) {
12016                         unsigned int port_mask;
12017                 case INTEL_OUTPUT_UNKNOWN:
12018                         if (WARN_ON(!HAS_DDI(dev)))
12019                                 break;
12020                 case INTEL_OUTPUT_DISPLAYPORT:
12021                 case INTEL_OUTPUT_HDMI:
12022                 case INTEL_OUTPUT_EDP:
12023                         port_mask = 1 << enc_to_dig_port(&encoder->base)->port;
12024
12025                         /* the same port mustn't appear more than once */
12026                         if (used_ports & port_mask)
12027                                 return false;
12028
12029                         used_ports |= port_mask;
12030                 default:
12031                         break;
12032                 }
12033         }
12034
12035         return true;
12036 }
12037
12038 static void
12039 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
12040 {
12041         struct drm_crtc_state tmp_state;
12042         struct intel_crtc_scaler_state scaler_state;
12043         struct intel_dpll_hw_state dpll_hw_state;
12044         enum intel_dpll_id shared_dpll;
12045         uint32_t ddi_pll_sel;
12046         bool force_thru;
12047
12048         /* FIXME: before the switch to atomic started, a new pipe_config was
12049          * kzalloc'd. Code that depends on any field being zero should be
12050          * fixed, so that the crtc_state can be safely duplicated. For now,
12051          * only fields that are know to not cause problems are preserved. */
12052
12053         tmp_state = crtc_state->base;
12054         scaler_state = crtc_state->scaler_state;
12055         shared_dpll = crtc_state->shared_dpll;
12056         dpll_hw_state = crtc_state->dpll_hw_state;
12057         ddi_pll_sel = crtc_state->ddi_pll_sel;
12058         force_thru = crtc_state->pch_pfit.force_thru;
12059
12060         memset(crtc_state, 0, sizeof *crtc_state);
12061
12062         crtc_state->base = tmp_state;
12063         crtc_state->scaler_state = scaler_state;
12064         crtc_state->shared_dpll = shared_dpll;
12065         crtc_state->dpll_hw_state = dpll_hw_state;
12066         crtc_state->ddi_pll_sel = ddi_pll_sel;
12067         crtc_state->pch_pfit.force_thru = force_thru;
12068 }
12069
12070 static int
12071 intel_modeset_pipe_config(struct drm_crtc *crtc,
12072                           struct intel_crtc_state *pipe_config)
12073 {
12074         struct drm_atomic_state *state = pipe_config->base.state;
12075         struct intel_encoder *encoder;
12076         struct drm_connector *connector;
12077         struct drm_connector_state *connector_state;
12078         int base_bpp, ret = -EINVAL;
12079         int i;
12080         bool retry = true;
12081
12082         clear_intel_crtc_state(pipe_config);
12083
12084         pipe_config->cpu_transcoder =
12085                 (enum transcoder) to_intel_crtc(crtc)->pipe;
12086
12087         /*
12088          * Sanitize sync polarity flags based on requested ones. If neither
12089          * positive or negative polarity is requested, treat this as meaning
12090          * negative polarity.
12091          */
12092         if (!(pipe_config->base.adjusted_mode.flags &
12093               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
12094                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
12095
12096         if (!(pipe_config->base.adjusted_mode.flags &
12097               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
12098                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
12099
12100         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
12101                                              pipe_config);
12102         if (base_bpp < 0)
12103                 goto fail;
12104
12105         /*
12106          * Determine the real pipe dimensions. Note that stereo modes can
12107          * increase the actual pipe size due to the frame doubling and
12108          * insertion of additional space for blanks between the frame. This
12109          * is stored in the crtc timings. We use the requested mode to do this
12110          * computation to clearly distinguish it from the adjusted mode, which
12111          * can be changed by the connectors in the below retry loop.
12112          */
12113         drm_crtc_get_hv_timing(&pipe_config->base.mode,
12114                                &pipe_config->pipe_src_w,
12115                                &pipe_config->pipe_src_h);
12116
12117 encoder_retry:
12118         /* Ensure the port clock defaults are reset when retrying. */
12119         pipe_config->port_clock = 0;
12120         pipe_config->pixel_multiplier = 1;
12121
12122         /* Fill in default crtc timings, allow encoders to overwrite them. */
12123         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
12124                               CRTC_STEREO_DOUBLE);
12125
12126         /* Pass our mode to the connectors and the CRTC to give them a chance to
12127          * adjust it according to limitations or connector properties, and also
12128          * a chance to reject the mode entirely.
12129          */
12130         for_each_connector_in_state(state, connector, connector_state, i) {
12131                 if (connector_state->crtc != crtc)
12132                         continue;
12133
12134                 encoder = to_intel_encoder(connector_state->best_encoder);
12135
12136                 if (!(encoder->compute_config(encoder, pipe_config))) {
12137                         DRM_DEBUG_KMS("Encoder config failure\n");
12138                         goto fail;
12139                 }
12140         }
12141
12142         /* Set default port clock if not overwritten by the encoder. Needs to be
12143          * done afterwards in case the encoder adjusts the mode. */
12144         if (!pipe_config->port_clock)
12145                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
12146                         * pipe_config->pixel_multiplier;
12147
12148         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
12149         if (ret < 0) {
12150                 DRM_DEBUG_KMS("CRTC fixup failed\n");
12151                 goto fail;
12152         }
12153
12154         if (ret == RETRY) {
12155                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
12156                         ret = -EINVAL;
12157                         goto fail;
12158                 }
12159
12160                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
12161                 retry = false;
12162                 goto encoder_retry;
12163         }
12164
12165         /* Dithering seems to not pass-through bits correctly when it should, so
12166          * only enable it on 6bpc panels. */
12167         pipe_config->dither = pipe_config->pipe_bpp == 6*3;
12168         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
12169                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
12170
12171 fail:
12172         return ret;
12173 }
12174
12175 static void
12176 intel_modeset_update_crtc_state(struct drm_atomic_state *state)
12177 {
12178         struct drm_crtc *crtc;
12179         struct drm_crtc_state *crtc_state;
12180         int i;
12181
12182         /* Double check state. */
12183         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12184                 to_intel_crtc(crtc)->config = to_intel_crtc_state(crtc->state);
12185
12186                 /* Update hwmode for vblank functions */
12187                 if (crtc->state->active)
12188                         crtc->hwmode = crtc->state->adjusted_mode;
12189                 else
12190                         crtc->hwmode.crtc_clock = 0;
12191         }
12192 }
12193
12194 static bool intel_fuzzy_clock_check(int clock1, int clock2)
12195 {
12196         int diff;
12197
12198         if (clock1 == clock2)
12199                 return true;
12200
12201         if (!clock1 || !clock2)
12202                 return false;
12203
12204         diff = abs(clock1 - clock2);
12205
12206         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
12207                 return true;
12208
12209         return false;
12210 }
12211
12212 #define for_each_intel_crtc_masked(dev, mask, intel_crtc) \
12213         list_for_each_entry((intel_crtc), \
12214                             &(dev)->mode_config.crtc_list, \
12215                             base.head) \
12216                 if (mask & (1 <<(intel_crtc)->pipe))
12217
12218
12219 static bool
12220 intel_compare_m_n(unsigned int m, unsigned int n,
12221                   unsigned int m2, unsigned int n2,
12222                   bool exact)
12223 {
12224         if (m == m2 && n == n2)
12225                 return true;
12226
12227         if (exact || !m || !n || !m2 || !n2)
12228                 return false;
12229
12230         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
12231
12232         if (m > m2) {
12233                 while (m > m2) {
12234                         m2 <<= 1;
12235                         n2 <<= 1;
12236                 }
12237         } else if (m < m2) {
12238                 while (m < m2) {
12239                         m <<= 1;
12240                         n <<= 1;
12241                 }
12242         }
12243
12244         return m == m2 && n == n2;
12245 }
12246
12247 static bool
12248 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
12249                        struct intel_link_m_n *m2_n2,
12250                        bool adjust)
12251 {
12252         if (m_n->tu == m2_n2->tu &&
12253             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
12254                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
12255             intel_compare_m_n(m_n->link_m, m_n->link_n,
12256                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
12257                 if (adjust)
12258                         *m2_n2 = *m_n;
12259
12260                 return true;
12261         }
12262
12263         return false;
12264 }
12265
12266 static bool
12267 intel_pipe_config_compare(struct drm_device *dev,
12268                           struct intel_crtc_state *current_config,
12269                           struct intel_crtc_state *pipe_config,
12270                           bool adjust)
12271 {
12272         bool ret = true;
12273
12274 #define INTEL_ERR_OR_DBG_KMS(fmt, ...) \
12275         do { \
12276                 if (!adjust) \
12277                         DRM_ERROR(fmt, ##__VA_ARGS__); \
12278                 else \
12279                         DRM_DEBUG_KMS(fmt, ##__VA_ARGS__); \
12280         } while (0)
12281
12282 #define PIPE_CONF_CHECK_X(name) \
12283         if (current_config->name != pipe_config->name) { \
12284                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12285                           "(expected 0x%08x, found 0x%08x)\n", \
12286                           current_config->name, \
12287                           pipe_config->name); \
12288                 ret = false; \
12289         }
12290
12291 #define PIPE_CONF_CHECK_I(name) \
12292         if (current_config->name != pipe_config->name) { \
12293                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12294                           "(expected %i, found %i)\n", \
12295                           current_config->name, \
12296                           pipe_config->name); \
12297                 ret = false; \
12298         }
12299
12300 #define PIPE_CONF_CHECK_M_N(name) \
12301         if (!intel_compare_link_m_n(&current_config->name, \
12302                                     &pipe_config->name,\
12303                                     adjust)) { \
12304                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12305                           "(expected tu %i gmch %i/%i link %i/%i, " \
12306                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12307                           current_config->name.tu, \
12308                           current_config->name.gmch_m, \
12309                           current_config->name.gmch_n, \
12310                           current_config->name.link_m, \
12311                           current_config->name.link_n, \
12312                           pipe_config->name.tu, \
12313                           pipe_config->name.gmch_m, \
12314                           pipe_config->name.gmch_n, \
12315                           pipe_config->name.link_m, \
12316                           pipe_config->name.link_n); \
12317                 ret = false; \
12318         }
12319
12320 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) \
12321         if (!intel_compare_link_m_n(&current_config->name, \
12322                                     &pipe_config->name, adjust) && \
12323             !intel_compare_link_m_n(&current_config->alt_name, \
12324                                     &pipe_config->name, adjust)) { \
12325                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12326                           "(expected tu %i gmch %i/%i link %i/%i, " \
12327                           "or tu %i gmch %i/%i link %i/%i, " \
12328                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12329                           current_config->name.tu, \
12330                           current_config->name.gmch_m, \
12331                           current_config->name.gmch_n, \
12332                           current_config->name.link_m, \
12333                           current_config->name.link_n, \
12334                           current_config->alt_name.tu, \
12335                           current_config->alt_name.gmch_m, \
12336                           current_config->alt_name.gmch_n, \
12337                           current_config->alt_name.link_m, \
12338                           current_config->alt_name.link_n, \
12339                           pipe_config->name.tu, \
12340                           pipe_config->name.gmch_m, \
12341                           pipe_config->name.gmch_n, \
12342                           pipe_config->name.link_m, \
12343                           pipe_config->name.link_n); \
12344                 ret = false; \
12345         }
12346
12347 /* This is required for BDW+ where there is only one set of registers for
12348  * switching between high and low RR.
12349  * This macro can be used whenever a comparison has to be made between one
12350  * hw state and multiple sw state variables.
12351  */
12352 #define PIPE_CONF_CHECK_I_ALT(name, alt_name) \
12353         if ((current_config->name != pipe_config->name) && \
12354                 (current_config->alt_name != pipe_config->name)) { \
12355                         INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12356                                   "(expected %i or %i, found %i)\n", \
12357                                   current_config->name, \
12358                                   current_config->alt_name, \
12359                                   pipe_config->name); \
12360                         ret = false; \
12361         }
12362
12363 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
12364         if ((current_config->name ^ pipe_config->name) & (mask)) { \
12365                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name "(" #mask ") " \
12366                           "(expected %i, found %i)\n", \
12367                           current_config->name & (mask), \
12368                           pipe_config->name & (mask)); \
12369                 ret = false; \
12370         }
12371
12372 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
12373         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
12374                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12375                           "(expected %i, found %i)\n", \
12376                           current_config->name, \
12377                           pipe_config->name); \
12378                 ret = false; \
12379         }
12380
12381 #define PIPE_CONF_QUIRK(quirk)  \
12382         ((current_config->quirks | pipe_config->quirks) & (quirk))
12383
12384         PIPE_CONF_CHECK_I(cpu_transcoder);
12385
12386         PIPE_CONF_CHECK_I(has_pch_encoder);
12387         PIPE_CONF_CHECK_I(fdi_lanes);
12388         PIPE_CONF_CHECK_M_N(fdi_m_n);
12389
12390         PIPE_CONF_CHECK_I(has_dp_encoder);
12391         PIPE_CONF_CHECK_I(lane_count);
12392
12393         if (INTEL_INFO(dev)->gen < 8) {
12394                 PIPE_CONF_CHECK_M_N(dp_m_n);
12395
12396                 PIPE_CONF_CHECK_I(has_drrs);
12397                 if (current_config->has_drrs)
12398                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
12399         } else
12400                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
12401
12402         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
12403         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
12404         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
12405         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
12406         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
12407         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
12408
12409         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
12410         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
12411         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
12412         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
12413         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
12414         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
12415
12416         PIPE_CONF_CHECK_I(pixel_multiplier);
12417         PIPE_CONF_CHECK_I(has_hdmi_sink);
12418         if ((INTEL_INFO(dev)->gen < 8 && !IS_HASWELL(dev)) ||
12419             IS_VALLEYVIEW(dev))
12420                 PIPE_CONF_CHECK_I(limited_color_range);
12421         PIPE_CONF_CHECK_I(has_infoframe);
12422
12423         PIPE_CONF_CHECK_I(has_audio);
12424
12425         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12426                               DRM_MODE_FLAG_INTERLACE);
12427
12428         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
12429                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12430                                       DRM_MODE_FLAG_PHSYNC);
12431                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12432                                       DRM_MODE_FLAG_NHSYNC);
12433                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12434                                       DRM_MODE_FLAG_PVSYNC);
12435                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12436                                       DRM_MODE_FLAG_NVSYNC);
12437         }
12438
12439         PIPE_CONF_CHECK_I(pipe_src_w);
12440         PIPE_CONF_CHECK_I(pipe_src_h);
12441
12442         PIPE_CONF_CHECK_X(gmch_pfit.control);
12443         /* pfit ratios are autocomputed by the hw on gen4+ */
12444         if (INTEL_INFO(dev)->gen < 4)
12445                 PIPE_CONF_CHECK_I(gmch_pfit.pgm_ratios);
12446         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
12447
12448         PIPE_CONF_CHECK_I(pch_pfit.enabled);
12449         if (current_config->pch_pfit.enabled) {
12450                 PIPE_CONF_CHECK_X(pch_pfit.pos);
12451                 PIPE_CONF_CHECK_X(pch_pfit.size);
12452         }
12453
12454         PIPE_CONF_CHECK_I(scaler_state.scaler_id);
12455
12456         /* BDW+ don't expose a synchronous way to read the state */
12457         if (IS_HASWELL(dev))
12458                 PIPE_CONF_CHECK_I(ips_enabled);
12459
12460         PIPE_CONF_CHECK_I(double_wide);
12461
12462         PIPE_CONF_CHECK_X(ddi_pll_sel);
12463
12464         PIPE_CONF_CHECK_I(shared_dpll);
12465         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
12466         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
12467         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
12468         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
12469         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
12470         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
12471         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
12472         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
12473
12474         if (IS_G4X(dev) || INTEL_INFO(dev)->gen >= 5)
12475                 PIPE_CONF_CHECK_I(pipe_bpp);
12476
12477         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
12478         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
12479
12480 #undef PIPE_CONF_CHECK_X
12481 #undef PIPE_CONF_CHECK_I
12482 #undef PIPE_CONF_CHECK_I_ALT
12483 #undef PIPE_CONF_CHECK_FLAGS
12484 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
12485 #undef PIPE_CONF_QUIRK
12486 #undef INTEL_ERR_OR_DBG_KMS
12487
12488         return ret;
12489 }
12490
12491 static void check_wm_state(struct drm_device *dev)
12492 {
12493         struct drm_i915_private *dev_priv = dev->dev_private;
12494         struct skl_ddb_allocation hw_ddb, *sw_ddb;
12495         struct intel_crtc *intel_crtc;
12496         int plane;
12497
12498         if (INTEL_INFO(dev)->gen < 9)
12499                 return;
12500
12501         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
12502         sw_ddb = &dev_priv->wm.skl_hw.ddb;
12503
12504         for_each_intel_crtc(dev, intel_crtc) {
12505                 struct skl_ddb_entry *hw_entry, *sw_entry;
12506                 const enum pipe pipe = intel_crtc->pipe;
12507
12508                 if (!intel_crtc->active)
12509                         continue;
12510
12511                 /* planes */
12512                 for_each_plane(dev_priv, pipe, plane) {
12513                         hw_entry = &hw_ddb.plane[pipe][plane];
12514                         sw_entry = &sw_ddb->plane[pipe][plane];
12515
12516                         if (skl_ddb_entry_equal(hw_entry, sw_entry))
12517                                 continue;
12518
12519                         DRM_ERROR("mismatch in DDB state pipe %c plane %d "
12520                                   "(expected (%u,%u), found (%u,%u))\n",
12521                                   pipe_name(pipe), plane + 1,
12522                                   sw_entry->start, sw_entry->end,
12523                                   hw_entry->start, hw_entry->end);
12524                 }
12525
12526                 /* cursor */
12527                 hw_entry = &hw_ddb.cursor[pipe];
12528                 sw_entry = &sw_ddb->cursor[pipe];
12529
12530                 if (skl_ddb_entry_equal(hw_entry, sw_entry))
12531                         continue;
12532
12533                 DRM_ERROR("mismatch in DDB state pipe %c cursor "
12534                           "(expected (%u,%u), found (%u,%u))\n",
12535                           pipe_name(pipe),
12536                           sw_entry->start, sw_entry->end,
12537                           hw_entry->start, hw_entry->end);
12538         }
12539 }
12540
12541 static void
12542 check_connector_state(struct drm_device *dev,
12543                       struct drm_atomic_state *old_state)
12544 {
12545         struct drm_connector_state *old_conn_state;
12546         struct drm_connector *connector;
12547         int i;
12548
12549         for_each_connector_in_state(old_state, connector, old_conn_state, i) {
12550                 struct drm_encoder *encoder = connector->encoder;
12551                 struct drm_connector_state *state = connector->state;
12552
12553                 /* This also checks the encoder/connector hw state with the
12554                  * ->get_hw_state callbacks. */
12555                 intel_connector_check_state(to_intel_connector(connector));
12556
12557                 I915_STATE_WARN(state->best_encoder != encoder,
12558                      "connector's atomic encoder doesn't match legacy encoder\n");
12559         }
12560 }
12561
12562 static void
12563 check_encoder_state(struct drm_device *dev)
12564 {
12565         struct intel_encoder *encoder;
12566         struct intel_connector *connector;
12567
12568         for_each_intel_encoder(dev, encoder) {
12569                 bool enabled = false;
12570                 enum pipe pipe;
12571
12572                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
12573                               encoder->base.base.id,
12574                               encoder->base.name);
12575
12576                 for_each_intel_connector(dev, connector) {
12577                         if (connector->base.state->best_encoder != &encoder->base)
12578                                 continue;
12579                         enabled = true;
12580
12581                         I915_STATE_WARN(connector->base.state->crtc !=
12582                                         encoder->base.crtc,
12583                              "connector's crtc doesn't match encoder crtc\n");
12584                 }
12585
12586                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
12587                      "encoder's enabled state mismatch "
12588                      "(expected %i, found %i)\n",
12589                      !!encoder->base.crtc, enabled);
12590
12591                 if (!encoder->base.crtc) {
12592                         bool active;
12593
12594                         active = encoder->get_hw_state(encoder, &pipe);
12595                         I915_STATE_WARN(active,
12596                              "encoder detached but still enabled on pipe %c.\n",
12597                              pipe_name(pipe));
12598                 }
12599         }
12600 }
12601
12602 static void
12603 check_crtc_state(struct drm_device *dev, struct drm_atomic_state *old_state)
12604 {
12605         struct drm_i915_private *dev_priv = dev->dev_private;
12606         struct intel_encoder *encoder;
12607         struct drm_crtc_state *old_crtc_state;
12608         struct drm_crtc *crtc;
12609         int i;
12610
12611         for_each_crtc_in_state(old_state, crtc, old_crtc_state, i) {
12612                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12613                 struct intel_crtc_state *pipe_config, *sw_config;
12614                 bool active;
12615
12616                 if (!needs_modeset(crtc->state))
12617                         continue;
12618
12619                 __drm_atomic_helper_crtc_destroy_state(crtc, old_crtc_state);
12620                 pipe_config = to_intel_crtc_state(old_crtc_state);
12621                 memset(pipe_config, 0, sizeof(*pipe_config));
12622                 pipe_config->base.crtc = crtc;
12623                 pipe_config->base.state = old_state;
12624
12625                 DRM_DEBUG_KMS("[CRTC:%d]\n",
12626                               crtc->base.id);
12627
12628                 active = dev_priv->display.get_pipe_config(intel_crtc,
12629                                                            pipe_config);
12630
12631                 /* hw state is inconsistent with the pipe quirk */
12632                 if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
12633                     (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
12634                         active = crtc->state->active;
12635
12636                 I915_STATE_WARN(crtc->state->active != active,
12637                      "crtc active state doesn't match with hw state "
12638                      "(expected %i, found %i)\n", crtc->state->active, active);
12639
12640                 I915_STATE_WARN(intel_crtc->active != crtc->state->active,
12641                      "transitional active state does not match atomic hw state "
12642                      "(expected %i, found %i)\n", crtc->state->active, intel_crtc->active);
12643
12644                 for_each_encoder_on_crtc(dev, crtc, encoder) {
12645                         enum pipe pipe;
12646
12647                         active = encoder->get_hw_state(encoder, &pipe);
12648                         I915_STATE_WARN(active != crtc->state->active,
12649                                 "[ENCODER:%i] active %i with crtc active %i\n",
12650                                 encoder->base.base.id, active, crtc->state->active);
12651
12652                         I915_STATE_WARN(active && intel_crtc->pipe != pipe,
12653                                         "Encoder connected to wrong pipe %c\n",
12654                                         pipe_name(pipe));
12655
12656                         if (active)
12657                                 encoder->get_config(encoder, pipe_config);
12658                 }
12659
12660                 if (!crtc->state->active)
12661                         continue;
12662
12663                 sw_config = to_intel_crtc_state(crtc->state);
12664                 if (!intel_pipe_config_compare(dev, sw_config,
12665                                                pipe_config, false)) {
12666                         I915_STATE_WARN(1, "pipe state doesn't match!\n");
12667                         intel_dump_pipe_config(intel_crtc, pipe_config,
12668                                                "[hw state]");
12669                         intel_dump_pipe_config(intel_crtc, sw_config,
12670                                                "[sw state]");
12671                 }
12672         }
12673 }
12674
12675 static void
12676 check_shared_dpll_state(struct drm_device *dev)
12677 {
12678         struct drm_i915_private *dev_priv = dev->dev_private;
12679         struct intel_crtc *crtc;
12680         struct intel_dpll_hw_state dpll_hw_state;
12681         int i;
12682
12683         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
12684                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
12685                 int enabled_crtcs = 0, active_crtcs = 0;
12686                 bool active;
12687
12688                 memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
12689
12690                 DRM_DEBUG_KMS("%s\n", pll->name);
12691
12692                 active = pll->get_hw_state(dev_priv, pll, &dpll_hw_state);
12693
12694                 I915_STATE_WARN(pll->active > hweight32(pll->config.crtc_mask),
12695                      "more active pll users than references: %i vs %i\n",
12696                      pll->active, hweight32(pll->config.crtc_mask));
12697                 I915_STATE_WARN(pll->active && !pll->on,
12698                      "pll in active use but not on in sw tracking\n");
12699                 I915_STATE_WARN(pll->on && !pll->active,
12700                      "pll in on but not on in use in sw tracking\n");
12701                 I915_STATE_WARN(pll->on != active,
12702                      "pll on state mismatch (expected %i, found %i)\n",
12703                      pll->on, active);
12704
12705                 for_each_intel_crtc(dev, crtc) {
12706                         if (crtc->base.state->enable && intel_crtc_to_shared_dpll(crtc) == pll)
12707                                 enabled_crtcs++;
12708                         if (crtc->active && intel_crtc_to_shared_dpll(crtc) == pll)
12709                                 active_crtcs++;
12710                 }
12711                 I915_STATE_WARN(pll->active != active_crtcs,
12712                      "pll active crtcs mismatch (expected %i, found %i)\n",
12713                      pll->active, active_crtcs);
12714                 I915_STATE_WARN(hweight32(pll->config.crtc_mask) != enabled_crtcs,
12715                      "pll enabled crtcs mismatch (expected %i, found %i)\n",
12716                      hweight32(pll->config.crtc_mask), enabled_crtcs);
12717
12718                 I915_STATE_WARN(pll->on && memcmp(&pll->config.hw_state, &dpll_hw_state,
12719                                        sizeof(dpll_hw_state)),
12720                      "pll hw state mismatch\n");
12721         }
12722 }
12723
12724 static void
12725 intel_modeset_check_state(struct drm_device *dev,
12726                           struct drm_atomic_state *old_state)
12727 {
12728         check_wm_state(dev);
12729         check_connector_state(dev, old_state);
12730         check_encoder_state(dev);
12731         check_crtc_state(dev, old_state);
12732         check_shared_dpll_state(dev);
12733 }
12734
12735 void ironlake_check_encoder_dotclock(const struct intel_crtc_state *pipe_config,
12736                                      int dotclock)
12737 {
12738         /*
12739          * FDI already provided one idea for the dotclock.
12740          * Yell if the encoder disagrees.
12741          */
12742         WARN(!intel_fuzzy_clock_check(pipe_config->base.adjusted_mode.crtc_clock, dotclock),
12743              "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
12744              pipe_config->base.adjusted_mode.crtc_clock, dotclock);
12745 }
12746
12747 static void update_scanline_offset(struct intel_crtc *crtc)
12748 {
12749         struct drm_device *dev = crtc->base.dev;
12750
12751         /*
12752          * The scanline counter increments at the leading edge of hsync.
12753          *
12754          * On most platforms it starts counting from vtotal-1 on the
12755          * first active line. That means the scanline counter value is
12756          * always one less than what we would expect. Ie. just after
12757          * start of vblank, which also occurs at start of hsync (on the
12758          * last active line), the scanline counter will read vblank_start-1.
12759          *
12760          * On gen2 the scanline counter starts counting from 1 instead
12761          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
12762          * to keep the value positive), instead of adding one.
12763          *
12764          * On HSW+ the behaviour of the scanline counter depends on the output
12765          * type. For DP ports it behaves like most other platforms, but on HDMI
12766          * there's an extra 1 line difference. So we need to add two instead of
12767          * one to the value.
12768          */
12769         if (IS_GEN2(dev)) {
12770                 const struct drm_display_mode *mode = &crtc->config->base.adjusted_mode;
12771                 int vtotal;
12772
12773                 vtotal = mode->crtc_vtotal;
12774                 if (mode->flags & DRM_MODE_FLAG_INTERLACE)
12775                         vtotal /= 2;
12776
12777                 crtc->scanline_offset = vtotal - 1;
12778         } else if (HAS_DDI(dev) &&
12779                    intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI)) {
12780                 crtc->scanline_offset = 2;
12781         } else
12782                 crtc->scanline_offset = 1;
12783 }
12784
12785 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
12786 {
12787         struct drm_device *dev = state->dev;
12788         struct drm_i915_private *dev_priv = to_i915(dev);
12789         struct intel_shared_dpll_config *shared_dpll = NULL;
12790         struct intel_crtc *intel_crtc;
12791         struct intel_crtc_state *intel_crtc_state;
12792         struct drm_crtc *crtc;
12793         struct drm_crtc_state *crtc_state;
12794         int i;
12795
12796         if (!dev_priv->display.crtc_compute_clock)
12797                 return;
12798
12799         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12800                 int dpll;
12801
12802                 intel_crtc = to_intel_crtc(crtc);
12803                 intel_crtc_state = to_intel_crtc_state(crtc_state);
12804                 dpll = intel_crtc_state->shared_dpll;
12805
12806                 if (!needs_modeset(crtc_state) || dpll == DPLL_ID_PRIVATE)
12807                         continue;
12808
12809                 intel_crtc_state->shared_dpll = DPLL_ID_PRIVATE;
12810
12811                 if (!shared_dpll)
12812                         shared_dpll = intel_atomic_get_shared_dpll_state(state);
12813
12814                 shared_dpll[dpll].crtc_mask &= ~(1 << intel_crtc->pipe);
12815         }
12816 }
12817
12818 /*
12819  * This implements the workaround described in the "notes" section of the mode
12820  * set sequence documentation. When going from no pipes or single pipe to
12821  * multiple pipes, and planes are enabled after the pipe, we need to wait at
12822  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
12823  */
12824 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
12825 {
12826         struct drm_crtc_state *crtc_state;
12827         struct intel_crtc *intel_crtc;
12828         struct drm_crtc *crtc;
12829         struct intel_crtc_state *first_crtc_state = NULL;
12830         struct intel_crtc_state *other_crtc_state = NULL;
12831         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
12832         int i;
12833
12834         /* look at all crtc's that are going to be enabled in during modeset */
12835         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12836                 intel_crtc = to_intel_crtc(crtc);
12837
12838                 if (!crtc_state->active || !needs_modeset(crtc_state))
12839                         continue;
12840
12841                 if (first_crtc_state) {
12842                         other_crtc_state = to_intel_crtc_state(crtc_state);
12843                         break;
12844                 } else {
12845                         first_crtc_state = to_intel_crtc_state(crtc_state);
12846                         first_pipe = intel_crtc->pipe;
12847                 }
12848         }
12849
12850         /* No workaround needed? */
12851         if (!first_crtc_state)
12852                 return 0;
12853
12854         /* w/a possibly needed, check how many crtc's are already enabled. */
12855         for_each_intel_crtc(state->dev, intel_crtc) {
12856                 struct intel_crtc_state *pipe_config;
12857
12858                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
12859                 if (IS_ERR(pipe_config))
12860                         return PTR_ERR(pipe_config);
12861
12862                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
12863
12864                 if (!pipe_config->base.active ||
12865                     needs_modeset(&pipe_config->base))
12866                         continue;
12867
12868                 /* 2 or more enabled crtcs means no need for w/a */
12869                 if (enabled_pipe != INVALID_PIPE)
12870                         return 0;
12871
12872                 enabled_pipe = intel_crtc->pipe;
12873         }
12874
12875         if (enabled_pipe != INVALID_PIPE)
12876                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
12877         else if (other_crtc_state)
12878                 other_crtc_state->hsw_workaround_pipe = first_pipe;
12879
12880         return 0;
12881 }
12882
12883 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
12884 {
12885         struct drm_crtc *crtc;
12886         struct drm_crtc_state *crtc_state;
12887         int ret = 0;
12888
12889         /* add all active pipes to the state */
12890         for_each_crtc(state->dev, crtc) {
12891                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
12892                 if (IS_ERR(crtc_state))
12893                         return PTR_ERR(crtc_state);
12894
12895                 if (!crtc_state->active || needs_modeset(crtc_state))
12896                         continue;
12897
12898                 crtc_state->mode_changed = true;
12899
12900                 ret = drm_atomic_add_affected_connectors(state, crtc);
12901                 if (ret)
12902                         break;
12903
12904                 ret = drm_atomic_add_affected_planes(state, crtc);
12905                 if (ret)
12906                         break;
12907         }
12908
12909         return ret;
12910 }
12911
12912
12913 static int intel_modeset_checks(struct drm_atomic_state *state)
12914 {
12915         struct drm_device *dev = state->dev;
12916         struct drm_i915_private *dev_priv = dev->dev_private;
12917         int ret;
12918
12919         if (!check_digital_port_conflicts(state)) {
12920                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
12921                 return -EINVAL;
12922         }
12923
12924         /*
12925          * See if the config requires any additional preparation, e.g.
12926          * to adjust global state with pipes off.  We need to do this
12927          * here so we can get the modeset_pipe updated config for the new
12928          * mode set on this crtc.  For other crtcs we need to use the
12929          * adjusted_mode bits in the crtc directly.
12930          */
12931         if (dev_priv->display.modeset_calc_cdclk) {
12932                 unsigned int cdclk;
12933
12934                 ret = dev_priv->display.modeset_calc_cdclk(state);
12935
12936                 cdclk = to_intel_atomic_state(state)->cdclk;
12937                 if (!ret && cdclk != dev_priv->cdclk_freq)
12938                         ret = intel_modeset_all_pipes(state);
12939
12940                 if (ret < 0)
12941                         return ret;
12942         } else
12943                 to_intel_atomic_state(state)->cdclk = dev_priv->cdclk_freq;
12944
12945         intel_modeset_clear_plls(state);
12946
12947         if (IS_HASWELL(dev))
12948                 return haswell_mode_set_planes_workaround(state);
12949
12950         return 0;
12951 }
12952
12953 /**
12954  * intel_atomic_check - validate state object
12955  * @dev: drm device
12956  * @state: state to validate
12957  */
12958 static int intel_atomic_check(struct drm_device *dev,
12959                               struct drm_atomic_state *state)
12960 {
12961         struct drm_crtc *crtc;
12962         struct drm_crtc_state *crtc_state;
12963         int ret, i;
12964         bool any_ms = false;
12965
12966         ret = drm_atomic_helper_check_modeset(dev, state);
12967         if (ret)
12968                 return ret;
12969
12970         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12971                 struct intel_crtc_state *pipe_config =
12972                         to_intel_crtc_state(crtc_state);
12973
12974                 /* Catch I915_MODE_FLAG_INHERITED */
12975                 if (crtc_state->mode.private_flags != crtc->state->mode.private_flags)
12976                         crtc_state->mode_changed = true;
12977
12978                 if (!crtc_state->enable) {
12979                         if (needs_modeset(crtc_state))
12980                                 any_ms = true;
12981                         continue;
12982                 }
12983
12984                 if (!needs_modeset(crtc_state))
12985                         continue;
12986
12987                 /* FIXME: For only active_changed we shouldn't need to do any
12988                  * state recomputation at all. */
12989
12990                 ret = drm_atomic_add_affected_connectors(state, crtc);
12991                 if (ret)
12992                         return ret;
12993
12994                 ret = intel_modeset_pipe_config(crtc, pipe_config);
12995                 if (ret)
12996                         return ret;
12997
12998                 if (i915.fastboot &&
12999                     intel_pipe_config_compare(state->dev,
13000                                         to_intel_crtc_state(crtc->state),
13001                                         pipe_config, true)) {
13002                         crtc_state->mode_changed = false;
13003                 }
13004
13005                 if (needs_modeset(crtc_state)) {
13006                         any_ms = true;
13007
13008                         ret = drm_atomic_add_affected_planes(state, crtc);
13009                         if (ret)
13010                                 return ret;
13011                 }
13012
13013                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
13014                                        needs_modeset(crtc_state) ?
13015                                        "[modeset]" : "[fastset]");
13016         }
13017
13018         if (any_ms) {
13019                 ret = intel_modeset_checks(state);
13020
13021                 if (ret)
13022                         return ret;
13023         } else
13024                 to_intel_atomic_state(state)->cdclk =
13025                         to_i915(state->dev)->cdclk_freq;
13026
13027         return drm_atomic_helper_check_planes(state->dev, state);
13028 }
13029
13030 /**
13031  * intel_atomic_commit - commit validated state object
13032  * @dev: DRM device
13033  * @state: the top-level driver state object
13034  * @async: asynchronous commit
13035  *
13036  * This function commits a top-level state object that has been validated
13037  * with drm_atomic_helper_check().
13038  *
13039  * FIXME:  Atomic modeset support for i915 is not yet complete.  At the moment
13040  * we can only handle plane-related operations and do not yet support
13041  * asynchronous commit.
13042  *
13043  * RETURNS
13044  * Zero for success or -errno.
13045  */
13046 static int intel_atomic_commit(struct drm_device *dev,
13047                                struct drm_atomic_state *state,
13048                                bool async)
13049 {
13050         struct drm_i915_private *dev_priv = dev->dev_private;
13051         struct drm_crtc *crtc;
13052         struct drm_crtc_state *crtc_state;
13053         int ret = 0;
13054         int i;
13055         bool any_ms = false;
13056
13057         if (async) {
13058                 DRM_DEBUG_KMS("i915 does not yet support async commit\n");
13059                 return -EINVAL;
13060         }
13061
13062         ret = drm_atomic_helper_prepare_planes(dev, state);
13063         if (ret)
13064                 return ret;
13065
13066         drm_atomic_helper_swap_state(dev, state);
13067
13068         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13069                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13070
13071                 if (!needs_modeset(crtc->state))
13072                         continue;
13073
13074                 any_ms = true;
13075                 intel_pre_plane_update(intel_crtc);
13076
13077                 if (crtc_state->active) {
13078                         intel_crtc_disable_planes(crtc, crtc_state->plane_mask);
13079                         dev_priv->display.crtc_disable(crtc);
13080                         intel_crtc->active = false;
13081                         intel_disable_shared_dpll(intel_crtc);
13082                 }
13083         }
13084
13085         /* Only after disabling all output pipelines that will be changed can we
13086          * update the the output configuration. */
13087         intel_modeset_update_crtc_state(state);
13088
13089         if (any_ms) {
13090                 intel_shared_dpll_commit(state);
13091
13092                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
13093                 modeset_update_crtc_power_domains(state);
13094         }
13095
13096         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
13097         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13098                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13099                 bool modeset = needs_modeset(crtc->state);
13100
13101                 if (modeset && crtc->state->active) {
13102                         update_scanline_offset(to_intel_crtc(crtc));
13103                         dev_priv->display.crtc_enable(crtc);
13104                 }
13105
13106                 if (!modeset)
13107                         intel_pre_plane_update(intel_crtc);
13108
13109                 drm_atomic_helper_commit_planes_on_crtc(crtc_state);
13110                 intel_post_plane_update(intel_crtc);
13111         }
13112
13113         /* FIXME: add subpixel order */
13114
13115         drm_atomic_helper_wait_for_vblanks(dev, state);
13116         drm_atomic_helper_cleanup_planes(dev, state);
13117
13118         if (any_ms)
13119                 intel_modeset_check_state(dev, state);
13120
13121         drm_atomic_state_free(state);
13122
13123         return 0;
13124 }
13125
13126 void intel_crtc_restore_mode(struct drm_crtc *crtc)
13127 {
13128         struct drm_device *dev = crtc->dev;
13129         struct drm_atomic_state *state;
13130         struct drm_crtc_state *crtc_state;
13131         int ret;
13132
13133         state = drm_atomic_state_alloc(dev);
13134         if (!state) {
13135                 DRM_DEBUG_KMS("[CRTC:%d] crtc restore failed, out of memory",
13136                               crtc->base.id);
13137                 return;
13138         }
13139
13140         state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
13141
13142 retry:
13143         crtc_state = drm_atomic_get_crtc_state(state, crtc);
13144         ret = PTR_ERR_OR_ZERO(crtc_state);
13145         if (!ret) {
13146                 if (!crtc_state->active)
13147                         goto out;
13148
13149                 crtc_state->mode_changed = true;
13150                 ret = drm_atomic_commit(state);
13151         }
13152
13153         if (ret == -EDEADLK) {
13154                 drm_atomic_state_clear(state);
13155                 drm_modeset_backoff(state->acquire_ctx);
13156                 goto retry;
13157         }
13158
13159         if (ret)
13160 out:
13161                 drm_atomic_state_free(state);
13162 }
13163
13164 #undef for_each_intel_crtc_masked
13165
13166 static const struct drm_crtc_funcs intel_crtc_funcs = {
13167         .gamma_set = intel_crtc_gamma_set,
13168         .set_config = drm_atomic_helper_set_config,
13169         .destroy = intel_crtc_destroy,
13170         .page_flip = intel_crtc_page_flip,
13171         .atomic_duplicate_state = intel_crtc_duplicate_state,
13172         .atomic_destroy_state = intel_crtc_destroy_state,
13173 };
13174
13175 static bool ibx_pch_dpll_get_hw_state(struct drm_i915_private *dev_priv,
13176                                       struct intel_shared_dpll *pll,
13177                                       struct intel_dpll_hw_state *hw_state)
13178 {
13179         uint32_t val;
13180
13181         if (!intel_display_power_is_enabled(dev_priv, POWER_DOMAIN_PLLS))
13182                 return false;
13183
13184         val = I915_READ(PCH_DPLL(pll->id));
13185         hw_state->dpll = val;
13186         hw_state->fp0 = I915_READ(PCH_FP0(pll->id));
13187         hw_state->fp1 = I915_READ(PCH_FP1(pll->id));
13188
13189         return val & DPLL_VCO_ENABLE;
13190 }
13191
13192 static void ibx_pch_dpll_mode_set(struct drm_i915_private *dev_priv,
13193                                   struct intel_shared_dpll *pll)
13194 {
13195         I915_WRITE(PCH_FP0(pll->id), pll->config.hw_state.fp0);
13196         I915_WRITE(PCH_FP1(pll->id), pll->config.hw_state.fp1);
13197 }
13198
13199 static void ibx_pch_dpll_enable(struct drm_i915_private *dev_priv,
13200                                 struct intel_shared_dpll *pll)
13201 {
13202         /* PCH refclock must be enabled first */
13203         ibx_assert_pch_refclk_enabled(dev_priv);
13204
13205         I915_WRITE(PCH_DPLL(pll->id), pll->config.hw_state.dpll);
13206
13207         /* Wait for the clocks to stabilize. */
13208         POSTING_READ(PCH_DPLL(pll->id));
13209         udelay(150);
13210
13211         /* The pixel multiplier can only be updated once the
13212          * DPLL is enabled and the clocks are stable.
13213          *
13214          * So write it again.
13215          */
13216         I915_WRITE(PCH_DPLL(pll->id), pll->config.hw_state.dpll);
13217         POSTING_READ(PCH_DPLL(pll->id));
13218         udelay(200);
13219 }
13220
13221 static void ibx_pch_dpll_disable(struct drm_i915_private *dev_priv,
13222                                  struct intel_shared_dpll *pll)
13223 {
13224         struct drm_device *dev = dev_priv->dev;
13225         struct intel_crtc *crtc;
13226
13227         /* Make sure no transcoder isn't still depending on us. */
13228         for_each_intel_crtc(dev, crtc) {
13229                 if (intel_crtc_to_shared_dpll(crtc) == pll)
13230                         assert_pch_transcoder_disabled(dev_priv, crtc->pipe);
13231         }
13232
13233         I915_WRITE(PCH_DPLL(pll->id), 0);
13234         POSTING_READ(PCH_DPLL(pll->id));
13235         udelay(200);
13236 }
13237
13238 static char *ibx_pch_dpll_names[] = {
13239         "PCH DPLL A",
13240         "PCH DPLL B",
13241 };
13242
13243 static void ibx_pch_dpll_init(struct drm_device *dev)
13244 {
13245         struct drm_i915_private *dev_priv = dev->dev_private;
13246         int i;
13247
13248         dev_priv->num_shared_dpll = 2;
13249
13250         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
13251                 dev_priv->shared_dplls[i].id = i;
13252                 dev_priv->shared_dplls[i].name = ibx_pch_dpll_names[i];
13253                 dev_priv->shared_dplls[i].mode_set = ibx_pch_dpll_mode_set;
13254                 dev_priv->shared_dplls[i].enable = ibx_pch_dpll_enable;
13255                 dev_priv->shared_dplls[i].disable = ibx_pch_dpll_disable;
13256                 dev_priv->shared_dplls[i].get_hw_state =
13257                         ibx_pch_dpll_get_hw_state;
13258         }
13259 }
13260
13261 static void intel_shared_dpll_init(struct drm_device *dev)
13262 {
13263         struct drm_i915_private *dev_priv = dev->dev_private;
13264
13265         intel_update_cdclk(dev);
13266
13267         if (HAS_DDI(dev))
13268                 intel_ddi_pll_init(dev);
13269         else if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
13270                 ibx_pch_dpll_init(dev);
13271         else
13272                 dev_priv->num_shared_dpll = 0;
13273
13274         BUG_ON(dev_priv->num_shared_dpll > I915_NUM_PLLS);
13275 }
13276
13277 /**
13278  * intel_prepare_plane_fb - Prepare fb for usage on plane
13279  * @plane: drm plane to prepare for
13280  * @fb: framebuffer to prepare for presentation
13281  *
13282  * Prepares a framebuffer for usage on a display plane.  Generally this
13283  * involves pinning the underlying object and updating the frontbuffer tracking
13284  * bits.  Some older platforms need special physical address handling for
13285  * cursor planes.
13286  *
13287  * Returns 0 on success, negative error code on failure.
13288  */
13289 int
13290 intel_prepare_plane_fb(struct drm_plane *plane,
13291                        const struct drm_plane_state *new_state)
13292 {
13293         struct drm_device *dev = plane->dev;
13294         struct drm_framebuffer *fb = new_state->fb;
13295         struct intel_plane *intel_plane = to_intel_plane(plane);
13296         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13297         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->fb);
13298         int ret = 0;
13299
13300         if (!obj)
13301                 return 0;
13302
13303         mutex_lock(&dev->struct_mutex);
13304
13305         if (plane->type == DRM_PLANE_TYPE_CURSOR &&
13306             INTEL_INFO(dev)->cursor_needs_physical) {
13307                 int align = IS_I830(dev) ? 16 * 1024 : 256;
13308                 ret = i915_gem_object_attach_phys(obj, align);
13309                 if (ret)
13310                         DRM_DEBUG_KMS("failed to attach phys object\n");
13311         } else {
13312                 ret = intel_pin_and_fence_fb_obj(plane, fb, new_state, NULL, NULL);
13313         }
13314
13315         if (ret == 0)
13316                 i915_gem_track_fb(old_obj, obj, intel_plane->frontbuffer_bit);
13317
13318         mutex_unlock(&dev->struct_mutex);
13319
13320         return ret;
13321 }
13322
13323 /**
13324  * intel_cleanup_plane_fb - Cleans up an fb after plane use
13325  * @plane: drm plane to clean up for
13326  * @fb: old framebuffer that was on plane
13327  *
13328  * Cleans up a framebuffer that has just been removed from a plane.
13329  */
13330 void
13331 intel_cleanup_plane_fb(struct drm_plane *plane,
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(old_state->fb);
13336
13337         if (!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(old_state->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         if (intel_crtc->cursor_bo == obj)
13637                 goto update;
13638
13639         if (!obj)
13640                 addr = 0;
13641         else if (!INTEL_INFO(dev)->cursor_needs_physical)
13642                 addr = i915_gem_obj_ggtt_offset(obj);
13643         else
13644                 addr = obj->phys_handle->busaddr;
13645
13646         intel_crtc->cursor_addr = addr;
13647         intel_crtc->cursor_bo = obj;
13648
13649 update:
13650         if (crtc->state->active)
13651                 intel_crtc_update_cursor(crtc, state->visible);
13652 }
13653
13654 static struct drm_plane *intel_cursor_plane_create(struct drm_device *dev,
13655                                                    int pipe)
13656 {
13657         struct intel_plane *cursor;
13658         struct intel_plane_state *state;
13659
13660         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
13661         if (cursor == NULL)
13662                 return NULL;
13663
13664         state = intel_create_plane_state(&cursor->base);
13665         if (!state) {
13666                 kfree(cursor);
13667                 return NULL;
13668         }
13669         cursor->base.state = &state->base;
13670
13671         cursor->can_scale = false;
13672         cursor->max_downscale = 1;
13673         cursor->pipe = pipe;
13674         cursor->plane = pipe;
13675         cursor->frontbuffer_bit = INTEL_FRONTBUFFER_CURSOR(pipe);
13676         cursor->check_plane = intel_check_cursor_plane;
13677         cursor->commit_plane = intel_commit_cursor_plane;
13678         cursor->disable_plane = intel_disable_cursor_plane;
13679
13680         drm_universal_plane_init(dev, &cursor->base, 0,
13681                                  &intel_plane_funcs,
13682                                  intel_cursor_formats,
13683                                  ARRAY_SIZE(intel_cursor_formats),
13684                                  DRM_PLANE_TYPE_CURSOR);
13685
13686         if (INTEL_INFO(dev)->gen >= 4) {
13687                 if (!dev->mode_config.rotation_property)
13688                         dev->mode_config.rotation_property =
13689                                 drm_mode_create_rotation_property(dev,
13690                                                         BIT(DRM_ROTATE_0) |
13691                                                         BIT(DRM_ROTATE_180));
13692                 if (dev->mode_config.rotation_property)
13693                         drm_object_attach_property(&cursor->base.base,
13694                                 dev->mode_config.rotation_property,
13695                                 state->base.rotation);
13696         }
13697
13698         if (INTEL_INFO(dev)->gen >=9)
13699                 state->scaler_id = -1;
13700
13701         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
13702
13703         return &cursor->base;
13704 }
13705
13706 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
13707         struct intel_crtc_state *crtc_state)
13708 {
13709         int i;
13710         struct intel_scaler *intel_scaler;
13711         struct intel_crtc_scaler_state *scaler_state = &crtc_state->scaler_state;
13712
13713         for (i = 0; i < intel_crtc->num_scalers; i++) {
13714                 intel_scaler = &scaler_state->scalers[i];
13715                 intel_scaler->in_use = 0;
13716                 intel_scaler->mode = PS_SCALER_MODE_DYN;
13717         }
13718
13719         scaler_state->scaler_id = -1;
13720 }
13721
13722 static void intel_crtc_init(struct drm_device *dev, int pipe)
13723 {
13724         struct drm_i915_private *dev_priv = dev->dev_private;
13725         struct intel_crtc *intel_crtc;
13726         struct intel_crtc_state *crtc_state = NULL;
13727         struct drm_plane *primary = NULL;
13728         struct drm_plane *cursor = NULL;
13729         int i, ret;
13730
13731         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
13732         if (intel_crtc == NULL)
13733                 return;
13734
13735         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
13736         if (!crtc_state)
13737                 goto fail;
13738         intel_crtc->config = crtc_state;
13739         intel_crtc->base.state = &crtc_state->base;
13740         crtc_state->base.crtc = &intel_crtc->base;
13741
13742         /* initialize shared scalers */
13743         if (INTEL_INFO(dev)->gen >= 9) {
13744                 if (pipe == PIPE_C)
13745                         intel_crtc->num_scalers = 1;
13746                 else
13747                         intel_crtc->num_scalers = SKL_NUM_SCALERS;
13748
13749                 skl_init_scalers(dev, intel_crtc, crtc_state);
13750         }
13751
13752         primary = intel_primary_plane_create(dev, pipe);
13753         if (!primary)
13754                 goto fail;
13755
13756         cursor = intel_cursor_plane_create(dev, pipe);
13757         if (!cursor)
13758                 goto fail;
13759
13760         ret = drm_crtc_init_with_planes(dev, &intel_crtc->base, primary,
13761                                         cursor, &intel_crtc_funcs);
13762         if (ret)
13763                 goto fail;
13764
13765         drm_mode_crtc_set_gamma_size(&intel_crtc->base, 256);
13766         for (i = 0; i < 256; i++) {
13767                 intel_crtc->lut_r[i] = i;
13768                 intel_crtc->lut_g[i] = i;
13769                 intel_crtc->lut_b[i] = i;
13770         }
13771
13772         /*
13773          * On gen2/3 only plane A can do fbc, but the panel fitter and lvds port
13774          * is hooked to pipe B. Hence we want plane A feeding pipe B.
13775          */
13776         intel_crtc->pipe = pipe;
13777         intel_crtc->plane = pipe;
13778         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4) {
13779                 DRM_DEBUG_KMS("swapping pipes & planes for FBC\n");
13780                 intel_crtc->plane = !pipe;
13781         }
13782
13783         intel_crtc->cursor_base = ~0;
13784         intel_crtc->cursor_cntl = ~0;
13785         intel_crtc->cursor_size = ~0;
13786
13787         intel_crtc->wm.cxsr_allowed = true;
13788
13789         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
13790                dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
13791         dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = &intel_crtc->base;
13792         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = &intel_crtc->base;
13793
13794         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
13795
13796         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
13797         return;
13798
13799 fail:
13800         if (primary)
13801                 drm_plane_cleanup(primary);
13802         if (cursor)
13803                 drm_plane_cleanup(cursor);
13804         kfree(crtc_state);
13805         kfree(intel_crtc);
13806 }
13807
13808 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
13809 {
13810         struct drm_encoder *encoder = connector->base.encoder;
13811         struct drm_device *dev = connector->base.dev;
13812
13813         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
13814
13815         if (!encoder || WARN_ON(!encoder->crtc))
13816                 return INVALID_PIPE;
13817
13818         return to_intel_crtc(encoder->crtc)->pipe;
13819 }
13820
13821 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
13822                                 struct drm_file *file)
13823 {
13824         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
13825         struct drm_crtc *drmmode_crtc;
13826         struct intel_crtc *crtc;
13827
13828         drmmode_crtc = drm_crtc_find(dev, pipe_from_crtc_id->crtc_id);
13829
13830         if (!drmmode_crtc) {
13831                 DRM_ERROR("no such CRTC id\n");
13832                 return -ENOENT;
13833         }
13834
13835         crtc = to_intel_crtc(drmmode_crtc);
13836         pipe_from_crtc_id->pipe = crtc->pipe;
13837
13838         return 0;
13839 }
13840
13841 static int intel_encoder_clones(struct intel_encoder *encoder)
13842 {
13843         struct drm_device *dev = encoder->base.dev;
13844         struct intel_encoder *source_encoder;
13845         int index_mask = 0;
13846         int entry = 0;
13847
13848         for_each_intel_encoder(dev, source_encoder) {
13849                 if (encoders_cloneable(encoder, source_encoder))
13850                         index_mask |= (1 << entry);
13851
13852                 entry++;
13853         }
13854
13855         return index_mask;
13856 }
13857
13858 static bool has_edp_a(struct drm_device *dev)
13859 {
13860         struct drm_i915_private *dev_priv = dev->dev_private;
13861
13862         if (!IS_MOBILE(dev))
13863                 return false;
13864
13865         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
13866                 return false;
13867
13868         if (IS_GEN5(dev) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
13869                 return false;
13870
13871         return true;
13872 }
13873
13874 static bool intel_crt_present(struct drm_device *dev)
13875 {
13876         struct drm_i915_private *dev_priv = dev->dev_private;
13877
13878         if (INTEL_INFO(dev)->gen >= 9)
13879                 return false;
13880
13881         if (IS_HSW_ULT(dev) || IS_BDW_ULT(dev))
13882                 return false;
13883
13884         if (IS_CHERRYVIEW(dev))
13885                 return false;
13886
13887         if (IS_VALLEYVIEW(dev) && !dev_priv->vbt.int_crt_support)
13888                 return false;
13889
13890         return true;
13891 }
13892
13893 static void intel_setup_outputs(struct drm_device *dev)
13894 {
13895         struct drm_i915_private *dev_priv = dev->dev_private;
13896         struct intel_encoder *encoder;
13897         bool dpd_is_edp = false;
13898
13899         intel_lvds_init(dev);
13900
13901         if (intel_crt_present(dev))
13902                 intel_crt_init(dev);
13903
13904         if (IS_BROXTON(dev)) {
13905                 /*
13906                  * FIXME: Broxton doesn't support port detection via the
13907                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
13908                  * detect the ports.
13909                  */
13910                 intel_ddi_init(dev, PORT_A);
13911                 intel_ddi_init(dev, PORT_B);
13912                 intel_ddi_init(dev, PORT_C);
13913         } else if (HAS_DDI(dev)) {
13914                 int found;
13915
13916                 /*
13917                  * Haswell uses DDI functions to detect digital outputs.
13918                  * On SKL pre-D0 the strap isn't connected, so we assume
13919                  * it's there.
13920                  */
13921                 found = I915_READ(DDI_BUF_CTL_A) & DDI_INIT_DISPLAY_DETECTED;
13922                 /* WaIgnoreDDIAStrap: skl */
13923                 if (found || IS_SKYLAKE(dev))
13924                         intel_ddi_init(dev, PORT_A);
13925
13926                 /* DDI B, C and D detection is indicated by the SFUSE_STRAP
13927                  * register */
13928                 found = I915_READ(SFUSE_STRAP);
13929
13930                 if (found & SFUSE_STRAP_DDIB_DETECTED)
13931                         intel_ddi_init(dev, PORT_B);
13932                 if (found & SFUSE_STRAP_DDIC_DETECTED)
13933                         intel_ddi_init(dev, PORT_C);
13934                 if (found & SFUSE_STRAP_DDID_DETECTED)
13935                         intel_ddi_init(dev, PORT_D);
13936                 /*
13937                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
13938                  */
13939                 if (IS_SKYLAKE(dev) &&
13940                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
13941                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
13942                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
13943                         intel_ddi_init(dev, PORT_E);
13944
13945         } else if (HAS_PCH_SPLIT(dev)) {
13946                 int found;
13947                 dpd_is_edp = intel_dp_is_edp(dev, PORT_D);
13948
13949                 if (has_edp_a(dev))
13950                         intel_dp_init(dev, DP_A, PORT_A);
13951
13952                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
13953                         /* PCH SDVOB multiplex with HDMIB */
13954                         found = intel_sdvo_init(dev, PCH_SDVOB, true);
13955                         if (!found)
13956                                 intel_hdmi_init(dev, PCH_HDMIB, PORT_B);
13957                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
13958                                 intel_dp_init(dev, PCH_DP_B, PORT_B);
13959                 }
13960
13961                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
13962                         intel_hdmi_init(dev, PCH_HDMIC, PORT_C);
13963
13964                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
13965                         intel_hdmi_init(dev, PCH_HDMID, PORT_D);
13966
13967                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
13968                         intel_dp_init(dev, PCH_DP_C, PORT_C);
13969
13970                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
13971                         intel_dp_init(dev, PCH_DP_D, PORT_D);
13972         } else if (IS_VALLEYVIEW(dev)) {
13973                 /*
13974                  * The DP_DETECTED bit is the latched state of the DDC
13975                  * SDA pin at boot. However since eDP doesn't require DDC
13976                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
13977                  * eDP ports may have been muxed to an alternate function.
13978                  * Thus we can't rely on the DP_DETECTED bit alone to detect
13979                  * eDP ports. Consult the VBT as well as DP_DETECTED to
13980                  * detect eDP ports.
13981                  */
13982                 if (I915_READ(VLV_DISPLAY_BASE + GEN4_HDMIB) & SDVO_DETECTED &&
13983                     !intel_dp_is_edp(dev, PORT_B))
13984                         intel_hdmi_init(dev, VLV_DISPLAY_BASE + GEN4_HDMIB,
13985                                         PORT_B);
13986                 if (I915_READ(VLV_DISPLAY_BASE + DP_B) & DP_DETECTED ||
13987                     intel_dp_is_edp(dev, PORT_B))
13988                         intel_dp_init(dev, VLV_DISPLAY_BASE + DP_B, PORT_B);
13989
13990                 if (I915_READ(VLV_DISPLAY_BASE + GEN4_HDMIC) & SDVO_DETECTED &&
13991                     !intel_dp_is_edp(dev, PORT_C))
13992                         intel_hdmi_init(dev, VLV_DISPLAY_BASE + GEN4_HDMIC,
13993                                         PORT_C);
13994                 if (I915_READ(VLV_DISPLAY_BASE + DP_C) & DP_DETECTED ||
13995                     intel_dp_is_edp(dev, PORT_C))
13996                         intel_dp_init(dev, VLV_DISPLAY_BASE + DP_C, PORT_C);
13997
13998                 if (IS_CHERRYVIEW(dev)) {
13999                         if (I915_READ(VLV_DISPLAY_BASE + CHV_HDMID) & SDVO_DETECTED)
14000                                 intel_hdmi_init(dev, VLV_DISPLAY_BASE + CHV_HDMID,
14001                                                 PORT_D);
14002                         /* eDP not supported on port D, so don't check VBT */
14003                         if (I915_READ(VLV_DISPLAY_BASE + DP_D) & DP_DETECTED)
14004                                 intel_dp_init(dev, VLV_DISPLAY_BASE + DP_D, PORT_D);
14005                 }
14006
14007                 intel_dsi_init(dev);
14008         } else if (!IS_GEN2(dev) && !IS_PINEVIEW(dev)) {
14009                 bool found = false;
14010
14011                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14012                         DRM_DEBUG_KMS("probing SDVOB\n");
14013                         found = intel_sdvo_init(dev, GEN3_SDVOB, true);
14014                         if (!found && IS_G4X(dev)) {
14015                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
14016                                 intel_hdmi_init(dev, GEN4_HDMIB, PORT_B);
14017                         }
14018
14019                         if (!found && IS_G4X(dev))
14020                                 intel_dp_init(dev, DP_B, PORT_B);
14021                 }
14022
14023                 /* Before G4X SDVOC doesn't have its own detect register */
14024
14025                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14026                         DRM_DEBUG_KMS("probing SDVOC\n");
14027                         found = intel_sdvo_init(dev, GEN3_SDVOC, false);
14028                 }
14029
14030                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
14031
14032                         if (IS_G4X(dev)) {
14033                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
14034                                 intel_hdmi_init(dev, GEN4_HDMIC, PORT_C);
14035                         }
14036                         if (IS_G4X(dev))
14037                                 intel_dp_init(dev, DP_C, PORT_C);
14038                 }
14039
14040                 if (IS_G4X(dev) &&
14041                     (I915_READ(DP_D) & DP_DETECTED))
14042                         intel_dp_init(dev, DP_D, PORT_D);
14043         } else if (IS_GEN2(dev))
14044                 intel_dvo_init(dev);
14045
14046         if (SUPPORTS_TV(dev))
14047                 intel_tv_init(dev);
14048
14049         intel_psr_init(dev);
14050
14051         for_each_intel_encoder(dev, encoder) {
14052                 encoder->base.possible_crtcs = encoder->crtc_mask;
14053                 encoder->base.possible_clones =
14054                         intel_encoder_clones(encoder);
14055         }
14056
14057         intel_init_pch_refclk(dev);
14058
14059         drm_helper_move_panel_connectors_to_head(dev);
14060 }
14061
14062 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
14063 {
14064         struct drm_device *dev = fb->dev;
14065         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14066
14067         drm_framebuffer_cleanup(fb);
14068         mutex_lock(&dev->struct_mutex);
14069         WARN_ON(!intel_fb->obj->framebuffer_references--);
14070         drm_gem_object_unreference(&intel_fb->obj->base);
14071         mutex_unlock(&dev->struct_mutex);
14072         kfree(intel_fb);
14073 }
14074
14075 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
14076                                                 struct drm_file *file,
14077                                                 unsigned int *handle)
14078 {
14079         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14080         struct drm_i915_gem_object *obj = intel_fb->obj;
14081
14082         return drm_gem_handle_create(file, &obj->base, handle);
14083 }
14084
14085 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
14086                                         struct drm_file *file,
14087                                         unsigned flags, unsigned color,
14088                                         struct drm_clip_rect *clips,
14089                                         unsigned num_clips)
14090 {
14091         struct drm_device *dev = fb->dev;
14092         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14093         struct drm_i915_gem_object *obj = intel_fb->obj;
14094
14095         mutex_lock(&dev->struct_mutex);
14096         intel_fb_obj_flush(obj, false, ORIGIN_DIRTYFB);
14097         mutex_unlock(&dev->struct_mutex);
14098
14099         return 0;
14100 }
14101
14102 static const struct drm_framebuffer_funcs intel_fb_funcs = {
14103         .destroy = intel_user_framebuffer_destroy,
14104         .create_handle = intel_user_framebuffer_create_handle,
14105         .dirty = intel_user_framebuffer_dirty,
14106 };
14107
14108 static
14109 u32 intel_fb_pitch_limit(struct drm_device *dev, uint64_t fb_modifier,
14110                          uint32_t pixel_format)
14111 {
14112         u32 gen = INTEL_INFO(dev)->gen;
14113
14114         if (gen >= 9) {
14115                 /* "The stride in bytes must not exceed the of the size of 8K
14116                  *  pixels and 32K bytes."
14117                  */
14118                  return min(8192*drm_format_plane_cpp(pixel_format, 0), 32768);
14119         } else if (gen >= 5 && !IS_VALLEYVIEW(dev)) {
14120                 return 32*1024;
14121         } else if (gen >= 4) {
14122                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14123                         return 16*1024;
14124                 else
14125                         return 32*1024;
14126         } else if (gen >= 3) {
14127                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14128                         return 8*1024;
14129                 else
14130                         return 16*1024;
14131         } else {
14132                 /* XXX DSPC is limited to 4k tiled */
14133                 return 8*1024;
14134         }
14135 }
14136
14137 static int intel_framebuffer_init(struct drm_device *dev,
14138                                   struct intel_framebuffer *intel_fb,
14139                                   struct drm_mode_fb_cmd2 *mode_cmd,
14140                                   struct drm_i915_gem_object *obj)
14141 {
14142         unsigned int aligned_height;
14143         int ret;
14144         u32 pitch_limit, stride_alignment;
14145
14146         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
14147
14148         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
14149                 /* Enforce that fb modifier and tiling mode match, but only for
14150                  * X-tiled. This is needed for FBC. */
14151                 if (!!(obj->tiling_mode == I915_TILING_X) !=
14152                     !!(mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED)) {
14153                         DRM_DEBUG("tiling_mode doesn't match fb modifier\n");
14154                         return -EINVAL;
14155                 }
14156         } else {
14157                 if (obj->tiling_mode == I915_TILING_X)
14158                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
14159                 else if (obj->tiling_mode == I915_TILING_Y) {
14160                         DRM_DEBUG("No Y tiling for legacy addfb\n");
14161                         return -EINVAL;
14162                 }
14163         }
14164
14165         /* Passed in modifier sanity checking. */
14166         switch (mode_cmd->modifier[0]) {
14167         case I915_FORMAT_MOD_Y_TILED:
14168         case I915_FORMAT_MOD_Yf_TILED:
14169                 if (INTEL_INFO(dev)->gen < 9) {
14170                         DRM_DEBUG("Unsupported tiling 0x%llx!\n",
14171                                   mode_cmd->modifier[0]);
14172                         return -EINVAL;
14173                 }
14174         case DRM_FORMAT_MOD_NONE:
14175         case I915_FORMAT_MOD_X_TILED:
14176                 break;
14177         default:
14178                 DRM_DEBUG("Unsupported fb modifier 0x%llx!\n",
14179                           mode_cmd->modifier[0]);
14180                 return -EINVAL;
14181         }
14182
14183         stride_alignment = intel_fb_stride_alignment(dev, mode_cmd->modifier[0],
14184                                                      mode_cmd->pixel_format);
14185         if (mode_cmd->pitches[0] & (stride_alignment - 1)) {
14186                 DRM_DEBUG("pitch (%d) must be at least %u byte aligned\n",
14187                           mode_cmd->pitches[0], stride_alignment);
14188                 return -EINVAL;
14189         }
14190
14191         pitch_limit = intel_fb_pitch_limit(dev, mode_cmd->modifier[0],
14192                                            mode_cmd->pixel_format);
14193         if (mode_cmd->pitches[0] > pitch_limit) {
14194                 DRM_DEBUG("%s pitch (%u) must be at less than %d\n",
14195                           mode_cmd->modifier[0] != DRM_FORMAT_MOD_NONE ?
14196                           "tiled" : "linear",
14197                           mode_cmd->pitches[0], pitch_limit);
14198                 return -EINVAL;
14199         }
14200
14201         if (mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED &&
14202             mode_cmd->pitches[0] != obj->stride) {
14203                 DRM_DEBUG("pitch (%d) must match tiling stride (%d)\n",
14204                           mode_cmd->pitches[0], obj->stride);
14205                 return -EINVAL;
14206         }
14207
14208         /* Reject formats not supported by any plane early. */
14209         switch (mode_cmd->pixel_format) {
14210         case DRM_FORMAT_C8:
14211         case DRM_FORMAT_RGB565:
14212         case DRM_FORMAT_XRGB8888:
14213         case DRM_FORMAT_ARGB8888:
14214                 break;
14215         case DRM_FORMAT_XRGB1555:
14216                 if (INTEL_INFO(dev)->gen > 3) {
14217                         DRM_DEBUG("unsupported pixel format: %s\n",
14218                                   drm_get_format_name(mode_cmd->pixel_format));
14219                         return -EINVAL;
14220                 }
14221                 break;
14222         case DRM_FORMAT_ABGR8888:
14223                 if (!IS_VALLEYVIEW(dev) && INTEL_INFO(dev)->gen < 9) {
14224                         DRM_DEBUG("unsupported pixel format: %s\n",
14225                                   drm_get_format_name(mode_cmd->pixel_format));
14226                         return -EINVAL;
14227                 }
14228                 break;
14229         case DRM_FORMAT_XBGR8888:
14230         case DRM_FORMAT_XRGB2101010:
14231         case DRM_FORMAT_XBGR2101010:
14232                 if (INTEL_INFO(dev)->gen < 4) {
14233                         DRM_DEBUG("unsupported pixel format: %s\n",
14234                                   drm_get_format_name(mode_cmd->pixel_format));
14235                         return -EINVAL;
14236                 }
14237                 break;
14238         case DRM_FORMAT_ABGR2101010:
14239                 if (!IS_VALLEYVIEW(dev)) {
14240                         DRM_DEBUG("unsupported pixel format: %s\n",
14241                                   drm_get_format_name(mode_cmd->pixel_format));
14242                         return -EINVAL;
14243                 }
14244                 break;
14245         case DRM_FORMAT_YUYV:
14246         case DRM_FORMAT_UYVY:
14247         case DRM_FORMAT_YVYU:
14248         case DRM_FORMAT_VYUY:
14249                 if (INTEL_INFO(dev)->gen < 5) {
14250                         DRM_DEBUG("unsupported pixel format: %s\n",
14251                                   drm_get_format_name(mode_cmd->pixel_format));
14252                         return -EINVAL;
14253                 }
14254                 break;
14255         default:
14256                 DRM_DEBUG("unsupported pixel format: %s\n",
14257                           drm_get_format_name(mode_cmd->pixel_format));
14258                 return -EINVAL;
14259         }
14260
14261         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14262         if (mode_cmd->offsets[0] != 0)
14263                 return -EINVAL;
14264
14265         aligned_height = intel_fb_align_height(dev, mode_cmd->height,
14266                                                mode_cmd->pixel_format,
14267                                                mode_cmd->modifier[0]);
14268         /* FIXME drm helper for size checks (especially planar formats)? */
14269         if (obj->base.size < aligned_height * mode_cmd->pitches[0])
14270                 return -EINVAL;
14271
14272         drm_helper_mode_fill_fb_struct(&intel_fb->base, mode_cmd);
14273         intel_fb->obj = obj;
14274         intel_fb->obj->framebuffer_references++;
14275
14276         ret = drm_framebuffer_init(dev, &intel_fb->base, &intel_fb_funcs);
14277         if (ret) {
14278                 DRM_ERROR("framebuffer init failed %d\n", ret);
14279                 return ret;
14280         }
14281
14282         return 0;
14283 }
14284
14285 static struct drm_framebuffer *
14286 intel_user_framebuffer_create(struct drm_device *dev,
14287                               struct drm_file *filp,
14288                               struct drm_mode_fb_cmd2 *mode_cmd)
14289 {
14290         struct drm_i915_gem_object *obj;
14291
14292         obj = to_intel_bo(drm_gem_object_lookup(dev, filp,
14293                                                 mode_cmd->handles[0]));
14294         if (&obj->base == NULL)
14295                 return ERR_PTR(-ENOENT);
14296
14297         return intel_framebuffer_create(dev, mode_cmd, obj);
14298 }
14299
14300 #ifndef CONFIG_DRM_FBDEV_EMULATION
14301 static inline void intel_fbdev_output_poll_changed(struct drm_device *dev)
14302 {
14303 }
14304 #endif
14305
14306 static const struct drm_mode_config_funcs intel_mode_funcs = {
14307         .fb_create = intel_user_framebuffer_create,
14308         .output_poll_changed = intel_fbdev_output_poll_changed,
14309         .atomic_check = intel_atomic_check,
14310         .atomic_commit = intel_atomic_commit,
14311         .atomic_state_alloc = intel_atomic_state_alloc,
14312         .atomic_state_clear = intel_atomic_state_clear,
14313 };
14314
14315 /* Set up chip specific display functions */
14316 static void intel_init_display(struct drm_device *dev)
14317 {
14318         struct drm_i915_private *dev_priv = dev->dev_private;
14319
14320         if (HAS_PCH_SPLIT(dev) || IS_G4X(dev))
14321                 dev_priv->display.find_dpll = g4x_find_best_dpll;
14322         else if (IS_CHERRYVIEW(dev))
14323                 dev_priv->display.find_dpll = chv_find_best_dpll;
14324         else if (IS_VALLEYVIEW(dev))
14325                 dev_priv->display.find_dpll = vlv_find_best_dpll;
14326         else if (IS_PINEVIEW(dev))
14327                 dev_priv->display.find_dpll = pnv_find_best_dpll;
14328         else
14329                 dev_priv->display.find_dpll = i9xx_find_best_dpll;
14330
14331         if (INTEL_INFO(dev)->gen >= 9) {
14332                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14333                 dev_priv->display.get_initial_plane_config =
14334                         skylake_get_initial_plane_config;
14335                 dev_priv->display.crtc_compute_clock =
14336                         haswell_crtc_compute_clock;
14337                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14338                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14339                 dev_priv->display.update_primary_plane =
14340                         skylake_update_primary_plane;
14341         } else if (HAS_DDI(dev)) {
14342                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14343                 dev_priv->display.get_initial_plane_config =
14344                         ironlake_get_initial_plane_config;
14345                 dev_priv->display.crtc_compute_clock =
14346                         haswell_crtc_compute_clock;
14347                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14348                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14349                 dev_priv->display.update_primary_plane =
14350                         ironlake_update_primary_plane;
14351         } else if (HAS_PCH_SPLIT(dev)) {
14352                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
14353                 dev_priv->display.get_initial_plane_config =
14354                         ironlake_get_initial_plane_config;
14355                 dev_priv->display.crtc_compute_clock =
14356                         ironlake_crtc_compute_clock;
14357                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
14358                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
14359                 dev_priv->display.update_primary_plane =
14360                         ironlake_update_primary_plane;
14361         } else if (IS_VALLEYVIEW(dev)) {
14362                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14363                 dev_priv->display.get_initial_plane_config =
14364                         i9xx_get_initial_plane_config;
14365                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14366                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14367                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14368                 dev_priv->display.update_primary_plane =
14369                         i9xx_update_primary_plane;
14370         } else {
14371                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14372                 dev_priv->display.get_initial_plane_config =
14373                         i9xx_get_initial_plane_config;
14374                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14375                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14376                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14377                 dev_priv->display.update_primary_plane =
14378                         i9xx_update_primary_plane;
14379         }
14380
14381         /* Returns the core display clock speed */
14382         if (IS_SKYLAKE(dev))
14383                 dev_priv->display.get_display_clock_speed =
14384                         skylake_get_display_clock_speed;
14385         else if (IS_BROXTON(dev))
14386                 dev_priv->display.get_display_clock_speed =
14387                         broxton_get_display_clock_speed;
14388         else if (IS_BROADWELL(dev))
14389                 dev_priv->display.get_display_clock_speed =
14390                         broadwell_get_display_clock_speed;
14391         else if (IS_HASWELL(dev))
14392                 dev_priv->display.get_display_clock_speed =
14393                         haswell_get_display_clock_speed;
14394         else if (IS_VALLEYVIEW(dev))
14395                 dev_priv->display.get_display_clock_speed =
14396                         valleyview_get_display_clock_speed;
14397         else if (IS_GEN5(dev))
14398                 dev_priv->display.get_display_clock_speed =
14399                         ilk_get_display_clock_speed;
14400         else if (IS_I945G(dev) || IS_BROADWATER(dev) ||
14401                  IS_GEN6(dev) || IS_IVYBRIDGE(dev))
14402                 dev_priv->display.get_display_clock_speed =
14403                         i945_get_display_clock_speed;
14404         else if (IS_GM45(dev))
14405                 dev_priv->display.get_display_clock_speed =
14406                         gm45_get_display_clock_speed;
14407         else if (IS_CRESTLINE(dev))
14408                 dev_priv->display.get_display_clock_speed =
14409                         i965gm_get_display_clock_speed;
14410         else if (IS_PINEVIEW(dev))
14411                 dev_priv->display.get_display_clock_speed =
14412                         pnv_get_display_clock_speed;
14413         else if (IS_G33(dev) || IS_G4X(dev))
14414                 dev_priv->display.get_display_clock_speed =
14415                         g33_get_display_clock_speed;
14416         else if (IS_I915G(dev))
14417                 dev_priv->display.get_display_clock_speed =
14418                         i915_get_display_clock_speed;
14419         else if (IS_I945GM(dev) || IS_845G(dev))
14420                 dev_priv->display.get_display_clock_speed =
14421                         i9xx_misc_get_display_clock_speed;
14422         else if (IS_PINEVIEW(dev))
14423                 dev_priv->display.get_display_clock_speed =
14424                         pnv_get_display_clock_speed;
14425         else if (IS_I915GM(dev))
14426                 dev_priv->display.get_display_clock_speed =
14427                         i915gm_get_display_clock_speed;
14428         else if (IS_I865G(dev))
14429                 dev_priv->display.get_display_clock_speed =
14430                         i865_get_display_clock_speed;
14431         else if (IS_I85X(dev))
14432                 dev_priv->display.get_display_clock_speed =
14433                         i85x_get_display_clock_speed;
14434         else { /* 830 */
14435                 WARN(!IS_I830(dev), "Unknown platform. Assuming 133 MHz CDCLK\n");
14436                 dev_priv->display.get_display_clock_speed =
14437                         i830_get_display_clock_speed;
14438         }
14439
14440         if (IS_GEN5(dev)) {
14441                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
14442         } else if (IS_GEN6(dev)) {
14443                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
14444         } else if (IS_IVYBRIDGE(dev)) {
14445                 /* FIXME: detect B0+ stepping and use auto training */
14446                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
14447         } else if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
14448                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
14449                 if (IS_BROADWELL(dev)) {
14450                         dev_priv->display.modeset_commit_cdclk =
14451                                 broadwell_modeset_commit_cdclk;
14452                         dev_priv->display.modeset_calc_cdclk =
14453                                 broadwell_modeset_calc_cdclk;
14454                 }
14455         } else if (IS_VALLEYVIEW(dev)) {
14456                 dev_priv->display.modeset_commit_cdclk =
14457                         valleyview_modeset_commit_cdclk;
14458                 dev_priv->display.modeset_calc_cdclk =
14459                         valleyview_modeset_calc_cdclk;
14460         } else if (IS_BROXTON(dev)) {
14461                 dev_priv->display.modeset_commit_cdclk =
14462                         broxton_modeset_commit_cdclk;
14463                 dev_priv->display.modeset_calc_cdclk =
14464                         broxton_modeset_calc_cdclk;
14465         }
14466
14467         switch (INTEL_INFO(dev)->gen) {
14468         case 2:
14469                 dev_priv->display.queue_flip = intel_gen2_queue_flip;
14470                 break;
14471
14472         case 3:
14473                 dev_priv->display.queue_flip = intel_gen3_queue_flip;
14474                 break;
14475
14476         case 4:
14477         case 5:
14478                 dev_priv->display.queue_flip = intel_gen4_queue_flip;
14479                 break;
14480
14481         case 6:
14482                 dev_priv->display.queue_flip = intel_gen6_queue_flip;
14483                 break;
14484         case 7:
14485         case 8: /* FIXME(BDW): Check that the gen8 RCS flip works. */
14486                 dev_priv->display.queue_flip = intel_gen7_queue_flip;
14487                 break;
14488         case 9:
14489                 /* Drop through - unsupported since execlist only. */
14490         default:
14491                 /* Default just returns -ENODEV to indicate unsupported */
14492                 dev_priv->display.queue_flip = intel_default_queue_flip;
14493         }
14494
14495         intel_panel_init_backlight_funcs(dev);
14496
14497         mutex_init(&dev_priv->pps_mutex);
14498 }
14499
14500 /*
14501  * Some BIOSes insist on assuming the GPU's pipe A is enabled at suspend,
14502  * resume, or other times.  This quirk makes sure that's the case for
14503  * affected systems.
14504  */
14505 static void quirk_pipea_force(struct drm_device *dev)
14506 {
14507         struct drm_i915_private *dev_priv = dev->dev_private;
14508
14509         dev_priv->quirks |= QUIRK_PIPEA_FORCE;
14510         DRM_INFO("applying pipe a force quirk\n");
14511 }
14512
14513 static void quirk_pipeb_force(struct drm_device *dev)
14514 {
14515         struct drm_i915_private *dev_priv = dev->dev_private;
14516
14517         dev_priv->quirks |= QUIRK_PIPEB_FORCE;
14518         DRM_INFO("applying pipe b force quirk\n");
14519 }
14520
14521 /*
14522  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
14523  */
14524 static void quirk_ssc_force_disable(struct drm_device *dev)
14525 {
14526         struct drm_i915_private *dev_priv = dev->dev_private;
14527         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
14528         DRM_INFO("applying lvds SSC disable quirk\n");
14529 }
14530
14531 /*
14532  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
14533  * brightness value
14534  */
14535 static void quirk_invert_brightness(struct drm_device *dev)
14536 {
14537         struct drm_i915_private *dev_priv = dev->dev_private;
14538         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
14539         DRM_INFO("applying inverted panel brightness quirk\n");
14540 }
14541
14542 /* Some VBT's incorrectly indicate no backlight is present */
14543 static void quirk_backlight_present(struct drm_device *dev)
14544 {
14545         struct drm_i915_private *dev_priv = dev->dev_private;
14546         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
14547         DRM_INFO("applying backlight present quirk\n");
14548 }
14549
14550 struct intel_quirk {
14551         int device;
14552         int subsystem_vendor;
14553         int subsystem_device;
14554         void (*hook)(struct drm_device *dev);
14555 };
14556
14557 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
14558 struct intel_dmi_quirk {
14559         void (*hook)(struct drm_device *dev);
14560         const struct dmi_system_id (*dmi_id_list)[];
14561 };
14562
14563 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
14564 {
14565         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
14566         return 1;
14567 }
14568
14569 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
14570         {
14571                 .dmi_id_list = &(const struct dmi_system_id[]) {
14572                         {
14573                                 .callback = intel_dmi_reverse_brightness,
14574                                 .ident = "NCR Corporation",
14575                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
14576                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
14577                                 },
14578                         },
14579                         { }  /* terminating entry */
14580                 },
14581                 .hook = quirk_invert_brightness,
14582         },
14583 };
14584
14585 static struct intel_quirk intel_quirks[] = {
14586         /* Toshiba Protege R-205, S-209 needs pipe A force quirk */
14587         { 0x2592, 0x1179, 0x0001, quirk_pipea_force },
14588
14589         /* ThinkPad T60 needs pipe A force quirk (bug #16494) */
14590         { 0x2782, 0x17aa, 0x201a, quirk_pipea_force },
14591
14592         /* 830 needs to leave pipe A & dpll A up */
14593         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipea_force },
14594
14595         /* 830 needs to leave pipe B & dpll B up */
14596         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipeb_force },
14597
14598         /* Lenovo U160 cannot use SSC on LVDS */
14599         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
14600
14601         /* Sony Vaio Y cannot use SSC on LVDS */
14602         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
14603
14604         /* Acer Aspire 5734Z must invert backlight brightness */
14605         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
14606
14607         /* Acer/eMachines G725 */
14608         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
14609
14610         /* Acer/eMachines e725 */
14611         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
14612
14613         /* Acer/Packard Bell NCL20 */
14614         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
14615
14616         /* Acer Aspire 4736Z */
14617         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
14618
14619         /* Acer Aspire 5336 */
14620         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
14621
14622         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
14623         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
14624
14625         /* Acer C720 Chromebook (Core i3 4005U) */
14626         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
14627
14628         /* Apple Macbook 2,1 (Core 2 T7400) */
14629         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
14630
14631         /* Toshiba CB35 Chromebook (Celeron 2955U) */
14632         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
14633
14634         /* HP Chromebook 14 (Celeron 2955U) */
14635         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
14636
14637         /* Dell Chromebook 11 */
14638         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
14639 };
14640
14641 static void intel_init_quirks(struct drm_device *dev)
14642 {
14643         struct pci_dev *d = dev->pdev;
14644         int i;
14645
14646         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
14647                 struct intel_quirk *q = &intel_quirks[i];
14648
14649                 if (d->device == q->device &&
14650                     (d->subsystem_vendor == q->subsystem_vendor ||
14651                      q->subsystem_vendor == PCI_ANY_ID) &&
14652                     (d->subsystem_device == q->subsystem_device ||
14653                      q->subsystem_device == PCI_ANY_ID))
14654                         q->hook(dev);
14655         }
14656         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
14657                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
14658                         intel_dmi_quirks[i].hook(dev);
14659         }
14660 }
14661
14662 /* Disable the VGA plane that we never use */
14663 static void i915_disable_vga(struct drm_device *dev)
14664 {
14665         struct drm_i915_private *dev_priv = dev->dev_private;
14666         u8 sr1;
14667         u32 vga_reg = i915_vgacntrl_reg(dev);
14668
14669         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
14670         vga_get_uninterruptible(dev->pdev, VGA_RSRC_LEGACY_IO);
14671         outb(SR01, VGA_SR_INDEX);
14672         sr1 = inb(VGA_SR_DATA);
14673         outb(sr1 | 1<<5, VGA_SR_DATA);
14674         vga_put(dev->pdev, VGA_RSRC_LEGACY_IO);
14675         udelay(300);
14676
14677         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
14678         POSTING_READ(vga_reg);
14679 }
14680
14681 void intel_modeset_init_hw(struct drm_device *dev)
14682 {
14683         intel_update_cdclk(dev);
14684         intel_prepare_ddi(dev);
14685         intel_init_clock_gating(dev);
14686         intel_enable_gt_powersave(dev);
14687 }
14688
14689 void intel_modeset_init(struct drm_device *dev)
14690 {
14691         struct drm_i915_private *dev_priv = dev->dev_private;
14692         int sprite, ret;
14693         enum pipe pipe;
14694         struct intel_crtc *crtc;
14695
14696         drm_mode_config_init(dev);
14697
14698         dev->mode_config.min_width = 0;
14699         dev->mode_config.min_height = 0;
14700
14701         dev->mode_config.preferred_depth = 24;
14702         dev->mode_config.prefer_shadow = 1;
14703
14704         dev->mode_config.allow_fb_modifiers = true;
14705
14706         dev->mode_config.funcs = &intel_mode_funcs;
14707
14708         intel_init_quirks(dev);
14709
14710         intel_init_pm(dev);
14711
14712         if (INTEL_INFO(dev)->num_pipes == 0)
14713                 return;
14714
14715         /*
14716          * There may be no VBT; and if the BIOS enabled SSC we can
14717          * just keep using it to avoid unnecessary flicker.  Whereas if the
14718          * BIOS isn't using it, don't assume it will work even if the VBT
14719          * indicates as much.
14720          */
14721         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev)) {
14722                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
14723                                             DREF_SSC1_ENABLE);
14724
14725                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
14726                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
14727                                      bios_lvds_use_ssc ? "en" : "dis",
14728                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
14729                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
14730                 }
14731         }
14732
14733         intel_init_display(dev);
14734         intel_init_audio(dev);
14735
14736         if (IS_GEN2(dev)) {
14737                 dev->mode_config.max_width = 2048;
14738                 dev->mode_config.max_height = 2048;
14739         } else if (IS_GEN3(dev)) {
14740                 dev->mode_config.max_width = 4096;
14741                 dev->mode_config.max_height = 4096;
14742         } else {
14743                 dev->mode_config.max_width = 8192;
14744                 dev->mode_config.max_height = 8192;
14745         }
14746
14747         if (IS_845G(dev) || IS_I865G(dev)) {
14748                 dev->mode_config.cursor_width = IS_845G(dev) ? 64 : 512;
14749                 dev->mode_config.cursor_height = 1023;
14750         } else if (IS_GEN2(dev)) {
14751                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
14752                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
14753         } else {
14754                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
14755                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
14756         }
14757
14758         dev->mode_config.fb_base = dev_priv->gtt.mappable_base;
14759
14760         DRM_DEBUG_KMS("%d display pipe%s available.\n",
14761                       INTEL_INFO(dev)->num_pipes,
14762                       INTEL_INFO(dev)->num_pipes > 1 ? "s" : "");
14763
14764         for_each_pipe(dev_priv, pipe) {
14765                 intel_crtc_init(dev, pipe);
14766                 for_each_sprite(dev_priv, pipe, sprite) {
14767                         ret = intel_plane_init(dev, pipe, sprite);
14768                         if (ret)
14769                                 DRM_DEBUG_KMS("pipe %c sprite %c init failed: %d\n",
14770                                               pipe_name(pipe), sprite_name(pipe, sprite), ret);
14771                 }
14772         }
14773
14774         intel_shared_dpll_init(dev);
14775
14776         /* Just disable it once at startup */
14777         i915_disable_vga(dev);
14778         intel_setup_outputs(dev);
14779
14780         /* Just in case the BIOS is doing something questionable. */
14781         intel_fbc_disable(dev_priv);
14782
14783         drm_modeset_lock_all(dev);
14784         intel_modeset_setup_hw_state(dev);
14785         drm_modeset_unlock_all(dev);
14786
14787         for_each_intel_crtc(dev, crtc) {
14788                 struct intel_initial_plane_config plane_config = {};
14789
14790                 if (!crtc->active)
14791                         continue;
14792
14793                 /*
14794                  * Note that reserving the BIOS fb up front prevents us
14795                  * from stuffing other stolen allocations like the ring
14796                  * on top.  This prevents some ugliness at boot time, and
14797                  * can even allow for smooth boot transitions if the BIOS
14798                  * fb is large enough for the active pipe configuration.
14799                  */
14800                 dev_priv->display.get_initial_plane_config(crtc,
14801                                                            &plane_config);
14802
14803                 /*
14804                  * If the fb is shared between multiple heads, we'll
14805                  * just get the first one.
14806                  */
14807                 intel_find_initial_plane_obj(crtc, &plane_config);
14808         }
14809 }
14810
14811 static void intel_enable_pipe_a(struct drm_device *dev)
14812 {
14813         struct intel_connector *connector;
14814         struct drm_connector *crt = NULL;
14815         struct intel_load_detect_pipe load_detect_temp;
14816         struct drm_modeset_acquire_ctx *ctx = dev->mode_config.acquire_ctx;
14817
14818         /* We can't just switch on the pipe A, we need to set things up with a
14819          * proper mode and output configuration. As a gross hack, enable pipe A
14820          * by enabling the load detect pipe once. */
14821         for_each_intel_connector(dev, connector) {
14822                 if (connector->encoder->type == INTEL_OUTPUT_ANALOG) {
14823                         crt = &connector->base;
14824                         break;
14825                 }
14826         }
14827
14828         if (!crt)
14829                 return;
14830
14831         if (intel_get_load_detect_pipe(crt, NULL, &load_detect_temp, ctx))
14832                 intel_release_load_detect_pipe(crt, &load_detect_temp, ctx);
14833 }
14834
14835 static bool
14836 intel_check_plane_mapping(struct intel_crtc *crtc)
14837 {
14838         struct drm_device *dev = crtc->base.dev;
14839         struct drm_i915_private *dev_priv = dev->dev_private;
14840         u32 reg, val;
14841
14842         if (INTEL_INFO(dev)->num_pipes == 1)
14843                 return true;
14844
14845         reg = DSPCNTR(!crtc->plane);
14846         val = I915_READ(reg);
14847
14848         if ((val & DISPLAY_PLANE_ENABLE) &&
14849             (!!(val & DISPPLANE_SEL_PIPE_MASK) == crtc->pipe))
14850                 return false;
14851
14852         return true;
14853 }
14854
14855 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
14856 {
14857         struct drm_device *dev = crtc->base.dev;
14858         struct intel_encoder *encoder;
14859
14860         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
14861                 return true;
14862
14863         return false;
14864 }
14865
14866 static void intel_sanitize_crtc(struct intel_crtc *crtc)
14867 {
14868         struct drm_device *dev = crtc->base.dev;
14869         struct drm_i915_private *dev_priv = dev->dev_private;
14870         u32 reg;
14871
14872         /* Clear any frame start delays used for debugging left by the BIOS */
14873         reg = PIPECONF(crtc->config->cpu_transcoder);
14874         I915_WRITE(reg, I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
14875
14876         /* restore vblank interrupts to correct state */
14877         drm_crtc_vblank_reset(&crtc->base);
14878         if (crtc->active) {
14879                 drm_calc_timestamping_constants(&crtc->base, &crtc->base.hwmode);
14880                 update_scanline_offset(crtc);
14881                 drm_crtc_vblank_on(&crtc->base);
14882         }
14883
14884         /* We need to sanitize the plane -> pipe mapping first because this will
14885          * disable the crtc (and hence change the state) if it is wrong. Note
14886          * that gen4+ has a fixed plane -> pipe mapping.  */
14887         if (INTEL_INFO(dev)->gen < 4 && !intel_check_plane_mapping(crtc)) {
14888                 bool plane;
14889
14890                 DRM_DEBUG_KMS("[CRTC:%d] wrong plane connection detected!\n",
14891                               crtc->base.base.id);
14892
14893                 /* Pipe has the wrong plane attached and the plane is active.
14894                  * Temporarily change the plane mapping and disable everything
14895                  * ...  */
14896                 plane = crtc->plane;
14897                 to_intel_plane_state(crtc->base.primary->state)->visible = true;
14898                 crtc->plane = !plane;
14899                 intel_crtc_disable_noatomic(&crtc->base);
14900                 crtc->plane = plane;
14901         }
14902
14903         if (dev_priv->quirks & QUIRK_PIPEA_FORCE &&
14904             crtc->pipe == PIPE_A && !crtc->active) {
14905                 /* BIOS forgot to enable pipe A, this mostly happens after
14906                  * resume. Force-enable the pipe to fix this, the update_dpms
14907                  * call below we restore the pipe to the right state, but leave
14908                  * the required bits on. */
14909                 intel_enable_pipe_a(dev);
14910         }
14911
14912         /* Adjust the state of the output pipe according to whether we
14913          * have active connectors/encoders. */
14914         if (!intel_crtc_has_encoders(crtc))
14915                 intel_crtc_disable_noatomic(&crtc->base);
14916
14917         if (crtc->active != crtc->base.state->active) {
14918                 struct intel_encoder *encoder;
14919
14920                 /* This can happen either due to bugs in the get_hw_state
14921                  * functions or because of calls to intel_crtc_disable_noatomic,
14922                  * or because the pipe is force-enabled due to the
14923                  * pipe A quirk. */
14924                 DRM_DEBUG_KMS("[CRTC:%d] hw state adjusted, was %s, now %s\n",
14925                               crtc->base.base.id,
14926                               crtc->base.state->enable ? "enabled" : "disabled",
14927                               crtc->active ? "enabled" : "disabled");
14928
14929                 WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, NULL) < 0);
14930                 crtc->base.state->active = crtc->active;
14931                 crtc->base.enabled = crtc->active;
14932
14933                 /* Because we only establish the connector -> encoder ->
14934                  * crtc links if something is active, this means the
14935                  * crtc is now deactivated. Break the links. connector
14936                  * -> encoder links are only establish when things are
14937                  *  actually up, hence no need to break them. */
14938                 WARN_ON(crtc->active);
14939
14940                 for_each_encoder_on_crtc(dev, &crtc->base, encoder)
14941                         encoder->base.crtc = NULL;
14942         }
14943
14944         if (crtc->active || HAS_GMCH_DISPLAY(dev)) {
14945                 /*
14946                  * We start out with underrun reporting disabled to avoid races.
14947                  * For correct bookkeeping mark this on active crtcs.
14948                  *
14949                  * Also on gmch platforms we dont have any hardware bits to
14950                  * disable the underrun reporting. Which means we need to start
14951                  * out with underrun reporting disabled also on inactive pipes,
14952                  * since otherwise we'll complain about the garbage we read when
14953                  * e.g. coming up after runtime pm.
14954                  *
14955                  * No protection against concurrent access is required - at
14956                  * worst a fifo underrun happens which also sets this to false.
14957                  */
14958                 crtc->cpu_fifo_underrun_disabled = true;
14959                 crtc->pch_fifo_underrun_disabled = true;
14960         }
14961 }
14962
14963 static void intel_sanitize_encoder(struct intel_encoder *encoder)
14964 {
14965         struct intel_connector *connector;
14966         struct drm_device *dev = encoder->base.dev;
14967         bool active = false;
14968
14969         /* We need to check both for a crtc link (meaning that the
14970          * encoder is active and trying to read from a pipe) and the
14971          * pipe itself being active. */
14972         bool has_active_crtc = encoder->base.crtc &&
14973                 to_intel_crtc(encoder->base.crtc)->active;
14974
14975         for_each_intel_connector(dev, connector) {
14976                 if (connector->base.encoder != &encoder->base)
14977                         continue;
14978
14979                 active = true;
14980                 break;
14981         }
14982
14983         if (active && !has_active_crtc) {
14984                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
14985                               encoder->base.base.id,
14986                               encoder->base.name);
14987
14988                 /* Connector is active, but has no active pipe. This is
14989                  * fallout from our resume register restoring. Disable
14990                  * the encoder manually again. */
14991                 if (encoder->base.crtc) {
14992                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
14993                                       encoder->base.base.id,
14994                                       encoder->base.name);
14995                         encoder->disable(encoder);
14996                         if (encoder->post_disable)
14997                                 encoder->post_disable(encoder);
14998                 }
14999                 encoder->base.crtc = NULL;
15000
15001                 /* Inconsistent output/port/pipe state happens presumably due to
15002                  * a bug in one of the get_hw_state functions. Or someplace else
15003                  * in our code, like the register restore mess on resume. Clamp
15004                  * things to off as a safer default. */
15005                 for_each_intel_connector(dev, connector) {
15006                         if (connector->encoder != encoder)
15007                                 continue;
15008                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15009                         connector->base.encoder = NULL;
15010                 }
15011         }
15012         /* Enabled encoders without active connectors will be fixed in
15013          * the crtc fixup. */
15014 }
15015
15016 void i915_redisable_vga_power_on(struct drm_device *dev)
15017 {
15018         struct drm_i915_private *dev_priv = dev->dev_private;
15019         u32 vga_reg = i915_vgacntrl_reg(dev);
15020
15021         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
15022                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
15023                 i915_disable_vga(dev);
15024         }
15025 }
15026
15027 void i915_redisable_vga(struct drm_device *dev)
15028 {
15029         struct drm_i915_private *dev_priv = dev->dev_private;
15030
15031         /* This function can be called both from intel_modeset_setup_hw_state or
15032          * at a very early point in our resume sequence, where the power well
15033          * structures are not yet restored. Since this function is at a very
15034          * paranoid "someone might have enabled VGA while we were not looking"
15035          * level, just check if the power well is enabled instead of trying to
15036          * follow the "don't touch the power well if we don't need it" policy
15037          * the rest of the driver uses. */
15038         if (!intel_display_power_is_enabled(dev_priv, POWER_DOMAIN_VGA))
15039                 return;
15040
15041         i915_redisable_vga_power_on(dev);
15042 }
15043
15044 static bool primary_get_hw_state(struct intel_crtc *crtc)
15045 {
15046         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
15047
15048         return !!(I915_READ(DSPCNTR(crtc->plane)) & DISPLAY_PLANE_ENABLE);
15049 }
15050
15051 static void readout_plane_state(struct intel_crtc *crtc,
15052                                 struct intel_crtc_state *crtc_state)
15053 {
15054         struct intel_plane *p;
15055         struct intel_plane_state *plane_state;
15056         bool active = crtc_state->base.active;
15057
15058         for_each_intel_plane(crtc->base.dev, p) {
15059                 if (crtc->pipe != p->pipe)
15060                         continue;
15061
15062                 plane_state = to_intel_plane_state(p->base.state);
15063
15064                 if (p->base.type == DRM_PLANE_TYPE_PRIMARY) {
15065                         plane_state->visible = primary_get_hw_state(crtc);
15066                         if (plane_state->visible)
15067                                 crtc->base.state->plane_mask |=
15068                                         1 << drm_plane_index(&p->base);
15069                 } else {
15070                         if (active)
15071                                 p->disable_plane(&p->base, &crtc->base);
15072
15073                         plane_state->visible = false;
15074                 }
15075         }
15076 }
15077
15078 static void intel_modeset_readout_hw_state(struct drm_device *dev)
15079 {
15080         struct drm_i915_private *dev_priv = dev->dev_private;
15081         enum pipe pipe;
15082         struct intel_crtc *crtc;
15083         struct intel_encoder *encoder;
15084         struct intel_connector *connector;
15085         int i;
15086
15087         for_each_intel_crtc(dev, crtc) {
15088                 __drm_atomic_helper_crtc_destroy_state(&crtc->base, crtc->base.state);
15089                 memset(crtc->config, 0, sizeof(*crtc->config));
15090                 crtc->config->base.crtc = &crtc->base;
15091
15092                 crtc->active = dev_priv->display.get_pipe_config(crtc,
15093                                                                  crtc->config);
15094
15095                 crtc->base.state->active = crtc->active;
15096                 crtc->base.enabled = crtc->active;
15097
15098                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
15099                 if (crtc->base.state->active) {
15100                         intel_mode_from_pipe_config(&crtc->base.mode, crtc->config);
15101                         intel_mode_from_pipe_config(&crtc->base.state->adjusted_mode, crtc->config);
15102                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
15103
15104                         /*
15105                          * The initial mode needs to be set in order to keep
15106                          * the atomic core happy. It wants a valid mode if the
15107                          * crtc's enabled, so we do the above call.
15108                          *
15109                          * At this point some state updated by the connectors
15110                          * in their ->detect() callback has not run yet, so
15111                          * no recalculation can be done yet.
15112                          *
15113                          * Even if we could do a recalculation and modeset
15114                          * right now it would cause a double modeset if
15115                          * fbdev or userspace chooses a different initial mode.
15116                          *
15117                          * If that happens, someone indicated they wanted a
15118                          * mode change, which means it's safe to do a full
15119                          * recalculation.
15120                          */
15121                         crtc->base.state->mode.private_flags = I915_MODE_FLAG_INHERITED;
15122                 }
15123
15124                 crtc->base.hwmode = crtc->config->base.adjusted_mode;
15125                 readout_plane_state(crtc, to_intel_crtc_state(crtc->base.state));
15126
15127                 DRM_DEBUG_KMS("[CRTC:%d] hw state readout: %s\n",
15128                               crtc->base.base.id,
15129                               crtc->active ? "enabled" : "disabled");
15130         }
15131
15132         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15133                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15134
15135                 pll->on = pll->get_hw_state(dev_priv, pll,
15136                                             &pll->config.hw_state);
15137                 pll->active = 0;
15138                 pll->config.crtc_mask = 0;
15139                 for_each_intel_crtc(dev, crtc) {
15140                         if (crtc->active && intel_crtc_to_shared_dpll(crtc) == pll) {
15141                                 pll->active++;
15142                                 pll->config.crtc_mask |= 1 << crtc->pipe;
15143                         }
15144                 }
15145
15146                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15147                               pll->name, pll->config.crtc_mask, pll->on);
15148
15149                 if (pll->config.crtc_mask)
15150                         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
15151         }
15152
15153         for_each_intel_encoder(dev, encoder) {
15154                 pipe = 0;
15155
15156                 if (encoder->get_hw_state(encoder, &pipe)) {
15157                         crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
15158                         encoder->base.crtc = &crtc->base;
15159                         encoder->get_config(encoder, crtc->config);
15160                 } else {
15161                         encoder->base.crtc = NULL;
15162                 }
15163
15164                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
15165                               encoder->base.base.id,
15166                               encoder->base.name,
15167                               encoder->base.crtc ? "enabled" : "disabled",
15168                               pipe_name(pipe));
15169         }
15170
15171         for_each_intel_connector(dev, connector) {
15172                 if (connector->get_hw_state(connector)) {
15173                         connector->base.dpms = DRM_MODE_DPMS_ON;
15174                         connector->base.encoder = &connector->encoder->base;
15175                 } else {
15176                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15177                         connector->base.encoder = NULL;
15178                 }
15179                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
15180                               connector->base.base.id,
15181                               connector->base.name,
15182                               connector->base.encoder ? "enabled" : "disabled");
15183         }
15184 }
15185
15186 /* Scan out the current hw modeset state,
15187  * and sanitizes it to the current state
15188  */
15189 static void
15190 intel_modeset_setup_hw_state(struct drm_device *dev)
15191 {
15192         struct drm_i915_private *dev_priv = dev->dev_private;
15193         enum pipe pipe;
15194         struct intel_crtc *crtc;
15195         struct intel_encoder *encoder;
15196         int i;
15197
15198         intel_modeset_readout_hw_state(dev);
15199
15200         /* HW state is read out, now we need to sanitize this mess. */
15201         for_each_intel_encoder(dev, encoder) {
15202                 intel_sanitize_encoder(encoder);
15203         }
15204
15205         for_each_pipe(dev_priv, pipe) {
15206                 crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
15207                 intel_sanitize_crtc(crtc);
15208                 intel_dump_pipe_config(crtc, crtc->config,
15209                                        "[setup_hw_state]");
15210         }
15211
15212         intel_modeset_update_connector_atomic_state(dev);
15213
15214         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15215                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15216
15217                 if (!pll->on || pll->active)
15218                         continue;
15219
15220                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
15221
15222                 pll->disable(dev_priv, pll);
15223                 pll->on = false;
15224         }
15225
15226         if (IS_VALLEYVIEW(dev))
15227                 vlv_wm_get_hw_state(dev);
15228         else if (IS_GEN9(dev))
15229                 skl_wm_get_hw_state(dev);
15230         else if (HAS_PCH_SPLIT(dev))
15231                 ilk_wm_get_hw_state(dev);
15232
15233         for_each_intel_crtc(dev, crtc) {
15234                 unsigned long put_domains;
15235
15236                 put_domains = modeset_get_crtc_power_domains(&crtc->base);
15237                 if (WARN_ON(put_domains))
15238                         modeset_put_power_domains(dev_priv, put_domains);
15239         }
15240         intel_display_set_init_power(dev_priv, false);
15241 }
15242
15243 void intel_display_resume(struct drm_device *dev)
15244 {
15245         struct drm_atomic_state *state = drm_atomic_state_alloc(dev);
15246         struct intel_connector *conn;
15247         struct intel_plane *plane;
15248         struct drm_crtc *crtc;
15249         int ret;
15250
15251         if (!state)
15252                 return;
15253
15254         state->acquire_ctx = dev->mode_config.acquire_ctx;
15255
15256         /* preserve complete old state, including dpll */
15257         intel_atomic_get_shared_dpll_state(state);
15258
15259         for_each_crtc(dev, crtc) {
15260                 struct drm_crtc_state *crtc_state =
15261                         drm_atomic_get_crtc_state(state, crtc);
15262
15263                 ret = PTR_ERR_OR_ZERO(crtc_state);
15264                 if (ret)
15265                         goto err;
15266
15267                 /* force a restore */
15268                 crtc_state->mode_changed = true;
15269         }
15270
15271         for_each_intel_plane(dev, plane) {
15272                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_plane_state(state, &plane->base));
15273                 if (ret)
15274                         goto err;
15275         }
15276
15277         for_each_intel_connector(dev, conn) {
15278                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(state, &conn->base));
15279                 if (ret)
15280                         goto err;
15281         }
15282
15283         intel_modeset_setup_hw_state(dev);
15284
15285         i915_redisable_vga(dev);
15286         ret = drm_atomic_commit(state);
15287         if (!ret)
15288                 return;
15289
15290 err:
15291         DRM_ERROR("Restoring old state failed with %i\n", ret);
15292         drm_atomic_state_free(state);
15293 }
15294
15295 void intel_modeset_gem_init(struct drm_device *dev)
15296 {
15297         struct drm_crtc *c;
15298         struct drm_i915_gem_object *obj;
15299         int ret;
15300
15301         mutex_lock(&dev->struct_mutex);
15302         intel_init_gt_powersave(dev);
15303         mutex_unlock(&dev->struct_mutex);
15304
15305         intel_modeset_init_hw(dev);
15306
15307         intel_setup_overlay(dev);
15308
15309         /*
15310          * Make sure any fbs we allocated at startup are properly
15311          * pinned & fenced.  When we do the allocation it's too early
15312          * for this.
15313          */
15314         for_each_crtc(dev, c) {
15315                 obj = intel_fb_obj(c->primary->fb);
15316                 if (obj == NULL)
15317                         continue;
15318
15319                 mutex_lock(&dev->struct_mutex);
15320                 ret = intel_pin_and_fence_fb_obj(c->primary,
15321                                                  c->primary->fb,
15322                                                  c->primary->state,
15323                                                  NULL, NULL);
15324                 mutex_unlock(&dev->struct_mutex);
15325                 if (ret) {
15326                         DRM_ERROR("failed to pin boot fb on pipe %d\n",
15327                                   to_intel_crtc(c)->pipe);
15328                         drm_framebuffer_unreference(c->primary->fb);
15329                         c->primary->fb = NULL;
15330                         c->primary->crtc = c->primary->state->crtc = NULL;
15331                         update_state_fb(c->primary);
15332                         c->state->plane_mask &= ~(1 << drm_plane_index(c->primary));
15333                 }
15334         }
15335
15336         intel_backlight_register(dev);
15337 }
15338
15339 void intel_connector_unregister(struct intel_connector *intel_connector)
15340 {
15341         struct drm_connector *connector = &intel_connector->base;
15342
15343         intel_panel_destroy_backlight(connector);
15344         drm_connector_unregister(connector);
15345 }
15346
15347 void intel_modeset_cleanup(struct drm_device *dev)
15348 {
15349         struct drm_i915_private *dev_priv = dev->dev_private;
15350         struct drm_connector *connector;
15351
15352         intel_disable_gt_powersave(dev);
15353
15354         intel_backlight_unregister(dev);
15355
15356         /*
15357          * Interrupts and polling as the first thing to avoid creating havoc.
15358          * Too much stuff here (turning of connectors, ...) would
15359          * experience fancy races otherwise.
15360          */
15361         intel_irq_uninstall(dev_priv);
15362
15363         /*
15364          * Due to the hpd irq storm handling the hotplug work can re-arm the
15365          * poll handlers. Hence disable polling after hpd handling is shut down.
15366          */
15367         drm_kms_helper_poll_fini(dev);
15368
15369         intel_unregister_dsm_handler();
15370
15371         intel_fbc_disable(dev_priv);
15372
15373         /* flush any delayed tasks or pending work */
15374         flush_scheduled_work();
15375
15376         /* destroy the backlight and sysfs files before encoders/connectors */
15377         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
15378                 struct intel_connector *intel_connector;
15379
15380                 intel_connector = to_intel_connector(connector);
15381                 intel_connector->unregister(intel_connector);
15382         }
15383
15384         drm_mode_config_cleanup(dev);
15385
15386         intel_cleanup_overlay(dev);
15387
15388         mutex_lock(&dev->struct_mutex);
15389         intel_cleanup_gt_powersave(dev);
15390         mutex_unlock(&dev->struct_mutex);
15391 }
15392
15393 /*
15394  * Return which encoder is currently attached for connector.
15395  */
15396 struct drm_encoder *intel_best_encoder(struct drm_connector *connector)
15397 {
15398         return &intel_attached_encoder(connector)->base;
15399 }
15400
15401 void intel_connector_attach_encoder(struct intel_connector *connector,
15402                                     struct intel_encoder *encoder)
15403 {
15404         connector->encoder = encoder;
15405         drm_mode_connector_attach_encoder(&connector->base,
15406                                           &encoder->base);
15407 }
15408
15409 /*
15410  * set vga decode state - true == enable VGA decode
15411  */
15412 int intel_modeset_vga_set_state(struct drm_device *dev, bool state)
15413 {
15414         struct drm_i915_private *dev_priv = dev->dev_private;
15415         unsigned reg = INTEL_INFO(dev)->gen >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
15416         u16 gmch_ctrl;
15417
15418         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
15419                 DRM_ERROR("failed to read control word\n");
15420                 return -EIO;
15421         }
15422
15423         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
15424                 return 0;
15425
15426         if (state)
15427                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
15428         else
15429                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
15430
15431         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
15432                 DRM_ERROR("failed to write control word\n");
15433                 return -EIO;
15434         }
15435
15436         return 0;
15437 }
15438
15439 struct intel_display_error_state {
15440
15441         u32 power_well_driver;
15442
15443         int num_transcoders;
15444
15445         struct intel_cursor_error_state {
15446                 u32 control;
15447                 u32 position;
15448                 u32 base;
15449                 u32 size;
15450         } cursor[I915_MAX_PIPES];
15451
15452         struct intel_pipe_error_state {
15453                 bool power_domain_on;
15454                 u32 source;
15455                 u32 stat;
15456         } pipe[I915_MAX_PIPES];
15457
15458         struct intel_plane_error_state {
15459                 u32 control;
15460                 u32 stride;
15461                 u32 size;
15462                 u32 pos;
15463                 u32 addr;
15464                 u32 surface;
15465                 u32 tile_offset;
15466         } plane[I915_MAX_PIPES];
15467
15468         struct intel_transcoder_error_state {
15469                 bool power_domain_on;
15470                 enum transcoder cpu_transcoder;
15471
15472                 u32 conf;
15473
15474                 u32 htotal;
15475                 u32 hblank;
15476                 u32 hsync;
15477                 u32 vtotal;
15478                 u32 vblank;
15479                 u32 vsync;
15480         } transcoder[4];
15481 };
15482
15483 struct intel_display_error_state *
15484 intel_display_capture_error_state(struct drm_device *dev)
15485 {
15486         struct drm_i915_private *dev_priv = dev->dev_private;
15487         struct intel_display_error_state *error;
15488         int transcoders[] = {
15489                 TRANSCODER_A,
15490                 TRANSCODER_B,
15491                 TRANSCODER_C,
15492                 TRANSCODER_EDP,
15493         };
15494         int i;
15495
15496         if (INTEL_INFO(dev)->num_pipes == 0)
15497                 return NULL;
15498
15499         error = kzalloc(sizeof(*error), GFP_ATOMIC);
15500         if (error == NULL)
15501                 return NULL;
15502
15503         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
15504                 error->power_well_driver = I915_READ(HSW_PWR_WELL_DRIVER);
15505
15506         for_each_pipe(dev_priv, i) {
15507                 error->pipe[i].power_domain_on =
15508                         __intel_display_power_is_enabled(dev_priv,
15509                                                          POWER_DOMAIN_PIPE(i));
15510                 if (!error->pipe[i].power_domain_on)
15511                         continue;
15512
15513                 error->cursor[i].control = I915_READ(CURCNTR(i));
15514                 error->cursor[i].position = I915_READ(CURPOS(i));
15515                 error->cursor[i].base = I915_READ(CURBASE(i));
15516
15517                 error->plane[i].control = I915_READ(DSPCNTR(i));
15518                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
15519                 if (INTEL_INFO(dev)->gen <= 3) {
15520                         error->plane[i].size = I915_READ(DSPSIZE(i));
15521                         error->plane[i].pos = I915_READ(DSPPOS(i));
15522                 }
15523                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
15524                         error->plane[i].addr = I915_READ(DSPADDR(i));
15525                 if (INTEL_INFO(dev)->gen >= 4) {
15526                         error->plane[i].surface = I915_READ(DSPSURF(i));
15527                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
15528                 }
15529
15530                 error->pipe[i].source = I915_READ(PIPESRC(i));
15531
15532                 if (HAS_GMCH_DISPLAY(dev))
15533                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
15534         }
15535
15536         error->num_transcoders = INTEL_INFO(dev)->num_pipes;
15537         if (HAS_DDI(dev_priv->dev))
15538                 error->num_transcoders++; /* Account for eDP. */
15539
15540         for (i = 0; i < error->num_transcoders; i++) {
15541                 enum transcoder cpu_transcoder = transcoders[i];
15542
15543                 error->transcoder[i].power_domain_on =
15544                         __intel_display_power_is_enabled(dev_priv,
15545                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
15546                 if (!error->transcoder[i].power_domain_on)
15547                         continue;
15548
15549                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
15550
15551                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
15552                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
15553                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
15554                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
15555                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
15556                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
15557                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
15558         }
15559
15560         return error;
15561 }
15562
15563 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
15564
15565 void
15566 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
15567                                 struct drm_device *dev,
15568                                 struct intel_display_error_state *error)
15569 {
15570         struct drm_i915_private *dev_priv = dev->dev_private;
15571         int i;
15572
15573         if (!error)
15574                 return;
15575
15576         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev)->num_pipes);
15577         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
15578                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
15579                            error->power_well_driver);
15580         for_each_pipe(dev_priv, i) {
15581                 err_printf(m, "Pipe [%d]:\n", i);
15582                 err_printf(m, "  Power: %s\n",
15583                            error->pipe[i].power_domain_on ? "on" : "off");
15584                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
15585                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
15586
15587                 err_printf(m, "Plane [%d]:\n", i);
15588                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
15589                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
15590                 if (INTEL_INFO(dev)->gen <= 3) {
15591                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
15592                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
15593                 }
15594                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
15595                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
15596                 if (INTEL_INFO(dev)->gen >= 4) {
15597                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
15598                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
15599                 }
15600
15601                 err_printf(m, "Cursor [%d]:\n", i);
15602                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
15603                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
15604                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
15605         }
15606
15607         for (i = 0; i < error->num_transcoders; i++) {
15608                 err_printf(m, "CPU transcoder: %c\n",
15609                            transcoder_name(error->transcoder[i].cpu_transcoder));
15610                 err_printf(m, "  Power: %s\n",
15611                            error->transcoder[i].power_domain_on ? "on" : "off");
15612                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
15613                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
15614                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
15615                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
15616                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
15617                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
15618                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
15619         }
15620 }
15621
15622 void intel_modeset_preclose(struct drm_device *dev, struct drm_file *file)
15623 {
15624         struct intel_crtc *crtc;
15625
15626         for_each_intel_crtc(dev, crtc) {
15627                 struct intel_unpin_work *work;
15628
15629                 spin_lock_irq(&dev->event_lock);
15630
15631                 work = crtc->unpin_work;
15632
15633                 if (work && work->event &&
15634                     work->event->base.file_priv == file) {
15635                         kfree(work->event);
15636                         work->event = NULL;
15637                 }
15638
15639                 spin_unlock_irq(&dev->event_lock);
15640         }
15641 }