drm/i915: Zero the mode in intel_sanitize_crtc when force disabling.
[linux-2.6-block.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 };
76
77 /* Cursor formats */
78 static const uint32_t intel_cursor_formats[] = {
79         DRM_FORMAT_ARGB8888,
80 };
81
82 static void intel_crtc_update_cursor(struct drm_crtc *crtc, bool on);
83
84 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
85                                 struct intel_crtc_state *pipe_config);
86 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
87                                    struct intel_crtc_state *pipe_config);
88
89 static int intel_set_mode(struct drm_atomic_state *state);
90 static int intel_framebuffer_init(struct drm_device *dev,
91                                   struct intel_framebuffer *ifb,
92                                   struct drm_mode_fb_cmd2 *mode_cmd,
93                                   struct drm_i915_gem_object *obj);
94 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc);
95 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc);
96 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
97                                          struct intel_link_m_n *m_n,
98                                          struct intel_link_m_n *m2_n2);
99 static void ironlake_set_pipeconf(struct drm_crtc *crtc);
100 static void haswell_set_pipeconf(struct drm_crtc *crtc);
101 static void intel_set_pipe_csc(struct drm_crtc *crtc);
102 static void vlv_prepare_pll(struct intel_crtc *crtc,
103                             const struct intel_crtc_state *pipe_config);
104 static void chv_prepare_pll(struct intel_crtc *crtc,
105                             const struct intel_crtc_state *pipe_config);
106 static void intel_begin_crtc_commit(struct drm_crtc *crtc);
107 static void intel_finish_crtc_commit(struct drm_crtc *crtc);
108 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
109         struct intel_crtc_state *crtc_state);
110 static int i9xx_get_refclk(const struct intel_crtc_state *crtc_state,
111                            int num_connectors);
112
113 static struct intel_encoder *intel_find_encoder(struct intel_connector *connector, int pipe)
114 {
115         if (!connector->mst_port)
116                 return connector->encoder;
117         else
118                 return &connector->mst_port->mst_encoders[pipe]->base;
119 }
120
121 typedef struct {
122         int     min, max;
123 } intel_range_t;
124
125 typedef struct {
126         int     dot_limit;
127         int     p2_slow, p2_fast;
128 } intel_p2_t;
129
130 typedef struct intel_limit intel_limit_t;
131 struct intel_limit {
132         intel_range_t   dot, vco, n, m, m1, m2, p, p1;
133         intel_p2_t          p2;
134 };
135
136 int
137 intel_pch_rawclk(struct drm_device *dev)
138 {
139         struct drm_i915_private *dev_priv = dev->dev_private;
140
141         WARN_ON(!HAS_PCH_SPLIT(dev));
142
143         return I915_READ(PCH_RAWCLK_FREQ) & RAWCLK_FREQ_MASK;
144 }
145
146 static inline u32 /* units of 100MHz */
147 intel_fdi_link_freq(struct drm_device *dev)
148 {
149         if (IS_GEN5(dev)) {
150                 struct drm_i915_private *dev_priv = dev->dev_private;
151                 return (I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK) + 2;
152         } else
153                 return 27;
154 }
155
156 static const intel_limit_t intel_limits_i8xx_dac = {
157         .dot = { .min = 25000, .max = 350000 },
158         .vco = { .min = 908000, .max = 1512000 },
159         .n = { .min = 2, .max = 16 },
160         .m = { .min = 96, .max = 140 },
161         .m1 = { .min = 18, .max = 26 },
162         .m2 = { .min = 6, .max = 16 },
163         .p = { .min = 4, .max = 128 },
164         .p1 = { .min = 2, .max = 33 },
165         .p2 = { .dot_limit = 165000,
166                 .p2_slow = 4, .p2_fast = 2 },
167 };
168
169 static const intel_limit_t intel_limits_i8xx_dvo = {
170         .dot = { .min = 25000, .max = 350000 },
171         .vco = { .min = 908000, .max = 1512000 },
172         .n = { .min = 2, .max = 16 },
173         .m = { .min = 96, .max = 140 },
174         .m1 = { .min = 18, .max = 26 },
175         .m2 = { .min = 6, .max = 16 },
176         .p = { .min = 4, .max = 128 },
177         .p1 = { .min = 2, .max = 33 },
178         .p2 = { .dot_limit = 165000,
179                 .p2_slow = 4, .p2_fast = 4 },
180 };
181
182 static const intel_limit_t intel_limits_i8xx_lvds = {
183         .dot = { .min = 25000, .max = 350000 },
184         .vco = { .min = 908000, .max = 1512000 },
185         .n = { .min = 2, .max = 16 },
186         .m = { .min = 96, .max = 140 },
187         .m1 = { .min = 18, .max = 26 },
188         .m2 = { .min = 6, .max = 16 },
189         .p = { .min = 4, .max = 128 },
190         .p1 = { .min = 1, .max = 6 },
191         .p2 = { .dot_limit = 165000,
192                 .p2_slow = 14, .p2_fast = 7 },
193 };
194
195 static const intel_limit_t intel_limits_i9xx_sdvo = {
196         .dot = { .min = 20000, .max = 400000 },
197         .vco = { .min = 1400000, .max = 2800000 },
198         .n = { .min = 1, .max = 6 },
199         .m = { .min = 70, .max = 120 },
200         .m1 = { .min = 8, .max = 18 },
201         .m2 = { .min = 3, .max = 7 },
202         .p = { .min = 5, .max = 80 },
203         .p1 = { .min = 1, .max = 8 },
204         .p2 = { .dot_limit = 200000,
205                 .p2_slow = 10, .p2_fast = 5 },
206 };
207
208 static const intel_limit_t intel_limits_i9xx_lvds = {
209         .dot = { .min = 20000, .max = 400000 },
210         .vco = { .min = 1400000, .max = 2800000 },
211         .n = { .min = 1, .max = 6 },
212         .m = { .min = 70, .max = 120 },
213         .m1 = { .min = 8, .max = 18 },
214         .m2 = { .min = 3, .max = 7 },
215         .p = { .min = 7, .max = 98 },
216         .p1 = { .min = 1, .max = 8 },
217         .p2 = { .dot_limit = 112000,
218                 .p2_slow = 14, .p2_fast = 7 },
219 };
220
221
222 static const intel_limit_t intel_limits_g4x_sdvo = {
223         .dot = { .min = 25000, .max = 270000 },
224         .vco = { .min = 1750000, .max = 3500000},
225         .n = { .min = 1, .max = 4 },
226         .m = { .min = 104, .max = 138 },
227         .m1 = { .min = 17, .max = 23 },
228         .m2 = { .min = 5, .max = 11 },
229         .p = { .min = 10, .max = 30 },
230         .p1 = { .min = 1, .max = 3},
231         .p2 = { .dot_limit = 270000,
232                 .p2_slow = 10,
233                 .p2_fast = 10
234         },
235 };
236
237 static const intel_limit_t intel_limits_g4x_hdmi = {
238         .dot = { .min = 22000, .max = 400000 },
239         .vco = { .min = 1750000, .max = 3500000},
240         .n = { .min = 1, .max = 4 },
241         .m = { .min = 104, .max = 138 },
242         .m1 = { .min = 16, .max = 23 },
243         .m2 = { .min = 5, .max = 11 },
244         .p = { .min = 5, .max = 80 },
245         .p1 = { .min = 1, .max = 8},
246         .p2 = { .dot_limit = 165000,
247                 .p2_slow = 10, .p2_fast = 5 },
248 };
249
250 static const intel_limit_t intel_limits_g4x_single_channel_lvds = {
251         .dot = { .min = 20000, .max = 115000 },
252         .vco = { .min = 1750000, .max = 3500000 },
253         .n = { .min = 1, .max = 3 },
254         .m = { .min = 104, .max = 138 },
255         .m1 = { .min = 17, .max = 23 },
256         .m2 = { .min = 5, .max = 11 },
257         .p = { .min = 28, .max = 112 },
258         .p1 = { .min = 2, .max = 8 },
259         .p2 = { .dot_limit = 0,
260                 .p2_slow = 14, .p2_fast = 14
261         },
262 };
263
264 static const intel_limit_t intel_limits_g4x_dual_channel_lvds = {
265         .dot = { .min = 80000, .max = 224000 },
266         .vco = { .min = 1750000, .max = 3500000 },
267         .n = { .min = 1, .max = 3 },
268         .m = { .min = 104, .max = 138 },
269         .m1 = { .min = 17, .max = 23 },
270         .m2 = { .min = 5, .max = 11 },
271         .p = { .min = 14, .max = 42 },
272         .p1 = { .min = 2, .max = 6 },
273         .p2 = { .dot_limit = 0,
274                 .p2_slow = 7, .p2_fast = 7
275         },
276 };
277
278 static const intel_limit_t intel_limits_pineview_sdvo = {
279         .dot = { .min = 20000, .max = 400000},
280         .vco = { .min = 1700000, .max = 3500000 },
281         /* Pineview's Ncounter is a ring counter */
282         .n = { .min = 3, .max = 6 },
283         .m = { .min = 2, .max = 256 },
284         /* Pineview only has one combined m divider, which we treat as m2. */
285         .m1 = { .min = 0, .max = 0 },
286         .m2 = { .min = 0, .max = 254 },
287         .p = { .min = 5, .max = 80 },
288         .p1 = { .min = 1, .max = 8 },
289         .p2 = { .dot_limit = 200000,
290                 .p2_slow = 10, .p2_fast = 5 },
291 };
292
293 static const intel_limit_t intel_limits_pineview_lvds = {
294         .dot = { .min = 20000, .max = 400000 },
295         .vco = { .min = 1700000, .max = 3500000 },
296         .n = { .min = 3, .max = 6 },
297         .m = { .min = 2, .max = 256 },
298         .m1 = { .min = 0, .max = 0 },
299         .m2 = { .min = 0, .max = 254 },
300         .p = { .min = 7, .max = 112 },
301         .p1 = { .min = 1, .max = 8 },
302         .p2 = { .dot_limit = 112000,
303                 .p2_slow = 14, .p2_fast = 14 },
304 };
305
306 /* Ironlake / Sandybridge
307  *
308  * We calculate clock using (register_value + 2) for N/M1/M2, so here
309  * the range value for them is (actual_value - 2).
310  */
311 static const intel_limit_t intel_limits_ironlake_dac = {
312         .dot = { .min = 25000, .max = 350000 },
313         .vco = { .min = 1760000, .max = 3510000 },
314         .n = { .min = 1, .max = 5 },
315         .m = { .min = 79, .max = 127 },
316         .m1 = { .min = 12, .max = 22 },
317         .m2 = { .min = 5, .max = 9 },
318         .p = { .min = 5, .max = 80 },
319         .p1 = { .min = 1, .max = 8 },
320         .p2 = { .dot_limit = 225000,
321                 .p2_slow = 10, .p2_fast = 5 },
322 };
323
324 static const intel_limit_t intel_limits_ironlake_single_lvds = {
325         .dot = { .min = 25000, .max = 350000 },
326         .vco = { .min = 1760000, .max = 3510000 },
327         .n = { .min = 1, .max = 3 },
328         .m = { .min = 79, .max = 118 },
329         .m1 = { .min = 12, .max = 22 },
330         .m2 = { .min = 5, .max = 9 },
331         .p = { .min = 28, .max = 112 },
332         .p1 = { .min = 2, .max = 8 },
333         .p2 = { .dot_limit = 225000,
334                 .p2_slow = 14, .p2_fast = 14 },
335 };
336
337 static const intel_limit_t intel_limits_ironlake_dual_lvds = {
338         .dot = { .min = 25000, .max = 350000 },
339         .vco = { .min = 1760000, .max = 3510000 },
340         .n = { .min = 1, .max = 3 },
341         .m = { .min = 79, .max = 127 },
342         .m1 = { .min = 12, .max = 22 },
343         .m2 = { .min = 5, .max = 9 },
344         .p = { .min = 14, .max = 56 },
345         .p1 = { .min = 2, .max = 8 },
346         .p2 = { .dot_limit = 225000,
347                 .p2_slow = 7, .p2_fast = 7 },
348 };
349
350 /* LVDS 100mhz refclk limits. */
351 static const intel_limit_t intel_limits_ironlake_single_lvds_100m = {
352         .dot = { .min = 25000, .max = 350000 },
353         .vco = { .min = 1760000, .max = 3510000 },
354         .n = { .min = 1, .max = 2 },
355         .m = { .min = 79, .max = 126 },
356         .m1 = { .min = 12, .max = 22 },
357         .m2 = { .min = 5, .max = 9 },
358         .p = { .min = 28, .max = 112 },
359         .p1 = { .min = 2, .max = 8 },
360         .p2 = { .dot_limit = 225000,
361                 .p2_slow = 14, .p2_fast = 14 },
362 };
363
364 static const intel_limit_t intel_limits_ironlake_dual_lvds_100m = {
365         .dot = { .min = 25000, .max = 350000 },
366         .vco = { .min = 1760000, .max = 3510000 },
367         .n = { .min = 1, .max = 3 },
368         .m = { .min = 79, .max = 126 },
369         .m1 = { .min = 12, .max = 22 },
370         .m2 = { .min = 5, .max = 9 },
371         .p = { .min = 14, .max = 42 },
372         .p1 = { .min = 2, .max = 6 },
373         .p2 = { .dot_limit = 225000,
374                 .p2_slow = 7, .p2_fast = 7 },
375 };
376
377 static const intel_limit_t intel_limits_vlv = {
378          /*
379           * These are the data rate limits (measured in fast clocks)
380           * since those are the strictest limits we have. The fast
381           * clock and actual rate limits are more relaxed, so checking
382           * them would make no difference.
383           */
384         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
385         .vco = { .min = 4000000, .max = 6000000 },
386         .n = { .min = 1, .max = 7 },
387         .m1 = { .min = 2, .max = 3 },
388         .m2 = { .min = 11, .max = 156 },
389         .p1 = { .min = 2, .max = 3 },
390         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
391 };
392
393 static const intel_limit_t intel_limits_chv = {
394         /*
395          * These are the data rate limits (measured in fast clocks)
396          * since those are the strictest limits we have.  The fast
397          * clock and actual rate limits are more relaxed, so checking
398          * them would make no difference.
399          */
400         .dot = { .min = 25000 * 5, .max = 540000 * 5},
401         .vco = { .min = 4800000, .max = 6480000 },
402         .n = { .min = 1, .max = 1 },
403         .m1 = { .min = 2, .max = 2 },
404         .m2 = { .min = 24 << 22, .max = 175 << 22 },
405         .p1 = { .min = 2, .max = 4 },
406         .p2 = { .p2_slow = 1, .p2_fast = 14 },
407 };
408
409 static const intel_limit_t intel_limits_bxt = {
410         /* FIXME: find real dot limits */
411         .dot = { .min = 0, .max = INT_MAX },
412         .vco = { .min = 4800000, .max = 6700000 },
413         .n = { .min = 1, .max = 1 },
414         .m1 = { .min = 2, .max = 2 },
415         /* FIXME: find real m2 limits */
416         .m2 = { .min = 2 << 22, .max = 255 << 22 },
417         .p1 = { .min = 2, .max = 4 },
418         .p2 = { .p2_slow = 1, .p2_fast = 20 },
419 };
420
421 static bool
422 needs_modeset(struct drm_crtc_state *state)
423 {
424         return state->mode_changed || state->active_changed;
425 }
426
427 /**
428  * Returns whether any output on the specified pipe is of the specified type
429  */
430 bool intel_pipe_has_type(struct intel_crtc *crtc, enum intel_output_type type)
431 {
432         struct drm_device *dev = crtc->base.dev;
433         struct intel_encoder *encoder;
434
435         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
436                 if (encoder->type == type)
437                         return true;
438
439         return false;
440 }
441
442 /**
443  * Returns whether any output on the specified pipe will have the specified
444  * type after a staged modeset is complete, i.e., the same as
445  * intel_pipe_has_type() but looking at encoder->new_crtc instead of
446  * encoder->crtc.
447  */
448 static bool intel_pipe_will_have_type(const struct intel_crtc_state *crtc_state,
449                                       int type)
450 {
451         struct drm_atomic_state *state = crtc_state->base.state;
452         struct drm_connector *connector;
453         struct drm_connector_state *connector_state;
454         struct intel_encoder *encoder;
455         int i, num_connectors = 0;
456
457         for_each_connector_in_state(state, connector, connector_state, i) {
458                 if (connector_state->crtc != crtc_state->base.crtc)
459                         continue;
460
461                 num_connectors++;
462
463                 encoder = to_intel_encoder(connector_state->best_encoder);
464                 if (encoder->type == type)
465                         return true;
466         }
467
468         WARN_ON(num_connectors == 0);
469
470         return false;
471 }
472
473 static const intel_limit_t *
474 intel_ironlake_limit(struct intel_crtc_state *crtc_state, int refclk)
475 {
476         struct drm_device *dev = crtc_state->base.crtc->dev;
477         const intel_limit_t *limit;
478
479         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
480                 if (intel_is_dual_link_lvds(dev)) {
481                         if (refclk == 100000)
482                                 limit = &intel_limits_ironlake_dual_lvds_100m;
483                         else
484                                 limit = &intel_limits_ironlake_dual_lvds;
485                 } else {
486                         if (refclk == 100000)
487                                 limit = &intel_limits_ironlake_single_lvds_100m;
488                         else
489                                 limit = &intel_limits_ironlake_single_lvds;
490                 }
491         } else
492                 limit = &intel_limits_ironlake_dac;
493
494         return limit;
495 }
496
497 static const intel_limit_t *
498 intel_g4x_limit(struct intel_crtc_state *crtc_state)
499 {
500         struct drm_device *dev = crtc_state->base.crtc->dev;
501         const intel_limit_t *limit;
502
503         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
504                 if (intel_is_dual_link_lvds(dev))
505                         limit = &intel_limits_g4x_dual_channel_lvds;
506                 else
507                         limit = &intel_limits_g4x_single_channel_lvds;
508         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_HDMI) ||
509                    intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
510                 limit = &intel_limits_g4x_hdmi;
511         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_SDVO)) {
512                 limit = &intel_limits_g4x_sdvo;
513         } else /* The option is for other outputs */
514                 limit = &intel_limits_i9xx_sdvo;
515
516         return limit;
517 }
518
519 static const intel_limit_t *
520 intel_limit(struct intel_crtc_state *crtc_state, int refclk)
521 {
522         struct drm_device *dev = crtc_state->base.crtc->dev;
523         const intel_limit_t *limit;
524
525         if (IS_BROXTON(dev))
526                 limit = &intel_limits_bxt;
527         else if (HAS_PCH_SPLIT(dev))
528                 limit = intel_ironlake_limit(crtc_state, refclk);
529         else if (IS_G4X(dev)) {
530                 limit = intel_g4x_limit(crtc_state);
531         } else if (IS_PINEVIEW(dev)) {
532                 if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
533                         limit = &intel_limits_pineview_lvds;
534                 else
535                         limit = &intel_limits_pineview_sdvo;
536         } else if (IS_CHERRYVIEW(dev)) {
537                 limit = &intel_limits_chv;
538         } else if (IS_VALLEYVIEW(dev)) {
539                 limit = &intel_limits_vlv;
540         } else if (!IS_GEN2(dev)) {
541                 if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
542                         limit = &intel_limits_i9xx_lvds;
543                 else
544                         limit = &intel_limits_i9xx_sdvo;
545         } else {
546                 if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
547                         limit = &intel_limits_i8xx_lvds;
548                 else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_DVO))
549                         limit = &intel_limits_i8xx_dvo;
550                 else
551                         limit = &intel_limits_i8xx_dac;
552         }
553         return limit;
554 }
555
556 /*
557  * Platform specific helpers to calculate the port PLL loopback- (clock.m),
558  * and post-divider (clock.p) values, pre- (clock.vco) and post-divided fast
559  * (clock.dot) clock rates. This fast dot clock is fed to the port's IO logic.
560  * The helpers' return value is the rate of the clock that is fed to the
561  * display engine's pipe which can be the above fast dot clock rate or a
562  * divided-down version of it.
563  */
564 /* m1 is reserved as 0 in Pineview, n is a ring counter */
565 static int pnv_calc_dpll_params(int refclk, intel_clock_t *clock)
566 {
567         clock->m = clock->m2 + 2;
568         clock->p = clock->p1 * clock->p2;
569         if (WARN_ON(clock->n == 0 || clock->p == 0))
570                 return 0;
571         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
572         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
573
574         return clock->dot;
575 }
576
577 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
578 {
579         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
580 }
581
582 static int i9xx_calc_dpll_params(int refclk, intel_clock_t *clock)
583 {
584         clock->m = i9xx_dpll_compute_m(clock);
585         clock->p = clock->p1 * clock->p2;
586         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
587                 return 0;
588         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
589         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
590
591         return clock->dot;
592 }
593
594 static int vlv_calc_dpll_params(int refclk, intel_clock_t *clock)
595 {
596         clock->m = clock->m1 * clock->m2;
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 / 5;
604 }
605
606 int chv_calc_dpll_params(int refclk, intel_clock_t *clock)
607 {
608         clock->m = clock->m1 * clock->m2;
609         clock->p = clock->p1 * clock->p2;
610         if (WARN_ON(clock->n == 0 || clock->p == 0))
611                 return 0;
612         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
613                         clock->n << 22);
614         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
615
616         return clock->dot / 5;
617 }
618
619 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
620 /**
621  * Returns whether the given set of divisors are valid for a given refclk with
622  * the given connectors.
623  */
624
625 static bool intel_PLL_is_valid(struct drm_device *dev,
626                                const intel_limit_t *limit,
627                                const intel_clock_t *clock)
628 {
629         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
630                 INTELPllInvalid("n out of range\n");
631         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
632                 INTELPllInvalid("p1 out of range\n");
633         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
634                 INTELPllInvalid("m2 out of range\n");
635         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
636                 INTELPllInvalid("m1 out of range\n");
637
638         if (!IS_PINEVIEW(dev) && !IS_VALLEYVIEW(dev) && !IS_BROXTON(dev))
639                 if (clock->m1 <= clock->m2)
640                         INTELPllInvalid("m1 <= m2\n");
641
642         if (!IS_VALLEYVIEW(dev) && !IS_BROXTON(dev)) {
643                 if (clock->p < limit->p.min || limit->p.max < clock->p)
644                         INTELPllInvalid("p out of range\n");
645                 if (clock->m < limit->m.min || limit->m.max < clock->m)
646                         INTELPllInvalid("m out of range\n");
647         }
648
649         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
650                 INTELPllInvalid("vco out of range\n");
651         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
652          * connector, etc., rather than just a single range.
653          */
654         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
655                 INTELPllInvalid("dot out of range\n");
656
657         return true;
658 }
659
660 static int
661 i9xx_select_p2_div(const intel_limit_t *limit,
662                    const struct intel_crtc_state *crtc_state,
663                    int target)
664 {
665         struct drm_device *dev = crtc_state->base.crtc->dev;
666
667         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
668                 /*
669                  * For LVDS just rely on its current settings for dual-channel.
670                  * We haven't figured out how to reliably set up different
671                  * single/dual channel state, if we even can.
672                  */
673                 if (intel_is_dual_link_lvds(dev))
674                         return limit->p2.p2_fast;
675                 else
676                         return limit->p2.p2_slow;
677         } else {
678                 if (target < limit->p2.dot_limit)
679                         return limit->p2.p2_slow;
680                 else
681                         return limit->p2.p2_fast;
682         }
683 }
684
685 static bool
686 i9xx_find_best_dpll(const intel_limit_t *limit,
687                     struct intel_crtc_state *crtc_state,
688                     int target, int refclk, intel_clock_t *match_clock,
689                     intel_clock_t *best_clock)
690 {
691         struct drm_device *dev = crtc_state->base.crtc->dev;
692         intel_clock_t clock;
693         int err = target;
694
695         memset(best_clock, 0, sizeof(*best_clock));
696
697         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
698
699         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
700              clock.m1++) {
701                 for (clock.m2 = limit->m2.min;
702                      clock.m2 <= limit->m2.max; clock.m2++) {
703                         if (clock.m2 >= clock.m1)
704                                 break;
705                         for (clock.n = limit->n.min;
706                              clock.n <= limit->n.max; clock.n++) {
707                                 for (clock.p1 = limit->p1.min;
708                                         clock.p1 <= limit->p1.max; clock.p1++) {
709                                         int this_err;
710
711                                         i9xx_calc_dpll_params(refclk, &clock);
712                                         if (!intel_PLL_is_valid(dev, limit,
713                                                                 &clock))
714                                                 continue;
715                                         if (match_clock &&
716                                             clock.p != match_clock->p)
717                                                 continue;
718
719                                         this_err = abs(clock.dot - target);
720                                         if (this_err < err) {
721                                                 *best_clock = clock;
722                                                 err = this_err;
723                                         }
724                                 }
725                         }
726                 }
727         }
728
729         return (err != target);
730 }
731
732 static bool
733 pnv_find_best_dpll(const intel_limit_t *limit,
734                    struct intel_crtc_state *crtc_state,
735                    int target, int refclk, intel_clock_t *match_clock,
736                    intel_clock_t *best_clock)
737 {
738         struct drm_device *dev = crtc_state->base.crtc->dev;
739         intel_clock_t clock;
740         int err = target;
741
742         memset(best_clock, 0, sizeof(*best_clock));
743
744         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
745
746         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
747              clock.m1++) {
748                 for (clock.m2 = limit->m2.min;
749                      clock.m2 <= limit->m2.max; clock.m2++) {
750                         for (clock.n = limit->n.min;
751                              clock.n <= limit->n.max; clock.n++) {
752                                 for (clock.p1 = limit->p1.min;
753                                         clock.p1 <= limit->p1.max; clock.p1++) {
754                                         int this_err;
755
756                                         pnv_calc_dpll_params(refclk, &clock);
757                                         if (!intel_PLL_is_valid(dev, limit,
758                                                                 &clock))
759                                                 continue;
760                                         if (match_clock &&
761                                             clock.p != match_clock->p)
762                                                 continue;
763
764                                         this_err = abs(clock.dot - target);
765                                         if (this_err < err) {
766                                                 *best_clock = clock;
767                                                 err = this_err;
768                                         }
769                                 }
770                         }
771                 }
772         }
773
774         return (err != target);
775 }
776
777 static bool
778 g4x_find_best_dpll(const intel_limit_t *limit,
779                    struct intel_crtc_state *crtc_state,
780                    int target, int refclk, intel_clock_t *match_clock,
781                    intel_clock_t *best_clock)
782 {
783         struct drm_device *dev = crtc_state->base.crtc->dev;
784         intel_clock_t clock;
785         int max_n;
786         bool found = false;
787         /* approximately equals target * 0.00585 */
788         int err_most = (target >> 8) + (target >> 9);
789
790         memset(best_clock, 0, sizeof(*best_clock));
791
792         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
793
794         max_n = limit->n.max;
795         /* based on hardware requirement, prefer smaller n to precision */
796         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
797                 /* based on hardware requirement, prefere larger m1,m2 */
798                 for (clock.m1 = limit->m1.max;
799                      clock.m1 >= limit->m1.min; clock.m1--) {
800                         for (clock.m2 = limit->m2.max;
801                              clock.m2 >= limit->m2.min; clock.m2--) {
802                                 for (clock.p1 = limit->p1.max;
803                                      clock.p1 >= limit->p1.min; clock.p1--) {
804                                         int this_err;
805
806                                         i9xx_calc_dpll_params(refclk, &clock);
807                                         if (!intel_PLL_is_valid(dev, limit,
808                                                                 &clock))
809                                                 continue;
810
811                                         this_err = abs(clock.dot - target);
812                                         if (this_err < err_most) {
813                                                 *best_clock = clock;
814                                                 err_most = this_err;
815                                                 max_n = clock.n;
816                                                 found = true;
817                                         }
818                                 }
819                         }
820                 }
821         }
822         return found;
823 }
824
825 /*
826  * Check if the calculated PLL configuration is more optimal compared to the
827  * best configuration and error found so far. Return the calculated error.
828  */
829 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
830                                const intel_clock_t *calculated_clock,
831                                const intel_clock_t *best_clock,
832                                unsigned int best_error_ppm,
833                                unsigned int *error_ppm)
834 {
835         /*
836          * For CHV ignore the error and consider only the P value.
837          * Prefer a bigger P value based on HW requirements.
838          */
839         if (IS_CHERRYVIEW(dev)) {
840                 *error_ppm = 0;
841
842                 return calculated_clock->p > best_clock->p;
843         }
844
845         if (WARN_ON_ONCE(!target_freq))
846                 return false;
847
848         *error_ppm = div_u64(1000000ULL *
849                                 abs(target_freq - calculated_clock->dot),
850                              target_freq);
851         /*
852          * Prefer a better P value over a better (smaller) error if the error
853          * is small. Ensure this preference for future configurations too by
854          * setting the error to 0.
855          */
856         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
857                 *error_ppm = 0;
858
859                 return true;
860         }
861
862         return *error_ppm + 10 < best_error_ppm;
863 }
864
865 static bool
866 vlv_find_best_dpll(const intel_limit_t *limit,
867                    struct intel_crtc_state *crtc_state,
868                    int target, int refclk, intel_clock_t *match_clock,
869                    intel_clock_t *best_clock)
870 {
871         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
872         struct drm_device *dev = crtc->base.dev;
873         intel_clock_t clock;
874         unsigned int bestppm = 1000000;
875         /* min update 19.2 MHz */
876         int max_n = min(limit->n.max, refclk / 19200);
877         bool found = false;
878
879         target *= 5; /* fast clock */
880
881         memset(best_clock, 0, sizeof(*best_clock));
882
883         /* based on hardware requirement, prefer smaller n to precision */
884         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
885                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
886                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
887                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
888                                 clock.p = clock.p1 * clock.p2;
889                                 /* based on hardware requirement, prefer bigger m1,m2 values */
890                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
891                                         unsigned int ppm;
892
893                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
894                                                                      refclk * clock.m1);
895
896                                         vlv_calc_dpll_params(refclk, &clock);
897
898                                         if (!intel_PLL_is_valid(dev, limit,
899                                                                 &clock))
900                                                 continue;
901
902                                         if (!vlv_PLL_is_optimal(dev, target,
903                                                                 &clock,
904                                                                 best_clock,
905                                                                 bestppm, &ppm))
906                                                 continue;
907
908                                         *best_clock = clock;
909                                         bestppm = ppm;
910                                         found = true;
911                                 }
912                         }
913                 }
914         }
915
916         return found;
917 }
918
919 static bool
920 chv_find_best_dpll(const intel_limit_t *limit,
921                    struct intel_crtc_state *crtc_state,
922                    int target, int refclk, intel_clock_t *match_clock,
923                    intel_clock_t *best_clock)
924 {
925         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
926         struct drm_device *dev = crtc->base.dev;
927         unsigned int best_error_ppm;
928         intel_clock_t clock;
929         uint64_t m2;
930         int found = false;
931
932         memset(best_clock, 0, sizeof(*best_clock));
933         best_error_ppm = 1000000;
934
935         /*
936          * Based on hardware doc, the n always set to 1, and m1 always
937          * set to 2.  If requires to support 200Mhz refclk, we need to
938          * revisit this because n may not 1 anymore.
939          */
940         clock.n = 1, clock.m1 = 2;
941         target *= 5;    /* fast clock */
942
943         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
944                 for (clock.p2 = limit->p2.p2_fast;
945                                 clock.p2 >= limit->p2.p2_slow;
946                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
947                         unsigned int error_ppm;
948
949                         clock.p = clock.p1 * clock.p2;
950
951                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
952                                         clock.n) << 22, refclk * clock.m1);
953
954                         if (m2 > INT_MAX/clock.m1)
955                                 continue;
956
957                         clock.m2 = m2;
958
959                         chv_calc_dpll_params(refclk, &clock);
960
961                         if (!intel_PLL_is_valid(dev, limit, &clock))
962                                 continue;
963
964                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
965                                                 best_error_ppm, &error_ppm))
966                                 continue;
967
968                         *best_clock = clock;
969                         best_error_ppm = error_ppm;
970                         found = true;
971                 }
972         }
973
974         return found;
975 }
976
977 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state, int target_clock,
978                         intel_clock_t *best_clock)
979 {
980         int refclk = i9xx_get_refclk(crtc_state, 0);
981
982         return chv_find_best_dpll(intel_limit(crtc_state, refclk), crtc_state,
983                                   target_clock, refclk, NULL, best_clock);
984 }
985
986 bool intel_crtc_active(struct drm_crtc *crtc)
987 {
988         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
989
990         /* Be paranoid as we can arrive here with only partial
991          * state retrieved from the hardware during setup.
992          *
993          * We can ditch the adjusted_mode.crtc_clock check as soon
994          * as Haswell has gained clock readout/fastboot support.
995          *
996          * We can ditch the crtc->primary->fb check as soon as we can
997          * properly reconstruct framebuffers.
998          *
999          * FIXME: The intel_crtc->active here should be switched to
1000          * crtc->state->active once we have proper CRTC states wired up
1001          * for atomic.
1002          */
1003         return intel_crtc->active && crtc->primary->state->fb &&
1004                 intel_crtc->config->base.adjusted_mode.crtc_clock;
1005 }
1006
1007 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
1008                                              enum pipe pipe)
1009 {
1010         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1011         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1012
1013         return intel_crtc->config->cpu_transcoder;
1014 }
1015
1016 static bool pipe_dsl_stopped(struct drm_device *dev, enum pipe pipe)
1017 {
1018         struct drm_i915_private *dev_priv = dev->dev_private;
1019         u32 reg = PIPEDSL(pipe);
1020         u32 line1, line2;
1021         u32 line_mask;
1022
1023         if (IS_GEN2(dev))
1024                 line_mask = DSL_LINEMASK_GEN2;
1025         else
1026                 line_mask = DSL_LINEMASK_GEN3;
1027
1028         line1 = I915_READ(reg) & line_mask;
1029         msleep(5);
1030         line2 = I915_READ(reg) & line_mask;
1031
1032         return line1 == line2;
1033 }
1034
1035 /*
1036  * intel_wait_for_pipe_off - wait for pipe to turn off
1037  * @crtc: crtc whose pipe to wait for
1038  *
1039  * After disabling a pipe, we can't wait for vblank in the usual way,
1040  * spinning on the vblank interrupt status bit, since we won't actually
1041  * see an interrupt when the pipe is disabled.
1042  *
1043  * On Gen4 and above:
1044  *   wait for the pipe register state bit to turn off
1045  *
1046  * Otherwise:
1047  *   wait for the display line value to settle (it usually
1048  *   ends up stopping at the start of the next frame).
1049  *
1050  */
1051 static void intel_wait_for_pipe_off(struct intel_crtc *crtc)
1052 {
1053         struct drm_device *dev = crtc->base.dev;
1054         struct drm_i915_private *dev_priv = dev->dev_private;
1055         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1056         enum pipe pipe = crtc->pipe;
1057
1058         if (INTEL_INFO(dev)->gen >= 4) {
1059                 int reg = PIPECONF(cpu_transcoder);
1060
1061                 /* Wait for the Pipe State to go off */
1062                 if (wait_for((I915_READ(reg) & I965_PIPECONF_ACTIVE) == 0,
1063                              100))
1064                         WARN(1, "pipe_off wait timed out\n");
1065         } else {
1066                 /* Wait for the display line to settle */
1067                 if (wait_for(pipe_dsl_stopped(dev, pipe), 100))
1068                         WARN(1, "pipe_off wait timed out\n");
1069         }
1070 }
1071
1072 /*
1073  * ibx_digital_port_connected - is the specified port connected?
1074  * @dev_priv: i915 private structure
1075  * @port: the port to test
1076  *
1077  * Returns true if @port is connected, false otherwise.
1078  */
1079 bool ibx_digital_port_connected(struct drm_i915_private *dev_priv,
1080                                 struct intel_digital_port *port)
1081 {
1082         u32 bit;
1083
1084         if (HAS_PCH_IBX(dev_priv->dev)) {
1085                 switch (port->port) {
1086                 case PORT_B:
1087                         bit = SDE_PORTB_HOTPLUG;
1088                         break;
1089                 case PORT_C:
1090                         bit = SDE_PORTC_HOTPLUG;
1091                         break;
1092                 case PORT_D:
1093                         bit = SDE_PORTD_HOTPLUG;
1094                         break;
1095                 default:
1096                         return true;
1097                 }
1098         } else {
1099                 switch (port->port) {
1100                 case PORT_B:
1101                         bit = SDE_PORTB_HOTPLUG_CPT;
1102                         break;
1103                 case PORT_C:
1104                         bit = SDE_PORTC_HOTPLUG_CPT;
1105                         break;
1106                 case PORT_D:
1107                         bit = SDE_PORTD_HOTPLUG_CPT;
1108                         break;
1109                 default:
1110                         return true;
1111                 }
1112         }
1113
1114         return I915_READ(SDEISR) & bit;
1115 }
1116
1117 static const char *state_string(bool enabled)
1118 {
1119         return enabled ? "on" : "off";
1120 }
1121
1122 /* Only for pre-ILK configs */
1123 void assert_pll(struct drm_i915_private *dev_priv,
1124                 enum pipe pipe, bool state)
1125 {
1126         int reg;
1127         u32 val;
1128         bool cur_state;
1129
1130         reg = DPLL(pipe);
1131         val = I915_READ(reg);
1132         cur_state = !!(val & DPLL_VCO_ENABLE);
1133         I915_STATE_WARN(cur_state != state,
1134              "PLL state assertion failure (expected %s, current %s)\n",
1135              state_string(state), state_string(cur_state));
1136 }
1137
1138 /* XXX: the dsi pll is shared between MIPI DSI ports */
1139 static void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1140 {
1141         u32 val;
1142         bool cur_state;
1143
1144         mutex_lock(&dev_priv->sb_lock);
1145         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1146         mutex_unlock(&dev_priv->sb_lock);
1147
1148         cur_state = val & DSI_PLL_VCO_EN;
1149         I915_STATE_WARN(cur_state != state,
1150              "DSI PLL state assertion failure (expected %s, current %s)\n",
1151              state_string(state), state_string(cur_state));
1152 }
1153 #define assert_dsi_pll_enabled(d) assert_dsi_pll(d, true)
1154 #define assert_dsi_pll_disabled(d) assert_dsi_pll(d, false)
1155
1156 struct intel_shared_dpll *
1157 intel_crtc_to_shared_dpll(struct intel_crtc *crtc)
1158 {
1159         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
1160
1161         if (crtc->config->shared_dpll < 0)
1162                 return NULL;
1163
1164         return &dev_priv->shared_dplls[crtc->config->shared_dpll];
1165 }
1166
1167 /* For ILK+ */
1168 void assert_shared_dpll(struct drm_i915_private *dev_priv,
1169                         struct intel_shared_dpll *pll,
1170                         bool state)
1171 {
1172         bool cur_state;
1173         struct intel_dpll_hw_state hw_state;
1174
1175         if (WARN (!pll,
1176                   "asserting DPLL %s with no DPLL\n", state_string(state)))
1177                 return;
1178
1179         cur_state = pll->get_hw_state(dev_priv, pll, &hw_state);
1180         I915_STATE_WARN(cur_state != state,
1181              "%s assertion failure (expected %s, current %s)\n",
1182              pll->name, state_string(state), state_string(cur_state));
1183 }
1184
1185 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1186                           enum pipe pipe, bool state)
1187 {
1188         int reg;
1189         u32 val;
1190         bool cur_state;
1191         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1192                                                                       pipe);
1193
1194         if (HAS_DDI(dev_priv->dev)) {
1195                 /* DDI does not have a specific FDI_TX register */
1196                 reg = TRANS_DDI_FUNC_CTL(cpu_transcoder);
1197                 val = I915_READ(reg);
1198                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1199         } else {
1200                 reg = FDI_TX_CTL(pipe);
1201                 val = I915_READ(reg);
1202                 cur_state = !!(val & FDI_TX_ENABLE);
1203         }
1204         I915_STATE_WARN(cur_state != state,
1205              "FDI TX state assertion failure (expected %s, current %s)\n",
1206              state_string(state), state_string(cur_state));
1207 }
1208 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1209 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1210
1211 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1212                           enum pipe pipe, bool state)
1213 {
1214         int reg;
1215         u32 val;
1216         bool cur_state;
1217
1218         reg = FDI_RX_CTL(pipe);
1219         val = I915_READ(reg);
1220         cur_state = !!(val & FDI_RX_ENABLE);
1221         I915_STATE_WARN(cur_state != state,
1222              "FDI RX state assertion failure (expected %s, current %s)\n",
1223              state_string(state), state_string(cur_state));
1224 }
1225 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1226 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1227
1228 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1229                                       enum pipe pipe)
1230 {
1231         int reg;
1232         u32 val;
1233
1234         /* ILK FDI PLL is always enabled */
1235         if (INTEL_INFO(dev_priv->dev)->gen == 5)
1236                 return;
1237
1238         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1239         if (HAS_DDI(dev_priv->dev))
1240                 return;
1241
1242         reg = FDI_TX_CTL(pipe);
1243         val = I915_READ(reg);
1244         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1245 }
1246
1247 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1248                        enum pipe pipe, bool state)
1249 {
1250         int reg;
1251         u32 val;
1252         bool cur_state;
1253
1254         reg = FDI_RX_CTL(pipe);
1255         val = I915_READ(reg);
1256         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1257         I915_STATE_WARN(cur_state != state,
1258              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1259              state_string(state), state_string(cur_state));
1260 }
1261
1262 void assert_panel_unlocked(struct drm_i915_private *dev_priv,
1263                            enum pipe pipe)
1264 {
1265         struct drm_device *dev = dev_priv->dev;
1266         int pp_reg;
1267         u32 val;
1268         enum pipe panel_pipe = PIPE_A;
1269         bool locked = true;
1270
1271         if (WARN_ON(HAS_DDI(dev)))
1272                 return;
1273
1274         if (HAS_PCH_SPLIT(dev)) {
1275                 u32 port_sel;
1276
1277                 pp_reg = PCH_PP_CONTROL;
1278                 port_sel = I915_READ(PCH_PP_ON_DELAYS) & PANEL_PORT_SELECT_MASK;
1279
1280                 if (port_sel == PANEL_PORT_SELECT_LVDS &&
1281                     I915_READ(PCH_LVDS) & LVDS_PIPEB_SELECT)
1282                         panel_pipe = PIPE_B;
1283                 /* XXX: else fix for eDP */
1284         } else if (IS_VALLEYVIEW(dev)) {
1285                 /* presumably write lock depends on pipe, not port select */
1286                 pp_reg = VLV_PIPE_PP_CONTROL(pipe);
1287                 panel_pipe = pipe;
1288         } else {
1289                 pp_reg = PP_CONTROL;
1290                 if (I915_READ(LVDS) & LVDS_PIPEB_SELECT)
1291                         panel_pipe = PIPE_B;
1292         }
1293
1294         val = I915_READ(pp_reg);
1295         if (!(val & PANEL_POWER_ON) ||
1296             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1297                 locked = false;
1298
1299         I915_STATE_WARN(panel_pipe == pipe && locked,
1300              "panel assertion failure, pipe %c regs locked\n",
1301              pipe_name(pipe));
1302 }
1303
1304 static void assert_cursor(struct drm_i915_private *dev_priv,
1305                           enum pipe pipe, bool state)
1306 {
1307         struct drm_device *dev = dev_priv->dev;
1308         bool cur_state;
1309
1310         if (IS_845G(dev) || IS_I865G(dev))
1311                 cur_state = I915_READ(_CURACNTR) & CURSOR_ENABLE;
1312         else
1313                 cur_state = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
1314
1315         I915_STATE_WARN(cur_state != state,
1316              "cursor on pipe %c assertion failure (expected %s, current %s)\n",
1317              pipe_name(pipe), state_string(state), state_string(cur_state));
1318 }
1319 #define assert_cursor_enabled(d, p) assert_cursor(d, p, true)
1320 #define assert_cursor_disabled(d, p) assert_cursor(d, p, false)
1321
1322 void assert_pipe(struct drm_i915_private *dev_priv,
1323                  enum pipe pipe, bool state)
1324 {
1325         int reg;
1326         u32 val;
1327         bool cur_state;
1328         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1329                                                                       pipe);
1330
1331         /* if we need the pipe quirk it must be always on */
1332         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1333             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1334                 state = true;
1335
1336         if (!intel_display_power_is_enabled(dev_priv,
1337                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder))) {
1338                 cur_state = false;
1339         } else {
1340                 reg = PIPECONF(cpu_transcoder);
1341                 val = I915_READ(reg);
1342                 cur_state = !!(val & PIPECONF_ENABLE);
1343         }
1344
1345         I915_STATE_WARN(cur_state != state,
1346              "pipe %c assertion failure (expected %s, current %s)\n",
1347              pipe_name(pipe), state_string(state), state_string(cur_state));
1348 }
1349
1350 static void assert_plane(struct drm_i915_private *dev_priv,
1351                          enum plane plane, bool state)
1352 {
1353         int reg;
1354         u32 val;
1355         bool cur_state;
1356
1357         reg = DSPCNTR(plane);
1358         val = I915_READ(reg);
1359         cur_state = !!(val & DISPLAY_PLANE_ENABLE);
1360         I915_STATE_WARN(cur_state != state,
1361              "plane %c assertion failure (expected %s, current %s)\n",
1362              plane_name(plane), state_string(state), state_string(cur_state));
1363 }
1364
1365 #define assert_plane_enabled(d, p) assert_plane(d, p, true)
1366 #define assert_plane_disabled(d, p) assert_plane(d, p, false)
1367
1368 static void assert_planes_disabled(struct drm_i915_private *dev_priv,
1369                                    enum pipe pipe)
1370 {
1371         struct drm_device *dev = dev_priv->dev;
1372         int reg, i;
1373         u32 val;
1374         int cur_pipe;
1375
1376         /* Primary planes are fixed to pipes on gen4+ */
1377         if (INTEL_INFO(dev)->gen >= 4) {
1378                 reg = DSPCNTR(pipe);
1379                 val = I915_READ(reg);
1380                 I915_STATE_WARN(val & DISPLAY_PLANE_ENABLE,
1381                      "plane %c assertion failure, should be disabled but not\n",
1382                      plane_name(pipe));
1383                 return;
1384         }
1385
1386         /* Need to check both planes against the pipe */
1387         for_each_pipe(dev_priv, i) {
1388                 reg = DSPCNTR(i);
1389                 val = I915_READ(reg);
1390                 cur_pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
1391                         DISPPLANE_SEL_PIPE_SHIFT;
1392                 I915_STATE_WARN((val & DISPLAY_PLANE_ENABLE) && pipe == cur_pipe,
1393                      "plane %c assertion failure, should be off on pipe %c but is still active\n",
1394                      plane_name(i), pipe_name(pipe));
1395         }
1396 }
1397
1398 static void assert_sprites_disabled(struct drm_i915_private *dev_priv,
1399                                     enum pipe pipe)
1400 {
1401         struct drm_device *dev = dev_priv->dev;
1402         int reg, sprite;
1403         u32 val;
1404
1405         if (INTEL_INFO(dev)->gen >= 9) {
1406                 for_each_sprite(dev_priv, pipe, sprite) {
1407                         val = I915_READ(PLANE_CTL(pipe, sprite));
1408                         I915_STATE_WARN(val & PLANE_CTL_ENABLE,
1409                              "plane %d assertion failure, should be off on pipe %c but is still active\n",
1410                              sprite, pipe_name(pipe));
1411                 }
1412         } else if (IS_VALLEYVIEW(dev)) {
1413                 for_each_sprite(dev_priv, pipe, sprite) {
1414                         reg = SPCNTR(pipe, sprite);
1415                         val = I915_READ(reg);
1416                         I915_STATE_WARN(val & SP_ENABLE,
1417                              "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1418                              sprite_name(pipe, sprite), pipe_name(pipe));
1419                 }
1420         } else if (INTEL_INFO(dev)->gen >= 7) {
1421                 reg = SPRCTL(pipe);
1422                 val = I915_READ(reg);
1423                 I915_STATE_WARN(val & SPRITE_ENABLE,
1424                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1425                      plane_name(pipe), pipe_name(pipe));
1426         } else if (INTEL_INFO(dev)->gen >= 5) {
1427                 reg = DVSCNTR(pipe);
1428                 val = I915_READ(reg);
1429                 I915_STATE_WARN(val & DVS_ENABLE,
1430                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1431                      plane_name(pipe), pipe_name(pipe));
1432         }
1433 }
1434
1435 static void assert_vblank_disabled(struct drm_crtc *crtc)
1436 {
1437         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1438                 drm_crtc_vblank_put(crtc);
1439 }
1440
1441 static void ibx_assert_pch_refclk_enabled(struct drm_i915_private *dev_priv)
1442 {
1443         u32 val;
1444         bool enabled;
1445
1446         I915_STATE_WARN_ON(!(HAS_PCH_IBX(dev_priv->dev) || HAS_PCH_CPT(dev_priv->dev)));
1447
1448         val = I915_READ(PCH_DREF_CONTROL);
1449         enabled = !!(val & (DREF_SSC_SOURCE_MASK | DREF_NONSPREAD_SOURCE_MASK |
1450                             DREF_SUPERSPREAD_SOURCE_MASK));
1451         I915_STATE_WARN(!enabled, "PCH refclk assertion failure, should be active but is disabled\n");
1452 }
1453
1454 static void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1455                                            enum pipe pipe)
1456 {
1457         int reg;
1458         u32 val;
1459         bool enabled;
1460
1461         reg = PCH_TRANSCONF(pipe);
1462         val = I915_READ(reg);
1463         enabled = !!(val & TRANS_ENABLE);
1464         I915_STATE_WARN(enabled,
1465              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1466              pipe_name(pipe));
1467 }
1468
1469 static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1470                             enum pipe pipe, u32 port_sel, u32 val)
1471 {
1472         if ((val & DP_PORT_EN) == 0)
1473                 return false;
1474
1475         if (HAS_PCH_CPT(dev_priv->dev)) {
1476                 u32     trans_dp_ctl_reg = TRANS_DP_CTL(pipe);
1477                 u32     trans_dp_ctl = I915_READ(trans_dp_ctl_reg);
1478                 if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1479                         return false;
1480         } else if (IS_CHERRYVIEW(dev_priv->dev)) {
1481                 if ((val & DP_PIPE_MASK_CHV) != DP_PIPE_SELECT_CHV(pipe))
1482                         return false;
1483         } else {
1484                 if ((val & DP_PIPE_MASK) != (pipe << 30))
1485                         return false;
1486         }
1487         return true;
1488 }
1489
1490 static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1491                               enum pipe pipe, u32 val)
1492 {
1493         if ((val & SDVO_ENABLE) == 0)
1494                 return false;
1495
1496         if (HAS_PCH_CPT(dev_priv->dev)) {
1497                 if ((val & SDVO_PIPE_SEL_MASK_CPT) != SDVO_PIPE_SEL_CPT(pipe))
1498                         return false;
1499         } else if (IS_CHERRYVIEW(dev_priv->dev)) {
1500                 if ((val & SDVO_PIPE_SEL_MASK_CHV) != SDVO_PIPE_SEL_CHV(pipe))
1501                         return false;
1502         } else {
1503                 if ((val & SDVO_PIPE_SEL_MASK) != SDVO_PIPE_SEL(pipe))
1504                         return false;
1505         }
1506         return true;
1507 }
1508
1509 static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1510                               enum pipe pipe, u32 val)
1511 {
1512         if ((val & LVDS_PORT_EN) == 0)
1513                 return false;
1514
1515         if (HAS_PCH_CPT(dev_priv->dev)) {
1516                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1517                         return false;
1518         } else {
1519                 if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1520                         return false;
1521         }
1522         return true;
1523 }
1524
1525 static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1526                               enum pipe pipe, u32 val)
1527 {
1528         if ((val & ADPA_DAC_ENABLE) == 0)
1529                 return false;
1530         if (HAS_PCH_CPT(dev_priv->dev)) {
1531                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1532                         return false;
1533         } else {
1534                 if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1535                         return false;
1536         }
1537         return true;
1538 }
1539
1540 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1541                                    enum pipe pipe, int reg, u32 port_sel)
1542 {
1543         u32 val = I915_READ(reg);
1544         I915_STATE_WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1545              "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1546              reg, pipe_name(pipe));
1547
1548         I915_STATE_WARN(HAS_PCH_IBX(dev_priv->dev) && (val & DP_PORT_EN) == 0
1549              && (val & DP_PIPEB_SELECT),
1550              "IBX PCH dp port still using transcoder B\n");
1551 }
1552
1553 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1554                                      enum pipe pipe, int reg)
1555 {
1556         u32 val = I915_READ(reg);
1557         I915_STATE_WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1558              "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1559              reg, pipe_name(pipe));
1560
1561         I915_STATE_WARN(HAS_PCH_IBX(dev_priv->dev) && (val & SDVO_ENABLE) == 0
1562              && (val & SDVO_PIPE_B_SELECT),
1563              "IBX PCH hdmi port still using transcoder B\n");
1564 }
1565
1566 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1567                                       enum pipe pipe)
1568 {
1569         int reg;
1570         u32 val;
1571
1572         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1573         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1574         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1575
1576         reg = PCH_ADPA;
1577         val = I915_READ(reg);
1578         I915_STATE_WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1579              "PCH VGA enabled on transcoder %c, should be disabled\n",
1580              pipe_name(pipe));
1581
1582         reg = PCH_LVDS;
1583         val = I915_READ(reg);
1584         I915_STATE_WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1585              "PCH LVDS enabled on transcoder %c, should be disabled\n",
1586              pipe_name(pipe));
1587
1588         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIB);
1589         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIC);
1590         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMID);
1591 }
1592
1593 static void intel_init_dpio(struct drm_device *dev)
1594 {
1595         struct drm_i915_private *dev_priv = dev->dev_private;
1596
1597         if (!IS_VALLEYVIEW(dev))
1598                 return;
1599
1600         /*
1601          * IOSF_PORT_DPIO is used for VLV x2 PHY (DP/HDMI B and C),
1602          * CHV x1 PHY (DP/HDMI D)
1603          * IOSF_PORT_DPIO_2 is used for CHV x2 PHY (DP/HDMI B and C)
1604          */
1605         if (IS_CHERRYVIEW(dev)) {
1606                 DPIO_PHY_IOSF_PORT(DPIO_PHY0) = IOSF_PORT_DPIO_2;
1607                 DPIO_PHY_IOSF_PORT(DPIO_PHY1) = IOSF_PORT_DPIO;
1608         } else {
1609                 DPIO_PHY_IOSF_PORT(DPIO_PHY0) = IOSF_PORT_DPIO;
1610         }
1611 }
1612
1613 static void vlv_enable_pll(struct intel_crtc *crtc,
1614                            const struct intel_crtc_state *pipe_config)
1615 {
1616         struct drm_device *dev = crtc->base.dev;
1617         struct drm_i915_private *dev_priv = dev->dev_private;
1618         int reg = DPLL(crtc->pipe);
1619         u32 dpll = pipe_config->dpll_hw_state.dpll;
1620
1621         assert_pipe_disabled(dev_priv, crtc->pipe);
1622
1623         /* No really, not for ILK+ */
1624         BUG_ON(!IS_VALLEYVIEW(dev_priv->dev));
1625
1626         /* PLL is protected by panel, make sure we can write it */
1627         if (IS_MOBILE(dev_priv->dev))
1628                 assert_panel_unlocked(dev_priv, crtc->pipe);
1629
1630         I915_WRITE(reg, dpll);
1631         POSTING_READ(reg);
1632         udelay(150);
1633
1634         if (wait_for(((I915_READ(reg) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1635                 DRM_ERROR("DPLL %d failed to lock\n", crtc->pipe);
1636
1637         I915_WRITE(DPLL_MD(crtc->pipe), pipe_config->dpll_hw_state.dpll_md);
1638         POSTING_READ(DPLL_MD(crtc->pipe));
1639
1640         /* We do this three times for luck */
1641         I915_WRITE(reg, dpll);
1642         POSTING_READ(reg);
1643         udelay(150); /* wait for warmup */
1644         I915_WRITE(reg, dpll);
1645         POSTING_READ(reg);
1646         udelay(150); /* wait for warmup */
1647         I915_WRITE(reg, dpll);
1648         POSTING_READ(reg);
1649         udelay(150); /* wait for warmup */
1650 }
1651
1652 static void chv_enable_pll(struct intel_crtc *crtc,
1653                            const struct intel_crtc_state *pipe_config)
1654 {
1655         struct drm_device *dev = crtc->base.dev;
1656         struct drm_i915_private *dev_priv = dev->dev_private;
1657         int pipe = crtc->pipe;
1658         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1659         u32 tmp;
1660
1661         assert_pipe_disabled(dev_priv, crtc->pipe);
1662
1663         BUG_ON(!IS_CHERRYVIEW(dev_priv->dev));
1664
1665         mutex_lock(&dev_priv->sb_lock);
1666
1667         /* Enable back the 10bit clock to display controller */
1668         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1669         tmp |= DPIO_DCLKP_EN;
1670         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1671
1672         mutex_unlock(&dev_priv->sb_lock);
1673
1674         /*
1675          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1676          */
1677         udelay(1);
1678
1679         /* Enable PLL */
1680         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1681
1682         /* Check PLL is locked */
1683         if (wait_for(((I915_READ(DPLL(pipe)) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1684                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1685
1686         /* not sure when this should be written */
1687         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1688         POSTING_READ(DPLL_MD(pipe));
1689 }
1690
1691 static int intel_num_dvo_pipes(struct drm_device *dev)
1692 {
1693         struct intel_crtc *crtc;
1694         int count = 0;
1695
1696         for_each_intel_crtc(dev, crtc)
1697                 count += crtc->base.state->active &&
1698                         intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO);
1699
1700         return count;
1701 }
1702
1703 static void i9xx_enable_pll(struct intel_crtc *crtc)
1704 {
1705         struct drm_device *dev = crtc->base.dev;
1706         struct drm_i915_private *dev_priv = dev->dev_private;
1707         int reg = DPLL(crtc->pipe);
1708         u32 dpll = crtc->config->dpll_hw_state.dpll;
1709
1710         assert_pipe_disabled(dev_priv, crtc->pipe);
1711
1712         /* No really, not for ILK+ */
1713         BUG_ON(INTEL_INFO(dev)->gen >= 5);
1714
1715         /* PLL is protected by panel, make sure we can write it */
1716         if (IS_MOBILE(dev) && !IS_I830(dev))
1717                 assert_panel_unlocked(dev_priv, crtc->pipe);
1718
1719         /* Enable DVO 2x clock on both PLLs if necessary */
1720         if (IS_I830(dev) && intel_num_dvo_pipes(dev) > 0) {
1721                 /*
1722                  * It appears to be important that we don't enable this
1723                  * for the current pipe before otherwise configuring the
1724                  * PLL. No idea how this should be handled if multiple
1725                  * DVO outputs are enabled simultaneosly.
1726                  */
1727                 dpll |= DPLL_DVO_2X_MODE;
1728                 I915_WRITE(DPLL(!crtc->pipe),
1729                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1730         }
1731
1732         /* Wait for the clocks to stabilize. */
1733         POSTING_READ(reg);
1734         udelay(150);
1735
1736         if (INTEL_INFO(dev)->gen >= 4) {
1737                 I915_WRITE(DPLL_MD(crtc->pipe),
1738                            crtc->config->dpll_hw_state.dpll_md);
1739         } else {
1740                 /* The pixel multiplier can only be updated once the
1741                  * DPLL is enabled and the clocks are stable.
1742                  *
1743                  * So write it again.
1744                  */
1745                 I915_WRITE(reg, dpll);
1746         }
1747
1748         /* We do this three times for luck */
1749         I915_WRITE(reg, dpll);
1750         POSTING_READ(reg);
1751         udelay(150); /* wait for warmup */
1752         I915_WRITE(reg, dpll);
1753         POSTING_READ(reg);
1754         udelay(150); /* wait for warmup */
1755         I915_WRITE(reg, dpll);
1756         POSTING_READ(reg);
1757         udelay(150); /* wait for warmup */
1758 }
1759
1760 /**
1761  * i9xx_disable_pll - disable a PLL
1762  * @dev_priv: i915 private structure
1763  * @pipe: pipe PLL to disable
1764  *
1765  * Disable the PLL for @pipe, making sure the pipe is off first.
1766  *
1767  * Note!  This is for pre-ILK only.
1768  */
1769 static void i9xx_disable_pll(struct intel_crtc *crtc)
1770 {
1771         struct drm_device *dev = crtc->base.dev;
1772         struct drm_i915_private *dev_priv = dev->dev_private;
1773         enum pipe pipe = crtc->pipe;
1774
1775         /* Disable DVO 2x clock on both PLLs if necessary */
1776         if (IS_I830(dev) &&
1777             intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO) &&
1778             !intel_num_dvo_pipes(dev)) {
1779                 I915_WRITE(DPLL(PIPE_B),
1780                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1781                 I915_WRITE(DPLL(PIPE_A),
1782                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1783         }
1784
1785         /* Don't disable pipe or pipe PLLs if needed */
1786         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1787             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1788                 return;
1789
1790         /* Make sure the pipe isn't still relying on us */
1791         assert_pipe_disabled(dev_priv, pipe);
1792
1793         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1794         POSTING_READ(DPLL(pipe));
1795 }
1796
1797 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1798 {
1799         u32 val;
1800
1801         /* Make sure the pipe isn't still relying on us */
1802         assert_pipe_disabled(dev_priv, pipe);
1803
1804         /*
1805          * Leave integrated clock source and reference clock enabled for pipe B.
1806          * The latter is needed for VGA hotplug / manual detection.
1807          */
1808         val = DPLL_VGA_MODE_DIS;
1809         if (pipe == PIPE_B)
1810                 val = DPLL_INTEGRATED_CRI_CLK_VLV | DPLL_REF_CLK_ENABLE_VLV;
1811         I915_WRITE(DPLL(pipe), val);
1812         POSTING_READ(DPLL(pipe));
1813
1814 }
1815
1816 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1817 {
1818         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1819         u32 val;
1820
1821         /* Make sure the pipe isn't still relying on us */
1822         assert_pipe_disabled(dev_priv, pipe);
1823
1824         /* Set PLL en = 0 */
1825         val = DPLL_SSC_REF_CLK_CHV |
1826                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1827         if (pipe != PIPE_A)
1828                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1829         I915_WRITE(DPLL(pipe), val);
1830         POSTING_READ(DPLL(pipe));
1831
1832         mutex_lock(&dev_priv->sb_lock);
1833
1834         /* Disable 10bit clock to display controller */
1835         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1836         val &= ~DPIO_DCLKP_EN;
1837         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1838
1839         /* disable left/right clock distribution */
1840         if (pipe != PIPE_B) {
1841                 val = vlv_dpio_read(dev_priv, pipe, _CHV_CMN_DW5_CH0);
1842                 val &= ~(CHV_BUFLEFTENA1_MASK | CHV_BUFRIGHTENA1_MASK);
1843                 vlv_dpio_write(dev_priv, pipe, _CHV_CMN_DW5_CH0, val);
1844         } else {
1845                 val = vlv_dpio_read(dev_priv, pipe, _CHV_CMN_DW1_CH1);
1846                 val &= ~(CHV_BUFLEFTENA2_MASK | CHV_BUFRIGHTENA2_MASK);
1847                 vlv_dpio_write(dev_priv, pipe, _CHV_CMN_DW1_CH1, val);
1848         }
1849
1850         mutex_unlock(&dev_priv->sb_lock);
1851 }
1852
1853 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1854                          struct intel_digital_port *dport,
1855                          unsigned int expected_mask)
1856 {
1857         u32 port_mask;
1858         int dpll_reg;
1859
1860         switch (dport->port) {
1861         case PORT_B:
1862                 port_mask = DPLL_PORTB_READY_MASK;
1863                 dpll_reg = DPLL(0);
1864                 break;
1865         case PORT_C:
1866                 port_mask = DPLL_PORTC_READY_MASK;
1867                 dpll_reg = DPLL(0);
1868                 expected_mask <<= 4;
1869                 break;
1870         case PORT_D:
1871                 port_mask = DPLL_PORTD_READY_MASK;
1872                 dpll_reg = DPIO_PHY_STATUS;
1873                 break;
1874         default:
1875                 BUG();
1876         }
1877
1878         if (wait_for((I915_READ(dpll_reg) & port_mask) == expected_mask, 1000))
1879                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1880                      port_name(dport->port), I915_READ(dpll_reg) & port_mask, expected_mask);
1881 }
1882
1883 static void intel_prepare_shared_dpll(struct intel_crtc *crtc)
1884 {
1885         struct drm_device *dev = crtc->base.dev;
1886         struct drm_i915_private *dev_priv = dev->dev_private;
1887         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1888
1889         if (WARN_ON(pll == NULL))
1890                 return;
1891
1892         WARN_ON(!pll->config.crtc_mask);
1893         if (pll->active == 0) {
1894                 DRM_DEBUG_DRIVER("setting up %s\n", pll->name);
1895                 WARN_ON(pll->on);
1896                 assert_shared_dpll_disabled(dev_priv, pll);
1897
1898                 pll->mode_set(dev_priv, pll);
1899         }
1900 }
1901
1902 /**
1903  * intel_enable_shared_dpll - enable PCH PLL
1904  * @dev_priv: i915 private structure
1905  * @pipe: pipe PLL to enable
1906  *
1907  * The PCH PLL needs to be enabled before the PCH transcoder, since it
1908  * drives the transcoder clock.
1909  */
1910 static void intel_enable_shared_dpll(struct intel_crtc *crtc)
1911 {
1912         struct drm_device *dev = crtc->base.dev;
1913         struct drm_i915_private *dev_priv = dev->dev_private;
1914         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1915
1916         if (WARN_ON(pll == NULL))
1917                 return;
1918
1919         if (WARN_ON(pll->config.crtc_mask == 0))
1920                 return;
1921
1922         DRM_DEBUG_KMS("enable %s (active %d, on? %d) for crtc %d\n",
1923                       pll->name, pll->active, pll->on,
1924                       crtc->base.base.id);
1925
1926         if (pll->active++) {
1927                 WARN_ON(!pll->on);
1928                 assert_shared_dpll_enabled(dev_priv, pll);
1929                 return;
1930         }
1931         WARN_ON(pll->on);
1932
1933         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
1934
1935         DRM_DEBUG_KMS("enabling %s\n", pll->name);
1936         pll->enable(dev_priv, pll);
1937         pll->on = true;
1938 }
1939
1940 static void intel_disable_shared_dpll(struct intel_crtc *crtc)
1941 {
1942         struct drm_device *dev = crtc->base.dev;
1943         struct drm_i915_private *dev_priv = dev->dev_private;
1944         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1945
1946         /* PCH only available on ILK+ */
1947         BUG_ON(INTEL_INFO(dev)->gen < 5);
1948         if (pll == NULL)
1949                 return;
1950
1951         if (WARN_ON(!(pll->config.crtc_mask & (1 << drm_crtc_index(&crtc->base)))))
1952                 return;
1953
1954         DRM_DEBUG_KMS("disable %s (active %d, on? %d) for crtc %d\n",
1955                       pll->name, pll->active, pll->on,
1956                       crtc->base.base.id);
1957
1958         if (WARN_ON(pll->active == 0)) {
1959                 assert_shared_dpll_disabled(dev_priv, pll);
1960                 return;
1961         }
1962
1963         assert_shared_dpll_enabled(dev_priv, pll);
1964         WARN_ON(!pll->on);
1965         if (--pll->active)
1966                 return;
1967
1968         DRM_DEBUG_KMS("disabling %s\n", pll->name);
1969         pll->disable(dev_priv, pll);
1970         pll->on = false;
1971
1972         intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS);
1973 }
1974
1975 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1976                                            enum pipe pipe)
1977 {
1978         struct drm_device *dev = dev_priv->dev;
1979         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1980         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1981         uint32_t reg, val, pipeconf_val;
1982
1983         /* PCH only available on ILK+ */
1984         BUG_ON(!HAS_PCH_SPLIT(dev));
1985
1986         /* Make sure PCH DPLL is enabled */
1987         assert_shared_dpll_enabled(dev_priv,
1988                                    intel_crtc_to_shared_dpll(intel_crtc));
1989
1990         /* FDI must be feeding us bits for PCH ports */
1991         assert_fdi_tx_enabled(dev_priv, pipe);
1992         assert_fdi_rx_enabled(dev_priv, pipe);
1993
1994         if (HAS_PCH_CPT(dev)) {
1995                 /* Workaround: Set the timing override bit before enabling the
1996                  * pch transcoder. */
1997                 reg = TRANS_CHICKEN2(pipe);
1998                 val = I915_READ(reg);
1999                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
2000                 I915_WRITE(reg, val);
2001         }
2002
2003         reg = PCH_TRANSCONF(pipe);
2004         val = I915_READ(reg);
2005         pipeconf_val = I915_READ(PIPECONF(pipe));
2006
2007         if (HAS_PCH_IBX(dev_priv->dev)) {
2008                 /*
2009                  * Make the BPC in transcoder be consistent with
2010                  * that in pipeconf reg. For HDMI we must use 8bpc
2011                  * here for both 8bpc and 12bpc.
2012                  */
2013                 val &= ~PIPECONF_BPC_MASK;
2014                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_HDMI))
2015                         val |= PIPECONF_8BPC;
2016                 else
2017                         val |= pipeconf_val & PIPECONF_BPC_MASK;
2018         }
2019
2020         val &= ~TRANS_INTERLACE_MASK;
2021         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
2022                 if (HAS_PCH_IBX(dev_priv->dev) &&
2023                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
2024                         val |= TRANS_LEGACY_INTERLACED_ILK;
2025                 else
2026                         val |= TRANS_INTERLACED;
2027         else
2028                 val |= TRANS_PROGRESSIVE;
2029
2030         I915_WRITE(reg, val | TRANS_ENABLE);
2031         if (wait_for(I915_READ(reg) & TRANS_STATE_ENABLE, 100))
2032                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
2033 }
2034
2035 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
2036                                       enum transcoder cpu_transcoder)
2037 {
2038         u32 val, pipeconf_val;
2039
2040         /* PCH only available on ILK+ */
2041         BUG_ON(!HAS_PCH_SPLIT(dev_priv->dev));
2042
2043         /* FDI must be feeding us bits for PCH ports */
2044         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
2045         assert_fdi_rx_enabled(dev_priv, TRANSCODER_A);
2046
2047         /* Workaround: set timing override bit. */
2048         val = I915_READ(_TRANSA_CHICKEN2);
2049         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
2050         I915_WRITE(_TRANSA_CHICKEN2, val);
2051
2052         val = TRANS_ENABLE;
2053         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
2054
2055         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
2056             PIPECONF_INTERLACED_ILK)
2057                 val |= TRANS_INTERLACED;
2058         else
2059                 val |= TRANS_PROGRESSIVE;
2060
2061         I915_WRITE(LPT_TRANSCONF, val);
2062         if (wait_for(I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE, 100))
2063                 DRM_ERROR("Failed to enable PCH transcoder\n");
2064 }
2065
2066 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
2067                                             enum pipe pipe)
2068 {
2069         struct drm_device *dev = dev_priv->dev;
2070         uint32_t reg, val;
2071
2072         /* FDI relies on the transcoder */
2073         assert_fdi_tx_disabled(dev_priv, pipe);
2074         assert_fdi_rx_disabled(dev_priv, pipe);
2075
2076         /* Ports must be off as well */
2077         assert_pch_ports_disabled(dev_priv, pipe);
2078
2079         reg = PCH_TRANSCONF(pipe);
2080         val = I915_READ(reg);
2081         val &= ~TRANS_ENABLE;
2082         I915_WRITE(reg, val);
2083         /* wait for PCH transcoder off, transcoder state */
2084         if (wait_for((I915_READ(reg) & TRANS_STATE_ENABLE) == 0, 50))
2085                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
2086
2087         if (!HAS_PCH_IBX(dev)) {
2088                 /* Workaround: Clear the timing override chicken bit again. */
2089                 reg = TRANS_CHICKEN2(pipe);
2090                 val = I915_READ(reg);
2091                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
2092                 I915_WRITE(reg, val);
2093         }
2094 }
2095
2096 static void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
2097 {
2098         u32 val;
2099
2100         val = I915_READ(LPT_TRANSCONF);
2101         val &= ~TRANS_ENABLE;
2102         I915_WRITE(LPT_TRANSCONF, val);
2103         /* wait for PCH transcoder off, transcoder state */
2104         if (wait_for((I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE) == 0, 50))
2105                 DRM_ERROR("Failed to disable PCH transcoder\n");
2106
2107         /* Workaround: clear timing override bit. */
2108         val = I915_READ(_TRANSA_CHICKEN2);
2109         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
2110         I915_WRITE(_TRANSA_CHICKEN2, val);
2111 }
2112
2113 /**
2114  * intel_enable_pipe - enable a pipe, asserting requirements
2115  * @crtc: crtc responsible for the pipe
2116  *
2117  * Enable @crtc's pipe, making sure that various hardware specific requirements
2118  * are met, if applicable, e.g. PLL enabled, LVDS pairs enabled, etc.
2119  */
2120 static void intel_enable_pipe(struct intel_crtc *crtc)
2121 {
2122         struct drm_device *dev = crtc->base.dev;
2123         struct drm_i915_private *dev_priv = dev->dev_private;
2124         enum pipe pipe = crtc->pipe;
2125         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
2126                                                                       pipe);
2127         enum pipe pch_transcoder;
2128         int reg;
2129         u32 val;
2130
2131         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
2132
2133         assert_planes_disabled(dev_priv, pipe);
2134         assert_cursor_disabled(dev_priv, pipe);
2135         assert_sprites_disabled(dev_priv, pipe);
2136
2137         if (HAS_PCH_LPT(dev_priv->dev))
2138                 pch_transcoder = TRANSCODER_A;
2139         else
2140                 pch_transcoder = pipe;
2141
2142         /*
2143          * A pipe without a PLL won't actually be able to drive bits from
2144          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
2145          * need the check.
2146          */
2147         if (HAS_GMCH_DISPLAY(dev_priv->dev))
2148                 if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DSI))
2149                         assert_dsi_pll_enabled(dev_priv);
2150                 else
2151                         assert_pll_enabled(dev_priv, pipe);
2152         else {
2153                 if (crtc->config->has_pch_encoder) {
2154                         /* if driving the PCH, we need FDI enabled */
2155                         assert_fdi_rx_pll_enabled(dev_priv, pch_transcoder);
2156                         assert_fdi_tx_pll_enabled(dev_priv,
2157                                                   (enum pipe) cpu_transcoder);
2158                 }
2159                 /* FIXME: assert CPU port conditions for SNB+ */
2160         }
2161
2162         reg = PIPECONF(cpu_transcoder);
2163         val = I915_READ(reg);
2164         if (val & PIPECONF_ENABLE) {
2165                 WARN_ON(!((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
2166                           (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE)));
2167                 return;
2168         }
2169
2170         I915_WRITE(reg, val | PIPECONF_ENABLE);
2171         POSTING_READ(reg);
2172 }
2173
2174 /**
2175  * intel_disable_pipe - disable a pipe, asserting requirements
2176  * @crtc: crtc whose pipes is to be disabled
2177  *
2178  * Disable the pipe of @crtc, making sure that various hardware
2179  * specific requirements are met, if applicable, e.g. plane
2180  * disabled, panel fitter off, etc.
2181  *
2182  * Will wait until the pipe has shut down before returning.
2183  */
2184 static void intel_disable_pipe(struct intel_crtc *crtc)
2185 {
2186         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
2187         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
2188         enum pipe pipe = crtc->pipe;
2189         int reg;
2190         u32 val;
2191
2192         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
2193
2194         /*
2195          * Make sure planes won't keep trying to pump pixels to us,
2196          * or we might hang the display.
2197          */
2198         assert_planes_disabled(dev_priv, pipe);
2199         assert_cursor_disabled(dev_priv, pipe);
2200         assert_sprites_disabled(dev_priv, pipe);
2201
2202         reg = PIPECONF(cpu_transcoder);
2203         val = I915_READ(reg);
2204         if ((val & PIPECONF_ENABLE) == 0)
2205                 return;
2206
2207         /*
2208          * Double wide has implications for planes
2209          * so best keep it disabled when not needed.
2210          */
2211         if (crtc->config->double_wide)
2212                 val &= ~PIPECONF_DOUBLE_WIDE;
2213
2214         /* Don't disable pipe or pipe PLLs if needed */
2215         if (!(pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) &&
2216             !(pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
2217                 val &= ~PIPECONF_ENABLE;
2218
2219         I915_WRITE(reg, val);
2220         if ((val & PIPECONF_ENABLE) == 0)
2221                 intel_wait_for_pipe_off(crtc);
2222 }
2223
2224 static bool need_vtd_wa(struct drm_device *dev)
2225 {
2226 #ifdef CONFIG_INTEL_IOMMU
2227         if (INTEL_INFO(dev)->gen >= 6 && intel_iommu_gfx_mapped)
2228                 return true;
2229 #endif
2230         return false;
2231 }
2232
2233 unsigned int
2234 intel_tile_height(struct drm_device *dev, uint32_t pixel_format,
2235                   uint64_t fb_format_modifier)
2236 {
2237         unsigned int tile_height;
2238         uint32_t pixel_bytes;
2239
2240         switch (fb_format_modifier) {
2241         case DRM_FORMAT_MOD_NONE:
2242                 tile_height = 1;
2243                 break;
2244         case I915_FORMAT_MOD_X_TILED:
2245                 tile_height = IS_GEN2(dev) ? 16 : 8;
2246                 break;
2247         case I915_FORMAT_MOD_Y_TILED:
2248                 tile_height = 32;
2249                 break;
2250         case I915_FORMAT_MOD_Yf_TILED:
2251                 pixel_bytes = drm_format_plane_cpp(pixel_format, 0);
2252                 switch (pixel_bytes) {
2253                 default:
2254                 case 1:
2255                         tile_height = 64;
2256                         break;
2257                 case 2:
2258                 case 4:
2259                         tile_height = 32;
2260                         break;
2261                 case 8:
2262                         tile_height = 16;
2263                         break;
2264                 case 16:
2265                         WARN_ONCE(1,
2266                                   "128-bit pixels are not supported for display!");
2267                         tile_height = 16;
2268                         break;
2269                 }
2270                 break;
2271         default:
2272                 MISSING_CASE(fb_format_modifier);
2273                 tile_height = 1;
2274                 break;
2275         }
2276
2277         return tile_height;
2278 }
2279
2280 unsigned int
2281 intel_fb_align_height(struct drm_device *dev, unsigned int height,
2282                       uint32_t pixel_format, uint64_t fb_format_modifier)
2283 {
2284         return ALIGN(height, intel_tile_height(dev, pixel_format,
2285                                                fb_format_modifier));
2286 }
2287
2288 static int
2289 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view, struct drm_framebuffer *fb,
2290                         const struct drm_plane_state *plane_state)
2291 {
2292         struct intel_rotation_info *info = &view->rotation_info;
2293         unsigned int tile_height, tile_pitch;
2294
2295         *view = i915_ggtt_view_normal;
2296
2297         if (!plane_state)
2298                 return 0;
2299
2300         if (!intel_rotation_90_or_270(plane_state->rotation))
2301                 return 0;
2302
2303         *view = i915_ggtt_view_rotated;
2304
2305         info->height = fb->height;
2306         info->pixel_format = fb->pixel_format;
2307         info->pitch = fb->pitches[0];
2308         info->fb_modifier = fb->modifier[0];
2309
2310         tile_height = intel_tile_height(fb->dev, fb->pixel_format,
2311                                         fb->modifier[0]);
2312         tile_pitch = PAGE_SIZE / tile_height;
2313         info->width_pages = DIV_ROUND_UP(fb->pitches[0], tile_pitch);
2314         info->height_pages = DIV_ROUND_UP(fb->height, tile_height);
2315         info->size = info->width_pages * info->height_pages * PAGE_SIZE;
2316
2317         return 0;
2318 }
2319
2320 static unsigned int intel_linear_alignment(struct drm_i915_private *dev_priv)
2321 {
2322         if (INTEL_INFO(dev_priv)->gen >= 9)
2323                 return 256 * 1024;
2324         else if (IS_BROADWATER(dev_priv) || IS_CRESTLINE(dev_priv) ||
2325                  IS_VALLEYVIEW(dev_priv))
2326                 return 128 * 1024;
2327         else if (INTEL_INFO(dev_priv)->gen >= 4)
2328                 return 4 * 1024;
2329         else
2330                 return 0;
2331 }
2332
2333 int
2334 intel_pin_and_fence_fb_obj(struct drm_plane *plane,
2335                            struct drm_framebuffer *fb,
2336                            const struct drm_plane_state *plane_state,
2337                            struct intel_engine_cs *pipelined,
2338                            struct drm_i915_gem_request **pipelined_request)
2339 {
2340         struct drm_device *dev = fb->dev;
2341         struct drm_i915_private *dev_priv = dev->dev_private;
2342         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2343         struct i915_ggtt_view view;
2344         u32 alignment;
2345         int ret;
2346
2347         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2348
2349         switch (fb->modifier[0]) {
2350         case DRM_FORMAT_MOD_NONE:
2351                 alignment = intel_linear_alignment(dev_priv);
2352                 break;
2353         case I915_FORMAT_MOD_X_TILED:
2354                 if (INTEL_INFO(dev)->gen >= 9)
2355                         alignment = 256 * 1024;
2356                 else {
2357                         /* pin() will align the object as required by fence */
2358                         alignment = 0;
2359                 }
2360                 break;
2361         case I915_FORMAT_MOD_Y_TILED:
2362         case I915_FORMAT_MOD_Yf_TILED:
2363                 if (WARN_ONCE(INTEL_INFO(dev)->gen < 9,
2364                           "Y tiling bo slipped through, driver bug!\n"))
2365                         return -EINVAL;
2366                 alignment = 1 * 1024 * 1024;
2367                 break;
2368         default:
2369                 MISSING_CASE(fb->modifier[0]);
2370                 return -EINVAL;
2371         }
2372
2373         ret = intel_fill_fb_ggtt_view(&view, fb, plane_state);
2374         if (ret)
2375                 return ret;
2376
2377         /* Note that the w/a also requires 64 PTE of padding following the
2378          * bo. We currently fill all unused PTE with the shadow page and so
2379          * we should always have valid PTE following the scanout preventing
2380          * the VT-d warning.
2381          */
2382         if (need_vtd_wa(dev) && alignment < 256 * 1024)
2383                 alignment = 256 * 1024;
2384
2385         /*
2386          * Global gtt pte registers are special registers which actually forward
2387          * writes to a chunk of system memory. Which means that there is no risk
2388          * that the register values disappear as soon as we call
2389          * intel_runtime_pm_put(), so it is correct to wrap only the
2390          * pin/unpin/fence and not more.
2391          */
2392         intel_runtime_pm_get(dev_priv);
2393
2394         dev_priv->mm.interruptible = false;
2395         ret = i915_gem_object_pin_to_display_plane(obj, alignment, pipelined,
2396                                                    pipelined_request, &view);
2397         if (ret)
2398                 goto err_interruptible;
2399
2400         /* Install a fence for tiled scan-out. Pre-i965 always needs a
2401          * fence, whereas 965+ only requires a fence if using
2402          * framebuffer compression.  For simplicity, we always install
2403          * a fence as the cost is not that onerous.
2404          */
2405         ret = i915_gem_object_get_fence(obj);
2406         if (ret)
2407                 goto err_unpin;
2408
2409         i915_gem_object_pin_fence(obj);
2410
2411         dev_priv->mm.interruptible = true;
2412         intel_runtime_pm_put(dev_priv);
2413         return 0;
2414
2415 err_unpin:
2416         i915_gem_object_unpin_from_display_plane(obj, &view);
2417 err_interruptible:
2418         dev_priv->mm.interruptible = true;
2419         intel_runtime_pm_put(dev_priv);
2420         return ret;
2421 }
2422
2423 static void intel_unpin_fb_obj(struct drm_framebuffer *fb,
2424                                const struct drm_plane_state *plane_state)
2425 {
2426         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2427         struct i915_ggtt_view view;
2428         int ret;
2429
2430         WARN_ON(!mutex_is_locked(&obj->base.dev->struct_mutex));
2431
2432         ret = intel_fill_fb_ggtt_view(&view, fb, plane_state);
2433         WARN_ONCE(ret, "Couldn't get view from plane state!");
2434
2435         i915_gem_object_unpin_fence(obj);
2436         i915_gem_object_unpin_from_display_plane(obj, &view);
2437 }
2438
2439 /* Computes the linear offset to the base tile and adjusts x, y. bytes per pixel
2440  * is assumed to be a power-of-two. */
2441 unsigned long intel_gen4_compute_page_offset(struct drm_i915_private *dev_priv,
2442                                              int *x, int *y,
2443                                              unsigned int tiling_mode,
2444                                              unsigned int cpp,
2445                                              unsigned int pitch)
2446 {
2447         if (tiling_mode != I915_TILING_NONE) {
2448                 unsigned int tile_rows, tiles;
2449
2450                 tile_rows = *y / 8;
2451                 *y %= 8;
2452
2453                 tiles = *x / (512/cpp);
2454                 *x %= 512/cpp;
2455
2456                 return tile_rows * pitch * 8 + tiles * 4096;
2457         } else {
2458                 unsigned int alignment = intel_linear_alignment(dev_priv) - 1;
2459                 unsigned int offset;
2460
2461                 offset = *y * pitch + *x * cpp;
2462                 *y = (offset & alignment) / pitch;
2463                 *x = ((offset & alignment) - *y * pitch) / cpp;
2464                 return offset & ~alignment;
2465         }
2466 }
2467
2468 static int i9xx_format_to_fourcc(int format)
2469 {
2470         switch (format) {
2471         case DISPPLANE_8BPP:
2472                 return DRM_FORMAT_C8;
2473         case DISPPLANE_BGRX555:
2474                 return DRM_FORMAT_XRGB1555;
2475         case DISPPLANE_BGRX565:
2476                 return DRM_FORMAT_RGB565;
2477         default:
2478         case DISPPLANE_BGRX888:
2479                 return DRM_FORMAT_XRGB8888;
2480         case DISPPLANE_RGBX888:
2481                 return DRM_FORMAT_XBGR8888;
2482         case DISPPLANE_BGRX101010:
2483                 return DRM_FORMAT_XRGB2101010;
2484         case DISPPLANE_RGBX101010:
2485                 return DRM_FORMAT_XBGR2101010;
2486         }
2487 }
2488
2489 static int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2490 {
2491         switch (format) {
2492         case PLANE_CTL_FORMAT_RGB_565:
2493                 return DRM_FORMAT_RGB565;
2494         default:
2495         case PLANE_CTL_FORMAT_XRGB_8888:
2496                 if (rgb_order) {
2497                         if (alpha)
2498                                 return DRM_FORMAT_ABGR8888;
2499                         else
2500                                 return DRM_FORMAT_XBGR8888;
2501                 } else {
2502                         if (alpha)
2503                                 return DRM_FORMAT_ARGB8888;
2504                         else
2505                                 return DRM_FORMAT_XRGB8888;
2506                 }
2507         case PLANE_CTL_FORMAT_XRGB_2101010:
2508                 if (rgb_order)
2509                         return DRM_FORMAT_XBGR2101010;
2510                 else
2511                         return DRM_FORMAT_XRGB2101010;
2512         }
2513 }
2514
2515 static bool
2516 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2517                               struct intel_initial_plane_config *plane_config)
2518 {
2519         struct drm_device *dev = crtc->base.dev;
2520         struct drm_i915_gem_object *obj = NULL;
2521         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2522         struct drm_framebuffer *fb = &plane_config->fb->base;
2523         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2524         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2525                                     PAGE_SIZE);
2526
2527         size_aligned -= base_aligned;
2528
2529         if (plane_config->size == 0)
2530                 return false;
2531
2532         obj = i915_gem_object_create_stolen_for_preallocated(dev,
2533                                                              base_aligned,
2534                                                              base_aligned,
2535                                                              size_aligned);
2536         if (!obj)
2537                 return false;
2538
2539         obj->tiling_mode = plane_config->tiling;
2540         if (obj->tiling_mode == I915_TILING_X)
2541                 obj->stride = fb->pitches[0];
2542
2543         mode_cmd.pixel_format = fb->pixel_format;
2544         mode_cmd.width = fb->width;
2545         mode_cmd.height = fb->height;
2546         mode_cmd.pitches[0] = fb->pitches[0];
2547         mode_cmd.modifier[0] = fb->modifier[0];
2548         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2549
2550         mutex_lock(&dev->struct_mutex);
2551         if (intel_framebuffer_init(dev, to_intel_framebuffer(fb),
2552                                    &mode_cmd, obj)) {
2553                 DRM_DEBUG_KMS("intel fb init failed\n");
2554                 goto out_unref_obj;
2555         }
2556         mutex_unlock(&dev->struct_mutex);
2557
2558         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2559         return true;
2560
2561 out_unref_obj:
2562         drm_gem_object_unreference(&obj->base);
2563         mutex_unlock(&dev->struct_mutex);
2564         return false;
2565 }
2566
2567 /* Update plane->state->fb to match plane->fb after driver-internal updates */
2568 static void
2569 update_state_fb(struct drm_plane *plane)
2570 {
2571         if (plane->fb == plane->state->fb)
2572                 return;
2573
2574         if (plane->state->fb)
2575                 drm_framebuffer_unreference(plane->state->fb);
2576         plane->state->fb = plane->fb;
2577         if (plane->state->fb)
2578                 drm_framebuffer_reference(plane->state->fb);
2579 }
2580
2581 static void
2582 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2583                              struct intel_initial_plane_config *plane_config)
2584 {
2585         struct drm_device *dev = intel_crtc->base.dev;
2586         struct drm_i915_private *dev_priv = dev->dev_private;
2587         struct drm_crtc *c;
2588         struct intel_crtc *i;
2589         struct drm_i915_gem_object *obj;
2590         struct drm_plane *primary = intel_crtc->base.primary;
2591         struct drm_plane_state *plane_state = primary->state;
2592         struct drm_framebuffer *fb;
2593
2594         if (!plane_config->fb)
2595                 return;
2596
2597         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2598                 fb = &plane_config->fb->base;
2599                 goto valid_fb;
2600         }
2601
2602         kfree(plane_config->fb);
2603
2604         /*
2605          * Failed to alloc the obj, check to see if we should share
2606          * an fb with another CRTC instead
2607          */
2608         for_each_crtc(dev, c) {
2609                 i = to_intel_crtc(c);
2610
2611                 if (c == &intel_crtc->base)
2612                         continue;
2613
2614                 if (!i->active)
2615                         continue;
2616
2617                 fb = c->primary->fb;
2618                 if (!fb)
2619                         continue;
2620
2621                 obj = intel_fb_obj(fb);
2622                 if (i915_gem_obj_ggtt_offset(obj) == plane_config->base) {
2623                         drm_framebuffer_reference(fb);
2624                         goto valid_fb;
2625                 }
2626         }
2627
2628         return;
2629
2630 valid_fb:
2631         plane_state->src_x = plane_state->src_y = 0;
2632         plane_state->src_w = fb->width << 16;
2633         plane_state->src_h = fb->height << 16;
2634
2635         plane_state->crtc_x = plane_state->src_y = 0;
2636         plane_state->crtc_w = fb->width;
2637         plane_state->crtc_h = fb->height;
2638
2639         obj = intel_fb_obj(fb);
2640         if (obj->tiling_mode != I915_TILING_NONE)
2641                 dev_priv->preserve_bios_swizzle = true;
2642
2643         drm_framebuffer_reference(fb);
2644         primary->fb = primary->state->fb = fb;
2645         primary->crtc = primary->state->crtc = &intel_crtc->base;
2646         intel_crtc->base.state->plane_mask |= (1 << drm_plane_index(primary));
2647         obj->frontbuffer_bits |= to_intel_plane(primary)->frontbuffer_bit;
2648 }
2649
2650 static void i9xx_update_primary_plane(struct drm_crtc *crtc,
2651                                       struct drm_framebuffer *fb,
2652                                       int x, int y)
2653 {
2654         struct drm_device *dev = crtc->dev;
2655         struct drm_i915_private *dev_priv = dev->dev_private;
2656         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2657         struct drm_plane *primary = crtc->primary;
2658         bool visible = to_intel_plane_state(primary->state)->visible;
2659         struct drm_i915_gem_object *obj;
2660         int plane = intel_crtc->plane;
2661         unsigned long linear_offset;
2662         u32 dspcntr;
2663         u32 reg = DSPCNTR(plane);
2664         int pixel_size;
2665
2666         if (!visible || !fb) {
2667                 I915_WRITE(reg, 0);
2668                 if (INTEL_INFO(dev)->gen >= 4)
2669                         I915_WRITE(DSPSURF(plane), 0);
2670                 else
2671                         I915_WRITE(DSPADDR(plane), 0);
2672                 POSTING_READ(reg);
2673                 return;
2674         }
2675
2676         obj = intel_fb_obj(fb);
2677         if (WARN_ON(obj == NULL))
2678                 return;
2679
2680         pixel_size = drm_format_plane_cpp(fb->pixel_format, 0);
2681
2682         dspcntr = DISPPLANE_GAMMA_ENABLE;
2683
2684         dspcntr |= DISPLAY_PLANE_ENABLE;
2685
2686         if (INTEL_INFO(dev)->gen < 4) {
2687                 if (intel_crtc->pipe == PIPE_B)
2688                         dspcntr |= DISPPLANE_SEL_PIPE_B;
2689
2690                 /* pipesrc and dspsize control the size that is scaled from,
2691                  * which should always be the user's requested size.
2692                  */
2693                 I915_WRITE(DSPSIZE(plane),
2694                            ((intel_crtc->config->pipe_src_h - 1) << 16) |
2695                            (intel_crtc->config->pipe_src_w - 1));
2696                 I915_WRITE(DSPPOS(plane), 0);
2697         } else if (IS_CHERRYVIEW(dev) && plane == PLANE_B) {
2698                 I915_WRITE(PRIMSIZE(plane),
2699                            ((intel_crtc->config->pipe_src_h - 1) << 16) |
2700                            (intel_crtc->config->pipe_src_w - 1));
2701                 I915_WRITE(PRIMPOS(plane), 0);
2702                 I915_WRITE(PRIMCNSTALPHA(plane), 0);
2703         }
2704
2705         switch (fb->pixel_format) {
2706         case DRM_FORMAT_C8:
2707                 dspcntr |= DISPPLANE_8BPP;
2708                 break;
2709         case DRM_FORMAT_XRGB1555:
2710                 dspcntr |= DISPPLANE_BGRX555;
2711                 break;
2712         case DRM_FORMAT_RGB565:
2713                 dspcntr |= DISPPLANE_BGRX565;
2714                 break;
2715         case DRM_FORMAT_XRGB8888:
2716                 dspcntr |= DISPPLANE_BGRX888;
2717                 break;
2718         case DRM_FORMAT_XBGR8888:
2719                 dspcntr |= DISPPLANE_RGBX888;
2720                 break;
2721         case DRM_FORMAT_XRGB2101010:
2722                 dspcntr |= DISPPLANE_BGRX101010;
2723                 break;
2724         case DRM_FORMAT_XBGR2101010:
2725                 dspcntr |= DISPPLANE_RGBX101010;
2726                 break;
2727         default:
2728                 BUG();
2729         }
2730
2731         if (INTEL_INFO(dev)->gen >= 4 &&
2732             obj->tiling_mode != I915_TILING_NONE)
2733                 dspcntr |= DISPPLANE_TILED;
2734
2735         if (IS_G4X(dev))
2736                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2737
2738         linear_offset = y * fb->pitches[0] + x * pixel_size;
2739
2740         if (INTEL_INFO(dev)->gen >= 4) {
2741                 intel_crtc->dspaddr_offset =
2742                         intel_gen4_compute_page_offset(dev_priv,
2743                                                        &x, &y, obj->tiling_mode,
2744                                                        pixel_size,
2745                                                        fb->pitches[0]);
2746                 linear_offset -= intel_crtc->dspaddr_offset;
2747         } else {
2748                 intel_crtc->dspaddr_offset = linear_offset;
2749         }
2750
2751         if (crtc->primary->state->rotation == BIT(DRM_ROTATE_180)) {
2752                 dspcntr |= DISPPLANE_ROTATE_180;
2753
2754                 x += (intel_crtc->config->pipe_src_w - 1);
2755                 y += (intel_crtc->config->pipe_src_h - 1);
2756
2757                 /* Finding the last pixel of the last line of the display
2758                 data and adding to linear_offset*/
2759                 linear_offset +=
2760                         (intel_crtc->config->pipe_src_h - 1) * fb->pitches[0] +
2761                         (intel_crtc->config->pipe_src_w - 1) * pixel_size;
2762         }
2763
2764         I915_WRITE(reg, dspcntr);
2765
2766         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2767         if (INTEL_INFO(dev)->gen >= 4) {
2768                 I915_WRITE(DSPSURF(plane),
2769                            i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2770                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2771                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2772         } else
2773                 I915_WRITE(DSPADDR(plane), i915_gem_obj_ggtt_offset(obj) + linear_offset);
2774         POSTING_READ(reg);
2775 }
2776
2777 static void ironlake_update_primary_plane(struct drm_crtc *crtc,
2778                                           struct drm_framebuffer *fb,
2779                                           int x, int y)
2780 {
2781         struct drm_device *dev = crtc->dev;
2782         struct drm_i915_private *dev_priv = dev->dev_private;
2783         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2784         struct drm_plane *primary = crtc->primary;
2785         bool visible = to_intel_plane_state(primary->state)->visible;
2786         struct drm_i915_gem_object *obj;
2787         int plane = intel_crtc->plane;
2788         unsigned long linear_offset;
2789         u32 dspcntr;
2790         u32 reg = DSPCNTR(plane);
2791         int pixel_size;
2792
2793         if (!visible || !fb) {
2794                 I915_WRITE(reg, 0);
2795                 I915_WRITE(DSPSURF(plane), 0);
2796                 POSTING_READ(reg);
2797                 return;
2798         }
2799
2800         obj = intel_fb_obj(fb);
2801         if (WARN_ON(obj == NULL))
2802                 return;
2803
2804         pixel_size = drm_format_plane_cpp(fb->pixel_format, 0);
2805
2806         dspcntr = DISPPLANE_GAMMA_ENABLE;
2807
2808         dspcntr |= DISPLAY_PLANE_ENABLE;
2809
2810         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
2811                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
2812
2813         switch (fb->pixel_format) {
2814         case DRM_FORMAT_C8:
2815                 dspcntr |= DISPPLANE_8BPP;
2816                 break;
2817         case DRM_FORMAT_RGB565:
2818                 dspcntr |= DISPPLANE_BGRX565;
2819                 break;
2820         case DRM_FORMAT_XRGB8888:
2821                 dspcntr |= DISPPLANE_BGRX888;
2822                 break;
2823         case DRM_FORMAT_XBGR8888:
2824                 dspcntr |= DISPPLANE_RGBX888;
2825                 break;
2826         case DRM_FORMAT_XRGB2101010:
2827                 dspcntr |= DISPPLANE_BGRX101010;
2828                 break;
2829         case DRM_FORMAT_XBGR2101010:
2830                 dspcntr |= DISPPLANE_RGBX101010;
2831                 break;
2832         default:
2833                 BUG();
2834         }
2835
2836         if (obj->tiling_mode != I915_TILING_NONE)
2837                 dspcntr |= DISPPLANE_TILED;
2838
2839         if (!IS_HASWELL(dev) && !IS_BROADWELL(dev))
2840                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2841
2842         linear_offset = y * fb->pitches[0] + x * pixel_size;
2843         intel_crtc->dspaddr_offset =
2844                 intel_gen4_compute_page_offset(dev_priv,
2845                                                &x, &y, obj->tiling_mode,
2846                                                pixel_size,
2847                                                fb->pitches[0]);
2848         linear_offset -= intel_crtc->dspaddr_offset;
2849         if (crtc->primary->state->rotation == BIT(DRM_ROTATE_180)) {
2850                 dspcntr |= DISPPLANE_ROTATE_180;
2851
2852                 if (!IS_HASWELL(dev) && !IS_BROADWELL(dev)) {
2853                         x += (intel_crtc->config->pipe_src_w - 1);
2854                         y += (intel_crtc->config->pipe_src_h - 1);
2855
2856                         /* Finding the last pixel of the last line of the display
2857                         data and adding to linear_offset*/
2858                         linear_offset +=
2859                                 (intel_crtc->config->pipe_src_h - 1) * fb->pitches[0] +
2860                                 (intel_crtc->config->pipe_src_w - 1) * pixel_size;
2861                 }
2862         }
2863
2864         I915_WRITE(reg, dspcntr);
2865
2866         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2867         I915_WRITE(DSPSURF(plane),
2868                    i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2869         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
2870                 I915_WRITE(DSPOFFSET(plane), (y << 16) | x);
2871         } else {
2872                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2873                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2874         }
2875         POSTING_READ(reg);
2876 }
2877
2878 u32 intel_fb_stride_alignment(struct drm_device *dev, uint64_t fb_modifier,
2879                               uint32_t pixel_format)
2880 {
2881         u32 bits_per_pixel = drm_format_plane_cpp(pixel_format, 0) * 8;
2882
2883         /*
2884          * The stride is either expressed as a multiple of 64 bytes
2885          * chunks for linear buffers or in number of tiles for tiled
2886          * buffers.
2887          */
2888         switch (fb_modifier) {
2889         case DRM_FORMAT_MOD_NONE:
2890                 return 64;
2891         case I915_FORMAT_MOD_X_TILED:
2892                 if (INTEL_INFO(dev)->gen == 2)
2893                         return 128;
2894                 return 512;
2895         case I915_FORMAT_MOD_Y_TILED:
2896                 /* No need to check for old gens and Y tiling since this is
2897                  * about the display engine and those will be blocked before
2898                  * we get here.
2899                  */
2900                 return 128;
2901         case I915_FORMAT_MOD_Yf_TILED:
2902                 if (bits_per_pixel == 8)
2903                         return 64;
2904                 else
2905                         return 128;
2906         default:
2907                 MISSING_CASE(fb_modifier);
2908                 return 64;
2909         }
2910 }
2911
2912 unsigned long intel_plane_obj_offset(struct intel_plane *intel_plane,
2913                                      struct drm_i915_gem_object *obj)
2914 {
2915         const struct i915_ggtt_view *view = &i915_ggtt_view_normal;
2916
2917         if (intel_rotation_90_or_270(intel_plane->base.state->rotation))
2918                 view = &i915_ggtt_view_rotated;
2919
2920         return i915_gem_obj_ggtt_offset_view(obj, view);
2921 }
2922
2923 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
2924 {
2925         struct drm_device *dev = intel_crtc->base.dev;
2926         struct drm_i915_private *dev_priv = dev->dev_private;
2927
2928         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
2929         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
2930         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
2931         DRM_DEBUG_KMS("CRTC:%d Disabled scaler id %u.%u\n",
2932                 intel_crtc->base.base.id, intel_crtc->pipe, id);
2933 }
2934
2935 /*
2936  * This function detaches (aka. unbinds) unused scalers in hardware
2937  */
2938 static void skl_detach_scalers(struct intel_crtc *intel_crtc)
2939 {
2940         struct intel_crtc_scaler_state *scaler_state;
2941         int i;
2942
2943         scaler_state = &intel_crtc->config->scaler_state;
2944
2945         /* loop through and disable scalers that aren't in use */
2946         for (i = 0; i < intel_crtc->num_scalers; i++) {
2947                 if (!scaler_state->scalers[i].in_use)
2948                         skl_detach_scaler(intel_crtc, i);
2949         }
2950 }
2951
2952 u32 skl_plane_ctl_format(uint32_t pixel_format)
2953 {
2954         switch (pixel_format) {
2955         case DRM_FORMAT_C8:
2956                 return PLANE_CTL_FORMAT_INDEXED;
2957         case DRM_FORMAT_RGB565:
2958                 return PLANE_CTL_FORMAT_RGB_565;
2959         case DRM_FORMAT_XBGR8888:
2960                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
2961         case DRM_FORMAT_XRGB8888:
2962                 return PLANE_CTL_FORMAT_XRGB_8888;
2963         /*
2964          * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
2965          * to be already pre-multiplied. We need to add a knob (or a different
2966          * DRM_FORMAT) for user-space to configure that.
2967          */
2968         case DRM_FORMAT_ABGR8888:
2969                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX |
2970                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
2971         case DRM_FORMAT_ARGB8888:
2972                 return PLANE_CTL_FORMAT_XRGB_8888 |
2973                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
2974         case DRM_FORMAT_XRGB2101010:
2975                 return PLANE_CTL_FORMAT_XRGB_2101010;
2976         case DRM_FORMAT_XBGR2101010:
2977                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
2978         case DRM_FORMAT_YUYV:
2979                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
2980         case DRM_FORMAT_YVYU:
2981                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
2982         case DRM_FORMAT_UYVY:
2983                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
2984         case DRM_FORMAT_VYUY:
2985                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
2986         default:
2987                 MISSING_CASE(pixel_format);
2988         }
2989
2990         return 0;
2991 }
2992
2993 u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
2994 {
2995         switch (fb_modifier) {
2996         case DRM_FORMAT_MOD_NONE:
2997                 break;
2998         case I915_FORMAT_MOD_X_TILED:
2999                 return PLANE_CTL_TILED_X;
3000         case I915_FORMAT_MOD_Y_TILED:
3001                 return PLANE_CTL_TILED_Y;
3002         case I915_FORMAT_MOD_Yf_TILED:
3003                 return PLANE_CTL_TILED_YF;
3004         default:
3005                 MISSING_CASE(fb_modifier);
3006         }
3007
3008         return 0;
3009 }
3010
3011 u32 skl_plane_ctl_rotation(unsigned int rotation)
3012 {
3013         switch (rotation) {
3014         case BIT(DRM_ROTATE_0):
3015                 break;
3016         /*
3017          * DRM_ROTATE_ is counter clockwise to stay compatible with Xrandr
3018          * while i915 HW rotation is clockwise, thats why this swapping.
3019          */
3020         case BIT(DRM_ROTATE_90):
3021                 return PLANE_CTL_ROTATE_270;
3022         case BIT(DRM_ROTATE_180):
3023                 return PLANE_CTL_ROTATE_180;
3024         case BIT(DRM_ROTATE_270):
3025                 return PLANE_CTL_ROTATE_90;
3026         default:
3027                 MISSING_CASE(rotation);
3028         }
3029
3030         return 0;
3031 }
3032
3033 static void skylake_update_primary_plane(struct drm_crtc *crtc,
3034                                          struct drm_framebuffer *fb,
3035                                          int x, int y)
3036 {
3037         struct drm_device *dev = crtc->dev;
3038         struct drm_i915_private *dev_priv = dev->dev_private;
3039         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3040         struct drm_plane *plane = crtc->primary;
3041         bool visible = to_intel_plane_state(plane->state)->visible;
3042         struct drm_i915_gem_object *obj;
3043         int pipe = intel_crtc->pipe;
3044         u32 plane_ctl, stride_div, stride;
3045         u32 tile_height, plane_offset, plane_size;
3046         unsigned int rotation;
3047         int x_offset, y_offset;
3048         unsigned long surf_addr;
3049         struct intel_crtc_state *crtc_state = intel_crtc->config;
3050         struct intel_plane_state *plane_state;
3051         int src_x = 0, src_y = 0, src_w = 0, src_h = 0;
3052         int dst_x = 0, dst_y = 0, dst_w = 0, dst_h = 0;
3053         int scaler_id = -1;
3054
3055         plane_state = to_intel_plane_state(plane->state);
3056
3057         if (!visible || !fb) {
3058                 I915_WRITE(PLANE_CTL(pipe, 0), 0);
3059                 I915_WRITE(PLANE_SURF(pipe, 0), 0);
3060                 POSTING_READ(PLANE_CTL(pipe, 0));
3061                 return;
3062         }
3063
3064         plane_ctl = PLANE_CTL_ENABLE |
3065                     PLANE_CTL_PIPE_GAMMA_ENABLE |
3066                     PLANE_CTL_PIPE_CSC_ENABLE;
3067
3068         plane_ctl |= skl_plane_ctl_format(fb->pixel_format);
3069         plane_ctl |= skl_plane_ctl_tiling(fb->modifier[0]);
3070         plane_ctl |= PLANE_CTL_PLANE_GAMMA_DISABLE;
3071
3072         rotation = plane->state->rotation;
3073         plane_ctl |= skl_plane_ctl_rotation(rotation);
3074
3075         obj = intel_fb_obj(fb);
3076         stride_div = intel_fb_stride_alignment(dev, fb->modifier[0],
3077                                                fb->pixel_format);
3078         surf_addr = intel_plane_obj_offset(to_intel_plane(plane), obj);
3079
3080         /*
3081          * FIXME: intel_plane_state->src, dst aren't set when transitional
3082          * update_plane helpers are called from legacy paths.
3083          * Once full atomic crtc is available, below check can be avoided.
3084          */
3085         if (drm_rect_width(&plane_state->src)) {
3086                 scaler_id = plane_state->scaler_id;
3087                 src_x = plane_state->src.x1 >> 16;
3088                 src_y = plane_state->src.y1 >> 16;
3089                 src_w = drm_rect_width(&plane_state->src) >> 16;
3090                 src_h = drm_rect_height(&plane_state->src) >> 16;
3091                 dst_x = plane_state->dst.x1;
3092                 dst_y = plane_state->dst.y1;
3093                 dst_w = drm_rect_width(&plane_state->dst);
3094                 dst_h = drm_rect_height(&plane_state->dst);
3095
3096                 WARN_ON(x != src_x || y != src_y);
3097         } else {
3098                 src_w = intel_crtc->config->pipe_src_w;
3099                 src_h = intel_crtc->config->pipe_src_h;
3100         }
3101
3102         if (intel_rotation_90_or_270(rotation)) {
3103                 /* stride = Surface height in tiles */
3104                 tile_height = intel_tile_height(dev, fb->pixel_format,
3105                                                 fb->modifier[0]);
3106                 stride = DIV_ROUND_UP(fb->height, tile_height);
3107                 x_offset = stride * tile_height - y - src_h;
3108                 y_offset = x;
3109                 plane_size = (src_w - 1) << 16 | (src_h - 1);
3110         } else {
3111                 stride = fb->pitches[0] / stride_div;
3112                 x_offset = x;
3113                 y_offset = y;
3114                 plane_size = (src_h - 1) << 16 | (src_w - 1);
3115         }
3116         plane_offset = y_offset << 16 | x_offset;
3117
3118         I915_WRITE(PLANE_CTL(pipe, 0), plane_ctl);
3119         I915_WRITE(PLANE_OFFSET(pipe, 0), plane_offset);
3120         I915_WRITE(PLANE_SIZE(pipe, 0), plane_size);
3121         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
3122
3123         if (scaler_id >= 0) {
3124                 uint32_t ps_ctrl = 0;
3125
3126                 WARN_ON(!dst_w || !dst_h);
3127                 ps_ctrl = PS_SCALER_EN | PS_PLANE_SEL(0) |
3128                         crtc_state->scaler_state.scalers[scaler_id].mode;
3129                 I915_WRITE(SKL_PS_CTRL(pipe, scaler_id), ps_ctrl);
3130                 I915_WRITE(SKL_PS_PWR_GATE(pipe, scaler_id), 0);
3131                 I915_WRITE(SKL_PS_WIN_POS(pipe, scaler_id), (dst_x << 16) | dst_y);
3132                 I915_WRITE(SKL_PS_WIN_SZ(pipe, scaler_id), (dst_w << 16) | dst_h);
3133                 I915_WRITE(PLANE_POS(pipe, 0), 0);
3134         } else {
3135                 I915_WRITE(PLANE_POS(pipe, 0), (dst_y << 16) | dst_x);
3136         }
3137
3138         I915_WRITE(PLANE_SURF(pipe, 0), surf_addr);
3139
3140         POSTING_READ(PLANE_SURF(pipe, 0));
3141 }
3142
3143 /* Assume fb object is pinned & idle & fenced and just update base pointers */
3144 static int
3145 intel_pipe_set_base_atomic(struct drm_crtc *crtc, struct drm_framebuffer *fb,
3146                            int x, int y, enum mode_set_atomic state)
3147 {
3148         struct drm_device *dev = crtc->dev;
3149         struct drm_i915_private *dev_priv = dev->dev_private;
3150
3151         if (dev_priv->fbc.disable_fbc)
3152                 dev_priv->fbc.disable_fbc(dev_priv);
3153
3154         dev_priv->display.update_primary_plane(crtc, fb, x, y);
3155
3156         return 0;
3157 }
3158
3159 static void intel_complete_page_flips(struct drm_device *dev)
3160 {
3161         struct drm_crtc *crtc;
3162
3163         for_each_crtc(dev, crtc) {
3164                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3165                 enum plane plane = intel_crtc->plane;
3166
3167                 intel_prepare_page_flip(dev, plane);
3168                 intel_finish_page_flip_plane(dev, plane);
3169         }
3170 }
3171
3172 static void intel_update_primary_planes(struct drm_device *dev)
3173 {
3174         struct drm_i915_private *dev_priv = dev->dev_private;
3175         struct drm_crtc *crtc;
3176
3177         for_each_crtc(dev, crtc) {
3178                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3179
3180                 drm_modeset_lock(&crtc->mutex, NULL);
3181                 /*
3182                  * FIXME: Once we have proper support for primary planes (and
3183                  * disabling them without disabling the entire crtc) allow again
3184                  * a NULL crtc->primary->fb.
3185                  */
3186                 if (intel_crtc->active && crtc->primary->fb)
3187                         dev_priv->display.update_primary_plane(crtc,
3188                                                                crtc->primary->fb,
3189                                                                crtc->x,
3190                                                                crtc->y);
3191                 drm_modeset_unlock(&crtc->mutex);
3192         }
3193 }
3194
3195 void intel_prepare_reset(struct drm_device *dev)
3196 {
3197         /* no reset support for gen2 */
3198         if (IS_GEN2(dev))
3199                 return;
3200
3201         /* reset doesn't touch the display */
3202         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
3203                 return;
3204
3205         drm_modeset_lock_all(dev);
3206         /*
3207          * Disabling the crtcs gracefully seems nicer. Also the
3208          * g33 docs say we should at least disable all the planes.
3209          */
3210         intel_display_suspend(dev);
3211 }
3212
3213 void intel_finish_reset(struct drm_device *dev)
3214 {
3215         struct drm_i915_private *dev_priv = to_i915(dev);
3216
3217         /*
3218          * Flips in the rings will be nuked by the reset,
3219          * so complete all pending flips so that user space
3220          * will get its events and not get stuck.
3221          */
3222         intel_complete_page_flips(dev);
3223
3224         /* no reset support for gen2 */
3225         if (IS_GEN2(dev))
3226                 return;
3227
3228         /* reset doesn't touch the display */
3229         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev)) {
3230                 /*
3231                  * Flips in the rings have been nuked by the reset,
3232                  * so update the base address of all primary
3233                  * planes to the the last fb to make sure we're
3234                  * showing the correct fb after a reset.
3235                  */
3236                 intel_update_primary_planes(dev);
3237                 return;
3238         }
3239
3240         /*
3241          * The display has been reset as well,
3242          * so need a full re-initialization.
3243          */
3244         intel_runtime_pm_disable_interrupts(dev_priv);
3245         intel_runtime_pm_enable_interrupts(dev_priv);
3246
3247         intel_modeset_init_hw(dev);
3248
3249         spin_lock_irq(&dev_priv->irq_lock);
3250         if (dev_priv->display.hpd_irq_setup)
3251                 dev_priv->display.hpd_irq_setup(dev);
3252         spin_unlock_irq(&dev_priv->irq_lock);
3253
3254         intel_modeset_setup_hw_state(dev, true);
3255
3256         intel_hpd_init(dev_priv);
3257
3258         drm_modeset_unlock_all(dev);
3259 }
3260
3261 static void
3262 intel_finish_fb(struct drm_framebuffer *old_fb)
3263 {
3264         struct drm_i915_gem_object *obj = intel_fb_obj(old_fb);
3265         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
3266         bool was_interruptible = dev_priv->mm.interruptible;
3267         int ret;
3268
3269         /* Big Hammer, we also need to ensure that any pending
3270          * MI_WAIT_FOR_EVENT inside a user batch buffer on the
3271          * current scanout is retired before unpinning the old
3272          * framebuffer. Note that we rely on userspace rendering
3273          * into the buffer attached to the pipe they are waiting
3274          * on. If not, userspace generates a GPU hang with IPEHR
3275          * point to the MI_WAIT_FOR_EVENT.
3276          *
3277          * This should only fail upon a hung GPU, in which case we
3278          * can safely continue.
3279          */
3280         dev_priv->mm.interruptible = false;
3281         ret = i915_gem_object_wait_rendering(obj, true);
3282         dev_priv->mm.interruptible = was_interruptible;
3283
3284         WARN_ON(ret);
3285 }
3286
3287 static bool intel_crtc_has_pending_flip(struct drm_crtc *crtc)
3288 {
3289         struct drm_device *dev = crtc->dev;
3290         struct drm_i915_private *dev_priv = dev->dev_private;
3291         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3292         bool pending;
3293
3294         if (i915_reset_in_progress(&dev_priv->gpu_error) ||
3295             intel_crtc->reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
3296                 return false;
3297
3298         spin_lock_irq(&dev->event_lock);
3299         pending = to_intel_crtc(crtc)->unpin_work != NULL;
3300         spin_unlock_irq(&dev->event_lock);
3301
3302         return pending;
3303 }
3304
3305 static void intel_update_pipe_size(struct intel_crtc *crtc)
3306 {
3307         struct drm_device *dev = crtc->base.dev;
3308         struct drm_i915_private *dev_priv = dev->dev_private;
3309         const struct drm_display_mode *adjusted_mode;
3310
3311         if (!i915.fastboot)
3312                 return;
3313
3314         /*
3315          * Update pipe size and adjust fitter if needed: the reason for this is
3316          * that in compute_mode_changes we check the native mode (not the pfit
3317          * mode) to see if we can flip rather than do a full mode set. In the
3318          * fastboot case, we'll flip, but if we don't update the pipesrc and
3319          * pfit state, we'll end up with a big fb scanned out into the wrong
3320          * sized surface.
3321          *
3322          * To fix this properly, we need to hoist the checks up into
3323          * compute_mode_changes (or above), check the actual pfit state and
3324          * whether the platform allows pfit disable with pipe active, and only
3325          * then update the pipesrc and pfit state, even on the flip path.
3326          */
3327
3328         adjusted_mode = &crtc->config->base.adjusted_mode;
3329
3330         I915_WRITE(PIPESRC(crtc->pipe),
3331                    ((adjusted_mode->crtc_hdisplay - 1) << 16) |
3332                    (adjusted_mode->crtc_vdisplay - 1));
3333         if (!crtc->config->pch_pfit.enabled &&
3334             (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS) ||
3335              intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP))) {
3336                 I915_WRITE(PF_CTL(crtc->pipe), 0);
3337                 I915_WRITE(PF_WIN_POS(crtc->pipe), 0);
3338                 I915_WRITE(PF_WIN_SZ(crtc->pipe), 0);
3339         }
3340         crtc->config->pipe_src_w = adjusted_mode->crtc_hdisplay;
3341         crtc->config->pipe_src_h = adjusted_mode->crtc_vdisplay;
3342 }
3343
3344 static void intel_fdi_normal_train(struct drm_crtc *crtc)
3345 {
3346         struct drm_device *dev = crtc->dev;
3347         struct drm_i915_private *dev_priv = dev->dev_private;
3348         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3349         int pipe = intel_crtc->pipe;
3350         u32 reg, temp;
3351
3352         /* enable normal train */
3353         reg = FDI_TX_CTL(pipe);
3354         temp = I915_READ(reg);
3355         if (IS_IVYBRIDGE(dev)) {
3356                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3357                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3358         } else {
3359                 temp &= ~FDI_LINK_TRAIN_NONE;
3360                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3361         }
3362         I915_WRITE(reg, temp);
3363
3364         reg = FDI_RX_CTL(pipe);
3365         temp = I915_READ(reg);
3366         if (HAS_PCH_CPT(dev)) {
3367                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3368                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3369         } else {
3370                 temp &= ~FDI_LINK_TRAIN_NONE;
3371                 temp |= FDI_LINK_TRAIN_NONE;
3372         }
3373         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3374
3375         /* wait one idle pattern time */
3376         POSTING_READ(reg);
3377         udelay(1000);
3378
3379         /* IVB wants error correction enabled */
3380         if (IS_IVYBRIDGE(dev))
3381                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3382                            FDI_FE_ERRC_ENABLE);
3383 }
3384
3385 /* The FDI link training functions for ILK/Ibexpeak. */
3386 static void ironlake_fdi_link_train(struct drm_crtc *crtc)
3387 {
3388         struct drm_device *dev = crtc->dev;
3389         struct drm_i915_private *dev_priv = dev->dev_private;
3390         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3391         int pipe = intel_crtc->pipe;
3392         u32 reg, temp, tries;
3393
3394         /* FDI needs bits from pipe first */
3395         assert_pipe_enabled(dev_priv, pipe);
3396
3397         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3398            for train result */
3399         reg = FDI_RX_IMR(pipe);
3400         temp = I915_READ(reg);
3401         temp &= ~FDI_RX_SYMBOL_LOCK;
3402         temp &= ~FDI_RX_BIT_LOCK;
3403         I915_WRITE(reg, temp);
3404         I915_READ(reg);
3405         udelay(150);
3406
3407         /* enable CPU FDI TX and PCH FDI RX */
3408         reg = FDI_TX_CTL(pipe);
3409         temp = I915_READ(reg);
3410         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3411         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3412         temp &= ~FDI_LINK_TRAIN_NONE;
3413         temp |= FDI_LINK_TRAIN_PATTERN_1;
3414         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3415
3416         reg = FDI_RX_CTL(pipe);
3417         temp = I915_READ(reg);
3418         temp &= ~FDI_LINK_TRAIN_NONE;
3419         temp |= FDI_LINK_TRAIN_PATTERN_1;
3420         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3421
3422         POSTING_READ(reg);
3423         udelay(150);
3424
3425         /* Ironlake workaround, enable clock pointer after FDI enable*/
3426         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3427         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3428                    FDI_RX_PHASE_SYNC_POINTER_EN);
3429
3430         reg = FDI_RX_IIR(pipe);
3431         for (tries = 0; tries < 5; tries++) {
3432                 temp = I915_READ(reg);
3433                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3434
3435                 if ((temp & FDI_RX_BIT_LOCK)) {
3436                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3437                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3438                         break;
3439                 }
3440         }
3441         if (tries == 5)
3442                 DRM_ERROR("FDI train 1 fail!\n");
3443
3444         /* Train 2 */
3445         reg = FDI_TX_CTL(pipe);
3446         temp = I915_READ(reg);
3447         temp &= ~FDI_LINK_TRAIN_NONE;
3448         temp |= FDI_LINK_TRAIN_PATTERN_2;
3449         I915_WRITE(reg, temp);
3450
3451         reg = FDI_RX_CTL(pipe);
3452         temp = I915_READ(reg);
3453         temp &= ~FDI_LINK_TRAIN_NONE;
3454         temp |= FDI_LINK_TRAIN_PATTERN_2;
3455         I915_WRITE(reg, temp);
3456
3457         POSTING_READ(reg);
3458         udelay(150);
3459
3460         reg = FDI_RX_IIR(pipe);
3461         for (tries = 0; tries < 5; tries++) {
3462                 temp = I915_READ(reg);
3463                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3464
3465                 if (temp & FDI_RX_SYMBOL_LOCK) {
3466                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3467                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3468                         break;
3469                 }
3470         }
3471         if (tries == 5)
3472                 DRM_ERROR("FDI train 2 fail!\n");
3473
3474         DRM_DEBUG_KMS("FDI train done\n");
3475
3476 }
3477
3478 static const int snb_b_fdi_train_param[] = {
3479         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3480         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3481         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3482         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3483 };
3484
3485 /* The FDI link training functions for SNB/Cougarpoint. */
3486 static void gen6_fdi_link_train(struct drm_crtc *crtc)
3487 {
3488         struct drm_device *dev = crtc->dev;
3489         struct drm_i915_private *dev_priv = dev->dev_private;
3490         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3491         int pipe = intel_crtc->pipe;
3492         u32 reg, temp, i, retry;
3493
3494         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3495            for train result */
3496         reg = FDI_RX_IMR(pipe);
3497         temp = I915_READ(reg);
3498         temp &= ~FDI_RX_SYMBOL_LOCK;
3499         temp &= ~FDI_RX_BIT_LOCK;
3500         I915_WRITE(reg, temp);
3501
3502         POSTING_READ(reg);
3503         udelay(150);
3504
3505         /* enable CPU FDI TX and PCH FDI RX */
3506         reg = FDI_TX_CTL(pipe);
3507         temp = I915_READ(reg);
3508         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3509         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3510         temp &= ~FDI_LINK_TRAIN_NONE;
3511         temp |= FDI_LINK_TRAIN_PATTERN_1;
3512         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3513         /* SNB-B */
3514         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3515         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3516
3517         I915_WRITE(FDI_RX_MISC(pipe),
3518                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3519
3520         reg = FDI_RX_CTL(pipe);
3521         temp = I915_READ(reg);
3522         if (HAS_PCH_CPT(dev)) {
3523                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3524                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3525         } else {
3526                 temp &= ~FDI_LINK_TRAIN_NONE;
3527                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3528         }
3529         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3530
3531         POSTING_READ(reg);
3532         udelay(150);
3533
3534         for (i = 0; i < 4; i++) {
3535                 reg = FDI_TX_CTL(pipe);
3536                 temp = I915_READ(reg);
3537                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3538                 temp |= snb_b_fdi_train_param[i];
3539                 I915_WRITE(reg, temp);
3540
3541                 POSTING_READ(reg);
3542                 udelay(500);
3543
3544                 for (retry = 0; retry < 5; retry++) {
3545                         reg = FDI_RX_IIR(pipe);
3546                         temp = I915_READ(reg);
3547                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3548                         if (temp & FDI_RX_BIT_LOCK) {
3549                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3550                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
3551                                 break;
3552                         }
3553                         udelay(50);
3554                 }
3555                 if (retry < 5)
3556                         break;
3557         }
3558         if (i == 4)
3559                 DRM_ERROR("FDI train 1 fail!\n");
3560
3561         /* Train 2 */
3562         reg = FDI_TX_CTL(pipe);
3563         temp = I915_READ(reg);
3564         temp &= ~FDI_LINK_TRAIN_NONE;
3565         temp |= FDI_LINK_TRAIN_PATTERN_2;
3566         if (IS_GEN6(dev)) {
3567                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3568                 /* SNB-B */
3569                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3570         }
3571         I915_WRITE(reg, temp);
3572
3573         reg = FDI_RX_CTL(pipe);
3574         temp = I915_READ(reg);
3575         if (HAS_PCH_CPT(dev)) {
3576                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3577                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3578         } else {
3579                 temp &= ~FDI_LINK_TRAIN_NONE;
3580                 temp |= FDI_LINK_TRAIN_PATTERN_2;
3581         }
3582         I915_WRITE(reg, temp);
3583
3584         POSTING_READ(reg);
3585         udelay(150);
3586
3587         for (i = 0; i < 4; i++) {
3588                 reg = FDI_TX_CTL(pipe);
3589                 temp = I915_READ(reg);
3590                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3591                 temp |= snb_b_fdi_train_param[i];
3592                 I915_WRITE(reg, temp);
3593
3594                 POSTING_READ(reg);
3595                 udelay(500);
3596
3597                 for (retry = 0; retry < 5; retry++) {
3598                         reg = FDI_RX_IIR(pipe);
3599                         temp = I915_READ(reg);
3600                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3601                         if (temp & FDI_RX_SYMBOL_LOCK) {
3602                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3603                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
3604                                 break;
3605                         }
3606                         udelay(50);
3607                 }
3608                 if (retry < 5)
3609                         break;
3610         }
3611         if (i == 4)
3612                 DRM_ERROR("FDI train 2 fail!\n");
3613
3614         DRM_DEBUG_KMS("FDI train done.\n");
3615 }
3616
3617 /* Manual link training for Ivy Bridge A0 parts */
3618 static void ivb_manual_fdi_link_train(struct drm_crtc *crtc)
3619 {
3620         struct drm_device *dev = crtc->dev;
3621         struct drm_i915_private *dev_priv = dev->dev_private;
3622         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3623         int pipe = intel_crtc->pipe;
3624         u32 reg, temp, i, j;
3625
3626         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3627            for train result */
3628         reg = FDI_RX_IMR(pipe);
3629         temp = I915_READ(reg);
3630         temp &= ~FDI_RX_SYMBOL_LOCK;
3631         temp &= ~FDI_RX_BIT_LOCK;
3632         I915_WRITE(reg, temp);
3633
3634         POSTING_READ(reg);
3635         udelay(150);
3636
3637         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
3638                       I915_READ(FDI_RX_IIR(pipe)));
3639
3640         /* Try each vswing and preemphasis setting twice before moving on */
3641         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
3642                 /* disable first in case we need to retry */
3643                 reg = FDI_TX_CTL(pipe);
3644                 temp = I915_READ(reg);
3645                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
3646                 temp &= ~FDI_TX_ENABLE;
3647                 I915_WRITE(reg, temp);
3648
3649                 reg = FDI_RX_CTL(pipe);
3650                 temp = I915_READ(reg);
3651                 temp &= ~FDI_LINK_TRAIN_AUTO;
3652                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3653                 temp &= ~FDI_RX_ENABLE;
3654                 I915_WRITE(reg, temp);
3655
3656                 /* enable CPU FDI TX and PCH FDI RX */
3657                 reg = FDI_TX_CTL(pipe);
3658                 temp = I915_READ(reg);
3659                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
3660                 temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3661                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
3662                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3663                 temp |= snb_b_fdi_train_param[j/2];
3664                 temp |= FDI_COMPOSITE_SYNC;
3665                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
3666
3667                 I915_WRITE(FDI_RX_MISC(pipe),
3668                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3669
3670                 reg = FDI_RX_CTL(pipe);
3671                 temp = I915_READ(reg);
3672                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3673                 temp |= FDI_COMPOSITE_SYNC;
3674                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
3675
3676                 POSTING_READ(reg);
3677                 udelay(1); /* should be 0.5us */
3678
3679                 for (i = 0; i < 4; i++) {
3680                         reg = FDI_RX_IIR(pipe);
3681                         temp = I915_READ(reg);
3682                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3683
3684                         if (temp & FDI_RX_BIT_LOCK ||
3685                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
3686                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3687                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
3688                                               i);
3689                                 break;
3690                         }
3691                         udelay(1); /* should be 0.5us */
3692                 }
3693                 if (i == 4) {
3694                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
3695                         continue;
3696                 }
3697
3698                 /* Train 2 */
3699                 reg = FDI_TX_CTL(pipe);
3700                 temp = I915_READ(reg);
3701                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3702                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
3703                 I915_WRITE(reg, temp);
3704
3705                 reg = FDI_RX_CTL(pipe);
3706                 temp = I915_READ(reg);
3707                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3708                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3709                 I915_WRITE(reg, temp);
3710
3711                 POSTING_READ(reg);
3712                 udelay(2); /* should be 1.5us */
3713
3714                 for (i = 0; i < 4; i++) {
3715                         reg = FDI_RX_IIR(pipe);
3716                         temp = I915_READ(reg);
3717                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3718
3719                         if (temp & FDI_RX_SYMBOL_LOCK ||
3720                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
3721                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3722                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
3723                                               i);
3724                                 goto train_done;
3725                         }
3726                         udelay(2); /* should be 1.5us */
3727                 }
3728                 if (i == 4)
3729                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
3730         }
3731
3732 train_done:
3733         DRM_DEBUG_KMS("FDI train done.\n");
3734 }
3735
3736 static void ironlake_fdi_pll_enable(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
3744         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
3745         reg = FDI_RX_CTL(pipe);
3746         temp = I915_READ(reg);
3747         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
3748         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3749         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3750         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
3751
3752         POSTING_READ(reg);
3753         udelay(200);
3754
3755         /* Switch from Rawclk to PCDclk */
3756         temp = I915_READ(reg);
3757         I915_WRITE(reg, temp | FDI_PCDCLK);
3758
3759         POSTING_READ(reg);
3760         udelay(200);
3761
3762         /* Enable CPU FDI TX PLL, always on for Ironlake */
3763         reg = FDI_TX_CTL(pipe);
3764         temp = I915_READ(reg);
3765         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
3766                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
3767
3768                 POSTING_READ(reg);
3769                 udelay(100);
3770         }
3771 }
3772
3773 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
3774 {
3775         struct drm_device *dev = intel_crtc->base.dev;
3776         struct drm_i915_private *dev_priv = dev->dev_private;
3777         int pipe = intel_crtc->pipe;
3778         u32 reg, temp;
3779
3780         /* Switch from PCDclk to Rawclk */
3781         reg = FDI_RX_CTL(pipe);
3782         temp = I915_READ(reg);
3783         I915_WRITE(reg, temp & ~FDI_PCDCLK);
3784
3785         /* Disable CPU FDI TX PLL */
3786         reg = FDI_TX_CTL(pipe);
3787         temp = I915_READ(reg);
3788         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
3789
3790         POSTING_READ(reg);
3791         udelay(100);
3792
3793         reg = FDI_RX_CTL(pipe);
3794         temp = I915_READ(reg);
3795         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
3796
3797         /* Wait for the clocks to turn off. */
3798         POSTING_READ(reg);
3799         udelay(100);
3800 }
3801
3802 static void ironlake_fdi_disable(struct drm_crtc *crtc)
3803 {
3804         struct drm_device *dev = crtc->dev;
3805         struct drm_i915_private *dev_priv = dev->dev_private;
3806         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3807         int pipe = intel_crtc->pipe;
3808         u32 reg, temp;
3809
3810         /* disable CPU FDI tx and PCH FDI rx */
3811         reg = FDI_TX_CTL(pipe);
3812         temp = I915_READ(reg);
3813         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
3814         POSTING_READ(reg);
3815
3816         reg = FDI_RX_CTL(pipe);
3817         temp = I915_READ(reg);
3818         temp &= ~(0x7 << 16);
3819         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3820         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
3821
3822         POSTING_READ(reg);
3823         udelay(100);
3824
3825         /* Ironlake workaround, disable clock pointer after downing FDI */
3826         if (HAS_PCH_IBX(dev))
3827                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3828
3829         /* still set train pattern 1 */
3830         reg = FDI_TX_CTL(pipe);
3831         temp = I915_READ(reg);
3832         temp &= ~FDI_LINK_TRAIN_NONE;
3833         temp |= FDI_LINK_TRAIN_PATTERN_1;
3834         I915_WRITE(reg, temp);
3835
3836         reg = FDI_RX_CTL(pipe);
3837         temp = I915_READ(reg);
3838         if (HAS_PCH_CPT(dev)) {
3839                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3840                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3841         } else {
3842                 temp &= ~FDI_LINK_TRAIN_NONE;
3843                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3844         }
3845         /* BPC in FDI rx is consistent with that in PIPECONF */
3846         temp &= ~(0x07 << 16);
3847         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3848         I915_WRITE(reg, temp);
3849
3850         POSTING_READ(reg);
3851         udelay(100);
3852 }
3853
3854 bool intel_has_pending_fb_unpin(struct drm_device *dev)
3855 {
3856         struct intel_crtc *crtc;
3857
3858         /* Note that we don't need to be called with mode_config.lock here
3859          * as our list of CRTC objects is static for the lifetime of the
3860          * device and so cannot disappear as we iterate. Similarly, we can
3861          * happily treat the predicates as racy, atomic checks as userspace
3862          * cannot claim and pin a new fb without at least acquring the
3863          * struct_mutex and so serialising with us.
3864          */
3865         for_each_intel_crtc(dev, crtc) {
3866                 if (atomic_read(&crtc->unpin_work_count) == 0)
3867                         continue;
3868
3869                 if (crtc->unpin_work)
3870                         intel_wait_for_vblank(dev, crtc->pipe);
3871
3872                 return true;
3873         }
3874
3875         return false;
3876 }
3877
3878 static void page_flip_completed(struct intel_crtc *intel_crtc)
3879 {
3880         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
3881         struct intel_unpin_work *work = intel_crtc->unpin_work;
3882
3883         /* ensure that the unpin work is consistent wrt ->pending. */
3884         smp_rmb();
3885         intel_crtc->unpin_work = NULL;
3886
3887         if (work->event)
3888                 drm_send_vblank_event(intel_crtc->base.dev,
3889                                       intel_crtc->pipe,
3890                                       work->event);
3891
3892         drm_crtc_vblank_put(&intel_crtc->base);
3893
3894         wake_up_all(&dev_priv->pending_flip_queue);
3895         queue_work(dev_priv->wq, &work->work);
3896
3897         trace_i915_flip_complete(intel_crtc->plane,
3898                                  work->pending_flip_obj);
3899 }
3900
3901 void intel_crtc_wait_for_pending_flips(struct drm_crtc *crtc)
3902 {
3903         struct drm_device *dev = crtc->dev;
3904         struct drm_i915_private *dev_priv = dev->dev_private;
3905
3906         WARN_ON(waitqueue_active(&dev_priv->pending_flip_queue));
3907         if (WARN_ON(wait_event_timeout(dev_priv->pending_flip_queue,
3908                                        !intel_crtc_has_pending_flip(crtc),
3909                                        60*HZ) == 0)) {
3910                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3911
3912                 spin_lock_irq(&dev->event_lock);
3913                 if (intel_crtc->unpin_work) {
3914                         WARN_ONCE(1, "Removing stuck page flip\n");
3915                         page_flip_completed(intel_crtc);
3916                 }
3917                 spin_unlock_irq(&dev->event_lock);
3918         }
3919
3920         if (crtc->primary->fb) {
3921                 mutex_lock(&dev->struct_mutex);
3922                 intel_finish_fb(crtc->primary->fb);
3923                 mutex_unlock(&dev->struct_mutex);
3924         }
3925 }
3926
3927 /* Program iCLKIP clock to the desired frequency */
3928 static void lpt_program_iclkip(struct drm_crtc *crtc)
3929 {
3930         struct drm_device *dev = crtc->dev;
3931         struct drm_i915_private *dev_priv = dev->dev_private;
3932         int clock = to_intel_crtc(crtc)->config->base.adjusted_mode.crtc_clock;
3933         u32 divsel, phaseinc, auxdiv, phasedir = 0;
3934         u32 temp;
3935
3936         mutex_lock(&dev_priv->sb_lock);
3937
3938         /* It is necessary to ungate the pixclk gate prior to programming
3939          * the divisors, and gate it back when it is done.
3940          */
3941         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
3942
3943         /* Disable SSCCTL */
3944         intel_sbi_write(dev_priv, SBI_SSCCTL6,
3945                         intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK) |
3946                                 SBI_SSCCTL_DISABLE,
3947                         SBI_ICLK);
3948
3949         /* 20MHz is a corner case which is out of range for the 7-bit divisor */
3950         if (clock == 20000) {
3951                 auxdiv = 1;
3952                 divsel = 0x41;
3953                 phaseinc = 0x20;
3954         } else {
3955                 /* The iCLK virtual clock root frequency is in MHz,
3956                  * but the adjusted_mode->crtc_clock in in KHz. To get the
3957                  * divisors, it is necessary to divide one by another, so we
3958                  * convert the virtual clock precision to KHz here for higher
3959                  * precision.
3960                  */
3961                 u32 iclk_virtual_root_freq = 172800 * 1000;
3962                 u32 iclk_pi_range = 64;
3963                 u32 desired_divisor, msb_divisor_value, pi_value;
3964
3965                 desired_divisor = (iclk_virtual_root_freq / clock);
3966                 msb_divisor_value = desired_divisor / iclk_pi_range;
3967                 pi_value = desired_divisor % iclk_pi_range;
3968
3969                 auxdiv = 0;
3970                 divsel = msb_divisor_value - 2;
3971                 phaseinc = pi_value;
3972         }
3973
3974         /* This should not happen with any sane values */
3975         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
3976                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
3977         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
3978                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
3979
3980         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
3981                         clock,
3982                         auxdiv,
3983                         divsel,
3984                         phasedir,
3985                         phaseinc);
3986
3987         /* Program SSCDIVINTPHASE6 */
3988         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
3989         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
3990         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
3991         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
3992         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
3993         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
3994         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
3995         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
3996
3997         /* Program SSCAUXDIV */
3998         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
3999         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
4000         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
4001         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
4002
4003         /* Enable modulator and associated divider */
4004         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4005         temp &= ~SBI_SSCCTL_DISABLE;
4006         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4007
4008         /* Wait for initialization time */
4009         udelay(24);
4010
4011         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
4012
4013         mutex_unlock(&dev_priv->sb_lock);
4014 }
4015
4016 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
4017                                                 enum pipe pch_transcoder)
4018 {
4019         struct drm_device *dev = crtc->base.dev;
4020         struct drm_i915_private *dev_priv = dev->dev_private;
4021         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
4022
4023         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
4024                    I915_READ(HTOTAL(cpu_transcoder)));
4025         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4026                    I915_READ(HBLANK(cpu_transcoder)));
4027         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4028                    I915_READ(HSYNC(cpu_transcoder)));
4029
4030         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4031                    I915_READ(VTOTAL(cpu_transcoder)));
4032         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4033                    I915_READ(VBLANK(cpu_transcoder)));
4034         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4035                    I915_READ(VSYNC(cpu_transcoder)));
4036         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4037                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4038 }
4039
4040 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4041 {
4042         struct drm_i915_private *dev_priv = dev->dev_private;
4043         uint32_t temp;
4044
4045         temp = I915_READ(SOUTH_CHICKEN1);
4046         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4047                 return;
4048
4049         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4050         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4051
4052         temp &= ~FDI_BC_BIFURCATION_SELECT;
4053         if (enable)
4054                 temp |= FDI_BC_BIFURCATION_SELECT;
4055
4056         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4057         I915_WRITE(SOUTH_CHICKEN1, temp);
4058         POSTING_READ(SOUTH_CHICKEN1);
4059 }
4060
4061 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4062 {
4063         struct drm_device *dev = intel_crtc->base.dev;
4064
4065         switch (intel_crtc->pipe) {
4066         case PIPE_A:
4067                 break;
4068         case PIPE_B:
4069                 if (intel_crtc->config->fdi_lanes > 2)
4070                         cpt_set_fdi_bc_bifurcation(dev, false);
4071                 else
4072                         cpt_set_fdi_bc_bifurcation(dev, true);
4073
4074                 break;
4075         case PIPE_C:
4076                 cpt_set_fdi_bc_bifurcation(dev, true);
4077
4078                 break;
4079         default:
4080                 BUG();
4081         }
4082 }
4083
4084 /*
4085  * Enable PCH resources required for PCH ports:
4086  *   - PCH PLLs
4087  *   - FDI training & RX/TX
4088  *   - update transcoder timings
4089  *   - DP transcoding bits
4090  *   - transcoder
4091  */
4092 static void ironlake_pch_enable(struct drm_crtc *crtc)
4093 {
4094         struct drm_device *dev = crtc->dev;
4095         struct drm_i915_private *dev_priv = dev->dev_private;
4096         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4097         int pipe = intel_crtc->pipe;
4098         u32 reg, temp;
4099
4100         assert_pch_transcoder_disabled(dev_priv, pipe);
4101
4102         if (IS_IVYBRIDGE(dev))
4103                 ivybridge_update_fdi_bc_bifurcation(intel_crtc);
4104
4105         /* Write the TU size bits before fdi link training, so that error
4106          * detection works. */
4107         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4108                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4109
4110         /* For PCH output, training FDI link */
4111         dev_priv->display.fdi_link_train(crtc);
4112
4113         /* We need to program the right clock selection before writing the pixel
4114          * mutliplier into the DPLL. */
4115         if (HAS_PCH_CPT(dev)) {
4116                 u32 sel;
4117
4118                 temp = I915_READ(PCH_DPLL_SEL);
4119                 temp |= TRANS_DPLL_ENABLE(pipe);
4120                 sel = TRANS_DPLLB_SEL(pipe);
4121                 if (intel_crtc->config->shared_dpll == DPLL_ID_PCH_PLL_B)
4122                         temp |= sel;
4123                 else
4124                         temp &= ~sel;
4125                 I915_WRITE(PCH_DPLL_SEL, temp);
4126         }
4127
4128         /* XXX: pch pll's can be enabled any time before we enable the PCH
4129          * transcoder, and we actually should do this to not upset any PCH
4130          * transcoder that already use the clock when we share it.
4131          *
4132          * Note that enable_shared_dpll tries to do the right thing, but
4133          * get_shared_dpll unconditionally resets the pll - we need that to have
4134          * the right LVDS enable sequence. */
4135         intel_enable_shared_dpll(intel_crtc);
4136
4137         /* set transcoder timing, panel must allow it */
4138         assert_panel_unlocked(dev_priv, pipe);
4139         ironlake_pch_transcoder_set_timings(intel_crtc, pipe);
4140
4141         intel_fdi_normal_train(crtc);
4142
4143         /* For PCH DP, enable TRANS_DP_CTL */
4144         if (HAS_PCH_CPT(dev) && intel_crtc->config->has_dp_encoder) {
4145                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4146                 reg = TRANS_DP_CTL(pipe);
4147                 temp = I915_READ(reg);
4148                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4149                           TRANS_DP_SYNC_MASK |
4150                           TRANS_DP_BPC_MASK);
4151                 temp |= TRANS_DP_OUTPUT_ENABLE;
4152                 temp |= bpc << 9; /* same format but at 11:9 */
4153
4154                 if (crtc->mode.flags & DRM_MODE_FLAG_PHSYNC)
4155                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4156                 if (crtc->mode.flags & DRM_MODE_FLAG_PVSYNC)
4157                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4158
4159                 switch (intel_trans_dp_port_sel(crtc)) {
4160                 case PCH_DP_B:
4161                         temp |= TRANS_DP_PORT_SEL_B;
4162                         break;
4163                 case PCH_DP_C:
4164                         temp |= TRANS_DP_PORT_SEL_C;
4165                         break;
4166                 case PCH_DP_D:
4167                         temp |= TRANS_DP_PORT_SEL_D;
4168                         break;
4169                 default:
4170                         BUG();
4171                 }
4172
4173                 I915_WRITE(reg, temp);
4174         }
4175
4176         ironlake_enable_pch_transcoder(dev_priv, pipe);
4177 }
4178
4179 static void lpt_pch_enable(struct drm_crtc *crtc)
4180 {
4181         struct drm_device *dev = crtc->dev;
4182         struct drm_i915_private *dev_priv = dev->dev_private;
4183         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4184         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4185
4186         assert_pch_transcoder_disabled(dev_priv, TRANSCODER_A);
4187
4188         lpt_program_iclkip(crtc);
4189
4190         /* Set transcoder timing. */
4191         ironlake_pch_transcoder_set_timings(intel_crtc, PIPE_A);
4192
4193         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4194 }
4195
4196 struct intel_shared_dpll *intel_get_shared_dpll(struct intel_crtc *crtc,
4197                                                 struct intel_crtc_state *crtc_state)
4198 {
4199         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
4200         struct intel_shared_dpll *pll;
4201         struct intel_shared_dpll_config *shared_dpll;
4202         enum intel_dpll_id i;
4203
4204         shared_dpll = intel_atomic_get_shared_dpll_state(crtc_state->base.state);
4205
4206         if (HAS_PCH_IBX(dev_priv->dev)) {
4207                 /* Ironlake PCH has a fixed PLL->PCH pipe mapping. */
4208                 i = (enum intel_dpll_id) crtc->pipe;
4209                 pll = &dev_priv->shared_dplls[i];
4210
4211                 DRM_DEBUG_KMS("CRTC:%d using pre-allocated %s\n",
4212                               crtc->base.base.id, pll->name);
4213
4214                 WARN_ON(shared_dpll[i].crtc_mask);
4215
4216                 goto found;
4217         }
4218
4219         if (IS_BROXTON(dev_priv->dev)) {
4220                 /* PLL is attached to port in bxt */
4221                 struct intel_encoder *encoder;
4222                 struct intel_digital_port *intel_dig_port;
4223
4224                 encoder = intel_ddi_get_crtc_new_encoder(crtc_state);
4225                 if (WARN_ON(!encoder))
4226                         return NULL;
4227
4228                 intel_dig_port = enc_to_dig_port(&encoder->base);
4229                 /* 1:1 mapping between ports and PLLs */
4230                 i = (enum intel_dpll_id)intel_dig_port->port;
4231                 pll = &dev_priv->shared_dplls[i];
4232                 DRM_DEBUG_KMS("CRTC:%d using pre-allocated %s\n",
4233                         crtc->base.base.id, pll->name);
4234                 WARN_ON(shared_dpll[i].crtc_mask);
4235
4236                 goto found;
4237         }
4238
4239         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4240                 pll = &dev_priv->shared_dplls[i];
4241
4242                 /* Only want to check enabled timings first */
4243                 if (shared_dpll[i].crtc_mask == 0)
4244                         continue;
4245
4246                 if (memcmp(&crtc_state->dpll_hw_state,
4247                            &shared_dpll[i].hw_state,
4248                            sizeof(crtc_state->dpll_hw_state)) == 0) {
4249                         DRM_DEBUG_KMS("CRTC:%d sharing existing %s (crtc mask 0x%08x, ative %d)\n",
4250                                       crtc->base.base.id, pll->name,
4251                                       shared_dpll[i].crtc_mask,
4252                                       pll->active);
4253                         goto found;
4254                 }
4255         }
4256
4257         /* Ok no matching timings, maybe there's a free one? */
4258         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4259                 pll = &dev_priv->shared_dplls[i];
4260                 if (shared_dpll[i].crtc_mask == 0) {
4261                         DRM_DEBUG_KMS("CRTC:%d allocated %s\n",
4262                                       crtc->base.base.id, pll->name);
4263                         goto found;
4264                 }
4265         }
4266
4267         return NULL;
4268
4269 found:
4270         if (shared_dpll[i].crtc_mask == 0)
4271                 shared_dpll[i].hw_state =
4272                         crtc_state->dpll_hw_state;
4273
4274         crtc_state->shared_dpll = i;
4275         DRM_DEBUG_DRIVER("using %s for pipe %c\n", pll->name,
4276                          pipe_name(crtc->pipe));
4277
4278         shared_dpll[i].crtc_mask |= 1 << crtc->pipe;
4279
4280         return pll;
4281 }
4282
4283 static void intel_shared_dpll_commit(struct drm_atomic_state *state)
4284 {
4285         struct drm_i915_private *dev_priv = to_i915(state->dev);
4286         struct intel_shared_dpll_config *shared_dpll;
4287         struct intel_shared_dpll *pll;
4288         enum intel_dpll_id i;
4289
4290         if (!to_intel_atomic_state(state)->dpll_set)
4291                 return;
4292
4293         shared_dpll = to_intel_atomic_state(state)->shared_dpll;
4294         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4295                 pll = &dev_priv->shared_dplls[i];
4296                 pll->config = shared_dpll[i];
4297         }
4298 }
4299
4300 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4301 {
4302         struct drm_i915_private *dev_priv = dev->dev_private;
4303         int dslreg = PIPEDSL(pipe);
4304         u32 temp;
4305
4306         temp = I915_READ(dslreg);
4307         udelay(500);
4308         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4309                 if (wait_for(I915_READ(dslreg) != temp, 5))
4310                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4311         }
4312 }
4313
4314 static int
4315 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4316                   unsigned scaler_user, int *scaler_id, unsigned int rotation,
4317                   int src_w, int src_h, int dst_w, int dst_h)
4318 {
4319         struct intel_crtc_scaler_state *scaler_state =
4320                 &crtc_state->scaler_state;
4321         struct intel_crtc *intel_crtc =
4322                 to_intel_crtc(crtc_state->base.crtc);
4323         int need_scaling;
4324
4325         need_scaling = intel_rotation_90_or_270(rotation) ?
4326                 (src_h != dst_w || src_w != dst_h):
4327                 (src_w != dst_w || src_h != dst_h);
4328
4329         /*
4330          * if plane is being disabled or scaler is no more required or force detach
4331          *  - free scaler binded to this plane/crtc
4332          *  - in order to do this, update crtc->scaler_usage
4333          *
4334          * Here scaler state in crtc_state is set free so that
4335          * scaler can be assigned to other user. Actual register
4336          * update to free the scaler is done in plane/panel-fit programming.
4337          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4338          */
4339         if (force_detach || !need_scaling) {
4340                 if (*scaler_id >= 0) {
4341                         scaler_state->scaler_users &= ~(1 << scaler_user);
4342                         scaler_state->scalers[*scaler_id].in_use = 0;
4343
4344                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4345                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4346                                 intel_crtc->pipe, scaler_user, *scaler_id,
4347                                 scaler_state->scaler_users);
4348                         *scaler_id = -1;
4349                 }
4350                 return 0;
4351         }
4352
4353         /* range checks */
4354         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4355                 dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4356
4357                 src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4358                 dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H) {
4359                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4360                         "size is out of scaler range\n",
4361                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4362                 return -EINVAL;
4363         }
4364
4365         /* mark this plane as a scaler user in crtc_state */
4366         scaler_state->scaler_users |= (1 << scaler_user);
4367         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4368                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4369                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4370                 scaler_state->scaler_users);
4371
4372         return 0;
4373 }
4374
4375 /**
4376  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4377  *
4378  * @state: crtc's scaler state
4379  *
4380  * Return
4381  *     0 - scaler_usage updated successfully
4382  *    error - requested scaling cannot be supported or other error condition
4383  */
4384 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4385 {
4386         struct intel_crtc *intel_crtc = to_intel_crtc(state->base.crtc);
4387         struct drm_display_mode *adjusted_mode =
4388                 &state->base.adjusted_mode;
4389
4390         DRM_DEBUG_KMS("Updating scaler for [CRTC:%i] scaler_user index %u.%u\n",
4391                       intel_crtc->base.base.id, intel_crtc->pipe, SKL_CRTC_INDEX);
4392
4393         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4394                 &state->scaler_state.scaler_id, DRM_ROTATE_0,
4395                 state->pipe_src_w, state->pipe_src_h,
4396                 adjusted_mode->hdisplay, adjusted_mode->vdisplay);
4397 }
4398
4399 /**
4400  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4401  *
4402  * @state: crtc's scaler state
4403  * @plane_state: atomic plane state to update
4404  *
4405  * Return
4406  *     0 - scaler_usage updated successfully
4407  *    error - requested scaling cannot be supported or other error condition
4408  */
4409 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4410                                    struct intel_plane_state *plane_state)
4411 {
4412
4413         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
4414         struct intel_plane *intel_plane =
4415                 to_intel_plane(plane_state->base.plane);
4416         struct drm_framebuffer *fb = plane_state->base.fb;
4417         int ret;
4418
4419         bool force_detach = !fb || !plane_state->visible;
4420
4421         DRM_DEBUG_KMS("Updating scaler for [PLANE:%d] scaler_user index %u.%u\n",
4422                       intel_plane->base.base.id, intel_crtc->pipe,
4423                       drm_plane_index(&intel_plane->base));
4424
4425         ret = skl_update_scaler(crtc_state, force_detach,
4426                                 drm_plane_index(&intel_plane->base),
4427                                 &plane_state->scaler_id,
4428                                 plane_state->base.rotation,
4429                                 drm_rect_width(&plane_state->src) >> 16,
4430                                 drm_rect_height(&plane_state->src) >> 16,
4431                                 drm_rect_width(&plane_state->dst),
4432                                 drm_rect_height(&plane_state->dst));
4433
4434         if (ret || plane_state->scaler_id < 0)
4435                 return ret;
4436
4437         /* check colorkey */
4438         if (plane_state->ckey.flags != I915_SET_COLORKEY_NONE) {
4439                 DRM_DEBUG_KMS("[PLANE:%d] scaling with color key not allowed",
4440                               intel_plane->base.base.id);
4441                 return -EINVAL;
4442         }
4443
4444         /* Check src format */
4445         switch (fb->pixel_format) {
4446         case DRM_FORMAT_RGB565:
4447         case DRM_FORMAT_XBGR8888:
4448         case DRM_FORMAT_XRGB8888:
4449         case DRM_FORMAT_ABGR8888:
4450         case DRM_FORMAT_ARGB8888:
4451         case DRM_FORMAT_XRGB2101010:
4452         case DRM_FORMAT_XBGR2101010:
4453         case DRM_FORMAT_YUYV:
4454         case DRM_FORMAT_YVYU:
4455         case DRM_FORMAT_UYVY:
4456         case DRM_FORMAT_VYUY:
4457                 break;
4458         default:
4459                 DRM_DEBUG_KMS("[PLANE:%d] FB:%d unsupported scaling format 0x%x\n",
4460                         intel_plane->base.base.id, fb->base.id, fb->pixel_format);
4461                 return -EINVAL;
4462         }
4463
4464         return 0;
4465 }
4466
4467 static void skylake_scaler_disable(struct intel_crtc *crtc)
4468 {
4469         int i;
4470
4471         for (i = 0; i < crtc->num_scalers; i++)
4472                 skl_detach_scaler(crtc, i);
4473 }
4474
4475 static void skylake_pfit_enable(struct intel_crtc *crtc)
4476 {
4477         struct drm_device *dev = crtc->base.dev;
4478         struct drm_i915_private *dev_priv = dev->dev_private;
4479         int pipe = crtc->pipe;
4480         struct intel_crtc_scaler_state *scaler_state =
4481                 &crtc->config->scaler_state;
4482
4483         DRM_DEBUG_KMS("for crtc_state = %p\n", crtc->config);
4484
4485         if (crtc->config->pch_pfit.enabled) {
4486                 int id;
4487
4488                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0)) {
4489                         DRM_ERROR("Requesting pfit without getting a scaler first\n");
4490                         return;
4491                 }
4492
4493                 id = scaler_state->scaler_id;
4494                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4495                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4496                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
4497                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
4498
4499                 DRM_DEBUG_KMS("for crtc_state = %p scaler_id = %d\n", crtc->config, id);
4500         }
4501 }
4502
4503 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4504 {
4505         struct drm_device *dev = crtc->base.dev;
4506         struct drm_i915_private *dev_priv = dev->dev_private;
4507         int pipe = crtc->pipe;
4508
4509         if (crtc->config->pch_pfit.enabled) {
4510                 /* Force use of hard-coded filter coefficients
4511                  * as some pre-programmed values are broken,
4512                  * e.g. x201.
4513                  */
4514                 if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev))
4515                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4516                                                  PF_PIPE_SEL_IVB(pipe));
4517                 else
4518                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4519                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4520                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4521         }
4522 }
4523
4524 void hsw_enable_ips(struct intel_crtc *crtc)
4525 {
4526         struct drm_device *dev = crtc->base.dev;
4527         struct drm_i915_private *dev_priv = dev->dev_private;
4528
4529         if (!crtc->config->ips_enabled)
4530                 return;
4531
4532         /* We can only enable IPS after we enable a plane and wait for a vblank */
4533         intel_wait_for_vblank(dev, crtc->pipe);
4534
4535         assert_plane_enabled(dev_priv, crtc->plane);
4536         if (IS_BROADWELL(dev)) {
4537                 mutex_lock(&dev_priv->rps.hw_lock);
4538                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0xc0000000));
4539                 mutex_unlock(&dev_priv->rps.hw_lock);
4540                 /* Quoting Art Runyan: "its not safe to expect any particular
4541                  * value in IPS_CTL bit 31 after enabling IPS through the
4542                  * mailbox." Moreover, the mailbox may return a bogus state,
4543                  * so we need to just enable it and continue on.
4544                  */
4545         } else {
4546                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4547                 /* The bit only becomes 1 in the next vblank, so this wait here
4548                  * is essentially intel_wait_for_vblank. If we don't have this
4549                  * and don't wait for vblanks until the end of crtc_enable, then
4550                  * the HW state readout code will complain that the expected
4551                  * IPS_CTL value is not the one we read. */
4552                 if (wait_for(I915_READ_NOTRACE(IPS_CTL) & IPS_ENABLE, 50))
4553                         DRM_ERROR("Timed out waiting for IPS enable\n");
4554         }
4555 }
4556
4557 void hsw_disable_ips(struct intel_crtc *crtc)
4558 {
4559         struct drm_device *dev = crtc->base.dev;
4560         struct drm_i915_private *dev_priv = dev->dev_private;
4561
4562         if (!crtc->config->ips_enabled)
4563                 return;
4564
4565         assert_plane_enabled(dev_priv, crtc->plane);
4566         if (IS_BROADWELL(dev)) {
4567                 mutex_lock(&dev_priv->rps.hw_lock);
4568                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4569                 mutex_unlock(&dev_priv->rps.hw_lock);
4570                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4571                 if (wait_for((I915_READ(IPS_CTL) & IPS_ENABLE) == 0, 42))
4572                         DRM_ERROR("Timed out waiting for IPS disable\n");
4573         } else {
4574                 I915_WRITE(IPS_CTL, 0);
4575                 POSTING_READ(IPS_CTL);
4576         }
4577
4578         /* We need to wait for a vblank before we can disable the plane. */
4579         intel_wait_for_vblank(dev, crtc->pipe);
4580 }
4581
4582 /** Loads the palette/gamma unit for the CRTC with the prepared values */
4583 static void intel_crtc_load_lut(struct drm_crtc *crtc)
4584 {
4585         struct drm_device *dev = crtc->dev;
4586         struct drm_i915_private *dev_priv = dev->dev_private;
4587         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4588         enum pipe pipe = intel_crtc->pipe;
4589         int palreg = PALETTE(pipe);
4590         int i;
4591         bool reenable_ips = false;
4592
4593         /* The clocks have to be on to load the palette. */
4594         if (!crtc->state->active)
4595                 return;
4596
4597         if (HAS_GMCH_DISPLAY(dev_priv->dev)) {
4598                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_DSI))
4599                         assert_dsi_pll_enabled(dev_priv);
4600                 else
4601                         assert_pll_enabled(dev_priv, pipe);
4602         }
4603
4604         /* use legacy palette for Ironlake */
4605         if (!HAS_GMCH_DISPLAY(dev))
4606                 palreg = LGC_PALETTE(pipe);
4607
4608         /* Workaround : Do not read or write the pipe palette/gamma data while
4609          * GAMMA_MODE is configured for split gamma and IPS_CTL has IPS enabled.
4610          */
4611         if (IS_HASWELL(dev) && intel_crtc->config->ips_enabled &&
4612             ((I915_READ(GAMMA_MODE(pipe)) & GAMMA_MODE_MODE_MASK) ==
4613              GAMMA_MODE_MODE_SPLIT)) {
4614                 hsw_disable_ips(intel_crtc);
4615                 reenable_ips = true;
4616         }
4617
4618         for (i = 0; i < 256; i++) {
4619                 I915_WRITE(palreg + 4 * i,
4620                            (intel_crtc->lut_r[i] << 16) |
4621                            (intel_crtc->lut_g[i] << 8) |
4622                            intel_crtc->lut_b[i]);
4623         }
4624
4625         if (reenable_ips)
4626                 hsw_enable_ips(intel_crtc);
4627 }
4628
4629 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
4630 {
4631         if (intel_crtc->overlay) {
4632                 struct drm_device *dev = intel_crtc->base.dev;
4633                 struct drm_i915_private *dev_priv = dev->dev_private;
4634
4635                 mutex_lock(&dev->struct_mutex);
4636                 dev_priv->mm.interruptible = false;
4637                 (void) intel_overlay_switch_off(intel_crtc->overlay);
4638                 dev_priv->mm.interruptible = true;
4639                 mutex_unlock(&dev->struct_mutex);
4640         }
4641
4642         /* Let userspace switch the overlay on again. In most cases userspace
4643          * has to recompute where to put it anyway.
4644          */
4645 }
4646
4647 /**
4648  * intel_post_enable_primary - Perform operations after enabling primary plane
4649  * @crtc: the CRTC whose primary plane was just enabled
4650  *
4651  * Performs potentially sleeping operations that must be done after the primary
4652  * plane is enabled, such as updating FBC and IPS.  Note that this may be
4653  * called due to an explicit primary plane update, or due to an implicit
4654  * re-enable that is caused when a sprite plane is updated to no longer
4655  * completely hide the primary plane.
4656  */
4657 static void
4658 intel_post_enable_primary(struct drm_crtc *crtc)
4659 {
4660         struct drm_device *dev = crtc->dev;
4661         struct drm_i915_private *dev_priv = dev->dev_private;
4662         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4663         int pipe = intel_crtc->pipe;
4664
4665         /*
4666          * BDW signals flip done immediately if the plane
4667          * is disabled, even if the plane enable is already
4668          * armed to occur at the next vblank :(
4669          */
4670         if (IS_BROADWELL(dev))
4671                 intel_wait_for_vblank(dev, pipe);
4672
4673         /*
4674          * FIXME IPS should be fine as long as one plane is
4675          * enabled, but in practice it seems to have problems
4676          * when going from primary only to sprite only and vice
4677          * versa.
4678          */
4679         hsw_enable_ips(intel_crtc);
4680
4681         /*
4682          * Gen2 reports pipe underruns whenever all planes are disabled.
4683          * So don't enable underrun reporting before at least some planes
4684          * are enabled.
4685          * FIXME: Need to fix the logic to work when we turn off all planes
4686          * but leave the pipe running.
4687          */
4688         if (IS_GEN2(dev))
4689                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4690
4691         /* Underruns don't raise interrupts, so check manually. */
4692         if (HAS_GMCH_DISPLAY(dev))
4693                 i9xx_check_fifo_underruns(dev_priv);
4694 }
4695
4696 /**
4697  * intel_pre_disable_primary - Perform operations before disabling primary plane
4698  * @crtc: the CRTC whose primary plane is to be disabled
4699  *
4700  * Performs potentially sleeping operations that must be done before the
4701  * primary plane is disabled, such as updating FBC and IPS.  Note that this may
4702  * be called due to an explicit primary plane update, or due to an implicit
4703  * disable that is caused when a sprite plane completely hides the primary
4704  * plane.
4705  */
4706 static void
4707 intel_pre_disable_primary(struct drm_crtc *crtc)
4708 {
4709         struct drm_device *dev = crtc->dev;
4710         struct drm_i915_private *dev_priv = dev->dev_private;
4711         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4712         int pipe = intel_crtc->pipe;
4713
4714         /*
4715          * Gen2 reports pipe underruns whenever all planes are disabled.
4716          * So diasble underrun reporting before all the planes get disabled.
4717          * FIXME: Need to fix the logic to work when we turn off all planes
4718          * but leave the pipe running.
4719          */
4720         if (IS_GEN2(dev))
4721                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4722
4723         /*
4724          * Vblank time updates from the shadow to live plane control register
4725          * are blocked if the memory self-refresh mode is active at that
4726          * moment. So to make sure the plane gets truly disabled, disable
4727          * first the self-refresh mode. The self-refresh enable bit in turn
4728          * will be checked/applied by the HW only at the next frame start
4729          * event which is after the vblank start event, so we need to have a
4730          * wait-for-vblank between disabling the plane and the pipe.
4731          */
4732         if (HAS_GMCH_DISPLAY(dev)) {
4733                 intel_set_memory_cxsr(dev_priv, false);
4734                 dev_priv->wm.vlv.cxsr = false;
4735                 intel_wait_for_vblank(dev, pipe);
4736         }
4737
4738         /*
4739          * FIXME IPS should be fine as long as one plane is
4740          * enabled, but in practice it seems to have problems
4741          * when going from primary only to sprite only and vice
4742          * versa.
4743          */
4744         hsw_disable_ips(intel_crtc);
4745 }
4746
4747 static void intel_post_plane_update(struct intel_crtc *crtc)
4748 {
4749         struct intel_crtc_atomic_commit *atomic = &crtc->atomic;
4750         struct drm_device *dev = crtc->base.dev;
4751         struct drm_i915_private *dev_priv = dev->dev_private;
4752         struct drm_plane *plane;
4753
4754         if (atomic->wait_vblank)
4755                 intel_wait_for_vblank(dev, crtc->pipe);
4756
4757         intel_frontbuffer_flip(dev, atomic->fb_bits);
4758
4759         if (atomic->disable_cxsr)
4760                 crtc->wm.cxsr_allowed = true;
4761
4762         if (crtc->atomic.update_wm_post)
4763                 intel_update_watermarks(&crtc->base);
4764
4765         if (atomic->update_fbc)
4766                 intel_fbc_update(dev_priv);
4767
4768         if (atomic->post_enable_primary)
4769                 intel_post_enable_primary(&crtc->base);
4770
4771         drm_for_each_plane_mask(plane, dev, atomic->update_sprite_watermarks)
4772                 intel_update_sprite_watermarks(plane, &crtc->base,
4773                                                0, 0, 0, false, false);
4774
4775         memset(atomic, 0, sizeof(*atomic));
4776 }
4777
4778 static void intel_pre_plane_update(struct intel_crtc *crtc)
4779 {
4780         struct drm_device *dev = crtc->base.dev;
4781         struct drm_i915_private *dev_priv = dev->dev_private;
4782         struct intel_crtc_atomic_commit *atomic = &crtc->atomic;
4783         struct drm_plane *p;
4784
4785         /* Track fb's for any planes being disabled */
4786         drm_for_each_plane_mask(p, dev, atomic->disabled_planes) {
4787                 struct intel_plane *plane = to_intel_plane(p);
4788
4789                 mutex_lock(&dev->struct_mutex);
4790                 i915_gem_track_fb(intel_fb_obj(plane->base.fb), NULL,
4791                                   plane->frontbuffer_bit);
4792                 mutex_unlock(&dev->struct_mutex);
4793         }
4794
4795         if (atomic->wait_for_flips)
4796                 intel_crtc_wait_for_pending_flips(&crtc->base);
4797
4798         if (atomic->disable_fbc)
4799                 intel_fbc_disable_crtc(crtc);
4800
4801         if (crtc->atomic.disable_ips)
4802                 hsw_disable_ips(crtc);
4803
4804         if (atomic->pre_disable_primary)
4805                 intel_pre_disable_primary(&crtc->base);
4806
4807         if (atomic->disable_cxsr) {
4808                 crtc->wm.cxsr_allowed = false;
4809                 intel_set_memory_cxsr(dev_priv, false);
4810         }
4811 }
4812
4813 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
4814 {
4815         struct drm_device *dev = crtc->dev;
4816         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4817         struct drm_plane *p;
4818         int pipe = intel_crtc->pipe;
4819
4820         intel_crtc_dpms_overlay_disable(intel_crtc);
4821
4822         drm_for_each_plane_mask(p, dev, plane_mask)
4823                 to_intel_plane(p)->disable_plane(p, crtc);
4824
4825         /*
4826          * FIXME: Once we grow proper nuclear flip support out of this we need
4827          * to compute the mask of flip planes precisely. For the time being
4828          * consider this a flip to a NULL plane.
4829          */
4830         intel_frontbuffer_flip(dev, INTEL_FRONTBUFFER_ALL_MASK(pipe));
4831 }
4832
4833 static void ironlake_crtc_enable(struct drm_crtc *crtc)
4834 {
4835         struct drm_device *dev = crtc->dev;
4836         struct drm_i915_private *dev_priv = dev->dev_private;
4837         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4838         struct intel_encoder *encoder;
4839         int pipe = intel_crtc->pipe;
4840
4841         if (WARN_ON(intel_crtc->active))
4842                 return;
4843
4844         if (intel_crtc->config->has_pch_encoder)
4845                 intel_prepare_shared_dpll(intel_crtc);
4846
4847         if (intel_crtc->config->has_dp_encoder)
4848                 intel_dp_set_m_n(intel_crtc, M1_N1);
4849
4850         intel_set_pipe_timings(intel_crtc);
4851
4852         if (intel_crtc->config->has_pch_encoder) {
4853                 intel_cpu_transcoder_set_m_n(intel_crtc,
4854                                      &intel_crtc->config->fdi_m_n, NULL);
4855         }
4856
4857         ironlake_set_pipeconf(crtc);
4858
4859         intel_crtc->active = true;
4860
4861         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4862         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
4863
4864         for_each_encoder_on_crtc(dev, crtc, encoder)
4865                 if (encoder->pre_enable)
4866                         encoder->pre_enable(encoder);
4867
4868         if (intel_crtc->config->has_pch_encoder) {
4869                 /* Note: FDI PLL enabling _must_ be done before we enable the
4870                  * cpu pipes, hence this is separate from all the other fdi/pch
4871                  * enabling. */
4872                 ironlake_fdi_pll_enable(intel_crtc);
4873         } else {
4874                 assert_fdi_tx_disabled(dev_priv, pipe);
4875                 assert_fdi_rx_disabled(dev_priv, pipe);
4876         }
4877
4878         ironlake_pfit_enable(intel_crtc);
4879
4880         /*
4881          * On ILK+ LUT must be loaded before the pipe is running but with
4882          * clocks enabled
4883          */
4884         intel_crtc_load_lut(crtc);
4885
4886         intel_update_watermarks(crtc);
4887         intel_enable_pipe(intel_crtc);
4888
4889         if (intel_crtc->config->has_pch_encoder)
4890                 ironlake_pch_enable(crtc);
4891
4892         assert_vblank_disabled(crtc);
4893         drm_crtc_vblank_on(crtc);
4894
4895         for_each_encoder_on_crtc(dev, crtc, encoder)
4896                 encoder->enable(encoder);
4897
4898         if (HAS_PCH_CPT(dev))
4899                 cpt_verify_modeset(dev, intel_crtc->pipe);
4900 }
4901
4902 /* IPS only exists on ULT machines and is tied to pipe A. */
4903 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
4904 {
4905         return HAS_IPS(crtc->base.dev) && crtc->pipe == PIPE_A;
4906 }
4907
4908 static void haswell_crtc_enable(struct drm_crtc *crtc)
4909 {
4910         struct drm_device *dev = crtc->dev;
4911         struct drm_i915_private *dev_priv = dev->dev_private;
4912         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4913         struct intel_encoder *encoder;
4914         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
4915         struct intel_crtc_state *pipe_config =
4916                 to_intel_crtc_state(crtc->state);
4917
4918         if (WARN_ON(intel_crtc->active))
4919                 return;
4920
4921         if (intel_crtc_to_shared_dpll(intel_crtc))
4922                 intel_enable_shared_dpll(intel_crtc);
4923
4924         if (intel_crtc->config->has_dp_encoder)
4925                 intel_dp_set_m_n(intel_crtc, M1_N1);
4926
4927         intel_set_pipe_timings(intel_crtc);
4928
4929         if (intel_crtc->config->cpu_transcoder != TRANSCODER_EDP) {
4930                 I915_WRITE(PIPE_MULT(intel_crtc->config->cpu_transcoder),
4931                            intel_crtc->config->pixel_multiplier - 1);
4932         }
4933
4934         if (intel_crtc->config->has_pch_encoder) {
4935                 intel_cpu_transcoder_set_m_n(intel_crtc,
4936                                      &intel_crtc->config->fdi_m_n, NULL);
4937         }
4938
4939         haswell_set_pipeconf(crtc);
4940
4941         intel_set_pipe_csc(crtc);
4942
4943         intel_crtc->active = true;
4944
4945         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4946         for_each_encoder_on_crtc(dev, crtc, encoder)
4947                 if (encoder->pre_enable)
4948                         encoder->pre_enable(encoder);
4949
4950         if (intel_crtc->config->has_pch_encoder) {
4951                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4952                                                       true);
4953                 dev_priv->display.fdi_link_train(crtc);
4954         }
4955
4956         intel_ddi_enable_pipe_clock(intel_crtc);
4957
4958         if (INTEL_INFO(dev)->gen == 9)
4959                 skylake_pfit_enable(intel_crtc);
4960         else if (INTEL_INFO(dev)->gen < 9)
4961                 ironlake_pfit_enable(intel_crtc);
4962         else
4963                 MISSING_CASE(INTEL_INFO(dev)->gen);
4964
4965         /*
4966          * On ILK+ LUT must be loaded before the pipe is running but with
4967          * clocks enabled
4968          */
4969         intel_crtc_load_lut(crtc);
4970
4971         intel_ddi_set_pipe_settings(crtc);
4972         intel_ddi_enable_transcoder_func(crtc);
4973
4974         intel_update_watermarks(crtc);
4975         intel_enable_pipe(intel_crtc);
4976
4977         if (intel_crtc->config->has_pch_encoder)
4978                 lpt_pch_enable(crtc);
4979
4980         if (intel_crtc->config->dp_encoder_is_mst)
4981                 intel_ddi_set_vc_payload_alloc(crtc, true);
4982
4983         assert_vblank_disabled(crtc);
4984         drm_crtc_vblank_on(crtc);
4985
4986         for_each_encoder_on_crtc(dev, crtc, encoder) {
4987                 encoder->enable(encoder);
4988                 intel_opregion_notify_encoder(encoder, true);
4989         }
4990
4991         /* If we change the relative order between pipe/planes enabling, we need
4992          * to change the workaround. */
4993         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
4994         if (IS_HASWELL(dev) && hsw_workaround_pipe != INVALID_PIPE) {
4995                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
4996                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
4997         }
4998 }
4999
5000 static void ironlake_pfit_disable(struct intel_crtc *crtc)
5001 {
5002         struct drm_device *dev = crtc->base.dev;
5003         struct drm_i915_private *dev_priv = dev->dev_private;
5004         int pipe = crtc->pipe;
5005
5006         /* To avoid upsetting the power well on haswell only disable the pfit if
5007          * it's in use. The hw state code will make sure we get this right. */
5008         if (crtc->config->pch_pfit.enabled) {
5009                 I915_WRITE(PF_CTL(pipe), 0);
5010                 I915_WRITE(PF_WIN_POS(pipe), 0);
5011                 I915_WRITE(PF_WIN_SZ(pipe), 0);
5012         }
5013 }
5014
5015 static void ironlake_crtc_disable(struct drm_crtc *crtc)
5016 {
5017         struct drm_device *dev = crtc->dev;
5018         struct drm_i915_private *dev_priv = dev->dev_private;
5019         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5020         struct intel_encoder *encoder;
5021         int pipe = intel_crtc->pipe;
5022         u32 reg, temp;
5023
5024         for_each_encoder_on_crtc(dev, crtc, encoder)
5025                 encoder->disable(encoder);
5026
5027         drm_crtc_vblank_off(crtc);
5028         assert_vblank_disabled(crtc);
5029
5030         if (intel_crtc->config->has_pch_encoder)
5031                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5032
5033         intel_disable_pipe(intel_crtc);
5034
5035         ironlake_pfit_disable(intel_crtc);
5036
5037         if (intel_crtc->config->has_pch_encoder)
5038                 ironlake_fdi_disable(crtc);
5039
5040         for_each_encoder_on_crtc(dev, crtc, encoder)
5041                 if (encoder->post_disable)
5042                         encoder->post_disable(encoder);
5043
5044         if (intel_crtc->config->has_pch_encoder) {
5045                 ironlake_disable_pch_transcoder(dev_priv, pipe);
5046
5047                 if (HAS_PCH_CPT(dev)) {
5048                         /* disable TRANS_DP_CTL */
5049                         reg = TRANS_DP_CTL(pipe);
5050                         temp = I915_READ(reg);
5051                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5052                                   TRANS_DP_PORT_SEL_MASK);
5053                         temp |= TRANS_DP_PORT_SEL_NONE;
5054                         I915_WRITE(reg, temp);
5055
5056                         /* disable DPLL_SEL */
5057                         temp = I915_READ(PCH_DPLL_SEL);
5058                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5059                         I915_WRITE(PCH_DPLL_SEL, temp);
5060                 }
5061
5062                 ironlake_fdi_pll_disable(intel_crtc);
5063         }
5064
5065         intel_crtc->active = false;
5066         intel_update_watermarks(crtc);
5067 }
5068
5069 static void haswell_crtc_disable(struct drm_crtc *crtc)
5070 {
5071         struct drm_device *dev = crtc->dev;
5072         struct drm_i915_private *dev_priv = dev->dev_private;
5073         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5074         struct intel_encoder *encoder;
5075         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5076
5077         for_each_encoder_on_crtc(dev, crtc, encoder) {
5078                 intel_opregion_notify_encoder(encoder, false);
5079                 encoder->disable(encoder);
5080         }
5081
5082         drm_crtc_vblank_off(crtc);
5083         assert_vblank_disabled(crtc);
5084
5085         if (intel_crtc->config->has_pch_encoder)
5086                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5087                                                       false);
5088         intel_disable_pipe(intel_crtc);
5089
5090         if (intel_crtc->config->dp_encoder_is_mst)
5091                 intel_ddi_set_vc_payload_alloc(crtc, false);
5092
5093         intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
5094
5095         if (INTEL_INFO(dev)->gen == 9)
5096                 skylake_scaler_disable(intel_crtc);
5097         else if (INTEL_INFO(dev)->gen < 9)
5098                 ironlake_pfit_disable(intel_crtc);
5099         else
5100                 MISSING_CASE(INTEL_INFO(dev)->gen);
5101
5102         intel_ddi_disable_pipe_clock(intel_crtc);
5103
5104         if (intel_crtc->config->has_pch_encoder) {
5105                 lpt_disable_pch_transcoder(dev_priv);
5106                 intel_ddi_fdi_disable(crtc);
5107         }
5108
5109         for_each_encoder_on_crtc(dev, crtc, encoder)
5110                 if (encoder->post_disable)
5111                         encoder->post_disable(encoder);
5112
5113         intel_crtc->active = false;
5114         intel_update_watermarks(crtc);
5115 }
5116
5117 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5118 {
5119         struct drm_device *dev = crtc->base.dev;
5120         struct drm_i915_private *dev_priv = dev->dev_private;
5121         struct intel_crtc_state *pipe_config = crtc->config;
5122
5123         if (!pipe_config->gmch_pfit.control)
5124                 return;
5125
5126         /*
5127          * The panel fitter should only be adjusted whilst the pipe is disabled,
5128          * according to register description and PRM.
5129          */
5130         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5131         assert_pipe_disabled(dev_priv, crtc->pipe);
5132
5133         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5134         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5135
5136         /* Border color in case we don't scale up to the full screen. Black by
5137          * default, change to something else for debugging. */
5138         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5139 }
5140
5141 static enum intel_display_power_domain port_to_power_domain(enum port port)
5142 {
5143         switch (port) {
5144         case PORT_A:
5145                 return POWER_DOMAIN_PORT_DDI_A_4_LANES;
5146         case PORT_B:
5147                 return POWER_DOMAIN_PORT_DDI_B_4_LANES;
5148         case PORT_C:
5149                 return POWER_DOMAIN_PORT_DDI_C_4_LANES;
5150         case PORT_D:
5151                 return POWER_DOMAIN_PORT_DDI_D_4_LANES;
5152         default:
5153                 WARN_ON_ONCE(1);
5154                 return POWER_DOMAIN_PORT_OTHER;
5155         }
5156 }
5157
5158 #define for_each_power_domain(domain, mask)                             \
5159         for ((domain) = 0; (domain) < POWER_DOMAIN_NUM; (domain)++)     \
5160                 if ((1 << (domain)) & (mask))
5161
5162 enum intel_display_power_domain
5163 intel_display_port_power_domain(struct intel_encoder *intel_encoder)
5164 {
5165         struct drm_device *dev = intel_encoder->base.dev;
5166         struct intel_digital_port *intel_dig_port;
5167
5168         switch (intel_encoder->type) {
5169         case INTEL_OUTPUT_UNKNOWN:
5170                 /* Only DDI platforms should ever use this output type */
5171                 WARN_ON_ONCE(!HAS_DDI(dev));
5172         case INTEL_OUTPUT_DISPLAYPORT:
5173         case INTEL_OUTPUT_HDMI:
5174         case INTEL_OUTPUT_EDP:
5175                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5176                 return port_to_power_domain(intel_dig_port->port);
5177         case INTEL_OUTPUT_DP_MST:
5178                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5179                 return port_to_power_domain(intel_dig_port->port);
5180         case INTEL_OUTPUT_ANALOG:
5181                 return POWER_DOMAIN_PORT_CRT;
5182         case INTEL_OUTPUT_DSI:
5183                 return POWER_DOMAIN_PORT_DSI;
5184         default:
5185                 return POWER_DOMAIN_PORT_OTHER;
5186         }
5187 }
5188
5189 static unsigned long get_crtc_power_domains(struct drm_crtc *crtc)
5190 {
5191         struct drm_device *dev = crtc->dev;
5192         struct intel_encoder *intel_encoder;
5193         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5194         enum pipe pipe = intel_crtc->pipe;
5195         unsigned long mask;
5196         enum transcoder transcoder;
5197
5198         transcoder = intel_pipe_to_cpu_transcoder(dev->dev_private, pipe);
5199
5200         mask = BIT(POWER_DOMAIN_PIPE(pipe));
5201         mask |= BIT(POWER_DOMAIN_TRANSCODER(transcoder));
5202         if (intel_crtc->config->pch_pfit.enabled ||
5203             intel_crtc->config->pch_pfit.force_thru)
5204                 mask |= BIT(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5205
5206         for_each_encoder_on_crtc(dev, crtc, intel_encoder)
5207                 mask |= BIT(intel_display_port_power_domain(intel_encoder));
5208
5209         return mask;
5210 }
5211
5212 static void modeset_update_crtc_power_domains(struct drm_atomic_state *state)
5213 {
5214         struct drm_device *dev = state->dev;
5215         struct drm_i915_private *dev_priv = dev->dev_private;
5216         unsigned long pipe_domains[I915_MAX_PIPES] = { 0, };
5217         struct intel_crtc *crtc;
5218
5219         /*
5220          * First get all needed power domains, then put all unneeded, to avoid
5221          * any unnecessary toggling of the power wells.
5222          */
5223         for_each_intel_crtc(dev, crtc) {
5224                 enum intel_display_power_domain domain;
5225
5226                 if (!crtc->base.state->enable)
5227                         continue;
5228
5229                 pipe_domains[crtc->pipe] = get_crtc_power_domains(&crtc->base);
5230
5231                 for_each_power_domain(domain, pipe_domains[crtc->pipe])
5232                         intel_display_power_get(dev_priv, domain);
5233         }
5234
5235         if (dev_priv->display.modeset_commit_cdclk) {
5236                 unsigned int cdclk = to_intel_atomic_state(state)->cdclk;
5237
5238                 if (cdclk != dev_priv->cdclk_freq &&
5239                     !WARN_ON(!state->allow_modeset))
5240                         dev_priv->display.modeset_commit_cdclk(state);
5241         }
5242
5243         for_each_intel_crtc(dev, crtc) {
5244                 enum intel_display_power_domain domain;
5245
5246                 for_each_power_domain(domain, crtc->enabled_power_domains)
5247                         intel_display_power_put(dev_priv, domain);
5248
5249                 crtc->enabled_power_domains = pipe_domains[crtc->pipe];
5250         }
5251
5252         intel_display_set_init_power(dev_priv, false);
5253 }
5254
5255 static void intel_update_max_cdclk(struct drm_device *dev)
5256 {
5257         struct drm_i915_private *dev_priv = dev->dev_private;
5258
5259         if (IS_SKYLAKE(dev)) {
5260                 u32 limit = I915_READ(SKL_DFSM) & SKL_DFSM_CDCLK_LIMIT_MASK;
5261
5262                 if (limit == SKL_DFSM_CDCLK_LIMIT_675)
5263                         dev_priv->max_cdclk_freq = 675000;
5264                 else if (limit == SKL_DFSM_CDCLK_LIMIT_540)
5265                         dev_priv->max_cdclk_freq = 540000;
5266                 else if (limit == SKL_DFSM_CDCLK_LIMIT_450)
5267                         dev_priv->max_cdclk_freq = 450000;
5268                 else
5269                         dev_priv->max_cdclk_freq = 337500;
5270         } else if (IS_BROADWELL(dev))  {
5271                 /*
5272                  * FIXME with extra cooling we can allow
5273                  * 540 MHz for ULX and 675 Mhz for ULT.
5274                  * How can we know if extra cooling is
5275                  * available? PCI ID, VTB, something else?
5276                  */
5277                 if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
5278                         dev_priv->max_cdclk_freq = 450000;
5279                 else if (IS_BDW_ULX(dev))
5280                         dev_priv->max_cdclk_freq = 450000;
5281                 else if (IS_BDW_ULT(dev))
5282                         dev_priv->max_cdclk_freq = 540000;
5283                 else
5284                         dev_priv->max_cdclk_freq = 675000;
5285         } else if (IS_CHERRYVIEW(dev)) {
5286                 dev_priv->max_cdclk_freq = 320000;
5287         } else if (IS_VALLEYVIEW(dev)) {
5288                 dev_priv->max_cdclk_freq = 400000;
5289         } else {
5290                 /* otherwise assume cdclk is fixed */
5291                 dev_priv->max_cdclk_freq = dev_priv->cdclk_freq;
5292         }
5293
5294         DRM_DEBUG_DRIVER("Max CD clock rate: %d kHz\n",
5295                          dev_priv->max_cdclk_freq);
5296 }
5297
5298 static void intel_update_cdclk(struct drm_device *dev)
5299 {
5300         struct drm_i915_private *dev_priv = dev->dev_private;
5301
5302         dev_priv->cdclk_freq = dev_priv->display.get_display_clock_speed(dev);
5303         DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz\n",
5304                          dev_priv->cdclk_freq);
5305
5306         /*
5307          * Program the gmbus_freq based on the cdclk frequency.
5308          * BSpec erroneously claims we should aim for 4MHz, but
5309          * in fact 1MHz is the correct frequency.
5310          */
5311         if (IS_VALLEYVIEW(dev)) {
5312                 /*
5313                  * Program the gmbus_freq based on the cdclk frequency.
5314                  * BSpec erroneously claims we should aim for 4MHz, but
5315                  * in fact 1MHz is the correct frequency.
5316                  */
5317                 I915_WRITE(GMBUSFREQ_VLV, DIV_ROUND_UP(dev_priv->cdclk_freq, 1000));
5318         }
5319
5320         if (dev_priv->max_cdclk_freq == 0)
5321                 intel_update_max_cdclk(dev);
5322 }
5323
5324 static void broxton_set_cdclk(struct drm_device *dev, int frequency)
5325 {
5326         struct drm_i915_private *dev_priv = dev->dev_private;
5327         uint32_t divider;
5328         uint32_t ratio;
5329         uint32_t current_freq;
5330         int ret;
5331
5332         /* frequency = 19.2MHz * ratio / 2 / div{1,1.5,2,4} */
5333         switch (frequency) {
5334         case 144000:
5335                 divider = BXT_CDCLK_CD2X_DIV_SEL_4;
5336                 ratio = BXT_DE_PLL_RATIO(60);
5337                 break;
5338         case 288000:
5339                 divider = BXT_CDCLK_CD2X_DIV_SEL_2;
5340                 ratio = BXT_DE_PLL_RATIO(60);
5341                 break;
5342         case 384000:
5343                 divider = BXT_CDCLK_CD2X_DIV_SEL_1_5;
5344                 ratio = BXT_DE_PLL_RATIO(60);
5345                 break;
5346         case 576000:
5347                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5348                 ratio = BXT_DE_PLL_RATIO(60);
5349                 break;
5350         case 624000:
5351                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5352                 ratio = BXT_DE_PLL_RATIO(65);
5353                 break;
5354         case 19200:
5355                 /*
5356                  * Bypass frequency with DE PLL disabled. Init ratio, divider
5357                  * to suppress GCC warning.
5358                  */
5359                 ratio = 0;
5360                 divider = 0;
5361                 break;
5362         default:
5363                 DRM_ERROR("unsupported CDCLK freq %d", frequency);
5364
5365                 return;
5366         }
5367
5368         mutex_lock(&dev_priv->rps.hw_lock);
5369         /* Inform power controller of upcoming frequency change */
5370         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5371                                       0x80000000);
5372         mutex_unlock(&dev_priv->rps.hw_lock);
5373
5374         if (ret) {
5375                 DRM_ERROR("PCode CDCLK freq change notify failed (err %d, freq %d)\n",
5376                           ret, frequency);
5377                 return;
5378         }
5379
5380         current_freq = I915_READ(CDCLK_CTL) & CDCLK_FREQ_DECIMAL_MASK;
5381         /* convert from .1 fixpoint MHz with -1MHz offset to kHz */
5382         current_freq = current_freq * 500 + 1000;
5383
5384         /*
5385          * DE PLL has to be disabled when
5386          * - setting to 19.2MHz (bypass, PLL isn't used)
5387          * - before setting to 624MHz (PLL needs toggling)
5388          * - before setting to any frequency from 624MHz (PLL needs toggling)
5389          */
5390         if (frequency == 19200 || frequency == 624000 ||
5391             current_freq == 624000) {
5392                 I915_WRITE(BXT_DE_PLL_ENABLE, ~BXT_DE_PLL_PLL_ENABLE);
5393                 /* Timeout 200us */
5394                 if (wait_for(!(I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_LOCK),
5395                              1))
5396                         DRM_ERROR("timout waiting for DE PLL unlock\n");
5397         }
5398
5399         if (frequency != 19200) {
5400                 uint32_t val;
5401
5402                 val = I915_READ(BXT_DE_PLL_CTL);
5403                 val &= ~BXT_DE_PLL_RATIO_MASK;
5404                 val |= ratio;
5405                 I915_WRITE(BXT_DE_PLL_CTL, val);
5406
5407                 I915_WRITE(BXT_DE_PLL_ENABLE, BXT_DE_PLL_PLL_ENABLE);
5408                 /* Timeout 200us */
5409                 if (wait_for(I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_LOCK, 1))
5410                         DRM_ERROR("timeout waiting for DE PLL lock\n");
5411
5412                 val = I915_READ(CDCLK_CTL);
5413                 val &= ~BXT_CDCLK_CD2X_DIV_SEL_MASK;
5414                 val |= divider;
5415                 /*
5416                  * Disable SSA Precharge when CD clock frequency < 500 MHz,
5417                  * enable otherwise.
5418                  */
5419                 val &= ~BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5420                 if (frequency >= 500000)
5421                         val |= BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5422
5423                 val &= ~CDCLK_FREQ_DECIMAL_MASK;
5424                 /* convert from kHz to .1 fixpoint MHz with -1MHz offset */
5425                 val |= (frequency - 1000) / 500;
5426                 I915_WRITE(CDCLK_CTL, val);
5427         }
5428
5429         mutex_lock(&dev_priv->rps.hw_lock);
5430         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5431                                       DIV_ROUND_UP(frequency, 25000));
5432         mutex_unlock(&dev_priv->rps.hw_lock);
5433
5434         if (ret) {
5435                 DRM_ERROR("PCode CDCLK freq set failed, (err %d, freq %d)\n",
5436                           ret, frequency);
5437                 return;
5438         }
5439
5440         intel_update_cdclk(dev);
5441 }
5442
5443 void broxton_init_cdclk(struct drm_device *dev)
5444 {
5445         struct drm_i915_private *dev_priv = dev->dev_private;
5446         uint32_t val;
5447
5448         /*
5449          * NDE_RSTWRN_OPT RST PCH Handshake En must always be 0b on BXT
5450          * or else the reset will hang because there is no PCH to respond.
5451          * Move the handshake programming to initialization sequence.
5452          * Previously was left up to BIOS.
5453          */
5454         val = I915_READ(HSW_NDE_RSTWRN_OPT);
5455         val &= ~RESET_PCH_HANDSHAKE_ENABLE;
5456         I915_WRITE(HSW_NDE_RSTWRN_OPT, val);
5457
5458         /* Enable PG1 for cdclk */
5459         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
5460
5461         /* check if cd clock is enabled */
5462         if (I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_PLL_ENABLE) {
5463                 DRM_DEBUG_KMS("Display already initialized\n");
5464                 return;
5465         }
5466
5467         /*
5468          * FIXME:
5469          * - The initial CDCLK needs to be read from VBT.
5470          *   Need to make this change after VBT has changes for BXT.
5471          * - check if setting the max (or any) cdclk freq is really necessary
5472          *   here, it belongs to modeset time
5473          */
5474         broxton_set_cdclk(dev, 624000);
5475
5476         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) | DBUF_POWER_REQUEST);
5477         POSTING_READ(DBUF_CTL);
5478
5479         udelay(10);
5480
5481         if (!(I915_READ(DBUF_CTL) & DBUF_POWER_STATE))
5482                 DRM_ERROR("DBuf power enable timeout!\n");
5483 }
5484
5485 void broxton_uninit_cdclk(struct drm_device *dev)
5486 {
5487         struct drm_i915_private *dev_priv = dev->dev_private;
5488
5489         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) & ~DBUF_POWER_REQUEST);
5490         POSTING_READ(DBUF_CTL);
5491
5492         udelay(10);
5493
5494         if (I915_READ(DBUF_CTL) & DBUF_POWER_STATE)
5495                 DRM_ERROR("DBuf power disable timeout!\n");
5496
5497         /* Set minimum (bypass) frequency, in effect turning off the DE PLL */
5498         broxton_set_cdclk(dev, 19200);
5499
5500         intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS);
5501 }
5502
5503 static const struct skl_cdclk_entry {
5504         unsigned int freq;
5505         unsigned int vco;
5506 } skl_cdclk_frequencies[] = {
5507         { .freq = 308570, .vco = 8640 },
5508         { .freq = 337500, .vco = 8100 },
5509         { .freq = 432000, .vco = 8640 },
5510         { .freq = 450000, .vco = 8100 },
5511         { .freq = 540000, .vco = 8100 },
5512         { .freq = 617140, .vco = 8640 },
5513         { .freq = 675000, .vco = 8100 },
5514 };
5515
5516 static unsigned int skl_cdclk_decimal(unsigned int freq)
5517 {
5518         return (freq - 1000) / 500;
5519 }
5520
5521 static unsigned int skl_cdclk_get_vco(unsigned int freq)
5522 {
5523         unsigned int i;
5524
5525         for (i = 0; i < ARRAY_SIZE(skl_cdclk_frequencies); i++) {
5526                 const struct skl_cdclk_entry *e = &skl_cdclk_frequencies[i];
5527
5528                 if (e->freq == freq)
5529                         return e->vco;
5530         }
5531
5532         return 8100;
5533 }
5534
5535 static void
5536 skl_dpll0_enable(struct drm_i915_private *dev_priv, unsigned int required_vco)
5537 {
5538         unsigned int min_freq;
5539         u32 val;
5540
5541         /* select the minimum CDCLK before enabling DPLL 0 */
5542         val = I915_READ(CDCLK_CTL);
5543         val &= ~CDCLK_FREQ_SEL_MASK | ~CDCLK_FREQ_DECIMAL_MASK;
5544         val |= CDCLK_FREQ_337_308;
5545
5546         if (required_vco == 8640)
5547                 min_freq = 308570;
5548         else
5549                 min_freq = 337500;
5550
5551         val = CDCLK_FREQ_337_308 | skl_cdclk_decimal(min_freq);
5552
5553         I915_WRITE(CDCLK_CTL, val);
5554         POSTING_READ(CDCLK_CTL);
5555
5556         /*
5557          * We always enable DPLL0 with the lowest link rate possible, but still
5558          * taking into account the VCO required to operate the eDP panel at the
5559          * desired frequency. The usual DP link rates operate with a VCO of
5560          * 8100 while the eDP 1.4 alternate link rates need a VCO of 8640.
5561          * The modeset code is responsible for the selection of the exact link
5562          * rate later on, with the constraint of choosing a frequency that
5563          * works with required_vco.
5564          */
5565         val = I915_READ(DPLL_CTRL1);
5566
5567         val &= ~(DPLL_CTRL1_HDMI_MODE(SKL_DPLL0) | DPLL_CTRL1_SSC(SKL_DPLL0) |
5568                  DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0));
5569         val |= DPLL_CTRL1_OVERRIDE(SKL_DPLL0);
5570         if (required_vco == 8640)
5571                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1080,
5572                                             SKL_DPLL0);
5573         else
5574                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_810,
5575                                             SKL_DPLL0);
5576
5577         I915_WRITE(DPLL_CTRL1, val);
5578         POSTING_READ(DPLL_CTRL1);
5579
5580         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) | LCPLL_PLL_ENABLE);
5581
5582         if (wait_for(I915_READ(LCPLL1_CTL) & LCPLL_PLL_LOCK, 5))
5583                 DRM_ERROR("DPLL0 not locked\n");
5584 }
5585
5586 static bool skl_cdclk_pcu_ready(struct drm_i915_private *dev_priv)
5587 {
5588         int ret;
5589         u32 val;
5590
5591         /* inform PCU we want to change CDCLK */
5592         val = SKL_CDCLK_PREPARE_FOR_CHANGE;
5593         mutex_lock(&dev_priv->rps.hw_lock);
5594         ret = sandybridge_pcode_read(dev_priv, SKL_PCODE_CDCLK_CONTROL, &val);
5595         mutex_unlock(&dev_priv->rps.hw_lock);
5596
5597         return ret == 0 && (val & SKL_CDCLK_READY_FOR_CHANGE);
5598 }
5599
5600 static bool skl_cdclk_wait_for_pcu_ready(struct drm_i915_private *dev_priv)
5601 {
5602         unsigned int i;
5603
5604         for (i = 0; i < 15; i++) {
5605                 if (skl_cdclk_pcu_ready(dev_priv))
5606                         return true;
5607                 udelay(10);
5608         }
5609
5610         return false;
5611 }
5612
5613 static void skl_set_cdclk(struct drm_i915_private *dev_priv, unsigned int freq)
5614 {
5615         struct drm_device *dev = dev_priv->dev;
5616         u32 freq_select, pcu_ack;
5617
5618         DRM_DEBUG_DRIVER("Changing CDCLK to %dKHz\n", freq);
5619
5620         if (!skl_cdclk_wait_for_pcu_ready(dev_priv)) {
5621                 DRM_ERROR("failed to inform PCU about cdclk change\n");
5622                 return;
5623         }
5624
5625         /* set CDCLK_CTL */
5626         switch(freq) {
5627         case 450000:
5628         case 432000:
5629                 freq_select = CDCLK_FREQ_450_432;
5630                 pcu_ack = 1;
5631                 break;
5632         case 540000:
5633                 freq_select = CDCLK_FREQ_540;
5634                 pcu_ack = 2;
5635                 break;
5636         case 308570:
5637         case 337500:
5638         default:
5639                 freq_select = CDCLK_FREQ_337_308;
5640                 pcu_ack = 0;
5641                 break;
5642         case 617140:
5643         case 675000:
5644                 freq_select = CDCLK_FREQ_675_617;
5645                 pcu_ack = 3;
5646                 break;
5647         }
5648
5649         I915_WRITE(CDCLK_CTL, freq_select | skl_cdclk_decimal(freq));
5650         POSTING_READ(CDCLK_CTL);
5651
5652         /* inform PCU of the change */
5653         mutex_lock(&dev_priv->rps.hw_lock);
5654         sandybridge_pcode_write(dev_priv, SKL_PCODE_CDCLK_CONTROL, pcu_ack);
5655         mutex_unlock(&dev_priv->rps.hw_lock);
5656
5657         intel_update_cdclk(dev);
5658 }
5659
5660 void skl_uninit_cdclk(struct drm_i915_private *dev_priv)
5661 {
5662         /* disable DBUF power */
5663         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) & ~DBUF_POWER_REQUEST);
5664         POSTING_READ(DBUF_CTL);
5665
5666         udelay(10);
5667
5668         if (I915_READ(DBUF_CTL) & DBUF_POWER_STATE)
5669                 DRM_ERROR("DBuf power disable timeout\n");
5670
5671         /* disable DPLL0 */
5672         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) & ~LCPLL_PLL_ENABLE);
5673         if (wait_for(!(I915_READ(LCPLL1_CTL) & LCPLL_PLL_LOCK), 1))
5674                 DRM_ERROR("Couldn't disable DPLL0\n");
5675
5676         intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS);
5677 }
5678
5679 void skl_init_cdclk(struct drm_i915_private *dev_priv)
5680 {
5681         u32 val;
5682         unsigned int required_vco;
5683
5684         /* enable PCH reset handshake */
5685         val = I915_READ(HSW_NDE_RSTWRN_OPT);
5686         I915_WRITE(HSW_NDE_RSTWRN_OPT, val | RESET_PCH_HANDSHAKE_ENABLE);
5687
5688         /* enable PG1 and Misc I/O */
5689         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
5690
5691         /* DPLL0 already enabed !? */
5692         if (I915_READ(LCPLL1_CTL) & LCPLL_PLL_ENABLE) {
5693                 DRM_DEBUG_DRIVER("DPLL0 already running\n");
5694                 return;
5695         }
5696
5697         /* enable DPLL0 */
5698         required_vco = skl_cdclk_get_vco(dev_priv->skl_boot_cdclk);
5699         skl_dpll0_enable(dev_priv, required_vco);
5700
5701         /* set CDCLK to the frequency the BIOS chose */
5702         skl_set_cdclk(dev_priv, dev_priv->skl_boot_cdclk);
5703
5704         /* enable DBUF power */
5705         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) | DBUF_POWER_REQUEST);
5706         POSTING_READ(DBUF_CTL);
5707
5708         udelay(10);
5709
5710         if (!(I915_READ(DBUF_CTL) & DBUF_POWER_STATE))
5711                 DRM_ERROR("DBuf power enable timeout\n");
5712 }
5713
5714 /* returns HPLL frequency in kHz */
5715 static int valleyview_get_vco(struct drm_i915_private *dev_priv)
5716 {
5717         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
5718
5719         /* Obtain SKU information */
5720         mutex_lock(&dev_priv->sb_lock);
5721         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
5722                 CCK_FUSE_HPLL_FREQ_MASK;
5723         mutex_unlock(&dev_priv->sb_lock);
5724
5725         return vco_freq[hpll_freq] * 1000;
5726 }
5727
5728 /* Adjust CDclk dividers to allow high res or save power if possible */
5729 static void valleyview_set_cdclk(struct drm_device *dev, int cdclk)
5730 {
5731         struct drm_i915_private *dev_priv = dev->dev_private;
5732         u32 val, cmd;
5733
5734         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5735                                         != dev_priv->cdclk_freq);
5736
5737         if (cdclk >= 320000) /* jump to highest voltage for 400MHz too */
5738                 cmd = 2;
5739         else if (cdclk == 266667)
5740                 cmd = 1;
5741         else
5742                 cmd = 0;
5743
5744         mutex_lock(&dev_priv->rps.hw_lock);
5745         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5746         val &= ~DSPFREQGUAR_MASK;
5747         val |= (cmd << DSPFREQGUAR_SHIFT);
5748         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5749         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5750                       DSPFREQSTAT_MASK) == (cmd << DSPFREQSTAT_SHIFT),
5751                      50)) {
5752                 DRM_ERROR("timed out waiting for CDclk change\n");
5753         }
5754         mutex_unlock(&dev_priv->rps.hw_lock);
5755
5756         mutex_lock(&dev_priv->sb_lock);
5757
5758         if (cdclk == 400000) {
5759                 u32 divider;
5760
5761                 divider = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5762
5763                 /* adjust cdclk divider */
5764                 val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
5765                 val &= ~DISPLAY_FREQUENCY_VALUES;
5766                 val |= divider;
5767                 vlv_cck_write(dev_priv, CCK_DISPLAY_CLOCK_CONTROL, val);
5768
5769                 if (wait_for((vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL) &
5770                               DISPLAY_FREQUENCY_STATUS) == (divider << DISPLAY_FREQUENCY_STATUS_SHIFT),
5771                              50))
5772                         DRM_ERROR("timed out waiting for CDclk change\n");
5773         }
5774
5775         /* adjust self-refresh exit latency value */
5776         val = vlv_bunit_read(dev_priv, BUNIT_REG_BISOC);
5777         val &= ~0x7f;
5778
5779         /*
5780          * For high bandwidth configs, we set a higher latency in the bunit
5781          * so that the core display fetch happens in time to avoid underruns.
5782          */
5783         if (cdclk == 400000)
5784                 val |= 4500 / 250; /* 4.5 usec */
5785         else
5786                 val |= 3000 / 250; /* 3.0 usec */
5787         vlv_bunit_write(dev_priv, BUNIT_REG_BISOC, val);
5788
5789         mutex_unlock(&dev_priv->sb_lock);
5790
5791         intel_update_cdclk(dev);
5792 }
5793
5794 static void cherryview_set_cdclk(struct drm_device *dev, int cdclk)
5795 {
5796         struct drm_i915_private *dev_priv = dev->dev_private;
5797         u32 val, cmd;
5798
5799         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5800                                                 != dev_priv->cdclk_freq);
5801
5802         switch (cdclk) {
5803         case 333333:
5804         case 320000:
5805         case 266667:
5806         case 200000:
5807                 break;
5808         default:
5809                 MISSING_CASE(cdclk);
5810                 return;
5811         }
5812
5813         /*
5814          * Specs are full of misinformation, but testing on actual
5815          * hardware has shown that we just need to write the desired
5816          * CCK divider into the Punit register.
5817          */
5818         cmd = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5819
5820         mutex_lock(&dev_priv->rps.hw_lock);
5821         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5822         val &= ~DSPFREQGUAR_MASK_CHV;
5823         val |= (cmd << DSPFREQGUAR_SHIFT_CHV);
5824         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5825         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5826                       DSPFREQSTAT_MASK_CHV) == (cmd << DSPFREQSTAT_SHIFT_CHV),
5827                      50)) {
5828                 DRM_ERROR("timed out waiting for CDclk change\n");
5829         }
5830         mutex_unlock(&dev_priv->rps.hw_lock);
5831
5832         intel_update_cdclk(dev);
5833 }
5834
5835 static int valleyview_calc_cdclk(struct drm_i915_private *dev_priv,
5836                                  int max_pixclk)
5837 {
5838         int freq_320 = (dev_priv->hpll_freq <<  1) % 320000 != 0 ? 333333 : 320000;
5839         int limit = IS_CHERRYVIEW(dev_priv) ? 95 : 90;
5840
5841         /*
5842          * Really only a few cases to deal with, as only 4 CDclks are supported:
5843          *   200MHz
5844          *   267MHz
5845          *   320/333MHz (depends on HPLL freq)
5846          *   400MHz (VLV only)
5847          * So we check to see whether we're above 90% (VLV) or 95% (CHV)
5848          * of the lower bin and adjust if needed.
5849          *
5850          * We seem to get an unstable or solid color picture at 200MHz.
5851          * Not sure what's wrong. For now use 200MHz only when all pipes
5852          * are off.
5853          */
5854         if (!IS_CHERRYVIEW(dev_priv) &&
5855             max_pixclk > freq_320*limit/100)
5856                 return 400000;
5857         else if (max_pixclk > 266667*limit/100)
5858                 return freq_320;
5859         else if (max_pixclk > 0)
5860                 return 266667;
5861         else
5862                 return 200000;
5863 }
5864
5865 static int broxton_calc_cdclk(struct drm_i915_private *dev_priv,
5866                               int max_pixclk)
5867 {
5868         /*
5869          * FIXME:
5870          * - remove the guardband, it's not needed on BXT
5871          * - set 19.2MHz bypass frequency if there are no active pipes
5872          */
5873         if (max_pixclk > 576000*9/10)
5874                 return 624000;
5875         else if (max_pixclk > 384000*9/10)
5876                 return 576000;
5877         else if (max_pixclk > 288000*9/10)
5878                 return 384000;
5879         else if (max_pixclk > 144000*9/10)
5880                 return 288000;
5881         else
5882                 return 144000;
5883 }
5884
5885 /* Compute the max pixel clock for new configuration. Uses atomic state if
5886  * that's non-NULL, look at current state otherwise. */
5887 static int intel_mode_max_pixclk(struct drm_device *dev,
5888                                  struct drm_atomic_state *state)
5889 {
5890         struct intel_crtc *intel_crtc;
5891         struct intel_crtc_state *crtc_state;
5892         int max_pixclk = 0;
5893
5894         for_each_intel_crtc(dev, intel_crtc) {
5895                 crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
5896                 if (IS_ERR(crtc_state))
5897                         return PTR_ERR(crtc_state);
5898
5899                 if (!crtc_state->base.enable)
5900                         continue;
5901
5902                 max_pixclk = max(max_pixclk,
5903                                  crtc_state->base.adjusted_mode.crtc_clock);
5904         }
5905
5906         return max_pixclk;
5907 }
5908
5909 static int valleyview_modeset_calc_cdclk(struct drm_atomic_state *state)
5910 {
5911         struct drm_device *dev = state->dev;
5912         struct drm_i915_private *dev_priv = dev->dev_private;
5913         int max_pixclk = intel_mode_max_pixclk(dev, state);
5914
5915         if (max_pixclk < 0)
5916                 return max_pixclk;
5917
5918         to_intel_atomic_state(state)->cdclk =
5919                 valleyview_calc_cdclk(dev_priv, max_pixclk);
5920
5921         return 0;
5922 }
5923
5924 static int broxton_modeset_calc_cdclk(struct drm_atomic_state *state)
5925 {
5926         struct drm_device *dev = state->dev;
5927         struct drm_i915_private *dev_priv = dev->dev_private;
5928         int max_pixclk = intel_mode_max_pixclk(dev, state);
5929
5930         if (max_pixclk < 0)
5931                 return max_pixclk;
5932
5933         to_intel_atomic_state(state)->cdclk =
5934                 broxton_calc_cdclk(dev_priv, max_pixclk);
5935
5936         return 0;
5937 }
5938
5939 static void vlv_program_pfi_credits(struct drm_i915_private *dev_priv)
5940 {
5941         unsigned int credits, default_credits;
5942
5943         if (IS_CHERRYVIEW(dev_priv))
5944                 default_credits = PFI_CREDIT(12);
5945         else
5946                 default_credits = PFI_CREDIT(8);
5947
5948         if (DIV_ROUND_CLOSEST(dev_priv->cdclk_freq, 1000) >= dev_priv->rps.cz_freq) {
5949                 /* CHV suggested value is 31 or 63 */
5950                 if (IS_CHERRYVIEW(dev_priv))
5951                         credits = PFI_CREDIT_63;
5952                 else
5953                         credits = PFI_CREDIT(15);
5954         } else {
5955                 credits = default_credits;
5956         }
5957
5958         /*
5959          * WA - write default credits before re-programming
5960          * FIXME: should we also set the resend bit here?
5961          */
5962         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
5963                    default_credits);
5964
5965         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
5966                    credits | PFI_CREDIT_RESEND);
5967
5968         /*
5969          * FIXME is this guaranteed to clear
5970          * immediately or should we poll for it?
5971          */
5972         WARN_ON(I915_READ(GCI_CONTROL) & PFI_CREDIT_RESEND);
5973 }
5974
5975 static void valleyview_modeset_commit_cdclk(struct drm_atomic_state *old_state)
5976 {
5977         struct drm_device *dev = old_state->dev;
5978         unsigned int req_cdclk = to_intel_atomic_state(old_state)->cdclk;
5979         struct drm_i915_private *dev_priv = dev->dev_private;
5980
5981         /*
5982          * FIXME: We can end up here with all power domains off, yet
5983          * with a CDCLK frequency other than the minimum. To account
5984          * for this take the PIPE-A power domain, which covers the HW
5985          * blocks needed for the following programming. This can be
5986          * removed once it's guaranteed that we get here either with
5987          * the minimum CDCLK set, or the required power domains
5988          * enabled.
5989          */
5990         intel_display_power_get(dev_priv, POWER_DOMAIN_PIPE_A);
5991
5992         if (IS_CHERRYVIEW(dev))
5993                 cherryview_set_cdclk(dev, req_cdclk);
5994         else
5995                 valleyview_set_cdclk(dev, req_cdclk);
5996
5997         vlv_program_pfi_credits(dev_priv);
5998
5999         intel_display_power_put(dev_priv, POWER_DOMAIN_PIPE_A);
6000 }
6001
6002 static void valleyview_crtc_enable(struct drm_crtc *crtc)
6003 {
6004         struct drm_device *dev = crtc->dev;
6005         struct drm_i915_private *dev_priv = to_i915(dev);
6006         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6007         struct intel_encoder *encoder;
6008         int pipe = intel_crtc->pipe;
6009         bool is_dsi;
6010
6011         if (WARN_ON(intel_crtc->active))
6012                 return;
6013
6014         is_dsi = intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_DSI);
6015
6016         if (!is_dsi) {
6017                 if (IS_CHERRYVIEW(dev))
6018                         chv_prepare_pll(intel_crtc, intel_crtc->config);
6019                 else
6020                         vlv_prepare_pll(intel_crtc, intel_crtc->config);
6021         }
6022
6023         if (intel_crtc->config->has_dp_encoder)
6024                 intel_dp_set_m_n(intel_crtc, M1_N1);
6025
6026         intel_set_pipe_timings(intel_crtc);
6027
6028         if (IS_CHERRYVIEW(dev) && pipe == PIPE_B) {
6029                 struct drm_i915_private *dev_priv = dev->dev_private;
6030
6031                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6032                 I915_WRITE(CHV_CANVAS(pipe), 0);
6033         }
6034
6035         i9xx_set_pipeconf(intel_crtc);
6036
6037         intel_crtc->active = true;
6038
6039         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6040
6041         for_each_encoder_on_crtc(dev, crtc, encoder)
6042                 if (encoder->pre_pll_enable)
6043                         encoder->pre_pll_enable(encoder);
6044
6045         if (!is_dsi) {
6046                 if (IS_CHERRYVIEW(dev))
6047                         chv_enable_pll(intel_crtc, intel_crtc->config);
6048                 else
6049                         vlv_enable_pll(intel_crtc, intel_crtc->config);
6050         }
6051
6052         for_each_encoder_on_crtc(dev, crtc, encoder)
6053                 if (encoder->pre_enable)
6054                         encoder->pre_enable(encoder);
6055
6056         i9xx_pfit_enable(intel_crtc);
6057
6058         intel_crtc_load_lut(crtc);
6059
6060         intel_enable_pipe(intel_crtc);
6061
6062         assert_vblank_disabled(crtc);
6063         drm_crtc_vblank_on(crtc);
6064
6065         for_each_encoder_on_crtc(dev, crtc, encoder)
6066                 encoder->enable(encoder);
6067 }
6068
6069 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
6070 {
6071         struct drm_device *dev = crtc->base.dev;
6072         struct drm_i915_private *dev_priv = dev->dev_private;
6073
6074         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
6075         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
6076 }
6077
6078 static void i9xx_crtc_enable(struct drm_crtc *crtc)
6079 {
6080         struct drm_device *dev = crtc->dev;
6081         struct drm_i915_private *dev_priv = to_i915(dev);
6082         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6083         struct intel_encoder *encoder;
6084         int pipe = intel_crtc->pipe;
6085
6086         if (WARN_ON(intel_crtc->active))
6087                 return;
6088
6089         i9xx_set_pll_dividers(intel_crtc);
6090
6091         if (intel_crtc->config->has_dp_encoder)
6092                 intel_dp_set_m_n(intel_crtc, M1_N1);
6093
6094         intel_set_pipe_timings(intel_crtc);
6095
6096         i9xx_set_pipeconf(intel_crtc);
6097
6098         intel_crtc->active = true;
6099
6100         if (!IS_GEN2(dev))
6101                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6102
6103         for_each_encoder_on_crtc(dev, crtc, encoder)
6104                 if (encoder->pre_enable)
6105                         encoder->pre_enable(encoder);
6106
6107         i9xx_enable_pll(intel_crtc);
6108
6109         i9xx_pfit_enable(intel_crtc);
6110
6111         intel_crtc_load_lut(crtc);
6112
6113         intel_update_watermarks(crtc);
6114         intel_enable_pipe(intel_crtc);
6115
6116         assert_vblank_disabled(crtc);
6117         drm_crtc_vblank_on(crtc);
6118
6119         for_each_encoder_on_crtc(dev, crtc, encoder)
6120                 encoder->enable(encoder);
6121 }
6122
6123 static void i9xx_pfit_disable(struct intel_crtc *crtc)
6124 {
6125         struct drm_device *dev = crtc->base.dev;
6126         struct drm_i915_private *dev_priv = dev->dev_private;
6127
6128         if (!crtc->config->gmch_pfit.control)
6129                 return;
6130
6131         assert_pipe_disabled(dev_priv, crtc->pipe);
6132
6133         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
6134                          I915_READ(PFIT_CONTROL));
6135         I915_WRITE(PFIT_CONTROL, 0);
6136 }
6137
6138 static void i9xx_crtc_disable(struct drm_crtc *crtc)
6139 {
6140         struct drm_device *dev = crtc->dev;
6141         struct drm_i915_private *dev_priv = dev->dev_private;
6142         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6143         struct intel_encoder *encoder;
6144         int pipe = intel_crtc->pipe;
6145
6146         /*
6147          * On gen2 planes are double buffered but the pipe isn't, so we must
6148          * wait for planes to fully turn off before disabling the pipe.
6149          * We also need to wait on all gmch platforms because of the
6150          * self-refresh mode constraint explained above.
6151          */
6152         intel_wait_for_vblank(dev, pipe);
6153
6154         for_each_encoder_on_crtc(dev, crtc, encoder)
6155                 encoder->disable(encoder);
6156
6157         drm_crtc_vblank_off(crtc);
6158         assert_vblank_disabled(crtc);
6159
6160         intel_disable_pipe(intel_crtc);
6161
6162         i9xx_pfit_disable(intel_crtc);
6163
6164         for_each_encoder_on_crtc(dev, crtc, encoder)
6165                 if (encoder->post_disable)
6166                         encoder->post_disable(encoder);
6167
6168         if (!intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_DSI)) {
6169                 if (IS_CHERRYVIEW(dev))
6170                         chv_disable_pll(dev_priv, pipe);
6171                 else if (IS_VALLEYVIEW(dev))
6172                         vlv_disable_pll(dev_priv, pipe);
6173                 else
6174                         i9xx_disable_pll(intel_crtc);
6175         }
6176
6177         if (!IS_GEN2(dev))
6178                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6179
6180         intel_crtc->active = false;
6181         intel_update_watermarks(crtc);
6182 }
6183
6184 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc)
6185 {
6186         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6187         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6188         enum intel_display_power_domain domain;
6189         unsigned long domains;
6190
6191         if (!intel_crtc->active)
6192                 return;
6193
6194         if (to_intel_plane_state(crtc->primary->state)->visible) {
6195                 intel_crtc_wait_for_pending_flips(crtc);
6196                 intel_pre_disable_primary(crtc);
6197         }
6198
6199         intel_crtc_disable_planes(crtc, crtc->state->plane_mask);
6200         dev_priv->display.crtc_disable(crtc);
6201
6202         domains = intel_crtc->enabled_power_domains;
6203         for_each_power_domain(domain, domains)
6204                 intel_display_power_put(dev_priv, domain);
6205         intel_crtc->enabled_power_domains = 0;
6206 }
6207
6208 /*
6209  * turn all crtc's off, but do not adjust state
6210  * This has to be paired with a call to intel_modeset_setup_hw_state.
6211  */
6212 void intel_display_suspend(struct drm_device *dev)
6213 {
6214         struct drm_crtc *crtc;
6215
6216         for_each_crtc(dev, crtc)
6217                 intel_crtc_disable_noatomic(crtc);
6218 }
6219
6220 /* Master function to enable/disable CRTC and corresponding power wells */
6221 int intel_crtc_control(struct drm_crtc *crtc, bool enable)
6222 {
6223         struct drm_device *dev = crtc->dev;
6224         struct drm_mode_config *config = &dev->mode_config;
6225         struct drm_modeset_acquire_ctx *ctx = config->acquire_ctx;
6226         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6227         struct intel_crtc_state *pipe_config;
6228         struct drm_atomic_state *state;
6229         int ret;
6230
6231         if (enable == intel_crtc->active)
6232                 return 0;
6233
6234         if (enable && !crtc->state->enable)
6235                 return 0;
6236
6237         /* this function should be called with drm_modeset_lock_all for now */
6238         if (WARN_ON(!ctx))
6239                 return -EIO;
6240         lockdep_assert_held(&ctx->ww_ctx);
6241
6242         state = drm_atomic_state_alloc(dev);
6243         if (WARN_ON(!state))
6244                 return -ENOMEM;
6245
6246         state->acquire_ctx = ctx;
6247         state->allow_modeset = true;
6248
6249         pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
6250         if (IS_ERR(pipe_config)) {
6251                 ret = PTR_ERR(pipe_config);
6252                 goto err;
6253         }
6254         pipe_config->base.active = enable;
6255
6256         ret = intel_set_mode(state);
6257         if (!ret)
6258                 return ret;
6259
6260 err:
6261         DRM_ERROR("Updating crtc active failed with %i\n", ret);
6262         drm_atomic_state_free(state);
6263         return ret;
6264 }
6265
6266 /**
6267  * Sets the power management mode of the pipe and plane.
6268  */
6269 void intel_crtc_update_dpms(struct drm_crtc *crtc)
6270 {
6271         struct drm_device *dev = crtc->dev;
6272         struct intel_encoder *intel_encoder;
6273         bool enable = false;
6274
6275         for_each_encoder_on_crtc(dev, crtc, intel_encoder)
6276                 enable |= intel_encoder->connectors_active;
6277
6278         intel_crtc_control(crtc, enable);
6279 }
6280
6281 void intel_encoder_destroy(struct drm_encoder *encoder)
6282 {
6283         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6284
6285         drm_encoder_cleanup(encoder);
6286         kfree(intel_encoder);
6287 }
6288
6289 /* Simple dpms helper for encoders with just one connector, no cloning and only
6290  * one kind of off state. It clamps all !ON modes to fully OFF and changes the
6291  * state of the entire output pipe. */
6292 static void intel_encoder_dpms(struct intel_encoder *encoder, int mode)
6293 {
6294         if (mode == DRM_MODE_DPMS_ON) {
6295                 encoder->connectors_active = true;
6296
6297                 intel_crtc_update_dpms(encoder->base.crtc);
6298         } else {
6299                 encoder->connectors_active = false;
6300
6301                 intel_crtc_update_dpms(encoder->base.crtc);
6302         }
6303 }
6304
6305 /* Cross check the actual hw state with our own modeset state tracking (and it's
6306  * internal consistency). */
6307 static void intel_connector_check_state(struct intel_connector *connector)
6308 {
6309         if (connector->get_hw_state(connector)) {
6310                 struct intel_encoder *encoder = connector->encoder;
6311                 struct drm_crtc *crtc;
6312                 bool encoder_enabled;
6313                 enum pipe pipe;
6314
6315                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6316                               connector->base.base.id,
6317                               connector->base.name);
6318
6319                 /* there is no real hw state for MST connectors */
6320                 if (connector->mst_port)
6321                         return;
6322
6323                 I915_STATE_WARN(connector->base.dpms == DRM_MODE_DPMS_OFF,
6324                      "wrong connector dpms state\n");
6325                 I915_STATE_WARN(connector->base.encoder != &encoder->base,
6326                      "active connector not linked to encoder\n");
6327
6328                 if (encoder) {
6329                         I915_STATE_WARN(!encoder->connectors_active,
6330                              "encoder->connectors_active not set\n");
6331
6332                         encoder_enabled = encoder->get_hw_state(encoder, &pipe);
6333                         I915_STATE_WARN(!encoder_enabled, "encoder not enabled\n");
6334                         if (I915_STATE_WARN_ON(!encoder->base.crtc))
6335                                 return;
6336
6337                         crtc = encoder->base.crtc;
6338
6339                         I915_STATE_WARN(!crtc->state->enable,
6340                                         "crtc not enabled\n");
6341                         I915_STATE_WARN(!to_intel_crtc(crtc)->active, "crtc not active\n");
6342                         I915_STATE_WARN(pipe != to_intel_crtc(crtc)->pipe,
6343                              "encoder active on the wrong pipe\n");
6344                 }
6345         }
6346 }
6347
6348 int intel_connector_init(struct intel_connector *connector)
6349 {
6350         struct drm_connector_state *connector_state;
6351
6352         connector_state = kzalloc(sizeof *connector_state, GFP_KERNEL);
6353         if (!connector_state)
6354                 return -ENOMEM;
6355
6356         connector->base.state = connector_state;
6357         return 0;
6358 }
6359
6360 struct intel_connector *intel_connector_alloc(void)
6361 {
6362         struct intel_connector *connector;
6363
6364         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6365         if (!connector)
6366                 return NULL;
6367
6368         if (intel_connector_init(connector) < 0) {
6369                 kfree(connector);
6370                 return NULL;
6371         }
6372
6373         return connector;
6374 }
6375
6376 /* Even simpler default implementation, if there's really no special case to
6377  * consider. */
6378 void intel_connector_dpms(struct drm_connector *connector, int mode)
6379 {
6380         /* All the simple cases only support two dpms states. */
6381         if (mode != DRM_MODE_DPMS_ON)
6382                 mode = DRM_MODE_DPMS_OFF;
6383
6384         if (mode == connector->dpms)
6385                 return;
6386
6387         connector->dpms = mode;
6388
6389         /* Only need to change hw state when actually enabled */
6390         if (connector->encoder)
6391                 intel_encoder_dpms(to_intel_encoder(connector->encoder), mode);
6392
6393         intel_modeset_check_state(connector->dev);
6394 }
6395
6396 /* Simple connector->get_hw_state implementation for encoders that support only
6397  * one connector and no cloning and hence the encoder state determines the state
6398  * of the connector. */
6399 bool intel_connector_get_hw_state(struct intel_connector *connector)
6400 {
6401         enum pipe pipe = 0;
6402         struct intel_encoder *encoder = connector->encoder;
6403
6404         return encoder->get_hw_state(encoder, &pipe);
6405 }
6406
6407 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6408 {
6409         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6410                 return crtc_state->fdi_lanes;
6411
6412         return 0;
6413 }
6414
6415 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6416                                      struct intel_crtc_state *pipe_config)
6417 {
6418         struct drm_atomic_state *state = pipe_config->base.state;
6419         struct intel_crtc *other_crtc;
6420         struct intel_crtc_state *other_crtc_state;
6421
6422         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6423                       pipe_name(pipe), pipe_config->fdi_lanes);
6424         if (pipe_config->fdi_lanes > 4) {
6425                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6426                               pipe_name(pipe), pipe_config->fdi_lanes);
6427                 return -EINVAL;
6428         }
6429
6430         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
6431                 if (pipe_config->fdi_lanes > 2) {
6432                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6433                                       pipe_config->fdi_lanes);
6434                         return -EINVAL;
6435                 } else {
6436                         return 0;
6437                 }
6438         }
6439
6440         if (INTEL_INFO(dev)->num_pipes == 2)
6441                 return 0;
6442
6443         /* Ivybridge 3 pipe is really complicated */
6444         switch (pipe) {
6445         case PIPE_A:
6446                 return 0;
6447         case PIPE_B:
6448                 if (pipe_config->fdi_lanes <= 2)
6449                         return 0;
6450
6451                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_C));
6452                 other_crtc_state =
6453                         intel_atomic_get_crtc_state(state, other_crtc);
6454                 if (IS_ERR(other_crtc_state))
6455                         return PTR_ERR(other_crtc_state);
6456
6457                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6458                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6459                                       pipe_name(pipe), pipe_config->fdi_lanes);
6460                         return -EINVAL;
6461                 }
6462                 return 0;
6463         case PIPE_C:
6464                 if (pipe_config->fdi_lanes > 2) {
6465                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6466                                       pipe_name(pipe), pipe_config->fdi_lanes);
6467                         return -EINVAL;
6468                 }
6469
6470                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_B));
6471                 other_crtc_state =
6472                         intel_atomic_get_crtc_state(state, other_crtc);
6473                 if (IS_ERR(other_crtc_state))
6474                         return PTR_ERR(other_crtc_state);
6475
6476                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6477                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6478                         return -EINVAL;
6479                 }
6480                 return 0;
6481         default:
6482                 BUG();
6483         }
6484 }
6485
6486 #define RETRY 1
6487 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6488                                        struct intel_crtc_state *pipe_config)
6489 {
6490         struct drm_device *dev = intel_crtc->base.dev;
6491         struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6492         int lane, link_bw, fdi_dotclock, ret;
6493         bool needs_recompute = false;
6494
6495 retry:
6496         /* FDI is a binary signal running at ~2.7GHz, encoding
6497          * each output octet as 10 bits. The actual frequency
6498          * is stored as a divider into a 100MHz clock, and the
6499          * mode pixel clock is stored in units of 1KHz.
6500          * Hence the bw of each lane in terms of the mode signal
6501          * is:
6502          */
6503         link_bw = intel_fdi_link_freq(dev) * MHz(100)/KHz(1)/10;
6504
6505         fdi_dotclock = adjusted_mode->crtc_clock;
6506
6507         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6508                                            pipe_config->pipe_bpp);
6509
6510         pipe_config->fdi_lanes = lane;
6511
6512         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6513                                link_bw, &pipe_config->fdi_m_n);
6514
6515         ret = ironlake_check_fdi_lanes(intel_crtc->base.dev,
6516                                        intel_crtc->pipe, pipe_config);
6517         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6518                 pipe_config->pipe_bpp -= 2*3;
6519                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6520                               pipe_config->pipe_bpp);
6521                 needs_recompute = true;
6522                 pipe_config->bw_constrained = true;
6523
6524                 goto retry;
6525         }
6526
6527         if (needs_recompute)
6528                 return RETRY;
6529
6530         return ret;
6531 }
6532
6533 static bool pipe_config_supports_ips(struct drm_i915_private *dev_priv,
6534                                      struct intel_crtc_state *pipe_config)
6535 {
6536         if (pipe_config->pipe_bpp > 24)
6537                 return false;
6538
6539         /* HSW can handle pixel rate up to cdclk? */
6540         if (IS_HASWELL(dev_priv->dev))
6541                 return true;
6542
6543         /*
6544          * We compare against max which means we must take
6545          * the increased cdclk requirement into account when
6546          * calculating the new cdclk.
6547          *
6548          * Should measure whether using a lower cdclk w/o IPS
6549          */
6550         return ilk_pipe_pixel_rate(pipe_config) <=
6551                 dev_priv->max_cdclk_freq * 95 / 100;
6552 }
6553
6554 static void hsw_compute_ips_config(struct intel_crtc *crtc,
6555                                    struct intel_crtc_state *pipe_config)
6556 {
6557         struct drm_device *dev = crtc->base.dev;
6558         struct drm_i915_private *dev_priv = dev->dev_private;
6559
6560         pipe_config->ips_enabled = i915.enable_ips &&
6561                 hsw_crtc_supports_ips(crtc) &&
6562                 pipe_config_supports_ips(dev_priv, pipe_config);
6563 }
6564
6565 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6566                                      struct intel_crtc_state *pipe_config)
6567 {
6568         struct drm_device *dev = crtc->base.dev;
6569         struct drm_i915_private *dev_priv = dev->dev_private;
6570         struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6571
6572         /* FIXME should check pixel clock limits on all platforms */
6573         if (INTEL_INFO(dev)->gen < 4) {
6574                 int clock_limit = dev_priv->max_cdclk_freq;
6575
6576                 /*
6577                  * Enable pixel doubling when the dot clock
6578                  * is > 90% of the (display) core speed.
6579                  *
6580                  * GDG double wide on either pipe,
6581                  * otherwise pipe A only.
6582                  */
6583                 if ((crtc->pipe == PIPE_A || IS_I915G(dev)) &&
6584                     adjusted_mode->crtc_clock > clock_limit * 9 / 10) {
6585                         clock_limit *= 2;
6586                         pipe_config->double_wide = true;
6587                 }
6588
6589                 if (adjusted_mode->crtc_clock > clock_limit * 9 / 10)
6590                         return -EINVAL;
6591         }
6592
6593         /*
6594          * Pipe horizontal size must be even in:
6595          * - DVO ganged mode
6596          * - LVDS dual channel mode
6597          * - Double wide pipe
6598          */
6599         if ((intel_pipe_will_have_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6600              intel_is_dual_link_lvds(dev)) || pipe_config->double_wide)
6601                 pipe_config->pipe_src_w &= ~1;
6602
6603         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6604          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6605          */
6606         if ((INTEL_INFO(dev)->gen > 4 || IS_G4X(dev)) &&
6607                 adjusted_mode->hsync_start == adjusted_mode->hdisplay)
6608                 return -EINVAL;
6609
6610         if (HAS_IPS(dev))
6611                 hsw_compute_ips_config(crtc, pipe_config);
6612
6613         if (pipe_config->has_pch_encoder)
6614                 return ironlake_fdi_compute_config(crtc, pipe_config);
6615
6616         return 0;
6617 }
6618
6619 static int skylake_get_display_clock_speed(struct drm_device *dev)
6620 {
6621         struct drm_i915_private *dev_priv = to_i915(dev);
6622         uint32_t lcpll1 = I915_READ(LCPLL1_CTL);
6623         uint32_t cdctl = I915_READ(CDCLK_CTL);
6624         uint32_t linkrate;
6625
6626         if (!(lcpll1 & LCPLL_PLL_ENABLE))
6627                 return 24000; /* 24MHz is the cd freq with NSSC ref */
6628
6629         if ((cdctl & CDCLK_FREQ_SEL_MASK) == CDCLK_FREQ_540)
6630                 return 540000;
6631
6632         linkrate = (I915_READ(DPLL_CTRL1) &
6633                     DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0)) >> 1;
6634
6635         if (linkrate == DPLL_CTRL1_LINK_RATE_2160 ||
6636             linkrate == DPLL_CTRL1_LINK_RATE_1080) {
6637                 /* vco 8640 */
6638                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6639                 case CDCLK_FREQ_450_432:
6640                         return 432000;
6641                 case CDCLK_FREQ_337_308:
6642                         return 308570;
6643                 case CDCLK_FREQ_675_617:
6644                         return 617140;
6645                 default:
6646                         WARN(1, "Unknown cd freq selection\n");
6647                 }
6648         } else {
6649                 /* vco 8100 */
6650                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6651                 case CDCLK_FREQ_450_432:
6652                         return 450000;
6653                 case CDCLK_FREQ_337_308:
6654                         return 337500;
6655                 case CDCLK_FREQ_675_617:
6656                         return 675000;
6657                 default:
6658                         WARN(1, "Unknown cd freq selection\n");
6659                 }
6660         }
6661
6662         /* error case, do as if DPLL0 isn't enabled */
6663         return 24000;
6664 }
6665
6666 static int broxton_get_display_clock_speed(struct drm_device *dev)
6667 {
6668         struct drm_i915_private *dev_priv = to_i915(dev);
6669         uint32_t cdctl = I915_READ(CDCLK_CTL);
6670         uint32_t pll_ratio = I915_READ(BXT_DE_PLL_CTL) & BXT_DE_PLL_RATIO_MASK;
6671         uint32_t pll_enab = I915_READ(BXT_DE_PLL_ENABLE);
6672         int cdclk;
6673
6674         if (!(pll_enab & BXT_DE_PLL_PLL_ENABLE))
6675                 return 19200;
6676
6677         cdclk = 19200 * pll_ratio / 2;
6678
6679         switch (cdctl & BXT_CDCLK_CD2X_DIV_SEL_MASK) {
6680         case BXT_CDCLK_CD2X_DIV_SEL_1:
6681                 return cdclk;  /* 576MHz or 624MHz */
6682         case BXT_CDCLK_CD2X_DIV_SEL_1_5:
6683                 return cdclk * 2 / 3; /* 384MHz */
6684         case BXT_CDCLK_CD2X_DIV_SEL_2:
6685                 return cdclk / 2; /* 288MHz */
6686         case BXT_CDCLK_CD2X_DIV_SEL_4:
6687                 return cdclk / 4; /* 144MHz */
6688         }
6689
6690         /* error case, do as if DE PLL isn't enabled */
6691         return 19200;
6692 }
6693
6694 static int broadwell_get_display_clock_speed(struct drm_device *dev)
6695 {
6696         struct drm_i915_private *dev_priv = dev->dev_private;
6697         uint32_t lcpll = I915_READ(LCPLL_CTL);
6698         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6699
6700         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6701                 return 800000;
6702         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6703                 return 450000;
6704         else if (freq == LCPLL_CLK_FREQ_450)
6705                 return 450000;
6706         else if (freq == LCPLL_CLK_FREQ_54O_BDW)
6707                 return 540000;
6708         else if (freq == LCPLL_CLK_FREQ_337_5_BDW)
6709                 return 337500;
6710         else
6711                 return 675000;
6712 }
6713
6714 static int haswell_get_display_clock_speed(struct drm_device *dev)
6715 {
6716         struct drm_i915_private *dev_priv = dev->dev_private;
6717         uint32_t lcpll = I915_READ(LCPLL_CTL);
6718         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6719
6720         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6721                 return 800000;
6722         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6723                 return 450000;
6724         else if (freq == LCPLL_CLK_FREQ_450)
6725                 return 450000;
6726         else if (IS_HSW_ULT(dev))
6727                 return 337500;
6728         else
6729                 return 540000;
6730 }
6731
6732 static int valleyview_get_display_clock_speed(struct drm_device *dev)
6733 {
6734         struct drm_i915_private *dev_priv = dev->dev_private;
6735         u32 val;
6736         int divider;
6737
6738         if (dev_priv->hpll_freq == 0)
6739                 dev_priv->hpll_freq = valleyview_get_vco(dev_priv);
6740
6741         mutex_lock(&dev_priv->sb_lock);
6742         val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
6743         mutex_unlock(&dev_priv->sb_lock);
6744
6745         divider = val & DISPLAY_FREQUENCY_VALUES;
6746
6747         WARN((val & DISPLAY_FREQUENCY_STATUS) !=
6748              (divider << DISPLAY_FREQUENCY_STATUS_SHIFT),
6749              "cdclk change in progress\n");
6750
6751         return DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, divider + 1);
6752 }
6753
6754 static int ilk_get_display_clock_speed(struct drm_device *dev)
6755 {
6756         return 450000;
6757 }
6758
6759 static int i945_get_display_clock_speed(struct drm_device *dev)
6760 {
6761         return 400000;
6762 }
6763
6764 static int i915_get_display_clock_speed(struct drm_device *dev)
6765 {
6766         return 333333;
6767 }
6768
6769 static int i9xx_misc_get_display_clock_speed(struct drm_device *dev)
6770 {
6771         return 200000;
6772 }
6773
6774 static int pnv_get_display_clock_speed(struct drm_device *dev)
6775 {
6776         u16 gcfgc = 0;
6777
6778         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6779
6780         switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6781         case GC_DISPLAY_CLOCK_267_MHZ_PNV:
6782                 return 266667;
6783         case GC_DISPLAY_CLOCK_333_MHZ_PNV:
6784                 return 333333;
6785         case GC_DISPLAY_CLOCK_444_MHZ_PNV:
6786                 return 444444;
6787         case GC_DISPLAY_CLOCK_200_MHZ_PNV:
6788                 return 200000;
6789         default:
6790                 DRM_ERROR("Unknown pnv display core clock 0x%04x\n", gcfgc);
6791         case GC_DISPLAY_CLOCK_133_MHZ_PNV:
6792                 return 133333;
6793         case GC_DISPLAY_CLOCK_167_MHZ_PNV:
6794                 return 166667;
6795         }
6796 }
6797
6798 static int i915gm_get_display_clock_speed(struct drm_device *dev)
6799 {
6800         u16 gcfgc = 0;
6801
6802         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6803
6804         if (gcfgc & GC_LOW_FREQUENCY_ENABLE)
6805                 return 133333;
6806         else {
6807                 switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6808                 case GC_DISPLAY_CLOCK_333_MHZ:
6809                         return 333333;
6810                 default:
6811                 case GC_DISPLAY_CLOCK_190_200_MHZ:
6812                         return 190000;
6813                 }
6814         }
6815 }
6816
6817 static int i865_get_display_clock_speed(struct drm_device *dev)
6818 {
6819         return 266667;
6820 }
6821
6822 static int i85x_get_display_clock_speed(struct drm_device *dev)
6823 {
6824         u16 hpllcc = 0;
6825
6826         /*
6827          * 852GM/852GMV only supports 133 MHz and the HPLLCC
6828          * encoding is different :(
6829          * FIXME is this the right way to detect 852GM/852GMV?
6830          */
6831         if (dev->pdev->revision == 0x1)
6832                 return 133333;
6833
6834         pci_bus_read_config_word(dev->pdev->bus,
6835                                  PCI_DEVFN(0, 3), HPLLCC, &hpllcc);
6836
6837         /* Assume that the hardware is in the high speed state.  This
6838          * should be the default.
6839          */
6840         switch (hpllcc & GC_CLOCK_CONTROL_MASK) {
6841         case GC_CLOCK_133_200:
6842         case GC_CLOCK_133_200_2:
6843         case GC_CLOCK_100_200:
6844                 return 200000;
6845         case GC_CLOCK_166_250:
6846                 return 250000;
6847         case GC_CLOCK_100_133:
6848                 return 133333;
6849         case GC_CLOCK_133_266:
6850         case GC_CLOCK_133_266_2:
6851         case GC_CLOCK_166_266:
6852                 return 266667;
6853         }
6854
6855         /* Shouldn't happen */
6856         return 0;
6857 }
6858
6859 static int i830_get_display_clock_speed(struct drm_device *dev)
6860 {
6861         return 133333;
6862 }
6863
6864 static unsigned int intel_hpll_vco(struct drm_device *dev)
6865 {
6866         struct drm_i915_private *dev_priv = dev->dev_private;
6867         static const unsigned int blb_vco[8] = {
6868                 [0] = 3200000,
6869                 [1] = 4000000,
6870                 [2] = 5333333,
6871                 [3] = 4800000,
6872                 [4] = 6400000,
6873         };
6874         static const unsigned int pnv_vco[8] = {
6875                 [0] = 3200000,
6876                 [1] = 4000000,
6877                 [2] = 5333333,
6878                 [3] = 4800000,
6879                 [4] = 2666667,
6880         };
6881         static const unsigned int cl_vco[8] = {
6882                 [0] = 3200000,
6883                 [1] = 4000000,
6884                 [2] = 5333333,
6885                 [3] = 6400000,
6886                 [4] = 3333333,
6887                 [5] = 3566667,
6888                 [6] = 4266667,
6889         };
6890         static const unsigned int elk_vco[8] = {
6891                 [0] = 3200000,
6892                 [1] = 4000000,
6893                 [2] = 5333333,
6894                 [3] = 4800000,
6895         };
6896         static const unsigned int ctg_vco[8] = {
6897                 [0] = 3200000,
6898                 [1] = 4000000,
6899                 [2] = 5333333,
6900                 [3] = 6400000,
6901                 [4] = 2666667,
6902                 [5] = 4266667,
6903         };
6904         const unsigned int *vco_table;
6905         unsigned int vco;
6906         uint8_t tmp = 0;
6907
6908         /* FIXME other chipsets? */
6909         if (IS_GM45(dev))
6910                 vco_table = ctg_vco;
6911         else if (IS_G4X(dev))
6912                 vco_table = elk_vco;
6913         else if (IS_CRESTLINE(dev))
6914                 vco_table = cl_vco;
6915         else if (IS_PINEVIEW(dev))
6916                 vco_table = pnv_vco;
6917         else if (IS_G33(dev))
6918                 vco_table = blb_vco;
6919         else
6920                 return 0;
6921
6922         tmp = I915_READ(IS_MOBILE(dev) ? HPLLVCO_MOBILE : HPLLVCO);
6923
6924         vco = vco_table[tmp & 0x7];
6925         if (vco == 0)
6926                 DRM_ERROR("Bad HPLL VCO (HPLLVCO=0x%02x)\n", tmp);
6927         else
6928                 DRM_DEBUG_KMS("HPLL VCO %u kHz\n", vco);
6929
6930         return vco;
6931 }
6932
6933 static int gm45_get_display_clock_speed(struct drm_device *dev)
6934 {
6935         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
6936         uint16_t tmp = 0;
6937
6938         pci_read_config_word(dev->pdev, GCFGC, &tmp);
6939
6940         cdclk_sel = (tmp >> 12) & 0x1;
6941
6942         switch (vco) {
6943         case 2666667:
6944         case 4000000:
6945         case 5333333:
6946                 return cdclk_sel ? 333333 : 222222;
6947         case 3200000:
6948                 return cdclk_sel ? 320000 : 228571;
6949         default:
6950                 DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u, CFGC=0x%04x\n", vco, tmp);
6951                 return 222222;
6952         }
6953 }
6954
6955 static int i965gm_get_display_clock_speed(struct drm_device *dev)
6956 {
6957         static const uint8_t div_3200[] = { 16, 10,  8 };
6958         static const uint8_t div_4000[] = { 20, 12, 10 };
6959         static const uint8_t div_5333[] = { 24, 16, 14 };
6960         const uint8_t *div_table;
6961         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
6962         uint16_t tmp = 0;
6963
6964         pci_read_config_word(dev->pdev, GCFGC, &tmp);
6965
6966         cdclk_sel = ((tmp >> 8) & 0x1f) - 1;
6967
6968         if (cdclk_sel >= ARRAY_SIZE(div_3200))
6969                 goto fail;
6970
6971         switch (vco) {
6972         case 3200000:
6973                 div_table = div_3200;
6974                 break;
6975         case 4000000:
6976                 div_table = div_4000;
6977                 break;
6978         case 5333333:
6979                 div_table = div_5333;
6980                 break;
6981         default:
6982                 goto fail;
6983         }
6984
6985         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
6986
6987 fail:
6988         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%04x\n", vco, tmp);
6989         return 200000;
6990 }
6991
6992 static int g33_get_display_clock_speed(struct drm_device *dev)
6993 {
6994         static const uint8_t div_3200[] = { 12, 10,  8,  7, 5, 16 };
6995         static const uint8_t div_4000[] = { 14, 12, 10,  8, 6, 20 };
6996         static const uint8_t div_4800[] = { 20, 14, 12, 10, 8, 24 };
6997         static const uint8_t div_5333[] = { 20, 16, 12, 12, 8, 28 };
6998         const uint8_t *div_table;
6999         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
7000         uint16_t tmp = 0;
7001
7002         pci_read_config_word(dev->pdev, GCFGC, &tmp);
7003
7004         cdclk_sel = (tmp >> 4) & 0x7;
7005
7006         if (cdclk_sel >= ARRAY_SIZE(div_3200))
7007                 goto fail;
7008
7009         switch (vco) {
7010         case 3200000:
7011                 div_table = div_3200;
7012                 break;
7013         case 4000000:
7014                 div_table = div_4000;
7015                 break;
7016         case 4800000:
7017                 div_table = div_4800;
7018                 break;
7019         case 5333333:
7020                 div_table = div_5333;
7021                 break;
7022         default:
7023                 goto fail;
7024         }
7025
7026         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
7027
7028 fail:
7029         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%08x\n", vco, tmp);
7030         return 190476;
7031 }
7032
7033 static void
7034 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
7035 {
7036         while (*num > DATA_LINK_M_N_MASK ||
7037                *den > DATA_LINK_M_N_MASK) {
7038                 *num >>= 1;
7039                 *den >>= 1;
7040         }
7041 }
7042
7043 static void compute_m_n(unsigned int m, unsigned int n,
7044                         uint32_t *ret_m, uint32_t *ret_n)
7045 {
7046         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
7047         *ret_m = div_u64((uint64_t) m * *ret_n, n);
7048         intel_reduce_m_n_ratio(ret_m, ret_n);
7049 }
7050
7051 void
7052 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
7053                        int pixel_clock, int link_clock,
7054                        struct intel_link_m_n *m_n)
7055 {
7056         m_n->tu = 64;
7057
7058         compute_m_n(bits_per_pixel * pixel_clock,
7059                     link_clock * nlanes * 8,
7060                     &m_n->gmch_m, &m_n->gmch_n);
7061
7062         compute_m_n(pixel_clock, link_clock,
7063                     &m_n->link_m, &m_n->link_n);
7064 }
7065
7066 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
7067 {
7068         if (i915.panel_use_ssc >= 0)
7069                 return i915.panel_use_ssc != 0;
7070         return dev_priv->vbt.lvds_use_ssc
7071                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
7072 }
7073
7074 static int i9xx_get_refclk(const struct intel_crtc_state *crtc_state,
7075                            int num_connectors)
7076 {
7077         struct drm_device *dev = crtc_state->base.crtc->dev;
7078         struct drm_i915_private *dev_priv = dev->dev_private;
7079         int refclk;
7080
7081         WARN_ON(!crtc_state->base.state);
7082
7083         if (IS_VALLEYVIEW(dev) || IS_BROXTON(dev)) {
7084                 refclk = 100000;
7085         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7086             intel_panel_use_ssc(dev_priv) && num_connectors < 2) {
7087                 refclk = dev_priv->vbt.lvds_ssc_freq;
7088                 DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7089         } else if (!IS_GEN2(dev)) {
7090                 refclk = 96000;
7091         } else {
7092                 refclk = 48000;
7093         }
7094
7095         return refclk;
7096 }
7097
7098 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
7099 {
7100         return (1 << dpll->n) << 16 | dpll->m2;
7101 }
7102
7103 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
7104 {
7105         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
7106 }
7107
7108 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
7109                                      struct intel_crtc_state *crtc_state,
7110                                      intel_clock_t *reduced_clock)
7111 {
7112         struct drm_device *dev = crtc->base.dev;
7113         u32 fp, fp2 = 0;
7114
7115         if (IS_PINEVIEW(dev)) {
7116                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
7117                 if (reduced_clock)
7118                         fp2 = pnv_dpll_compute_fp(reduced_clock);
7119         } else {
7120                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
7121                 if (reduced_clock)
7122                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
7123         }
7124
7125         crtc_state->dpll_hw_state.fp0 = fp;
7126
7127         crtc->lowfreq_avail = false;
7128         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7129             reduced_clock) {
7130                 crtc_state->dpll_hw_state.fp1 = fp2;
7131                 crtc->lowfreq_avail = true;
7132         } else {
7133                 crtc_state->dpll_hw_state.fp1 = fp;
7134         }
7135 }
7136
7137 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
7138                 pipe)
7139 {
7140         u32 reg_val;
7141
7142         /*
7143          * PLLB opamp always calibrates to max value of 0x3f, force enable it
7144          * and set it to a reasonable value instead.
7145          */
7146         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7147         reg_val &= 0xffffff00;
7148         reg_val |= 0x00000030;
7149         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7150
7151         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7152         reg_val &= 0x8cffffff;
7153         reg_val = 0x8c000000;
7154         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7155
7156         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7157         reg_val &= 0xffffff00;
7158         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7159
7160         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7161         reg_val &= 0x00ffffff;
7162         reg_val |= 0xb0000000;
7163         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7164 }
7165
7166 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
7167                                          struct intel_link_m_n *m_n)
7168 {
7169         struct drm_device *dev = crtc->base.dev;
7170         struct drm_i915_private *dev_priv = dev->dev_private;
7171         int pipe = crtc->pipe;
7172
7173         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7174         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
7175         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
7176         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
7177 }
7178
7179 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
7180                                          struct intel_link_m_n *m_n,
7181                                          struct intel_link_m_n *m2_n2)
7182 {
7183         struct drm_device *dev = crtc->base.dev;
7184         struct drm_i915_private *dev_priv = dev->dev_private;
7185         int pipe = crtc->pipe;
7186         enum transcoder transcoder = crtc->config->cpu_transcoder;
7187
7188         if (INTEL_INFO(dev)->gen >= 5) {
7189                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
7190                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
7191                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
7192                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
7193                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
7194                  * for gen < 8) and if DRRS is supported (to make sure the
7195                  * registers are not unnecessarily accessed).
7196                  */
7197                 if (m2_n2 && (IS_CHERRYVIEW(dev) || INTEL_INFO(dev)->gen < 8) &&
7198                         crtc->config->has_drrs) {
7199                         I915_WRITE(PIPE_DATA_M2(transcoder),
7200                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
7201                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
7202                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
7203                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
7204                 }
7205         } else {
7206                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7207                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
7208                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
7209                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
7210         }
7211 }
7212
7213 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
7214 {
7215         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
7216
7217         if (m_n == M1_N1) {
7218                 dp_m_n = &crtc->config->dp_m_n;
7219                 dp_m2_n2 = &crtc->config->dp_m2_n2;
7220         } else if (m_n == M2_N2) {
7221
7222                 /*
7223                  * M2_N2 registers are not supported. Hence m2_n2 divider value
7224                  * needs to be programmed into M1_N1.
7225                  */
7226                 dp_m_n = &crtc->config->dp_m2_n2;
7227         } else {
7228                 DRM_ERROR("Unsupported divider value\n");
7229                 return;
7230         }
7231
7232         if (crtc->config->has_pch_encoder)
7233                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
7234         else
7235                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
7236 }
7237
7238 static void vlv_compute_dpll(struct intel_crtc *crtc,
7239                              struct intel_crtc_state *pipe_config)
7240 {
7241         u32 dpll, dpll_md;
7242
7243         /*
7244          * Enable DPIO clock input. We should never disable the reference
7245          * clock for pipe B, since VGA hotplug / manual detection depends
7246          * on it.
7247          */
7248         dpll = DPLL_EXT_BUFFER_ENABLE_VLV | DPLL_REF_CLK_ENABLE_VLV |
7249                 DPLL_VGA_MODE_DIS | DPLL_INTEGRATED_REF_CLK_VLV;
7250         /* We should never disable this, set it here for state tracking */
7251         if (crtc->pipe == PIPE_B)
7252                 dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7253         dpll |= DPLL_VCO_ENABLE;
7254         pipe_config->dpll_hw_state.dpll = dpll;
7255
7256         dpll_md = (pipe_config->pixel_multiplier - 1)
7257                 << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7258         pipe_config->dpll_hw_state.dpll_md = dpll_md;
7259 }
7260
7261 static void vlv_prepare_pll(struct intel_crtc *crtc,
7262                             const struct intel_crtc_state *pipe_config)
7263 {
7264         struct drm_device *dev = crtc->base.dev;
7265         struct drm_i915_private *dev_priv = dev->dev_private;
7266         int pipe = crtc->pipe;
7267         u32 mdiv;
7268         u32 bestn, bestm1, bestm2, bestp1, bestp2;
7269         u32 coreclk, reg_val;
7270
7271         mutex_lock(&dev_priv->sb_lock);
7272
7273         bestn = pipe_config->dpll.n;
7274         bestm1 = pipe_config->dpll.m1;
7275         bestm2 = pipe_config->dpll.m2;
7276         bestp1 = pipe_config->dpll.p1;
7277         bestp2 = pipe_config->dpll.p2;
7278
7279         /* See eDP HDMI DPIO driver vbios notes doc */
7280
7281         /* PLL B needs special handling */
7282         if (pipe == PIPE_B)
7283                 vlv_pllb_recal_opamp(dev_priv, pipe);
7284
7285         /* Set up Tx target for periodic Rcomp update */
7286         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
7287
7288         /* Disable target IRef on PLL */
7289         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
7290         reg_val &= 0x00ffffff;
7291         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
7292
7293         /* Disable fast lock */
7294         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
7295
7296         /* Set idtafcrecal before PLL is enabled */
7297         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
7298         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
7299         mdiv |= ((bestn << DPIO_N_SHIFT));
7300         mdiv |= (1 << DPIO_K_SHIFT);
7301
7302         /*
7303          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
7304          * but we don't support that).
7305          * Note: don't use the DAC post divider as it seems unstable.
7306          */
7307         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
7308         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7309
7310         mdiv |= DPIO_ENABLE_CALIBRATION;
7311         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7312
7313         /* Set HBR and RBR LPF coefficients */
7314         if (pipe_config->port_clock == 162000 ||
7315             intel_pipe_has_type(crtc, INTEL_OUTPUT_ANALOG) ||
7316             intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI))
7317                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7318                                  0x009f0003);
7319         else
7320                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7321                                  0x00d0000f);
7322
7323         if (pipe_config->has_dp_encoder) {
7324                 /* Use SSC source */
7325                 if (pipe == PIPE_A)
7326                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7327                                          0x0df40000);
7328                 else
7329                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7330                                          0x0df70000);
7331         } else { /* HDMI or VGA */
7332                 /* Use bend source */
7333                 if (pipe == PIPE_A)
7334                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7335                                          0x0df70000);
7336                 else
7337                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7338                                          0x0df40000);
7339         }
7340
7341         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
7342         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
7343         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DISPLAYPORT) ||
7344             intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP))
7345                 coreclk |= 0x01000000;
7346         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
7347
7348         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
7349         mutex_unlock(&dev_priv->sb_lock);
7350 }
7351
7352 static void chv_compute_dpll(struct intel_crtc *crtc,
7353                              struct intel_crtc_state *pipe_config)
7354 {
7355         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
7356                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS |
7357                 DPLL_VCO_ENABLE;
7358         if (crtc->pipe != PIPE_A)
7359                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7360
7361         pipe_config->dpll_hw_state.dpll_md =
7362                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7363 }
7364
7365 static void chv_prepare_pll(struct intel_crtc *crtc,
7366                             const struct intel_crtc_state *pipe_config)
7367 {
7368         struct drm_device *dev = crtc->base.dev;
7369         struct drm_i915_private *dev_priv = dev->dev_private;
7370         int pipe = crtc->pipe;
7371         int dpll_reg = DPLL(crtc->pipe);
7372         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7373         u32 loopfilter, tribuf_calcntr;
7374         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
7375         u32 dpio_val;
7376         int vco;
7377
7378         bestn = pipe_config->dpll.n;
7379         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
7380         bestm1 = pipe_config->dpll.m1;
7381         bestm2 = pipe_config->dpll.m2 >> 22;
7382         bestp1 = pipe_config->dpll.p1;
7383         bestp2 = pipe_config->dpll.p2;
7384         vco = pipe_config->dpll.vco;
7385         dpio_val = 0;
7386         loopfilter = 0;
7387
7388         /*
7389          * Enable Refclk and SSC
7390          */
7391         I915_WRITE(dpll_reg,
7392                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
7393
7394         mutex_lock(&dev_priv->sb_lock);
7395
7396         /* p1 and p2 divider */
7397         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
7398                         5 << DPIO_CHV_S1_DIV_SHIFT |
7399                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
7400                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
7401                         1 << DPIO_CHV_K_DIV_SHIFT);
7402
7403         /* Feedback post-divider - m2 */
7404         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
7405
7406         /* Feedback refclk divider - n and m1 */
7407         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
7408                         DPIO_CHV_M1_DIV_BY_2 |
7409                         1 << DPIO_CHV_N_DIV_SHIFT);
7410
7411         /* M2 fraction division */
7412         if (bestm2_frac)
7413                 vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
7414
7415         /* M2 fraction division enable */
7416         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7417         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
7418         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
7419         if (bestm2_frac)
7420                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
7421         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
7422
7423         /* Program digital lock detect threshold */
7424         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
7425         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
7426                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
7427         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
7428         if (!bestm2_frac)
7429                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
7430         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
7431
7432         /* Loop filter */
7433         if (vco == 5400000) {
7434                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
7435                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
7436                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
7437                 tribuf_calcntr = 0x9;
7438         } else if (vco <= 6200000) {
7439                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
7440                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
7441                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7442                 tribuf_calcntr = 0x9;
7443         } else if (vco <= 6480000) {
7444                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7445                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7446                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7447                 tribuf_calcntr = 0x8;
7448         } else {
7449                 /* Not supported. Apply the same limits as in the max case */
7450                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7451                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7452                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7453                 tribuf_calcntr = 0;
7454         }
7455         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
7456
7457         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
7458         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
7459         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
7460         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
7461
7462         /* AFC Recal */
7463         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
7464                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
7465                         DPIO_AFC_RECAL);
7466
7467         mutex_unlock(&dev_priv->sb_lock);
7468 }
7469
7470 /**
7471  * vlv_force_pll_on - forcibly enable just the PLL
7472  * @dev_priv: i915 private structure
7473  * @pipe: pipe PLL to enable
7474  * @dpll: PLL configuration
7475  *
7476  * Enable the PLL for @pipe using the supplied @dpll config. To be used
7477  * in cases where we need the PLL enabled even when @pipe is not going to
7478  * be enabled.
7479  */
7480 void vlv_force_pll_on(struct drm_device *dev, enum pipe pipe,
7481                       const struct dpll *dpll)
7482 {
7483         struct intel_crtc *crtc =
7484                 to_intel_crtc(intel_get_crtc_for_pipe(dev, pipe));
7485         struct intel_crtc_state pipe_config = {
7486                 .base.crtc = &crtc->base,
7487                 .pixel_multiplier = 1,
7488                 .dpll = *dpll,
7489         };
7490
7491         if (IS_CHERRYVIEW(dev)) {
7492                 chv_compute_dpll(crtc, &pipe_config);
7493                 chv_prepare_pll(crtc, &pipe_config);
7494                 chv_enable_pll(crtc, &pipe_config);
7495         } else {
7496                 vlv_compute_dpll(crtc, &pipe_config);
7497                 vlv_prepare_pll(crtc, &pipe_config);
7498                 vlv_enable_pll(crtc, &pipe_config);
7499         }
7500 }
7501
7502 /**
7503  * vlv_force_pll_off - forcibly disable just the PLL
7504  * @dev_priv: i915 private structure
7505  * @pipe: pipe PLL to disable
7506  *
7507  * Disable the PLL for @pipe. To be used in cases where we need
7508  * the PLL enabled even when @pipe is not going to be enabled.
7509  */
7510 void vlv_force_pll_off(struct drm_device *dev, enum pipe pipe)
7511 {
7512         if (IS_CHERRYVIEW(dev))
7513                 chv_disable_pll(to_i915(dev), pipe);
7514         else
7515                 vlv_disable_pll(to_i915(dev), pipe);
7516 }
7517
7518 static void i9xx_compute_dpll(struct intel_crtc *crtc,
7519                               struct intel_crtc_state *crtc_state,
7520                               intel_clock_t *reduced_clock,
7521                               int num_connectors)
7522 {
7523         struct drm_device *dev = crtc->base.dev;
7524         struct drm_i915_private *dev_priv = dev->dev_private;
7525         u32 dpll;
7526         bool is_sdvo;
7527         struct dpll *clock = &crtc_state->dpll;
7528
7529         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7530
7531         is_sdvo = intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7532                 intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_HDMI);
7533
7534         dpll = DPLL_VGA_MODE_DIS;
7535
7536         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
7537                 dpll |= DPLLB_MODE_LVDS;
7538         else
7539                 dpll |= DPLLB_MODE_DAC_SERIAL;
7540
7541         if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
7542                 dpll |= (crtc_state->pixel_multiplier - 1)
7543                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7544         }
7545
7546         if (is_sdvo)
7547                 dpll |= DPLL_SDVO_HIGH_SPEED;
7548
7549         if (crtc_state->has_dp_encoder)
7550                 dpll |= DPLL_SDVO_HIGH_SPEED;
7551
7552         /* compute bitmask from p1 value */
7553         if (IS_PINEVIEW(dev))
7554                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7555         else {
7556                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7557                 if (IS_G4X(dev) && reduced_clock)
7558                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7559         }
7560         switch (clock->p2) {
7561         case 5:
7562                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7563                 break;
7564         case 7:
7565                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7566                 break;
7567         case 10:
7568                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7569                 break;
7570         case 14:
7571                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7572                 break;
7573         }
7574         if (INTEL_INFO(dev)->gen >= 4)
7575                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7576
7577         if (crtc_state->sdvo_tv_clock)
7578                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7579         else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7580                  intel_panel_use_ssc(dev_priv) && num_connectors < 2)
7581                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7582         else
7583                 dpll |= PLL_REF_INPUT_DREFCLK;
7584
7585         dpll |= DPLL_VCO_ENABLE;
7586         crtc_state->dpll_hw_state.dpll = dpll;
7587
7588         if (INTEL_INFO(dev)->gen >= 4) {
7589                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7590                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7591                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7592         }
7593 }
7594
7595 static void i8xx_compute_dpll(struct intel_crtc *crtc,
7596                               struct intel_crtc_state *crtc_state,
7597                               intel_clock_t *reduced_clock,
7598                               int num_connectors)
7599 {
7600         struct drm_device *dev = crtc->base.dev;
7601         struct drm_i915_private *dev_priv = dev->dev_private;
7602         u32 dpll;
7603         struct dpll *clock = &crtc_state->dpll;
7604
7605         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7606
7607         dpll = DPLL_VGA_MODE_DIS;
7608
7609         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7610                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7611         } else {
7612                 if (clock->p1 == 2)
7613                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7614                 else
7615                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7616                 if (clock->p2 == 4)
7617                         dpll |= PLL_P2_DIVIDE_BY_4;
7618         }
7619
7620         if (!IS_I830(dev) && intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_DVO))
7621                 dpll |= DPLL_DVO_2X_MODE;
7622
7623         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7624                  intel_panel_use_ssc(dev_priv) && num_connectors < 2)
7625                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7626         else
7627                 dpll |= PLL_REF_INPUT_DREFCLK;
7628
7629         dpll |= DPLL_VCO_ENABLE;
7630         crtc_state->dpll_hw_state.dpll = dpll;
7631 }
7632
7633 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
7634 {
7635         struct drm_device *dev = intel_crtc->base.dev;
7636         struct drm_i915_private *dev_priv = dev->dev_private;
7637         enum pipe pipe = intel_crtc->pipe;
7638         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
7639         struct drm_display_mode *adjusted_mode =
7640                 &intel_crtc->config->base.adjusted_mode;
7641         uint32_t crtc_vtotal, crtc_vblank_end;
7642         int vsyncshift = 0;
7643
7644         /* We need to be careful not to changed the adjusted mode, for otherwise
7645          * the hw state checker will get angry at the mismatch. */
7646         crtc_vtotal = adjusted_mode->crtc_vtotal;
7647         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7648
7649         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7650                 /* the chip adds 2 halflines automatically */
7651                 crtc_vtotal -= 1;
7652                 crtc_vblank_end -= 1;
7653
7654                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
7655                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7656                 else
7657                         vsyncshift = adjusted_mode->crtc_hsync_start -
7658                                 adjusted_mode->crtc_htotal / 2;
7659                 if (vsyncshift < 0)
7660                         vsyncshift += adjusted_mode->crtc_htotal;
7661         }
7662
7663         if (INTEL_INFO(dev)->gen > 3)
7664                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7665
7666         I915_WRITE(HTOTAL(cpu_transcoder),
7667                    (adjusted_mode->crtc_hdisplay - 1) |
7668                    ((adjusted_mode->crtc_htotal - 1) << 16));
7669         I915_WRITE(HBLANK(cpu_transcoder),
7670                    (adjusted_mode->crtc_hblank_start - 1) |
7671                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7672         I915_WRITE(HSYNC(cpu_transcoder),
7673                    (adjusted_mode->crtc_hsync_start - 1) |
7674                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7675
7676         I915_WRITE(VTOTAL(cpu_transcoder),
7677                    (adjusted_mode->crtc_vdisplay - 1) |
7678                    ((crtc_vtotal - 1) << 16));
7679         I915_WRITE(VBLANK(cpu_transcoder),
7680                    (adjusted_mode->crtc_vblank_start - 1) |
7681                    ((crtc_vblank_end - 1) << 16));
7682         I915_WRITE(VSYNC(cpu_transcoder),
7683                    (adjusted_mode->crtc_vsync_start - 1) |
7684                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7685
7686         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7687          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7688          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7689          * bits. */
7690         if (IS_HASWELL(dev) && cpu_transcoder == TRANSCODER_EDP &&
7691             (pipe == PIPE_B || pipe == PIPE_C))
7692                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7693
7694         /* pipesrc controls the size that is scaled from, which should
7695          * always be the user's requested size.
7696          */
7697         I915_WRITE(PIPESRC(pipe),
7698                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
7699                    (intel_crtc->config->pipe_src_h - 1));
7700 }
7701
7702 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7703                                    struct intel_crtc_state *pipe_config)
7704 {
7705         struct drm_device *dev = crtc->base.dev;
7706         struct drm_i915_private *dev_priv = dev->dev_private;
7707         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7708         uint32_t tmp;
7709
7710         tmp = I915_READ(HTOTAL(cpu_transcoder));
7711         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7712         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7713         tmp = I915_READ(HBLANK(cpu_transcoder));
7714         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7715         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7716         tmp = I915_READ(HSYNC(cpu_transcoder));
7717         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7718         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7719
7720         tmp = I915_READ(VTOTAL(cpu_transcoder));
7721         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7722         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7723         tmp = I915_READ(VBLANK(cpu_transcoder));
7724         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7725         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7726         tmp = I915_READ(VSYNC(cpu_transcoder));
7727         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7728         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7729
7730         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7731                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7732                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7733                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7734         }
7735
7736         tmp = I915_READ(PIPESRC(crtc->pipe));
7737         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7738         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7739
7740         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7741         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7742 }
7743
7744 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7745                                  struct intel_crtc_state *pipe_config)
7746 {
7747         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7748         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7749         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7750         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7751
7752         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7753         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7754         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7755         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7756
7757         mode->flags = pipe_config->base.adjusted_mode.flags;
7758
7759         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7760         mode->flags |= pipe_config->base.adjusted_mode.flags;
7761 }
7762
7763 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
7764 {
7765         struct drm_device *dev = intel_crtc->base.dev;
7766         struct drm_i915_private *dev_priv = dev->dev_private;
7767         uint32_t pipeconf;
7768
7769         pipeconf = 0;
7770
7771         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
7772             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
7773                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
7774
7775         if (intel_crtc->config->double_wide)
7776                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7777
7778         /* only g4x and later have fancy bpc/dither controls */
7779         if (IS_G4X(dev) || IS_VALLEYVIEW(dev)) {
7780                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7781                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
7782                         pipeconf |= PIPECONF_DITHER_EN |
7783                                     PIPECONF_DITHER_TYPE_SP;
7784
7785                 switch (intel_crtc->config->pipe_bpp) {
7786                 case 18:
7787                         pipeconf |= PIPECONF_6BPC;
7788                         break;
7789                 case 24:
7790                         pipeconf |= PIPECONF_8BPC;
7791                         break;
7792                 case 30:
7793                         pipeconf |= PIPECONF_10BPC;
7794                         break;
7795                 default:
7796                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7797                         BUG();
7798                 }
7799         }
7800
7801         if (HAS_PIPE_CXSR(dev)) {
7802                 if (intel_crtc->lowfreq_avail) {
7803                         DRM_DEBUG_KMS("enabling CxSR downclocking\n");
7804                         pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
7805                 } else {
7806                         DRM_DEBUG_KMS("disabling CxSR downclocking\n");
7807                 }
7808         }
7809
7810         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7811                 if (INTEL_INFO(dev)->gen < 4 ||
7812                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
7813                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7814                 else
7815                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7816         } else
7817                 pipeconf |= PIPECONF_PROGRESSIVE;
7818
7819         if (IS_VALLEYVIEW(dev) && intel_crtc->config->limited_color_range)
7820                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7821
7822         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
7823         POSTING_READ(PIPECONF(intel_crtc->pipe));
7824 }
7825
7826 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7827                                    struct intel_crtc_state *crtc_state)
7828 {
7829         struct drm_device *dev = crtc->base.dev;
7830         struct drm_i915_private *dev_priv = dev->dev_private;
7831         int refclk, num_connectors = 0;
7832         intel_clock_t clock;
7833         bool ok;
7834         bool is_dsi = false;
7835         struct intel_encoder *encoder;
7836         const intel_limit_t *limit;
7837         struct drm_atomic_state *state = crtc_state->base.state;
7838         struct drm_connector *connector;
7839         struct drm_connector_state *connector_state;
7840         int i;
7841
7842         memset(&crtc_state->dpll_hw_state, 0,
7843                sizeof(crtc_state->dpll_hw_state));
7844
7845         for_each_connector_in_state(state, connector, connector_state, i) {
7846                 if (connector_state->crtc != &crtc->base)
7847                         continue;
7848
7849                 encoder = to_intel_encoder(connector_state->best_encoder);
7850
7851                 switch (encoder->type) {
7852                 case INTEL_OUTPUT_DSI:
7853                         is_dsi = true;
7854                         break;
7855                 default:
7856                         break;
7857                 }
7858
7859                 num_connectors++;
7860         }
7861
7862         if (is_dsi)
7863                 return 0;
7864
7865         if (!crtc_state->clock_set) {
7866                 refclk = i9xx_get_refclk(crtc_state, num_connectors);
7867
7868                 /*
7869                  * Returns a set of divisors for the desired target clock with
7870                  * the given refclk, or FALSE.  The returned values represent
7871                  * the clock equation: reflck * (5 * (m1 + 2) + (m2 + 2)) / (n +
7872                  * 2) / p1 / p2.
7873                  */
7874                 limit = intel_limit(crtc_state, refclk);
7875                 ok = dev_priv->display.find_dpll(limit, crtc_state,
7876                                                  crtc_state->port_clock,
7877                                                  refclk, NULL, &clock);
7878                 if (!ok) {
7879                         DRM_ERROR("Couldn't find PLL settings for mode!\n");
7880                         return -EINVAL;
7881                 }
7882
7883                 /* Compat-code for transition, will disappear. */
7884                 crtc_state->dpll.n = clock.n;
7885                 crtc_state->dpll.m1 = clock.m1;
7886                 crtc_state->dpll.m2 = clock.m2;
7887                 crtc_state->dpll.p1 = clock.p1;
7888                 crtc_state->dpll.p2 = clock.p2;
7889         }
7890
7891         if (IS_GEN2(dev)) {
7892                 i8xx_compute_dpll(crtc, crtc_state, NULL,
7893                                   num_connectors);
7894         } else if (IS_CHERRYVIEW(dev)) {
7895                 chv_compute_dpll(crtc, crtc_state);
7896         } else if (IS_VALLEYVIEW(dev)) {
7897                 vlv_compute_dpll(crtc, crtc_state);
7898         } else {
7899                 i9xx_compute_dpll(crtc, crtc_state, NULL,
7900                                   num_connectors);
7901         }
7902
7903         return 0;
7904 }
7905
7906 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
7907                                  struct intel_crtc_state *pipe_config)
7908 {
7909         struct drm_device *dev = crtc->base.dev;
7910         struct drm_i915_private *dev_priv = dev->dev_private;
7911         uint32_t tmp;
7912
7913         if (INTEL_INFO(dev)->gen <= 3 && (IS_I830(dev) || !IS_MOBILE(dev)))
7914                 return;
7915
7916         tmp = I915_READ(PFIT_CONTROL);
7917         if (!(tmp & PFIT_ENABLE))
7918                 return;
7919
7920         /* Check whether the pfit is attached to our pipe. */
7921         if (INTEL_INFO(dev)->gen < 4) {
7922                 if (crtc->pipe != PIPE_B)
7923                         return;
7924         } else {
7925                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
7926                         return;
7927         }
7928
7929         pipe_config->gmch_pfit.control = tmp;
7930         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
7931         if (INTEL_INFO(dev)->gen < 5)
7932                 pipe_config->gmch_pfit.lvds_border_bits =
7933                         I915_READ(LVDS) & LVDS_BORDER_ENABLE;
7934 }
7935
7936 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
7937                                struct intel_crtc_state *pipe_config)
7938 {
7939         struct drm_device *dev = crtc->base.dev;
7940         struct drm_i915_private *dev_priv = dev->dev_private;
7941         int pipe = pipe_config->cpu_transcoder;
7942         intel_clock_t clock;
7943         u32 mdiv;
7944         int refclk = 100000;
7945
7946         /* In case of MIPI DPLL will not even be used */
7947         if (!(pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE))
7948                 return;
7949
7950         mutex_lock(&dev_priv->sb_lock);
7951         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
7952         mutex_unlock(&dev_priv->sb_lock);
7953
7954         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
7955         clock.m2 = mdiv & DPIO_M2DIV_MASK;
7956         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
7957         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
7958         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
7959
7960         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
7961 }
7962
7963 static void
7964 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
7965                               struct intel_initial_plane_config *plane_config)
7966 {
7967         struct drm_device *dev = crtc->base.dev;
7968         struct drm_i915_private *dev_priv = dev->dev_private;
7969         u32 val, base, offset;
7970         int pipe = crtc->pipe, plane = crtc->plane;
7971         int fourcc, pixel_format;
7972         unsigned int aligned_height;
7973         struct drm_framebuffer *fb;
7974         struct intel_framebuffer *intel_fb;
7975
7976         val = I915_READ(DSPCNTR(plane));
7977         if (!(val & DISPLAY_PLANE_ENABLE))
7978                 return;
7979
7980         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
7981         if (!intel_fb) {
7982                 DRM_DEBUG_KMS("failed to alloc fb\n");
7983                 return;
7984         }
7985
7986         fb = &intel_fb->base;
7987
7988         if (INTEL_INFO(dev)->gen >= 4) {
7989                 if (val & DISPPLANE_TILED) {
7990                         plane_config->tiling = I915_TILING_X;
7991                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
7992                 }
7993         }
7994
7995         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
7996         fourcc = i9xx_format_to_fourcc(pixel_format);
7997         fb->pixel_format = fourcc;
7998         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
7999
8000         if (INTEL_INFO(dev)->gen >= 4) {
8001                 if (plane_config->tiling)
8002                         offset = I915_READ(DSPTILEOFF(plane));
8003                 else
8004                         offset = I915_READ(DSPLINOFF(plane));
8005                 base = I915_READ(DSPSURF(plane)) & 0xfffff000;
8006         } else {
8007                 base = I915_READ(DSPADDR(plane));
8008         }
8009         plane_config->base = base;
8010
8011         val = I915_READ(PIPESRC(pipe));
8012         fb->width = ((val >> 16) & 0xfff) + 1;
8013         fb->height = ((val >> 0) & 0xfff) + 1;
8014
8015         val = I915_READ(DSPSTRIDE(pipe));
8016         fb->pitches[0] = val & 0xffffffc0;
8017
8018         aligned_height = intel_fb_align_height(dev, fb->height,
8019                                                fb->pixel_format,
8020                                                fb->modifier[0]);
8021
8022         plane_config->size = fb->pitches[0] * aligned_height;
8023
8024         DRM_DEBUG_KMS("pipe/plane %c/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8025                       pipe_name(pipe), plane, fb->width, fb->height,
8026                       fb->bits_per_pixel, base, fb->pitches[0],
8027                       plane_config->size);
8028
8029         plane_config->fb = intel_fb;
8030 }
8031
8032 static void chv_crtc_clock_get(struct intel_crtc *crtc,
8033                                struct intel_crtc_state *pipe_config)
8034 {
8035         struct drm_device *dev = crtc->base.dev;
8036         struct drm_i915_private *dev_priv = dev->dev_private;
8037         int pipe = pipe_config->cpu_transcoder;
8038         enum dpio_channel port = vlv_pipe_to_channel(pipe);
8039         intel_clock_t clock;
8040         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2;
8041         int refclk = 100000;
8042
8043         mutex_lock(&dev_priv->sb_lock);
8044         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
8045         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
8046         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
8047         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
8048         mutex_unlock(&dev_priv->sb_lock);
8049
8050         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
8051         clock.m2 = ((pll_dw0 & 0xff) << 22) | (pll_dw2 & 0x3fffff);
8052         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
8053         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
8054         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
8055
8056         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
8057 }
8058
8059 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
8060                                  struct intel_crtc_state *pipe_config)
8061 {
8062         struct drm_device *dev = crtc->base.dev;
8063         struct drm_i915_private *dev_priv = dev->dev_private;
8064         uint32_t tmp;
8065
8066         if (!intel_display_power_is_enabled(dev_priv,
8067                                             POWER_DOMAIN_PIPE(crtc->pipe)))
8068                 return false;
8069
8070         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8071         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
8072
8073         tmp = I915_READ(PIPECONF(crtc->pipe));
8074         if (!(tmp & PIPECONF_ENABLE))
8075                 return false;
8076
8077         if (IS_G4X(dev) || IS_VALLEYVIEW(dev)) {
8078                 switch (tmp & PIPECONF_BPC_MASK) {
8079                 case PIPECONF_6BPC:
8080                         pipe_config->pipe_bpp = 18;
8081                         break;
8082                 case PIPECONF_8BPC:
8083                         pipe_config->pipe_bpp = 24;
8084                         break;
8085                 case PIPECONF_10BPC:
8086                         pipe_config->pipe_bpp = 30;
8087                         break;
8088                 default:
8089                         break;
8090                 }
8091         }
8092
8093         if (IS_VALLEYVIEW(dev) && (tmp & PIPECONF_COLOR_RANGE_SELECT))
8094                 pipe_config->limited_color_range = true;
8095
8096         if (INTEL_INFO(dev)->gen < 4)
8097                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
8098
8099         intel_get_pipe_timings(crtc, pipe_config);
8100
8101         i9xx_get_pfit_config(crtc, pipe_config);
8102
8103         if (INTEL_INFO(dev)->gen >= 4) {
8104                 tmp = I915_READ(DPLL_MD(crtc->pipe));
8105                 pipe_config->pixel_multiplier =
8106                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
8107                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
8108                 pipe_config->dpll_hw_state.dpll_md = tmp;
8109         } else if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
8110                 tmp = I915_READ(DPLL(crtc->pipe));
8111                 pipe_config->pixel_multiplier =
8112                         ((tmp & SDVO_MULTIPLIER_MASK)
8113                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
8114         } else {
8115                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
8116                  * port and will be fixed up in the encoder->get_config
8117                  * function. */
8118                 pipe_config->pixel_multiplier = 1;
8119         }
8120         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
8121         if (!IS_VALLEYVIEW(dev)) {
8122                 /*
8123                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
8124                  * on 830. Filter it out here so that we don't
8125                  * report errors due to that.
8126                  */
8127                 if (IS_I830(dev))
8128                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
8129
8130                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
8131                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
8132         } else {
8133                 /* Mask out read-only status bits. */
8134                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
8135                                                      DPLL_PORTC_READY_MASK |
8136                                                      DPLL_PORTB_READY_MASK);
8137         }
8138
8139         if (IS_CHERRYVIEW(dev))
8140                 chv_crtc_clock_get(crtc, pipe_config);
8141         else if (IS_VALLEYVIEW(dev))
8142                 vlv_crtc_clock_get(crtc, pipe_config);
8143         else
8144                 i9xx_crtc_clock_get(crtc, pipe_config);
8145
8146         return true;
8147 }
8148
8149 static void ironlake_init_pch_refclk(struct drm_device *dev)
8150 {
8151         struct drm_i915_private *dev_priv = dev->dev_private;
8152         struct intel_encoder *encoder;
8153         u32 val, final;
8154         bool has_lvds = false;
8155         bool has_cpu_edp = false;
8156         bool has_panel = false;
8157         bool has_ck505 = false;
8158         bool can_ssc = false;
8159
8160         /* We need to take the global config into account */
8161         for_each_intel_encoder(dev, encoder) {
8162                 switch (encoder->type) {
8163                 case INTEL_OUTPUT_LVDS:
8164                         has_panel = true;
8165                         has_lvds = true;
8166                         break;
8167                 case INTEL_OUTPUT_EDP:
8168                         has_panel = true;
8169                         if (enc_to_dig_port(&encoder->base)->port == PORT_A)
8170                                 has_cpu_edp = true;
8171                         break;
8172                 default:
8173                         break;
8174                 }
8175         }
8176
8177         if (HAS_PCH_IBX(dev)) {
8178                 has_ck505 = dev_priv->vbt.display_clock_mode;
8179                 can_ssc = has_ck505;
8180         } else {
8181                 has_ck505 = false;
8182                 can_ssc = true;
8183         }
8184
8185         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d\n",
8186                       has_panel, has_lvds, has_ck505);
8187
8188         /* Ironlake: try to setup display ref clock before DPLL
8189          * enabling. This is only under driver's control after
8190          * PCH B stepping, previous chipset stepping should be
8191          * ignoring this setting.
8192          */
8193         val = I915_READ(PCH_DREF_CONTROL);
8194
8195         /* As we must carefully and slowly disable/enable each source in turn,
8196          * compute the final state we want first and check if we need to
8197          * make any changes at all.
8198          */
8199         final = val;
8200         final &= ~DREF_NONSPREAD_SOURCE_MASK;
8201         if (has_ck505)
8202                 final |= DREF_NONSPREAD_CK505_ENABLE;
8203         else
8204                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
8205
8206         final &= ~DREF_SSC_SOURCE_MASK;
8207         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8208         final &= ~DREF_SSC1_ENABLE;
8209
8210         if (has_panel) {
8211                 final |= DREF_SSC_SOURCE_ENABLE;
8212
8213                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
8214                         final |= DREF_SSC1_ENABLE;
8215
8216                 if (has_cpu_edp) {
8217                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
8218                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8219                         else
8220                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8221                 } else
8222                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8223         } else {
8224                 final |= DREF_SSC_SOURCE_DISABLE;
8225                 final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8226         }
8227
8228         if (final == val)
8229                 return;
8230
8231         /* Always enable nonspread source */
8232         val &= ~DREF_NONSPREAD_SOURCE_MASK;
8233
8234         if (has_ck505)
8235                 val |= DREF_NONSPREAD_CK505_ENABLE;
8236         else
8237                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
8238
8239         if (has_panel) {
8240                 val &= ~DREF_SSC_SOURCE_MASK;
8241                 val |= DREF_SSC_SOURCE_ENABLE;
8242
8243                 /* SSC must be turned on before enabling the CPU output  */
8244                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8245                         DRM_DEBUG_KMS("Using SSC on panel\n");
8246                         val |= DREF_SSC1_ENABLE;
8247                 } else
8248                         val &= ~DREF_SSC1_ENABLE;
8249
8250                 /* Get SSC going before enabling the outputs */
8251                 I915_WRITE(PCH_DREF_CONTROL, val);
8252                 POSTING_READ(PCH_DREF_CONTROL);
8253                 udelay(200);
8254
8255                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8256
8257                 /* Enable CPU source on CPU attached eDP */
8258                 if (has_cpu_edp) {
8259                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8260                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
8261                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8262                         } else
8263                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8264                 } else
8265                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8266
8267                 I915_WRITE(PCH_DREF_CONTROL, val);
8268                 POSTING_READ(PCH_DREF_CONTROL);
8269                 udelay(200);
8270         } else {
8271                 DRM_DEBUG_KMS("Disabling SSC entirely\n");
8272
8273                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8274
8275                 /* Turn off CPU output */
8276                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8277
8278                 I915_WRITE(PCH_DREF_CONTROL, val);
8279                 POSTING_READ(PCH_DREF_CONTROL);
8280                 udelay(200);
8281
8282                 /* Turn off the SSC source */
8283                 val &= ~DREF_SSC_SOURCE_MASK;
8284                 val |= DREF_SSC_SOURCE_DISABLE;
8285
8286                 /* Turn off SSC1 */
8287                 val &= ~DREF_SSC1_ENABLE;
8288
8289                 I915_WRITE(PCH_DREF_CONTROL, val);
8290                 POSTING_READ(PCH_DREF_CONTROL);
8291                 udelay(200);
8292         }
8293
8294         BUG_ON(val != final);
8295 }
8296
8297 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
8298 {
8299         uint32_t tmp;
8300
8301         tmp = I915_READ(SOUTH_CHICKEN2);
8302         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
8303         I915_WRITE(SOUTH_CHICKEN2, tmp);
8304
8305         if (wait_for_atomic_us(I915_READ(SOUTH_CHICKEN2) &
8306                                FDI_MPHY_IOSFSB_RESET_STATUS, 100))
8307                 DRM_ERROR("FDI mPHY reset assert timeout\n");
8308
8309         tmp = I915_READ(SOUTH_CHICKEN2);
8310         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
8311         I915_WRITE(SOUTH_CHICKEN2, tmp);
8312
8313         if (wait_for_atomic_us((I915_READ(SOUTH_CHICKEN2) &
8314                                 FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
8315                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
8316 }
8317
8318 /* WaMPhyProgramming:hsw */
8319 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
8320 {
8321         uint32_t tmp;
8322
8323         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
8324         tmp &= ~(0xFF << 24);
8325         tmp |= (0x12 << 24);
8326         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
8327
8328         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
8329         tmp |= (1 << 11);
8330         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
8331
8332         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
8333         tmp |= (1 << 11);
8334         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
8335
8336         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
8337         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8338         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
8339
8340         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
8341         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8342         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
8343
8344         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
8345         tmp &= ~(7 << 13);
8346         tmp |= (5 << 13);
8347         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
8348
8349         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
8350         tmp &= ~(7 << 13);
8351         tmp |= (5 << 13);
8352         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
8353
8354         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
8355         tmp &= ~0xFF;
8356         tmp |= 0x1C;
8357         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
8358
8359         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
8360         tmp &= ~0xFF;
8361         tmp |= 0x1C;
8362         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
8363
8364         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
8365         tmp &= ~(0xFF << 16);
8366         tmp |= (0x1C << 16);
8367         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
8368
8369         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
8370         tmp &= ~(0xFF << 16);
8371         tmp |= (0x1C << 16);
8372         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
8373
8374         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8375         tmp |= (1 << 27);
8376         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8377
8378         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8379         tmp |= (1 << 27);
8380         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8381
8382         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8383         tmp &= ~(0xF << 28);
8384         tmp |= (4 << 28);
8385         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8386
8387         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
8388         tmp &= ~(0xF << 28);
8389         tmp |= (4 << 28);
8390         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
8391 }
8392
8393 /* Implements 3 different sequences from BSpec chapter "Display iCLK
8394  * Programming" based on the parameters passed:
8395  * - Sequence to enable CLKOUT_DP
8396  * - Sequence to enable CLKOUT_DP without spread
8397  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
8398  */
8399 static void lpt_enable_clkout_dp(struct drm_device *dev, bool with_spread,
8400                                  bool with_fdi)
8401 {
8402         struct drm_i915_private *dev_priv = dev->dev_private;
8403         uint32_t reg, tmp;
8404
8405         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
8406                 with_spread = true;
8407         if (WARN(dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE &&
8408                  with_fdi, "LP PCH doesn't have FDI\n"))
8409                 with_fdi = false;
8410
8411         mutex_lock(&dev_priv->sb_lock);
8412
8413         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8414         tmp &= ~SBI_SSCCTL_DISABLE;
8415         tmp |= SBI_SSCCTL_PATHALT;
8416         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8417
8418         udelay(24);
8419
8420         if (with_spread) {
8421                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8422                 tmp &= ~SBI_SSCCTL_PATHALT;
8423                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8424
8425                 if (with_fdi) {
8426                         lpt_reset_fdi_mphy(dev_priv);
8427                         lpt_program_fdi_mphy(dev_priv);
8428                 }
8429         }
8430
8431         reg = (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) ?
8432                SBI_GEN0 : SBI_DBUFF0;
8433         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8434         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8435         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8436
8437         mutex_unlock(&dev_priv->sb_lock);
8438 }
8439
8440 /* Sequence to disable CLKOUT_DP */
8441 static void lpt_disable_clkout_dp(struct drm_device *dev)
8442 {
8443         struct drm_i915_private *dev_priv = dev->dev_private;
8444         uint32_t reg, tmp;
8445
8446         mutex_lock(&dev_priv->sb_lock);
8447
8448         reg = (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) ?
8449                SBI_GEN0 : SBI_DBUFF0;
8450         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8451         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8452         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8453
8454         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8455         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8456                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8457                         tmp |= SBI_SSCCTL_PATHALT;
8458                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8459                         udelay(32);
8460                 }
8461                 tmp |= SBI_SSCCTL_DISABLE;
8462                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8463         }
8464
8465         mutex_unlock(&dev_priv->sb_lock);
8466 }
8467
8468 static void lpt_init_pch_refclk(struct drm_device *dev)
8469 {
8470         struct intel_encoder *encoder;
8471         bool has_vga = false;
8472
8473         for_each_intel_encoder(dev, encoder) {
8474                 switch (encoder->type) {
8475                 case INTEL_OUTPUT_ANALOG:
8476                         has_vga = true;
8477                         break;
8478                 default:
8479                         break;
8480                 }
8481         }
8482
8483         if (has_vga)
8484                 lpt_enable_clkout_dp(dev, true, true);
8485         else
8486                 lpt_disable_clkout_dp(dev);
8487 }
8488
8489 /*
8490  * Initialize reference clocks when the driver loads
8491  */
8492 void intel_init_pch_refclk(struct drm_device *dev)
8493 {
8494         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
8495                 ironlake_init_pch_refclk(dev);
8496         else if (HAS_PCH_LPT(dev))
8497                 lpt_init_pch_refclk(dev);
8498 }
8499
8500 static int ironlake_get_refclk(struct intel_crtc_state *crtc_state)
8501 {
8502         struct drm_device *dev = crtc_state->base.crtc->dev;
8503         struct drm_i915_private *dev_priv = dev->dev_private;
8504         struct drm_atomic_state *state = crtc_state->base.state;
8505         struct drm_connector *connector;
8506         struct drm_connector_state *connector_state;
8507         struct intel_encoder *encoder;
8508         int num_connectors = 0, i;
8509         bool is_lvds = false;
8510
8511         for_each_connector_in_state(state, connector, connector_state, i) {
8512                 if (connector_state->crtc != crtc_state->base.crtc)
8513                         continue;
8514
8515                 encoder = to_intel_encoder(connector_state->best_encoder);
8516
8517                 switch (encoder->type) {
8518                 case INTEL_OUTPUT_LVDS:
8519                         is_lvds = true;
8520                         break;
8521                 default:
8522                         break;
8523                 }
8524                 num_connectors++;
8525         }
8526
8527         if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2) {
8528                 DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8529                               dev_priv->vbt.lvds_ssc_freq);
8530                 return dev_priv->vbt.lvds_ssc_freq;
8531         }
8532
8533         return 120000;
8534 }
8535
8536 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
8537 {
8538         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
8539         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8540         int pipe = intel_crtc->pipe;
8541         uint32_t val;
8542
8543         val = 0;
8544
8545         switch (intel_crtc->config->pipe_bpp) {
8546         case 18:
8547                 val |= PIPECONF_6BPC;
8548                 break;
8549         case 24:
8550                 val |= PIPECONF_8BPC;
8551                 break;
8552         case 30:
8553                 val |= PIPECONF_10BPC;
8554                 break;
8555         case 36:
8556                 val |= PIPECONF_12BPC;
8557                 break;
8558         default:
8559                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8560                 BUG();
8561         }
8562
8563         if (intel_crtc->config->dither)
8564                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8565
8566         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8567                 val |= PIPECONF_INTERLACED_ILK;
8568         else
8569                 val |= PIPECONF_PROGRESSIVE;
8570
8571         if (intel_crtc->config->limited_color_range)
8572                 val |= PIPECONF_COLOR_RANGE_SELECT;
8573
8574         I915_WRITE(PIPECONF(pipe), val);
8575         POSTING_READ(PIPECONF(pipe));
8576 }
8577
8578 /*
8579  * Set up the pipe CSC unit.
8580  *
8581  * Currently only full range RGB to limited range RGB conversion
8582  * is supported, but eventually this should handle various
8583  * RGB<->YCbCr scenarios as well.
8584  */
8585 static void intel_set_pipe_csc(struct drm_crtc *crtc)
8586 {
8587         struct drm_device *dev = crtc->dev;
8588         struct drm_i915_private *dev_priv = dev->dev_private;
8589         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8590         int pipe = intel_crtc->pipe;
8591         uint16_t coeff = 0x7800; /* 1.0 */
8592
8593         /*
8594          * TODO: Check what kind of values actually come out of the pipe
8595          * with these coeff/postoff values and adjust to get the best
8596          * accuracy. Perhaps we even need to take the bpc value into
8597          * consideration.
8598          */
8599
8600         if (intel_crtc->config->limited_color_range)
8601                 coeff = ((235 - 16) * (1 << 12) / 255) & 0xff8; /* 0.xxx... */
8602
8603         /*
8604          * GY/GU and RY/RU should be the other way around according
8605          * to BSpec, but reality doesn't agree. Just set them up in
8606          * a way that results in the correct picture.
8607          */
8608         I915_WRITE(PIPE_CSC_COEFF_RY_GY(pipe), coeff << 16);
8609         I915_WRITE(PIPE_CSC_COEFF_BY(pipe), 0);
8610
8611         I915_WRITE(PIPE_CSC_COEFF_RU_GU(pipe), coeff);
8612         I915_WRITE(PIPE_CSC_COEFF_BU(pipe), 0);
8613
8614         I915_WRITE(PIPE_CSC_COEFF_RV_GV(pipe), 0);
8615         I915_WRITE(PIPE_CSC_COEFF_BV(pipe), coeff << 16);
8616
8617         I915_WRITE(PIPE_CSC_PREOFF_HI(pipe), 0);
8618         I915_WRITE(PIPE_CSC_PREOFF_ME(pipe), 0);
8619         I915_WRITE(PIPE_CSC_PREOFF_LO(pipe), 0);
8620
8621         if (INTEL_INFO(dev)->gen > 6) {
8622                 uint16_t postoff = 0;
8623
8624                 if (intel_crtc->config->limited_color_range)
8625                         postoff = (16 * (1 << 12) / 255) & 0x1fff;
8626
8627                 I915_WRITE(PIPE_CSC_POSTOFF_HI(pipe), postoff);
8628                 I915_WRITE(PIPE_CSC_POSTOFF_ME(pipe), postoff);
8629                 I915_WRITE(PIPE_CSC_POSTOFF_LO(pipe), postoff);
8630
8631                 I915_WRITE(PIPE_CSC_MODE(pipe), 0);
8632         } else {
8633                 uint32_t mode = CSC_MODE_YUV_TO_RGB;
8634
8635                 if (intel_crtc->config->limited_color_range)
8636                         mode |= CSC_BLACK_SCREEN_OFFSET;
8637
8638                 I915_WRITE(PIPE_CSC_MODE(pipe), mode);
8639         }
8640 }
8641
8642 static void haswell_set_pipeconf(struct drm_crtc *crtc)
8643 {
8644         struct drm_device *dev = crtc->dev;
8645         struct drm_i915_private *dev_priv = dev->dev_private;
8646         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8647         enum pipe pipe = intel_crtc->pipe;
8648         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8649         uint32_t val;
8650
8651         val = 0;
8652
8653         if (IS_HASWELL(dev) && intel_crtc->config->dither)
8654                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8655
8656         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8657                 val |= PIPECONF_INTERLACED_ILK;
8658         else
8659                 val |= PIPECONF_PROGRESSIVE;
8660
8661         I915_WRITE(PIPECONF(cpu_transcoder), val);
8662         POSTING_READ(PIPECONF(cpu_transcoder));
8663
8664         I915_WRITE(GAMMA_MODE(intel_crtc->pipe), GAMMA_MODE_MODE_8BIT);
8665         POSTING_READ(GAMMA_MODE(intel_crtc->pipe));
8666
8667         if (IS_BROADWELL(dev) || INTEL_INFO(dev)->gen >= 9) {
8668                 val = 0;
8669
8670                 switch (intel_crtc->config->pipe_bpp) {
8671                 case 18:
8672                         val |= PIPEMISC_DITHER_6_BPC;
8673                         break;
8674                 case 24:
8675                         val |= PIPEMISC_DITHER_8_BPC;
8676                         break;
8677                 case 30:
8678                         val |= PIPEMISC_DITHER_10_BPC;
8679                         break;
8680                 case 36:
8681                         val |= PIPEMISC_DITHER_12_BPC;
8682                         break;
8683                 default:
8684                         /* Case prevented by pipe_config_set_bpp. */
8685                         BUG();
8686                 }
8687
8688                 if (intel_crtc->config->dither)
8689                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8690
8691                 I915_WRITE(PIPEMISC(pipe), val);
8692         }
8693 }
8694
8695 static bool ironlake_compute_clocks(struct drm_crtc *crtc,
8696                                     struct intel_crtc_state *crtc_state,
8697                                     intel_clock_t *clock,
8698                                     bool *has_reduced_clock,
8699                                     intel_clock_t *reduced_clock)
8700 {
8701         struct drm_device *dev = crtc->dev;
8702         struct drm_i915_private *dev_priv = dev->dev_private;
8703         int refclk;
8704         const intel_limit_t *limit;
8705         bool ret;
8706
8707         refclk = ironlake_get_refclk(crtc_state);
8708
8709         /*
8710          * Returns a set of divisors for the desired target clock with the given
8711          * refclk, or FALSE.  The returned values represent the clock equation:
8712          * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
8713          */
8714         limit = intel_limit(crtc_state, refclk);
8715         ret = dev_priv->display.find_dpll(limit, crtc_state,
8716                                           crtc_state->port_clock,
8717                                           refclk, NULL, clock);
8718         if (!ret)
8719                 return false;
8720
8721         return true;
8722 }
8723
8724 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8725 {
8726         /*
8727          * Account for spread spectrum to avoid
8728          * oversubscribing the link. Max center spread
8729          * is 2.5%; use 5% for safety's sake.
8730          */
8731         u32 bps = target_clock * bpp * 21 / 20;
8732         return DIV_ROUND_UP(bps, link_bw * 8);
8733 }
8734
8735 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8736 {
8737         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8738 }
8739
8740 static uint32_t ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8741                                       struct intel_crtc_state *crtc_state,
8742                                       u32 *fp,
8743                                       intel_clock_t *reduced_clock, u32 *fp2)
8744 {
8745         struct drm_crtc *crtc = &intel_crtc->base;
8746         struct drm_device *dev = crtc->dev;
8747         struct drm_i915_private *dev_priv = dev->dev_private;
8748         struct drm_atomic_state *state = crtc_state->base.state;
8749         struct drm_connector *connector;
8750         struct drm_connector_state *connector_state;
8751         struct intel_encoder *encoder;
8752         uint32_t dpll;
8753         int factor, num_connectors = 0, i;
8754         bool is_lvds = false, is_sdvo = false;
8755
8756         for_each_connector_in_state(state, connector, connector_state, i) {
8757                 if (connector_state->crtc != crtc_state->base.crtc)
8758                         continue;
8759
8760                 encoder = to_intel_encoder(connector_state->best_encoder);
8761
8762                 switch (encoder->type) {
8763                 case INTEL_OUTPUT_LVDS:
8764                         is_lvds = true;
8765                         break;
8766                 case INTEL_OUTPUT_SDVO:
8767                 case INTEL_OUTPUT_HDMI:
8768                         is_sdvo = true;
8769                         break;
8770                 default:
8771                         break;
8772                 }
8773
8774                 num_connectors++;
8775         }
8776
8777         /* Enable autotuning of the PLL clock (if permissible) */
8778         factor = 21;
8779         if (is_lvds) {
8780                 if ((intel_panel_use_ssc(dev_priv) &&
8781                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8782                     (HAS_PCH_IBX(dev) && intel_is_dual_link_lvds(dev)))
8783                         factor = 25;
8784         } else if (crtc_state->sdvo_tv_clock)
8785                 factor = 20;
8786
8787         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8788                 *fp |= FP_CB_TUNE;
8789
8790         if (fp2 && (reduced_clock->m < factor * reduced_clock->n))
8791                 *fp2 |= FP_CB_TUNE;
8792
8793         dpll = 0;
8794
8795         if (is_lvds)
8796                 dpll |= DPLLB_MODE_LVDS;
8797         else
8798                 dpll |= DPLLB_MODE_DAC_SERIAL;
8799
8800         dpll |= (crtc_state->pixel_multiplier - 1)
8801                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8802
8803         if (is_sdvo)
8804                 dpll |= DPLL_SDVO_HIGH_SPEED;
8805         if (crtc_state->has_dp_encoder)
8806                 dpll |= DPLL_SDVO_HIGH_SPEED;
8807
8808         /* compute bitmask from p1 value */
8809         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8810         /* also FPA1 */
8811         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8812
8813         switch (crtc_state->dpll.p2) {
8814         case 5:
8815                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8816                 break;
8817         case 7:
8818                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8819                 break;
8820         case 10:
8821                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8822                 break;
8823         case 14:
8824                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8825                 break;
8826         }
8827
8828         if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2)
8829                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8830         else
8831                 dpll |= PLL_REF_INPUT_DREFCLK;
8832
8833         return dpll | DPLL_VCO_ENABLE;
8834 }
8835
8836 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
8837                                        struct intel_crtc_state *crtc_state)
8838 {
8839         struct drm_device *dev = crtc->base.dev;
8840         intel_clock_t clock, reduced_clock;
8841         u32 dpll = 0, fp = 0, fp2 = 0;
8842         bool ok, has_reduced_clock = false;
8843         bool is_lvds = false;
8844         struct intel_shared_dpll *pll;
8845
8846         memset(&crtc_state->dpll_hw_state, 0,
8847                sizeof(crtc_state->dpll_hw_state));
8848
8849         is_lvds = intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS);
8850
8851         WARN(!(HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev)),
8852              "Unexpected PCH type %d\n", INTEL_PCH_TYPE(dev));
8853
8854         ok = ironlake_compute_clocks(&crtc->base, crtc_state, &clock,
8855                                      &has_reduced_clock, &reduced_clock);
8856         if (!ok && !crtc_state->clock_set) {
8857                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8858                 return -EINVAL;
8859         }
8860         /* Compat-code for transition, will disappear. */
8861         if (!crtc_state->clock_set) {
8862                 crtc_state->dpll.n = clock.n;
8863                 crtc_state->dpll.m1 = clock.m1;
8864                 crtc_state->dpll.m2 = clock.m2;
8865                 crtc_state->dpll.p1 = clock.p1;
8866                 crtc_state->dpll.p2 = clock.p2;
8867         }
8868
8869         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
8870         if (crtc_state->has_pch_encoder) {
8871                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8872                 if (has_reduced_clock)
8873                         fp2 = i9xx_dpll_compute_fp(&reduced_clock);
8874
8875                 dpll = ironlake_compute_dpll(crtc, crtc_state,
8876                                              &fp, &reduced_clock,
8877                                              has_reduced_clock ? &fp2 : NULL);
8878
8879                 crtc_state->dpll_hw_state.dpll = dpll;
8880                 crtc_state->dpll_hw_state.fp0 = fp;
8881                 if (has_reduced_clock)
8882                         crtc_state->dpll_hw_state.fp1 = fp2;
8883                 else
8884                         crtc_state->dpll_hw_state.fp1 = fp;
8885
8886                 pll = intel_get_shared_dpll(crtc, crtc_state);
8887                 if (pll == NULL) {
8888                         DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
8889                                          pipe_name(crtc->pipe));
8890                         return -EINVAL;
8891                 }
8892         }
8893
8894         if (is_lvds && has_reduced_clock)
8895                 crtc->lowfreq_avail = true;
8896         else
8897                 crtc->lowfreq_avail = false;
8898
8899         return 0;
8900 }
8901
8902 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
8903                                          struct intel_link_m_n *m_n)
8904 {
8905         struct drm_device *dev = crtc->base.dev;
8906         struct drm_i915_private *dev_priv = dev->dev_private;
8907         enum pipe pipe = crtc->pipe;
8908
8909         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
8910         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
8911         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
8912                 & ~TU_SIZE_MASK;
8913         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
8914         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
8915                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8916 }
8917
8918 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
8919                                          enum transcoder transcoder,
8920                                          struct intel_link_m_n *m_n,
8921                                          struct intel_link_m_n *m2_n2)
8922 {
8923         struct drm_device *dev = crtc->base.dev;
8924         struct drm_i915_private *dev_priv = dev->dev_private;
8925         enum pipe pipe = crtc->pipe;
8926
8927         if (INTEL_INFO(dev)->gen >= 5) {
8928                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
8929                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
8930                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
8931                         & ~TU_SIZE_MASK;
8932                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
8933                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
8934                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8935                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
8936                  * gen < 8) and if DRRS is supported (to make sure the
8937                  * registers are not unnecessarily read).
8938                  */
8939                 if (m2_n2 && INTEL_INFO(dev)->gen < 8 &&
8940                         crtc->config->has_drrs) {
8941                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
8942                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
8943                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
8944                                         & ~TU_SIZE_MASK;
8945                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
8946                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
8947                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8948                 }
8949         } else {
8950                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
8951                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
8952                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
8953                         & ~TU_SIZE_MASK;
8954                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
8955                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
8956                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8957         }
8958 }
8959
8960 void intel_dp_get_m_n(struct intel_crtc *crtc,
8961                       struct intel_crtc_state *pipe_config)
8962 {
8963         if (pipe_config->has_pch_encoder)
8964                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
8965         else
8966                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8967                                              &pipe_config->dp_m_n,
8968                                              &pipe_config->dp_m2_n2);
8969 }
8970
8971 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
8972                                         struct intel_crtc_state *pipe_config)
8973 {
8974         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8975                                      &pipe_config->fdi_m_n, NULL);
8976 }
8977
8978 static void skylake_get_pfit_config(struct intel_crtc *crtc,
8979                                     struct intel_crtc_state *pipe_config)
8980 {
8981         struct drm_device *dev = crtc->base.dev;
8982         struct drm_i915_private *dev_priv = dev->dev_private;
8983         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
8984         uint32_t ps_ctrl = 0;
8985         int id = -1;
8986         int i;
8987
8988         /* find scaler attached to this pipe */
8989         for (i = 0; i < crtc->num_scalers; i++) {
8990                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
8991                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
8992                         id = i;
8993                         pipe_config->pch_pfit.enabled = true;
8994                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
8995                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
8996                         break;
8997                 }
8998         }
8999
9000         scaler_state->scaler_id = id;
9001         if (id >= 0) {
9002                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
9003         } else {
9004                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
9005         }
9006 }
9007
9008 static void
9009 skylake_get_initial_plane_config(struct intel_crtc *crtc,
9010                                  struct intel_initial_plane_config *plane_config)
9011 {
9012         struct drm_device *dev = crtc->base.dev;
9013         struct drm_i915_private *dev_priv = dev->dev_private;
9014         u32 val, base, offset, stride_mult, tiling;
9015         int pipe = crtc->pipe;
9016         int fourcc, pixel_format;
9017         unsigned int aligned_height;
9018         struct drm_framebuffer *fb;
9019         struct intel_framebuffer *intel_fb;
9020
9021         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9022         if (!intel_fb) {
9023                 DRM_DEBUG_KMS("failed to alloc fb\n");
9024                 return;
9025         }
9026
9027         fb = &intel_fb->base;
9028
9029         val = I915_READ(PLANE_CTL(pipe, 0));
9030         if (!(val & PLANE_CTL_ENABLE))
9031                 goto error;
9032
9033         pixel_format = val & PLANE_CTL_FORMAT_MASK;
9034         fourcc = skl_format_to_fourcc(pixel_format,
9035                                       val & PLANE_CTL_ORDER_RGBX,
9036                                       val & PLANE_CTL_ALPHA_MASK);
9037         fb->pixel_format = fourcc;
9038         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9039
9040         tiling = val & PLANE_CTL_TILED_MASK;
9041         switch (tiling) {
9042         case PLANE_CTL_TILED_LINEAR:
9043                 fb->modifier[0] = DRM_FORMAT_MOD_NONE;
9044                 break;
9045         case PLANE_CTL_TILED_X:
9046                 plane_config->tiling = I915_TILING_X;
9047                 fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9048                 break;
9049         case PLANE_CTL_TILED_Y:
9050                 fb->modifier[0] = I915_FORMAT_MOD_Y_TILED;
9051                 break;
9052         case PLANE_CTL_TILED_YF:
9053                 fb->modifier[0] = I915_FORMAT_MOD_Yf_TILED;
9054                 break;
9055         default:
9056                 MISSING_CASE(tiling);
9057                 goto error;
9058         }
9059
9060         base = I915_READ(PLANE_SURF(pipe, 0)) & 0xfffff000;
9061         plane_config->base = base;
9062
9063         offset = I915_READ(PLANE_OFFSET(pipe, 0));
9064
9065         val = I915_READ(PLANE_SIZE(pipe, 0));
9066         fb->height = ((val >> 16) & 0xfff) + 1;
9067         fb->width = ((val >> 0) & 0x1fff) + 1;
9068
9069         val = I915_READ(PLANE_STRIDE(pipe, 0));
9070         stride_mult = intel_fb_stride_alignment(dev, fb->modifier[0],
9071                                                 fb->pixel_format);
9072         fb->pitches[0] = (val & 0x3ff) * stride_mult;
9073
9074         aligned_height = intel_fb_align_height(dev, fb->height,
9075                                                fb->pixel_format,
9076                                                fb->modifier[0]);
9077
9078         plane_config->size = fb->pitches[0] * aligned_height;
9079
9080         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9081                       pipe_name(pipe), fb->width, fb->height,
9082                       fb->bits_per_pixel, base, fb->pitches[0],
9083                       plane_config->size);
9084
9085         plane_config->fb = intel_fb;
9086         return;
9087
9088 error:
9089         kfree(fb);
9090 }
9091
9092 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
9093                                      struct intel_crtc_state *pipe_config)
9094 {
9095         struct drm_device *dev = crtc->base.dev;
9096         struct drm_i915_private *dev_priv = dev->dev_private;
9097         uint32_t tmp;
9098
9099         tmp = I915_READ(PF_CTL(crtc->pipe));
9100
9101         if (tmp & PF_ENABLE) {
9102                 pipe_config->pch_pfit.enabled = true;
9103                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
9104                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
9105
9106                 /* We currently do not free assignements of panel fitters on
9107                  * ivb/hsw (since we don't use the higher upscaling modes which
9108                  * differentiates them) so just WARN about this case for now. */
9109                 if (IS_GEN7(dev)) {
9110                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
9111                                 PF_PIPE_SEL_IVB(crtc->pipe));
9112                 }
9113         }
9114 }
9115
9116 static void
9117 ironlake_get_initial_plane_config(struct intel_crtc *crtc,
9118                                   struct intel_initial_plane_config *plane_config)
9119 {
9120         struct drm_device *dev = crtc->base.dev;
9121         struct drm_i915_private *dev_priv = dev->dev_private;
9122         u32 val, base, offset;
9123         int pipe = crtc->pipe;
9124         int fourcc, pixel_format;
9125         unsigned int aligned_height;
9126         struct drm_framebuffer *fb;
9127         struct intel_framebuffer *intel_fb;
9128
9129         val = I915_READ(DSPCNTR(pipe));
9130         if (!(val & DISPLAY_PLANE_ENABLE))
9131                 return;
9132
9133         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9134         if (!intel_fb) {
9135                 DRM_DEBUG_KMS("failed to alloc fb\n");
9136                 return;
9137         }
9138
9139         fb = &intel_fb->base;
9140
9141         if (INTEL_INFO(dev)->gen >= 4) {
9142                 if (val & DISPPLANE_TILED) {
9143                         plane_config->tiling = I915_TILING_X;
9144                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9145                 }
9146         }
9147
9148         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
9149         fourcc = i9xx_format_to_fourcc(pixel_format);
9150         fb->pixel_format = fourcc;
9151         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9152
9153         base = I915_READ(DSPSURF(pipe)) & 0xfffff000;
9154         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
9155                 offset = I915_READ(DSPOFFSET(pipe));
9156         } else {
9157                 if (plane_config->tiling)
9158                         offset = I915_READ(DSPTILEOFF(pipe));
9159                 else
9160                         offset = I915_READ(DSPLINOFF(pipe));
9161         }
9162         plane_config->base = base;
9163
9164         val = I915_READ(PIPESRC(pipe));
9165         fb->width = ((val >> 16) & 0xfff) + 1;
9166         fb->height = ((val >> 0) & 0xfff) + 1;
9167
9168         val = I915_READ(DSPSTRIDE(pipe));
9169         fb->pitches[0] = val & 0xffffffc0;
9170
9171         aligned_height = intel_fb_align_height(dev, fb->height,
9172                                                fb->pixel_format,
9173                                                fb->modifier[0]);
9174
9175         plane_config->size = fb->pitches[0] * aligned_height;
9176
9177         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9178                       pipe_name(pipe), fb->width, fb->height,
9179                       fb->bits_per_pixel, base, fb->pitches[0],
9180                       plane_config->size);
9181
9182         plane_config->fb = intel_fb;
9183 }
9184
9185 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
9186                                      struct intel_crtc_state *pipe_config)
9187 {
9188         struct drm_device *dev = crtc->base.dev;
9189         struct drm_i915_private *dev_priv = dev->dev_private;
9190         uint32_t tmp;
9191
9192         if (!intel_display_power_is_enabled(dev_priv,
9193                                             POWER_DOMAIN_PIPE(crtc->pipe)))
9194                 return false;
9195
9196         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9197         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
9198
9199         tmp = I915_READ(PIPECONF(crtc->pipe));
9200         if (!(tmp & PIPECONF_ENABLE))
9201                 return false;
9202
9203         switch (tmp & PIPECONF_BPC_MASK) {
9204         case PIPECONF_6BPC:
9205                 pipe_config->pipe_bpp = 18;
9206                 break;
9207         case PIPECONF_8BPC:
9208                 pipe_config->pipe_bpp = 24;
9209                 break;
9210         case PIPECONF_10BPC:
9211                 pipe_config->pipe_bpp = 30;
9212                 break;
9213         case PIPECONF_12BPC:
9214                 pipe_config->pipe_bpp = 36;
9215                 break;
9216         default:
9217                 break;
9218         }
9219
9220         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
9221                 pipe_config->limited_color_range = true;
9222
9223         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
9224                 struct intel_shared_dpll *pll;
9225
9226                 pipe_config->has_pch_encoder = true;
9227
9228                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
9229                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9230                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9231
9232                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9233
9234                 if (HAS_PCH_IBX(dev_priv->dev)) {
9235                         pipe_config->shared_dpll =
9236                                 (enum intel_dpll_id) crtc->pipe;
9237                 } else {
9238                         tmp = I915_READ(PCH_DPLL_SEL);
9239                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
9240                                 pipe_config->shared_dpll = DPLL_ID_PCH_PLL_B;
9241                         else
9242                                 pipe_config->shared_dpll = DPLL_ID_PCH_PLL_A;
9243                 }
9244
9245                 pll = &dev_priv->shared_dplls[pipe_config->shared_dpll];
9246
9247                 WARN_ON(!pll->get_hw_state(dev_priv, pll,
9248                                            &pipe_config->dpll_hw_state));
9249
9250                 tmp = pipe_config->dpll_hw_state.dpll;
9251                 pipe_config->pixel_multiplier =
9252                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
9253                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
9254
9255                 ironlake_pch_clock_get(crtc, pipe_config);
9256         } else {
9257                 pipe_config->pixel_multiplier = 1;
9258         }
9259
9260         intel_get_pipe_timings(crtc, pipe_config);
9261
9262         ironlake_get_pfit_config(crtc, pipe_config);
9263
9264         return true;
9265 }
9266
9267 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
9268 {
9269         struct drm_device *dev = dev_priv->dev;
9270         struct intel_crtc *crtc;
9271
9272         for_each_intel_crtc(dev, crtc)
9273                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
9274                      pipe_name(crtc->pipe));
9275
9276         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_DRIVER), "Power well on\n");
9277         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
9278         I915_STATE_WARN(I915_READ(WRPLL_CTL1) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
9279         I915_STATE_WARN(I915_READ(WRPLL_CTL2) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
9280         I915_STATE_WARN(I915_READ(PCH_PP_STATUS) & PP_ON, "Panel power on\n");
9281         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
9282              "CPU PWM1 enabled\n");
9283         if (IS_HASWELL(dev))
9284                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
9285                      "CPU PWM2 enabled\n");
9286         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
9287              "PCH PWM1 enabled\n");
9288         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
9289              "Utility pin enabled\n");
9290         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
9291
9292         /*
9293          * In theory we can still leave IRQs enabled, as long as only the HPD
9294          * interrupts remain enabled. We used to check for that, but since it's
9295          * gen-specific and since we only disable LCPLL after we fully disable
9296          * the interrupts, the check below should be enough.
9297          */
9298         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
9299 }
9300
9301 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
9302 {
9303         struct drm_device *dev = dev_priv->dev;
9304
9305         if (IS_HASWELL(dev))
9306                 return I915_READ(D_COMP_HSW);
9307         else
9308                 return I915_READ(D_COMP_BDW);
9309 }
9310
9311 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
9312 {
9313         struct drm_device *dev = dev_priv->dev;
9314
9315         if (IS_HASWELL(dev)) {
9316                 mutex_lock(&dev_priv->rps.hw_lock);
9317                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
9318                                             val))
9319                         DRM_ERROR("Failed to write to D_COMP\n");
9320                 mutex_unlock(&dev_priv->rps.hw_lock);
9321         } else {
9322                 I915_WRITE(D_COMP_BDW, val);
9323                 POSTING_READ(D_COMP_BDW);
9324         }
9325 }
9326
9327 /*
9328  * This function implements pieces of two sequences from BSpec:
9329  * - Sequence for display software to disable LCPLL
9330  * - Sequence for display software to allow package C8+
9331  * The steps implemented here are just the steps that actually touch the LCPLL
9332  * register. Callers should take care of disabling all the display engine
9333  * functions, doing the mode unset, fixing interrupts, etc.
9334  */
9335 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
9336                               bool switch_to_fclk, bool allow_power_down)
9337 {
9338         uint32_t val;
9339
9340         assert_can_disable_lcpll(dev_priv);
9341
9342         val = I915_READ(LCPLL_CTL);
9343
9344         if (switch_to_fclk) {
9345                 val |= LCPLL_CD_SOURCE_FCLK;
9346                 I915_WRITE(LCPLL_CTL, val);
9347
9348                 if (wait_for_atomic_us(I915_READ(LCPLL_CTL) &
9349                                        LCPLL_CD_SOURCE_FCLK_DONE, 1))
9350                         DRM_ERROR("Switching to FCLK failed\n");
9351
9352                 val = I915_READ(LCPLL_CTL);
9353         }
9354
9355         val |= LCPLL_PLL_DISABLE;
9356         I915_WRITE(LCPLL_CTL, val);
9357         POSTING_READ(LCPLL_CTL);
9358
9359         if (wait_for((I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK) == 0, 1))
9360                 DRM_ERROR("LCPLL still locked\n");
9361
9362         val = hsw_read_dcomp(dev_priv);
9363         val |= D_COMP_COMP_DISABLE;
9364         hsw_write_dcomp(dev_priv, val);
9365         ndelay(100);
9366
9367         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
9368                      1))
9369                 DRM_ERROR("D_COMP RCOMP still in progress\n");
9370
9371         if (allow_power_down) {
9372                 val = I915_READ(LCPLL_CTL);
9373                 val |= LCPLL_POWER_DOWN_ALLOW;
9374                 I915_WRITE(LCPLL_CTL, val);
9375                 POSTING_READ(LCPLL_CTL);
9376         }
9377 }
9378
9379 /*
9380  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
9381  * source.
9382  */
9383 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
9384 {
9385         uint32_t val;
9386
9387         val = I915_READ(LCPLL_CTL);
9388
9389         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
9390                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
9391                 return;
9392
9393         /*
9394          * Make sure we're not on PC8 state before disabling PC8, otherwise
9395          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
9396          */
9397         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
9398
9399         if (val & LCPLL_POWER_DOWN_ALLOW) {
9400                 val &= ~LCPLL_POWER_DOWN_ALLOW;
9401                 I915_WRITE(LCPLL_CTL, val);
9402                 POSTING_READ(LCPLL_CTL);
9403         }
9404
9405         val = hsw_read_dcomp(dev_priv);
9406         val |= D_COMP_COMP_FORCE;
9407         val &= ~D_COMP_COMP_DISABLE;
9408         hsw_write_dcomp(dev_priv, val);
9409
9410         val = I915_READ(LCPLL_CTL);
9411         val &= ~LCPLL_PLL_DISABLE;
9412         I915_WRITE(LCPLL_CTL, val);
9413
9414         if (wait_for(I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK, 5))
9415                 DRM_ERROR("LCPLL not locked yet\n");
9416
9417         if (val & LCPLL_CD_SOURCE_FCLK) {
9418                 val = I915_READ(LCPLL_CTL);
9419                 val &= ~LCPLL_CD_SOURCE_FCLK;
9420                 I915_WRITE(LCPLL_CTL, val);
9421
9422                 if (wait_for_atomic_us((I915_READ(LCPLL_CTL) &
9423                                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9424                         DRM_ERROR("Switching back to LCPLL failed\n");
9425         }
9426
9427         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
9428         intel_update_cdclk(dev_priv->dev);
9429 }
9430
9431 /*
9432  * Package states C8 and deeper are really deep PC states that can only be
9433  * reached when all the devices on the system allow it, so even if the graphics
9434  * device allows PC8+, it doesn't mean the system will actually get to these
9435  * states. Our driver only allows PC8+ when going into runtime PM.
9436  *
9437  * The requirements for PC8+ are that all the outputs are disabled, the power
9438  * well is disabled and most interrupts are disabled, and these are also
9439  * requirements for runtime PM. When these conditions are met, we manually do
9440  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
9441  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
9442  * hang the machine.
9443  *
9444  * When we really reach PC8 or deeper states (not just when we allow it) we lose
9445  * the state of some registers, so when we come back from PC8+ we need to
9446  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
9447  * need to take care of the registers kept by RC6. Notice that this happens even
9448  * if we don't put the device in PCI D3 state (which is what currently happens
9449  * because of the runtime PM support).
9450  *
9451  * For more, read "Display Sequences for Package C8" on the hardware
9452  * documentation.
9453  */
9454 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
9455 {
9456         struct drm_device *dev = dev_priv->dev;
9457         uint32_t val;
9458
9459         DRM_DEBUG_KMS("Enabling package C8+\n");
9460
9461         if (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) {
9462                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9463                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
9464                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9465         }
9466
9467         lpt_disable_clkout_dp(dev);
9468         hsw_disable_lcpll(dev_priv, true, true);
9469 }
9470
9471 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
9472 {
9473         struct drm_device *dev = dev_priv->dev;
9474         uint32_t val;
9475
9476         DRM_DEBUG_KMS("Disabling package C8+\n");
9477
9478         hsw_restore_lcpll(dev_priv);
9479         lpt_init_pch_refclk(dev);
9480
9481         if (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) {
9482                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9483                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
9484                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9485         }
9486
9487         intel_prepare_ddi(dev);
9488 }
9489
9490 static void broxton_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9491 {
9492         struct drm_device *dev = old_state->dev;
9493         unsigned int req_cdclk = to_intel_atomic_state(old_state)->cdclk;
9494
9495         broxton_set_cdclk(dev, req_cdclk);
9496 }
9497
9498 /* compute the max rate for new configuration */
9499 static int ilk_max_pixel_rate(struct drm_atomic_state *state)
9500 {
9501         struct intel_crtc *intel_crtc;
9502         struct intel_crtc_state *crtc_state;
9503         int max_pixel_rate = 0;
9504
9505         for_each_intel_crtc(state->dev, intel_crtc) {
9506                 int pixel_rate;
9507
9508                 crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
9509                 if (IS_ERR(crtc_state))
9510                         return PTR_ERR(crtc_state);
9511
9512                 if (!crtc_state->base.enable)
9513                         continue;
9514
9515                 pixel_rate = ilk_pipe_pixel_rate(crtc_state);
9516
9517                 /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
9518                 if (IS_BROADWELL(state->dev) && crtc_state->ips_enabled)
9519                         pixel_rate = DIV_ROUND_UP(pixel_rate * 100, 95);
9520
9521                 max_pixel_rate = max(max_pixel_rate, pixel_rate);
9522         }
9523
9524         return max_pixel_rate;
9525 }
9526
9527 static void broadwell_set_cdclk(struct drm_device *dev, int cdclk)
9528 {
9529         struct drm_i915_private *dev_priv = dev->dev_private;
9530         uint32_t val, data;
9531         int ret;
9532
9533         if (WARN((I915_READ(LCPLL_CTL) &
9534                   (LCPLL_PLL_DISABLE | LCPLL_PLL_LOCK |
9535                    LCPLL_CD_CLOCK_DISABLE | LCPLL_ROOT_CD_CLOCK_DISABLE |
9536                    LCPLL_CD2X_CLOCK_DISABLE | LCPLL_POWER_DOWN_ALLOW |
9537                    LCPLL_CD_SOURCE_FCLK)) != LCPLL_PLL_LOCK,
9538                  "trying to change cdclk frequency with cdclk not enabled\n"))
9539                 return;
9540
9541         mutex_lock(&dev_priv->rps.hw_lock);
9542         ret = sandybridge_pcode_write(dev_priv,
9543                                       BDW_PCODE_DISPLAY_FREQ_CHANGE_REQ, 0x0);
9544         mutex_unlock(&dev_priv->rps.hw_lock);
9545         if (ret) {
9546                 DRM_ERROR("failed to inform pcode about cdclk change\n");
9547                 return;
9548         }
9549
9550         val = I915_READ(LCPLL_CTL);
9551         val |= LCPLL_CD_SOURCE_FCLK;
9552         I915_WRITE(LCPLL_CTL, val);
9553
9554         if (wait_for_atomic_us(I915_READ(LCPLL_CTL) &
9555                                LCPLL_CD_SOURCE_FCLK_DONE, 1))
9556                 DRM_ERROR("Switching to FCLK failed\n");
9557
9558         val = I915_READ(LCPLL_CTL);
9559         val &= ~LCPLL_CLK_FREQ_MASK;
9560
9561         switch (cdclk) {
9562         case 450000:
9563                 val |= LCPLL_CLK_FREQ_450;
9564                 data = 0;
9565                 break;
9566         case 540000:
9567                 val |= LCPLL_CLK_FREQ_54O_BDW;
9568                 data = 1;
9569                 break;
9570         case 337500:
9571                 val |= LCPLL_CLK_FREQ_337_5_BDW;
9572                 data = 2;
9573                 break;
9574         case 675000:
9575                 val |= LCPLL_CLK_FREQ_675_BDW;
9576                 data = 3;
9577                 break;
9578         default:
9579                 WARN(1, "invalid cdclk frequency\n");
9580                 return;
9581         }
9582
9583         I915_WRITE(LCPLL_CTL, val);
9584
9585         val = I915_READ(LCPLL_CTL);
9586         val &= ~LCPLL_CD_SOURCE_FCLK;
9587         I915_WRITE(LCPLL_CTL, val);
9588
9589         if (wait_for_atomic_us((I915_READ(LCPLL_CTL) &
9590                                 LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9591                 DRM_ERROR("Switching back to LCPLL failed\n");
9592
9593         mutex_lock(&dev_priv->rps.hw_lock);
9594         sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ, data);
9595         mutex_unlock(&dev_priv->rps.hw_lock);
9596
9597         intel_update_cdclk(dev);
9598
9599         WARN(cdclk != dev_priv->cdclk_freq,
9600              "cdclk requested %d kHz but got %d kHz\n",
9601              cdclk, dev_priv->cdclk_freq);
9602 }
9603
9604 static int broadwell_modeset_calc_cdclk(struct drm_atomic_state *state)
9605 {
9606         struct drm_i915_private *dev_priv = to_i915(state->dev);
9607         int max_pixclk = ilk_max_pixel_rate(state);
9608         int cdclk;
9609
9610         /*
9611          * FIXME should also account for plane ratio
9612          * once 64bpp pixel formats are supported.
9613          */
9614         if (max_pixclk > 540000)
9615                 cdclk = 675000;
9616         else if (max_pixclk > 450000)
9617                 cdclk = 540000;
9618         else if (max_pixclk > 337500)
9619                 cdclk = 450000;
9620         else
9621                 cdclk = 337500;
9622
9623         /*
9624          * FIXME move the cdclk caclulation to
9625          * compute_config() so we can fail gracegully.
9626          */
9627         if (cdclk > dev_priv->max_cdclk_freq) {
9628                 DRM_ERROR("requested cdclk (%d kHz) exceeds max (%d kHz)\n",
9629                           cdclk, dev_priv->max_cdclk_freq);
9630                 cdclk = dev_priv->max_cdclk_freq;
9631         }
9632
9633         to_intel_atomic_state(state)->cdclk = cdclk;
9634
9635         return 0;
9636 }
9637
9638 static void broadwell_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9639 {
9640         struct drm_device *dev = old_state->dev;
9641         unsigned int req_cdclk = to_intel_atomic_state(old_state)->cdclk;
9642
9643         broadwell_set_cdclk(dev, req_cdclk);
9644 }
9645
9646 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9647                                       struct intel_crtc_state *crtc_state)
9648 {
9649         if (!intel_ddi_pll_select(crtc, crtc_state))
9650                 return -EINVAL;
9651
9652         crtc->lowfreq_avail = false;
9653
9654         return 0;
9655 }
9656
9657 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9658                                 enum port port,
9659                                 struct intel_crtc_state *pipe_config)
9660 {
9661         switch (port) {
9662         case PORT_A:
9663                 pipe_config->ddi_pll_sel = SKL_DPLL0;
9664                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL1;
9665                 break;
9666         case PORT_B:
9667                 pipe_config->ddi_pll_sel = SKL_DPLL1;
9668                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL2;
9669                 break;
9670         case PORT_C:
9671                 pipe_config->ddi_pll_sel = SKL_DPLL2;
9672                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL3;
9673                 break;
9674         default:
9675                 DRM_ERROR("Incorrect port type\n");
9676         }
9677 }
9678
9679 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9680                                 enum port port,
9681                                 struct intel_crtc_state *pipe_config)
9682 {
9683         u32 temp, dpll_ctl1;
9684
9685         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9686         pipe_config->ddi_pll_sel = temp >> (port * 3 + 1);
9687
9688         switch (pipe_config->ddi_pll_sel) {
9689         case SKL_DPLL0:
9690                 /*
9691                  * On SKL the eDP DPLL (DPLL0 as we don't use SSC) is not part
9692                  * of the shared DPLL framework and thus needs to be read out
9693                  * separately
9694                  */
9695                 dpll_ctl1 = I915_READ(DPLL_CTRL1);
9696                 pipe_config->dpll_hw_state.ctrl1 = dpll_ctl1 & 0x3f;
9697                 break;
9698         case SKL_DPLL1:
9699                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL1;
9700                 break;
9701         case SKL_DPLL2:
9702                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL2;
9703                 break;
9704         case SKL_DPLL3:
9705                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL3;
9706                 break;
9707         }
9708 }
9709
9710 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9711                                 enum port port,
9712                                 struct intel_crtc_state *pipe_config)
9713 {
9714         pipe_config->ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9715
9716         switch (pipe_config->ddi_pll_sel) {
9717         case PORT_CLK_SEL_WRPLL1:
9718                 pipe_config->shared_dpll = DPLL_ID_WRPLL1;
9719                 break;
9720         case PORT_CLK_SEL_WRPLL2:
9721                 pipe_config->shared_dpll = DPLL_ID_WRPLL2;
9722                 break;
9723         }
9724 }
9725
9726 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9727                                        struct intel_crtc_state *pipe_config)
9728 {
9729         struct drm_device *dev = crtc->base.dev;
9730         struct drm_i915_private *dev_priv = dev->dev_private;
9731         struct intel_shared_dpll *pll;
9732         enum port port;
9733         uint32_t tmp;
9734
9735         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9736
9737         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9738
9739         if (IS_SKYLAKE(dev))
9740                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
9741         else if (IS_BROXTON(dev))
9742                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
9743         else
9744                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
9745
9746         if (pipe_config->shared_dpll >= 0) {
9747                 pll = &dev_priv->shared_dplls[pipe_config->shared_dpll];
9748
9749                 WARN_ON(!pll->get_hw_state(dev_priv, pll,
9750                                            &pipe_config->dpll_hw_state));
9751         }
9752
9753         /*
9754          * Haswell has only FDI/PCH transcoder A. It is which is connected to
9755          * DDI E. So just check whether this pipe is wired to DDI E and whether
9756          * the PCH transcoder is on.
9757          */
9758         if (INTEL_INFO(dev)->gen < 9 &&
9759             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
9760                 pipe_config->has_pch_encoder = true;
9761
9762                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
9763                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9764                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9765
9766                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9767         }
9768 }
9769
9770 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
9771                                     struct intel_crtc_state *pipe_config)
9772 {
9773         struct drm_device *dev = crtc->base.dev;
9774         struct drm_i915_private *dev_priv = dev->dev_private;
9775         enum intel_display_power_domain pfit_domain;
9776         uint32_t tmp;
9777
9778         if (!intel_display_power_is_enabled(dev_priv,
9779                                          POWER_DOMAIN_PIPE(crtc->pipe)))
9780                 return false;
9781
9782         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9783         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
9784
9785         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
9786         if (tmp & TRANS_DDI_FUNC_ENABLE) {
9787                 enum pipe trans_edp_pipe;
9788                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9789                 default:
9790                         WARN(1, "unknown pipe linked to edp transcoder\n");
9791                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9792                 case TRANS_DDI_EDP_INPUT_A_ON:
9793                         trans_edp_pipe = PIPE_A;
9794                         break;
9795                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
9796                         trans_edp_pipe = PIPE_B;
9797                         break;
9798                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
9799                         trans_edp_pipe = PIPE_C;
9800                         break;
9801                 }
9802
9803                 if (trans_edp_pipe == crtc->pipe)
9804                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
9805         }
9806
9807         if (!intel_display_power_is_enabled(dev_priv,
9808                         POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder)))
9809                 return false;
9810
9811         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
9812         if (!(tmp & PIPECONF_ENABLE))
9813                 return false;
9814
9815         haswell_get_ddi_port_state(crtc, pipe_config);
9816
9817         intel_get_pipe_timings(crtc, pipe_config);
9818
9819         if (INTEL_INFO(dev)->gen >= 9) {
9820                 skl_init_scalers(dev, crtc, pipe_config);
9821         }
9822
9823         pfit_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
9824
9825         if (INTEL_INFO(dev)->gen >= 9) {
9826                 pipe_config->scaler_state.scaler_id = -1;
9827                 pipe_config->scaler_state.scaler_users &= ~(1 << SKL_CRTC_INDEX);
9828         }
9829
9830         if (intel_display_power_is_enabled(dev_priv, pfit_domain)) {
9831                 if (INTEL_INFO(dev)->gen == 9)
9832                         skylake_get_pfit_config(crtc, pipe_config);
9833                 else if (INTEL_INFO(dev)->gen < 9)
9834                         ironlake_get_pfit_config(crtc, pipe_config);
9835                 else
9836                         MISSING_CASE(INTEL_INFO(dev)->gen);
9837         }
9838
9839         if (IS_HASWELL(dev))
9840                 pipe_config->ips_enabled = hsw_crtc_supports_ips(crtc) &&
9841                         (I915_READ(IPS_CTL) & IPS_ENABLE);
9842
9843         if (pipe_config->cpu_transcoder != TRANSCODER_EDP) {
9844                 pipe_config->pixel_multiplier =
9845                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
9846         } else {
9847                 pipe_config->pixel_multiplier = 1;
9848         }
9849
9850         return true;
9851 }
9852
9853 static void i845_update_cursor(struct drm_crtc *crtc, u32 base)
9854 {
9855         struct drm_device *dev = crtc->dev;
9856         struct drm_i915_private *dev_priv = dev->dev_private;
9857         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9858         uint32_t cntl = 0, size = 0;
9859
9860         if (base) {
9861                 unsigned int width = intel_crtc->base.cursor->state->crtc_w;
9862                 unsigned int height = intel_crtc->base.cursor->state->crtc_h;
9863                 unsigned int stride = roundup_pow_of_two(width) * 4;
9864
9865                 switch (stride) {
9866                 default:
9867                         WARN_ONCE(1, "Invalid cursor width/stride, width=%u, stride=%u\n",
9868                                   width, stride);
9869                         stride = 256;
9870                         /* fallthrough */
9871                 case 256:
9872                 case 512:
9873                 case 1024:
9874                 case 2048:
9875                         break;
9876                 }
9877
9878                 cntl |= CURSOR_ENABLE |
9879                         CURSOR_GAMMA_ENABLE |
9880                         CURSOR_FORMAT_ARGB |
9881                         CURSOR_STRIDE(stride);
9882
9883                 size = (height << 12) | width;
9884         }
9885
9886         if (intel_crtc->cursor_cntl != 0 &&
9887             (intel_crtc->cursor_base != base ||
9888              intel_crtc->cursor_size != size ||
9889              intel_crtc->cursor_cntl != cntl)) {
9890                 /* On these chipsets we can only modify the base/size/stride
9891                  * whilst the cursor is disabled.
9892                  */
9893                 I915_WRITE(_CURACNTR, 0);
9894                 POSTING_READ(_CURACNTR);
9895                 intel_crtc->cursor_cntl = 0;
9896         }
9897
9898         if (intel_crtc->cursor_base != base) {
9899                 I915_WRITE(_CURABASE, base);
9900                 intel_crtc->cursor_base = base;
9901         }
9902
9903         if (intel_crtc->cursor_size != size) {
9904                 I915_WRITE(CURSIZE, size);
9905                 intel_crtc->cursor_size = size;
9906         }
9907
9908         if (intel_crtc->cursor_cntl != cntl) {
9909                 I915_WRITE(_CURACNTR, cntl);
9910                 POSTING_READ(_CURACNTR);
9911                 intel_crtc->cursor_cntl = cntl;
9912         }
9913 }
9914
9915 static void i9xx_update_cursor(struct drm_crtc *crtc, u32 base)
9916 {
9917         struct drm_device *dev = crtc->dev;
9918         struct drm_i915_private *dev_priv = dev->dev_private;
9919         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9920         int pipe = intel_crtc->pipe;
9921         uint32_t cntl;
9922
9923         cntl = 0;
9924         if (base) {
9925                 cntl = MCURSOR_GAMMA_ENABLE;
9926                 switch (intel_crtc->base.cursor->state->crtc_w) {
9927                         case 64:
9928                                 cntl |= CURSOR_MODE_64_ARGB_AX;
9929                                 break;
9930                         case 128:
9931                                 cntl |= CURSOR_MODE_128_ARGB_AX;
9932                                 break;
9933                         case 256:
9934                                 cntl |= CURSOR_MODE_256_ARGB_AX;
9935                                 break;
9936                         default:
9937                                 MISSING_CASE(intel_crtc->base.cursor->state->crtc_w);
9938                                 return;
9939                 }
9940                 cntl |= pipe << 28; /* Connect to correct pipe */
9941
9942                 if (IS_HASWELL(dev) || IS_BROADWELL(dev))
9943                         cntl |= CURSOR_PIPE_CSC_ENABLE;
9944         }
9945
9946         if (crtc->cursor->state->rotation == BIT(DRM_ROTATE_180))
9947                 cntl |= CURSOR_ROTATE_180;
9948
9949         if (intel_crtc->cursor_cntl != cntl) {
9950                 I915_WRITE(CURCNTR(pipe), cntl);
9951                 POSTING_READ(CURCNTR(pipe));
9952                 intel_crtc->cursor_cntl = cntl;
9953         }
9954
9955         /* and commit changes on next vblank */
9956         I915_WRITE(CURBASE(pipe), base);
9957         POSTING_READ(CURBASE(pipe));
9958
9959         intel_crtc->cursor_base = base;
9960 }
9961
9962 /* If no-part of the cursor is visible on the framebuffer, then the GPU may hang... */
9963 static void intel_crtc_update_cursor(struct drm_crtc *crtc,
9964                                      bool on)
9965 {
9966         struct drm_device *dev = crtc->dev;
9967         struct drm_i915_private *dev_priv = dev->dev_private;
9968         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9969         int pipe = intel_crtc->pipe;
9970         int x = crtc->cursor_x;
9971         int y = crtc->cursor_y;
9972         u32 base = 0, pos = 0;
9973
9974         if (on)
9975                 base = intel_crtc->cursor_addr;
9976
9977         if (x >= intel_crtc->config->pipe_src_w)
9978                 base = 0;
9979
9980         if (y >= intel_crtc->config->pipe_src_h)
9981                 base = 0;
9982
9983         if (x < 0) {
9984                 if (x + intel_crtc->base.cursor->state->crtc_w <= 0)
9985                         base = 0;
9986
9987                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
9988                 x = -x;
9989         }
9990         pos |= x << CURSOR_X_SHIFT;
9991
9992         if (y < 0) {
9993                 if (y + intel_crtc->base.cursor->state->crtc_h <= 0)
9994                         base = 0;
9995
9996                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
9997                 y = -y;
9998         }
9999         pos |= y << CURSOR_Y_SHIFT;
10000
10001         if (base == 0 && intel_crtc->cursor_base == 0)
10002                 return;
10003
10004         I915_WRITE(CURPOS(pipe), pos);
10005
10006         /* ILK+ do this automagically */
10007         if (HAS_GMCH_DISPLAY(dev) &&
10008             crtc->cursor->state->rotation == BIT(DRM_ROTATE_180)) {
10009                 base += (intel_crtc->base.cursor->state->crtc_h *
10010                         intel_crtc->base.cursor->state->crtc_w - 1) * 4;
10011         }
10012
10013         if (IS_845G(dev) || IS_I865G(dev))
10014                 i845_update_cursor(crtc, base);
10015         else
10016                 i9xx_update_cursor(crtc, base);
10017 }
10018
10019 static bool cursor_size_ok(struct drm_device *dev,
10020                            uint32_t width, uint32_t height)
10021 {
10022         if (width == 0 || height == 0)
10023                 return false;
10024
10025         /*
10026          * 845g/865g are special in that they are only limited by
10027          * the width of their cursors, the height is arbitrary up to
10028          * the precision of the register. Everything else requires
10029          * square cursors, limited to a few power-of-two sizes.
10030          */
10031         if (IS_845G(dev) || IS_I865G(dev)) {
10032                 if ((width & 63) != 0)
10033                         return false;
10034
10035                 if (width > (IS_845G(dev) ? 64 : 512))
10036                         return false;
10037
10038                 if (height > 1023)
10039                         return false;
10040         } else {
10041                 switch (width | height) {
10042                 case 256:
10043                 case 128:
10044                         if (IS_GEN2(dev))
10045                                 return false;
10046                 case 64:
10047                         break;
10048                 default:
10049                         return false;
10050                 }
10051         }
10052
10053         return true;
10054 }
10055
10056 static void intel_crtc_gamma_set(struct drm_crtc *crtc, u16 *red, u16 *green,
10057                                  u16 *blue, uint32_t start, uint32_t size)
10058 {
10059         int end = (start + size > 256) ? 256 : start + size, i;
10060         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10061
10062         for (i = start; i < end; i++) {
10063                 intel_crtc->lut_r[i] = red[i] >> 8;
10064                 intel_crtc->lut_g[i] = green[i] >> 8;
10065                 intel_crtc->lut_b[i] = blue[i] >> 8;
10066         }
10067
10068         intel_crtc_load_lut(crtc);
10069 }
10070
10071 /* VESA 640x480x72Hz mode to set on the pipe */
10072 static struct drm_display_mode load_detect_mode = {
10073         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10074                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10075 };
10076
10077 struct drm_framebuffer *
10078 __intel_framebuffer_create(struct drm_device *dev,
10079                            struct drm_mode_fb_cmd2 *mode_cmd,
10080                            struct drm_i915_gem_object *obj)
10081 {
10082         struct intel_framebuffer *intel_fb;
10083         int ret;
10084
10085         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10086         if (!intel_fb) {
10087                 drm_gem_object_unreference(&obj->base);
10088                 return ERR_PTR(-ENOMEM);
10089         }
10090
10091         ret = intel_framebuffer_init(dev, intel_fb, mode_cmd, obj);
10092         if (ret)
10093                 goto err;
10094
10095         return &intel_fb->base;
10096 err:
10097         drm_gem_object_unreference(&obj->base);
10098         kfree(intel_fb);
10099
10100         return ERR_PTR(ret);
10101 }
10102
10103 static struct drm_framebuffer *
10104 intel_framebuffer_create(struct drm_device *dev,
10105                          struct drm_mode_fb_cmd2 *mode_cmd,
10106                          struct drm_i915_gem_object *obj)
10107 {
10108         struct drm_framebuffer *fb;
10109         int ret;
10110
10111         ret = i915_mutex_lock_interruptible(dev);
10112         if (ret)
10113                 return ERR_PTR(ret);
10114         fb = __intel_framebuffer_create(dev, mode_cmd, obj);
10115         mutex_unlock(&dev->struct_mutex);
10116
10117         return fb;
10118 }
10119
10120 static u32
10121 intel_framebuffer_pitch_for_width(int width, int bpp)
10122 {
10123         u32 pitch = DIV_ROUND_UP(width * bpp, 8);
10124         return ALIGN(pitch, 64);
10125 }
10126
10127 static u32
10128 intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
10129 {
10130         u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
10131         return PAGE_ALIGN(pitch * mode->vdisplay);
10132 }
10133
10134 static struct drm_framebuffer *
10135 intel_framebuffer_create_for_mode(struct drm_device *dev,
10136                                   struct drm_display_mode *mode,
10137                                   int depth, int bpp)
10138 {
10139         struct drm_i915_gem_object *obj;
10140         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
10141
10142         obj = i915_gem_alloc_object(dev,
10143                                     intel_framebuffer_size_for_mode(mode, bpp));
10144         if (obj == NULL)
10145                 return ERR_PTR(-ENOMEM);
10146
10147         mode_cmd.width = mode->hdisplay;
10148         mode_cmd.height = mode->vdisplay;
10149         mode_cmd.pitches[0] = intel_framebuffer_pitch_for_width(mode_cmd.width,
10150                                                                 bpp);
10151         mode_cmd.pixel_format = drm_mode_legacy_fb_format(bpp, depth);
10152
10153         return intel_framebuffer_create(dev, &mode_cmd, obj);
10154 }
10155
10156 static struct drm_framebuffer *
10157 mode_fits_in_fbdev(struct drm_device *dev,
10158                    struct drm_display_mode *mode)
10159 {
10160 #ifdef CONFIG_DRM_I915_FBDEV
10161         struct drm_i915_private *dev_priv = dev->dev_private;
10162         struct drm_i915_gem_object *obj;
10163         struct drm_framebuffer *fb;
10164
10165         if (!dev_priv->fbdev)
10166                 return NULL;
10167
10168         if (!dev_priv->fbdev->fb)
10169                 return NULL;
10170
10171         obj = dev_priv->fbdev->fb->obj;
10172         BUG_ON(!obj);
10173
10174         fb = &dev_priv->fbdev->fb->base;
10175         if (fb->pitches[0] < intel_framebuffer_pitch_for_width(mode->hdisplay,
10176                                                                fb->bits_per_pixel))
10177                 return NULL;
10178
10179         if (obj->base.size < mode->vdisplay * fb->pitches[0])
10180                 return NULL;
10181
10182         return fb;
10183 #else
10184         return NULL;
10185 #endif
10186 }
10187
10188 static int intel_modeset_setup_plane_state(struct drm_atomic_state *state,
10189                                            struct drm_crtc *crtc,
10190                                            struct drm_display_mode *mode,
10191                                            struct drm_framebuffer *fb,
10192                                            int x, int y)
10193 {
10194         struct drm_plane_state *plane_state;
10195         int hdisplay, vdisplay;
10196         int ret;
10197
10198         plane_state = drm_atomic_get_plane_state(state, crtc->primary);
10199         if (IS_ERR(plane_state))
10200                 return PTR_ERR(plane_state);
10201
10202         if (mode)
10203                 drm_crtc_get_hv_timing(mode, &hdisplay, &vdisplay);
10204         else
10205                 hdisplay = vdisplay = 0;
10206
10207         ret = drm_atomic_set_crtc_for_plane(plane_state, fb ? crtc : NULL);
10208         if (ret)
10209                 return ret;
10210         drm_atomic_set_fb_for_plane(plane_state, fb);
10211         plane_state->crtc_x = 0;
10212         plane_state->crtc_y = 0;
10213         plane_state->crtc_w = hdisplay;
10214         plane_state->crtc_h = vdisplay;
10215         plane_state->src_x = x << 16;
10216         plane_state->src_y = y << 16;
10217         plane_state->src_w = hdisplay << 16;
10218         plane_state->src_h = vdisplay << 16;
10219
10220         return 0;
10221 }
10222
10223 bool intel_get_load_detect_pipe(struct drm_connector *connector,
10224                                 struct drm_display_mode *mode,
10225                                 struct intel_load_detect_pipe *old,
10226                                 struct drm_modeset_acquire_ctx *ctx)
10227 {
10228         struct intel_crtc *intel_crtc;
10229         struct intel_encoder *intel_encoder =
10230                 intel_attached_encoder(connector);
10231         struct drm_crtc *possible_crtc;
10232         struct drm_encoder *encoder = &intel_encoder->base;
10233         struct drm_crtc *crtc = NULL;
10234         struct drm_device *dev = encoder->dev;
10235         struct drm_framebuffer *fb;
10236         struct drm_mode_config *config = &dev->mode_config;
10237         struct drm_atomic_state *state = NULL;
10238         struct drm_connector_state *connector_state;
10239         struct intel_crtc_state *crtc_state;
10240         int ret, i = -1;
10241
10242         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10243                       connector->base.id, connector->name,
10244                       encoder->base.id, encoder->name);
10245
10246 retry:
10247         ret = drm_modeset_lock(&config->connection_mutex, ctx);
10248         if (ret)
10249                 goto fail_unlock;
10250
10251         /*
10252          * Algorithm gets a little messy:
10253          *
10254          *   - if the connector already has an assigned crtc, use it (but make
10255          *     sure it's on first)
10256          *
10257          *   - try to find the first unused crtc that can drive this connector,
10258          *     and use that if we find one
10259          */
10260
10261         /* See if we already have a CRTC for this connector */
10262         if (encoder->crtc) {
10263                 crtc = encoder->crtc;
10264
10265                 ret = drm_modeset_lock(&crtc->mutex, ctx);
10266                 if (ret)
10267                         goto fail_unlock;
10268                 ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
10269                 if (ret)
10270                         goto fail_unlock;
10271
10272                 old->dpms_mode = connector->dpms;
10273                 old->load_detect_temp = false;
10274
10275                 /* Make sure the crtc and connector are running */
10276                 if (connector->dpms != DRM_MODE_DPMS_ON)
10277                         connector->funcs->dpms(connector, DRM_MODE_DPMS_ON);
10278
10279                 return true;
10280         }
10281
10282         /* Find an unused one (if possible) */
10283         for_each_crtc(dev, possible_crtc) {
10284                 i++;
10285                 if (!(encoder->possible_crtcs & (1 << i)))
10286                         continue;
10287                 if (possible_crtc->state->enable)
10288                         continue;
10289                 /* This can occur when applying the pipe A quirk on resume. */
10290                 if (to_intel_crtc(possible_crtc)->new_enabled)
10291                         continue;
10292
10293                 crtc = possible_crtc;
10294                 break;
10295         }
10296
10297         /*
10298          * If we didn't find an unused CRTC, don't use any.
10299          */
10300         if (!crtc) {
10301                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
10302                 goto fail_unlock;
10303         }
10304
10305         ret = drm_modeset_lock(&crtc->mutex, ctx);
10306         if (ret)
10307                 goto fail_unlock;
10308         ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
10309         if (ret)
10310                 goto fail_unlock;
10311         intel_encoder->new_crtc = to_intel_crtc(crtc);
10312         to_intel_connector(connector)->new_encoder = intel_encoder;
10313
10314         intel_crtc = to_intel_crtc(crtc);
10315         intel_crtc->new_enabled = true;
10316         old->dpms_mode = connector->dpms;
10317         old->load_detect_temp = true;
10318         old->release_fb = NULL;
10319
10320         state = drm_atomic_state_alloc(dev);
10321         if (!state)
10322                 return false;
10323
10324         state->acquire_ctx = ctx;
10325
10326         connector_state = drm_atomic_get_connector_state(state, connector);
10327         if (IS_ERR(connector_state)) {
10328                 ret = PTR_ERR(connector_state);
10329                 goto fail;
10330         }
10331
10332         connector_state->crtc = crtc;
10333         connector_state->best_encoder = &intel_encoder->base;
10334
10335         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10336         if (IS_ERR(crtc_state)) {
10337                 ret = PTR_ERR(crtc_state);
10338                 goto fail;
10339         }
10340
10341         crtc_state->base.active = crtc_state->base.enable = true;
10342
10343         if (!mode)
10344                 mode = &load_detect_mode;
10345
10346         /* We need a framebuffer large enough to accommodate all accesses
10347          * that the plane may generate whilst we perform load detection.
10348          * We can not rely on the fbcon either being present (we get called
10349          * during its initialisation to detect all boot displays, or it may
10350          * not even exist) or that it is large enough to satisfy the
10351          * requested mode.
10352          */
10353         fb = mode_fits_in_fbdev(dev, mode);
10354         if (fb == NULL) {
10355                 DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
10356                 fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
10357                 old->release_fb = fb;
10358         } else
10359                 DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
10360         if (IS_ERR(fb)) {
10361                 DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
10362                 goto fail;
10363         }
10364
10365         ret = intel_modeset_setup_plane_state(state, crtc, mode, fb, 0, 0);
10366         if (ret)
10367                 goto fail;
10368
10369         drm_mode_copy(&crtc_state->base.mode, mode);
10370
10371         if (intel_set_mode(state)) {
10372                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
10373                 if (old->release_fb)
10374                         old->release_fb->funcs->destroy(old->release_fb);
10375                 goto fail;
10376         }
10377         crtc->primary->crtc = crtc;
10378
10379         /* let the connector get through one full cycle before testing */
10380         intel_wait_for_vblank(dev, intel_crtc->pipe);
10381         return true;
10382
10383  fail:
10384         intel_crtc->new_enabled = crtc->state->enable;
10385 fail_unlock:
10386         drm_atomic_state_free(state);
10387         state = NULL;
10388
10389         if (ret == -EDEADLK) {
10390                 drm_modeset_backoff(ctx);
10391                 goto retry;
10392         }
10393
10394         return false;
10395 }
10396
10397 void intel_release_load_detect_pipe(struct drm_connector *connector,
10398                                     struct intel_load_detect_pipe *old,
10399                                     struct drm_modeset_acquire_ctx *ctx)
10400 {
10401         struct drm_device *dev = connector->dev;
10402         struct intel_encoder *intel_encoder =
10403                 intel_attached_encoder(connector);
10404         struct drm_encoder *encoder = &intel_encoder->base;
10405         struct drm_crtc *crtc = encoder->crtc;
10406         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10407         struct drm_atomic_state *state;
10408         struct drm_connector_state *connector_state;
10409         struct intel_crtc_state *crtc_state;
10410         int ret;
10411
10412         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10413                       connector->base.id, connector->name,
10414                       encoder->base.id, encoder->name);
10415
10416         if (old->load_detect_temp) {
10417                 state = drm_atomic_state_alloc(dev);
10418                 if (!state)
10419                         goto fail;
10420
10421                 state->acquire_ctx = ctx;
10422
10423                 connector_state = drm_atomic_get_connector_state(state, connector);
10424                 if (IS_ERR(connector_state))
10425                         goto fail;
10426
10427                 crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10428                 if (IS_ERR(crtc_state))
10429                         goto fail;
10430
10431                 to_intel_connector(connector)->new_encoder = NULL;
10432                 intel_encoder->new_crtc = NULL;
10433                 intel_crtc->new_enabled = false;
10434
10435                 connector_state->best_encoder = NULL;
10436                 connector_state->crtc = NULL;
10437
10438                 crtc_state->base.enable = crtc_state->base.active = false;
10439
10440                 ret = intel_modeset_setup_plane_state(state, crtc, NULL, NULL,
10441                                                       0, 0);
10442                 if (ret)
10443                         goto fail;
10444
10445                 ret = intel_set_mode(state);
10446                 if (ret)
10447                         goto fail;
10448
10449                 if (old->release_fb) {
10450                         drm_framebuffer_unregister_private(old->release_fb);
10451                         drm_framebuffer_unreference(old->release_fb);
10452                 }
10453
10454                 return;
10455         }
10456
10457         /* Switch crtc and encoder back off if necessary */
10458         if (old->dpms_mode != DRM_MODE_DPMS_ON)
10459                 connector->funcs->dpms(connector, old->dpms_mode);
10460
10461         return;
10462 fail:
10463         DRM_DEBUG_KMS("Couldn't release load detect pipe.\n");
10464         drm_atomic_state_free(state);
10465 }
10466
10467 static int i9xx_pll_refclk(struct drm_device *dev,
10468                            const struct intel_crtc_state *pipe_config)
10469 {
10470         struct drm_i915_private *dev_priv = dev->dev_private;
10471         u32 dpll = pipe_config->dpll_hw_state.dpll;
10472
10473         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10474                 return dev_priv->vbt.lvds_ssc_freq;
10475         else if (HAS_PCH_SPLIT(dev))
10476                 return 120000;
10477         else if (!IS_GEN2(dev))
10478                 return 96000;
10479         else
10480                 return 48000;
10481 }
10482
10483 /* Returns the clock of the currently programmed mode of the given pipe. */
10484 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
10485                                 struct intel_crtc_state *pipe_config)
10486 {
10487         struct drm_device *dev = crtc->base.dev;
10488         struct drm_i915_private *dev_priv = dev->dev_private;
10489         int pipe = pipe_config->cpu_transcoder;
10490         u32 dpll = pipe_config->dpll_hw_state.dpll;
10491         u32 fp;
10492         intel_clock_t clock;
10493         int port_clock;
10494         int refclk = i9xx_pll_refclk(dev, pipe_config);
10495
10496         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10497                 fp = pipe_config->dpll_hw_state.fp0;
10498         else
10499                 fp = pipe_config->dpll_hw_state.fp1;
10500
10501         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10502         if (IS_PINEVIEW(dev)) {
10503                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10504                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10505         } else {
10506                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10507                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10508         }
10509
10510         if (!IS_GEN2(dev)) {
10511                 if (IS_PINEVIEW(dev))
10512                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10513                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10514                 else
10515                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10516                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10517
10518                 switch (dpll & DPLL_MODE_MASK) {
10519                 case DPLLB_MODE_DAC_SERIAL:
10520                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10521                                 5 : 10;
10522                         break;
10523                 case DPLLB_MODE_LVDS:
10524                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10525                                 7 : 14;
10526                         break;
10527                 default:
10528                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10529                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10530                         return;
10531                 }
10532
10533                 if (IS_PINEVIEW(dev))
10534                         port_clock = pnv_calc_dpll_params(refclk, &clock);
10535                 else
10536                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
10537         } else {
10538                 u32 lvds = IS_I830(dev) ? 0 : I915_READ(LVDS);
10539                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10540
10541                 if (is_lvds) {
10542                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10543                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10544
10545                         if (lvds & LVDS_CLKB_POWER_UP)
10546                                 clock.p2 = 7;
10547                         else
10548                                 clock.p2 = 14;
10549                 } else {
10550                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10551                                 clock.p1 = 2;
10552                         else {
10553                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10554                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10555                         }
10556                         if (dpll & PLL_P2_DIVIDE_BY_4)
10557                                 clock.p2 = 4;
10558                         else
10559                                 clock.p2 = 2;
10560                 }
10561
10562                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10563         }
10564
10565         /*
10566          * This value includes pixel_multiplier. We will use
10567          * port_clock to compute adjusted_mode.crtc_clock in the
10568          * encoder's get_config() function.
10569          */
10570         pipe_config->port_clock = port_clock;
10571 }
10572
10573 int intel_dotclock_calculate(int link_freq,
10574                              const struct intel_link_m_n *m_n)
10575 {
10576         /*
10577          * The calculation for the data clock is:
10578          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10579          * But we want to avoid losing precison if possible, so:
10580          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10581          *
10582          * and the link clock is simpler:
10583          * link_clock = (m * link_clock) / n
10584          */
10585
10586         if (!m_n->link_n)
10587                 return 0;
10588
10589         return div_u64((u64)m_n->link_m * link_freq, m_n->link_n);
10590 }
10591
10592 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10593                                    struct intel_crtc_state *pipe_config)
10594 {
10595         struct drm_device *dev = crtc->base.dev;
10596
10597         /* read out port_clock from the DPLL */
10598         i9xx_crtc_clock_get(crtc, pipe_config);
10599
10600         /*
10601          * This value does not include pixel_multiplier.
10602          * We will check that port_clock and adjusted_mode.crtc_clock
10603          * agree once we know their relationship in the encoder's
10604          * get_config() function.
10605          */
10606         pipe_config->base.adjusted_mode.crtc_clock =
10607                 intel_dotclock_calculate(intel_fdi_link_freq(dev) * 10000,
10608                                          &pipe_config->fdi_m_n);
10609 }
10610
10611 /** Returns the currently programmed mode of the given pipe. */
10612 struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
10613                                              struct drm_crtc *crtc)
10614 {
10615         struct drm_i915_private *dev_priv = dev->dev_private;
10616         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10617         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
10618         struct drm_display_mode *mode;
10619         struct intel_crtc_state pipe_config;
10620         int htot = I915_READ(HTOTAL(cpu_transcoder));
10621         int hsync = I915_READ(HSYNC(cpu_transcoder));
10622         int vtot = I915_READ(VTOTAL(cpu_transcoder));
10623         int vsync = I915_READ(VSYNC(cpu_transcoder));
10624         enum pipe pipe = intel_crtc->pipe;
10625
10626         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10627         if (!mode)
10628                 return NULL;
10629
10630         /*
10631          * Construct a pipe_config sufficient for getting the clock info
10632          * back out of crtc_clock_get.
10633          *
10634          * Note, if LVDS ever uses a non-1 pixel multiplier, we'll need
10635          * to use a real value here instead.
10636          */
10637         pipe_config.cpu_transcoder = (enum transcoder) pipe;
10638         pipe_config.pixel_multiplier = 1;
10639         pipe_config.dpll_hw_state.dpll = I915_READ(DPLL(pipe));
10640         pipe_config.dpll_hw_state.fp0 = I915_READ(FP0(pipe));
10641         pipe_config.dpll_hw_state.fp1 = I915_READ(FP1(pipe));
10642         i9xx_crtc_clock_get(intel_crtc, &pipe_config);
10643
10644         mode->clock = pipe_config.port_clock / pipe_config.pixel_multiplier;
10645         mode->hdisplay = (htot & 0xffff) + 1;
10646         mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
10647         mode->hsync_start = (hsync & 0xffff) + 1;
10648         mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
10649         mode->vdisplay = (vtot & 0xffff) + 1;
10650         mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
10651         mode->vsync_start = (vsync & 0xffff) + 1;
10652         mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
10653
10654         drm_mode_set_name(mode);
10655
10656         return mode;
10657 }
10658
10659 void intel_mark_busy(struct drm_device *dev)
10660 {
10661         struct drm_i915_private *dev_priv = dev->dev_private;
10662
10663         if (dev_priv->mm.busy)
10664                 return;
10665
10666         intel_runtime_pm_get(dev_priv);
10667         i915_update_gfx_val(dev_priv);
10668         if (INTEL_INFO(dev)->gen >= 6)
10669                 gen6_rps_busy(dev_priv);
10670         dev_priv->mm.busy = true;
10671 }
10672
10673 void intel_mark_idle(struct drm_device *dev)
10674 {
10675         struct drm_i915_private *dev_priv = dev->dev_private;
10676
10677         if (!dev_priv->mm.busy)
10678                 return;
10679
10680         dev_priv->mm.busy = false;
10681
10682         if (INTEL_INFO(dev)->gen >= 6)
10683                 gen6_rps_idle(dev->dev_private);
10684
10685         intel_runtime_pm_put(dev_priv);
10686 }
10687
10688 static void intel_crtc_destroy(struct drm_crtc *crtc)
10689 {
10690         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10691         struct drm_device *dev = crtc->dev;
10692         struct intel_unpin_work *work;
10693
10694         spin_lock_irq(&dev->event_lock);
10695         work = intel_crtc->unpin_work;
10696         intel_crtc->unpin_work = NULL;
10697         spin_unlock_irq(&dev->event_lock);
10698
10699         if (work) {
10700                 cancel_work_sync(&work->work);
10701                 kfree(work);
10702         }
10703
10704         drm_crtc_cleanup(crtc);
10705
10706         kfree(intel_crtc);
10707 }
10708
10709 static void intel_unpin_work_fn(struct work_struct *__work)
10710 {
10711         struct intel_unpin_work *work =
10712                 container_of(__work, struct intel_unpin_work, work);
10713         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
10714         struct drm_device *dev = crtc->base.dev;
10715         struct drm_i915_private *dev_priv = dev->dev_private;
10716         struct drm_plane *primary = crtc->base.primary;
10717
10718         mutex_lock(&dev->struct_mutex);
10719         intel_unpin_fb_obj(work->old_fb, primary->state);
10720         drm_gem_object_unreference(&work->pending_flip_obj->base);
10721
10722         intel_fbc_update(dev_priv);
10723
10724         if (work->flip_queued_req)
10725                 i915_gem_request_assign(&work->flip_queued_req, NULL);
10726         mutex_unlock(&dev->struct_mutex);
10727
10728         intel_frontbuffer_flip_complete(dev, to_intel_plane(primary)->frontbuffer_bit);
10729         drm_framebuffer_unreference(work->old_fb);
10730
10731         BUG_ON(atomic_read(&crtc->unpin_work_count) == 0);
10732         atomic_dec(&crtc->unpin_work_count);
10733
10734         kfree(work);
10735 }
10736
10737 static void do_intel_finish_page_flip(struct drm_device *dev,
10738                                       struct drm_crtc *crtc)
10739 {
10740         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10741         struct intel_unpin_work *work;
10742         unsigned long flags;
10743
10744         /* Ignore early vblank irqs */
10745         if (intel_crtc == NULL)
10746                 return;
10747
10748         /*
10749          * This is called both by irq handlers and the reset code (to complete
10750          * lost pageflips) so needs the full irqsave spinlocks.
10751          */
10752         spin_lock_irqsave(&dev->event_lock, flags);
10753         work = intel_crtc->unpin_work;
10754
10755         /* Ensure we don't miss a work->pending update ... */
10756         smp_rmb();
10757
10758         if (work == NULL || atomic_read(&work->pending) < INTEL_FLIP_COMPLETE) {
10759                 spin_unlock_irqrestore(&dev->event_lock, flags);
10760                 return;
10761         }
10762
10763         page_flip_completed(intel_crtc);
10764
10765         spin_unlock_irqrestore(&dev->event_lock, flags);
10766 }
10767
10768 void intel_finish_page_flip(struct drm_device *dev, int pipe)
10769 {
10770         struct drm_i915_private *dev_priv = dev->dev_private;
10771         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
10772
10773         do_intel_finish_page_flip(dev, crtc);
10774 }
10775
10776 void intel_finish_page_flip_plane(struct drm_device *dev, int plane)
10777 {
10778         struct drm_i915_private *dev_priv = dev->dev_private;
10779         struct drm_crtc *crtc = dev_priv->plane_to_crtc_mapping[plane];
10780
10781         do_intel_finish_page_flip(dev, crtc);
10782 }
10783
10784 /* Is 'a' after or equal to 'b'? */
10785 static bool g4x_flip_count_after_eq(u32 a, u32 b)
10786 {
10787         return !((a - b) & 0x80000000);
10788 }
10789
10790 static bool page_flip_finished(struct intel_crtc *crtc)
10791 {
10792         struct drm_device *dev = crtc->base.dev;
10793         struct drm_i915_private *dev_priv = dev->dev_private;
10794
10795         if (i915_reset_in_progress(&dev_priv->gpu_error) ||
10796             crtc->reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
10797                 return true;
10798
10799         /*
10800          * The relevant registers doen't exist on pre-ctg.
10801          * As the flip done interrupt doesn't trigger for mmio
10802          * flips on gmch platforms, a flip count check isn't
10803          * really needed there. But since ctg has the registers,
10804          * include it in the check anyway.
10805          */
10806         if (INTEL_INFO(dev)->gen < 5 && !IS_G4X(dev))
10807                 return true;
10808
10809         /*
10810          * A DSPSURFLIVE check isn't enough in case the mmio and CS flips
10811          * used the same base address. In that case the mmio flip might
10812          * have completed, but the CS hasn't even executed the flip yet.
10813          *
10814          * A flip count check isn't enough as the CS might have updated
10815          * the base address just after start of vblank, but before we
10816          * managed to process the interrupt. This means we'd complete the
10817          * CS flip too soon.
10818          *
10819          * Combining both checks should get us a good enough result. It may
10820          * still happen that the CS flip has been executed, but has not
10821          * yet actually completed. But in case the base address is the same
10822          * anyway, we don't really care.
10823          */
10824         return (I915_READ(DSPSURFLIVE(crtc->plane)) & ~0xfff) ==
10825                 crtc->unpin_work->gtt_offset &&
10826                 g4x_flip_count_after_eq(I915_READ(PIPE_FLIPCOUNT_GM45(crtc->pipe)),
10827                                     crtc->unpin_work->flip_count);
10828 }
10829
10830 void intel_prepare_page_flip(struct drm_device *dev, int plane)
10831 {
10832         struct drm_i915_private *dev_priv = dev->dev_private;
10833         struct intel_crtc *intel_crtc =
10834                 to_intel_crtc(dev_priv->plane_to_crtc_mapping[plane]);
10835         unsigned long flags;
10836
10837
10838         /*
10839          * This is called both by irq handlers and the reset code (to complete
10840          * lost pageflips) so needs the full irqsave spinlocks.
10841          *
10842          * NB: An MMIO update of the plane base pointer will also
10843          * generate a page-flip completion irq, i.e. every modeset
10844          * is also accompanied by a spurious intel_prepare_page_flip().
10845          */
10846         spin_lock_irqsave(&dev->event_lock, flags);
10847         if (intel_crtc->unpin_work && page_flip_finished(intel_crtc))
10848                 atomic_inc_not_zero(&intel_crtc->unpin_work->pending);
10849         spin_unlock_irqrestore(&dev->event_lock, flags);
10850 }
10851
10852 static inline void intel_mark_page_flip_active(struct intel_crtc *intel_crtc)
10853 {
10854         /* Ensure that the work item is consistent when activating it ... */
10855         smp_wmb();
10856         atomic_set(&intel_crtc->unpin_work->pending, INTEL_FLIP_PENDING);
10857         /* and that it is marked active as soon as the irq could fire. */
10858         smp_wmb();
10859 }
10860
10861 static int intel_gen2_queue_flip(struct drm_device *dev,
10862                                  struct drm_crtc *crtc,
10863                                  struct drm_framebuffer *fb,
10864                                  struct drm_i915_gem_object *obj,
10865                                  struct drm_i915_gem_request *req,
10866                                  uint32_t flags)
10867 {
10868         struct intel_engine_cs *ring = req->ring;
10869         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10870         u32 flip_mask;
10871         int ret;
10872
10873         ret = intel_ring_begin(req, 6);
10874         if (ret)
10875                 return ret;
10876
10877         /* Can't queue multiple flips, so wait for the previous
10878          * one to finish before executing the next.
10879          */
10880         if (intel_crtc->plane)
10881                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
10882         else
10883                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
10884         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
10885         intel_ring_emit(ring, MI_NOOP);
10886         intel_ring_emit(ring, MI_DISPLAY_FLIP |
10887                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
10888         intel_ring_emit(ring, fb->pitches[0]);
10889         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
10890         intel_ring_emit(ring, 0); /* aux display base address, unused */
10891
10892         intel_mark_page_flip_active(intel_crtc);
10893         return 0;
10894 }
10895
10896 static int intel_gen3_queue_flip(struct drm_device *dev,
10897                                  struct drm_crtc *crtc,
10898                                  struct drm_framebuffer *fb,
10899                                  struct drm_i915_gem_object *obj,
10900                                  struct drm_i915_gem_request *req,
10901                                  uint32_t flags)
10902 {
10903         struct intel_engine_cs *ring = req->ring;
10904         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10905         u32 flip_mask;
10906         int ret;
10907
10908         ret = intel_ring_begin(req, 6);
10909         if (ret)
10910                 return ret;
10911
10912         if (intel_crtc->plane)
10913                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
10914         else
10915                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
10916         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
10917         intel_ring_emit(ring, MI_NOOP);
10918         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 |
10919                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
10920         intel_ring_emit(ring, fb->pitches[0]);
10921         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
10922         intel_ring_emit(ring, MI_NOOP);
10923
10924         intel_mark_page_flip_active(intel_crtc);
10925         return 0;
10926 }
10927
10928 static int intel_gen4_queue_flip(struct drm_device *dev,
10929                                  struct drm_crtc *crtc,
10930                                  struct drm_framebuffer *fb,
10931                                  struct drm_i915_gem_object *obj,
10932                                  struct drm_i915_gem_request *req,
10933                                  uint32_t flags)
10934 {
10935         struct intel_engine_cs *ring = req->ring;
10936         struct drm_i915_private *dev_priv = dev->dev_private;
10937         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10938         uint32_t pf, pipesrc;
10939         int ret;
10940
10941         ret = intel_ring_begin(req, 4);
10942         if (ret)
10943                 return ret;
10944
10945         /* i965+ uses the linear or tiled offsets from the
10946          * Display Registers (which do not change across a page-flip)
10947          * so we need only reprogram the base address.
10948          */
10949         intel_ring_emit(ring, MI_DISPLAY_FLIP |
10950                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
10951         intel_ring_emit(ring, fb->pitches[0]);
10952         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset |
10953                         obj->tiling_mode);
10954
10955         /* XXX Enabling the panel-fitter across page-flip is so far
10956          * untested on non-native modes, so ignore it for now.
10957          * pf = I915_READ(pipe == 0 ? PFA_CTL_1 : PFB_CTL_1) & PF_ENABLE;
10958          */
10959         pf = 0;
10960         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
10961         intel_ring_emit(ring, pf | pipesrc);
10962
10963         intel_mark_page_flip_active(intel_crtc);
10964         return 0;
10965 }
10966
10967 static int intel_gen6_queue_flip(struct drm_device *dev,
10968                                  struct drm_crtc *crtc,
10969                                  struct drm_framebuffer *fb,
10970                                  struct drm_i915_gem_object *obj,
10971                                  struct drm_i915_gem_request *req,
10972                                  uint32_t flags)
10973 {
10974         struct intel_engine_cs *ring = req->ring;
10975         struct drm_i915_private *dev_priv = dev->dev_private;
10976         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10977         uint32_t pf, pipesrc;
10978         int ret;
10979
10980         ret = intel_ring_begin(req, 4);
10981         if (ret)
10982                 return ret;
10983
10984         intel_ring_emit(ring, MI_DISPLAY_FLIP |
10985                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
10986         intel_ring_emit(ring, fb->pitches[0] | obj->tiling_mode);
10987         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
10988
10989         /* Contrary to the suggestions in the documentation,
10990          * "Enable Panel Fitter" does not seem to be required when page
10991          * flipping with a non-native mode, and worse causes a normal
10992          * modeset to fail.
10993          * pf = I915_READ(PF_CTL(intel_crtc->pipe)) & PF_ENABLE;
10994          */
10995         pf = 0;
10996         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
10997         intel_ring_emit(ring, pf | pipesrc);
10998
10999         intel_mark_page_flip_active(intel_crtc);
11000         return 0;
11001 }
11002
11003 static int intel_gen7_queue_flip(struct drm_device *dev,
11004                                  struct drm_crtc *crtc,
11005                                  struct drm_framebuffer *fb,
11006                                  struct drm_i915_gem_object *obj,
11007                                  struct drm_i915_gem_request *req,
11008                                  uint32_t flags)
11009 {
11010         struct intel_engine_cs *ring = req->ring;
11011         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11012         uint32_t plane_bit = 0;
11013         int len, ret;
11014
11015         switch (intel_crtc->plane) {
11016         case PLANE_A:
11017                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_A;
11018                 break;
11019         case PLANE_B:
11020                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_B;
11021                 break;
11022         case PLANE_C:
11023                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_C;
11024                 break;
11025         default:
11026                 WARN_ONCE(1, "unknown plane in flip command\n");
11027                 return -ENODEV;
11028         }
11029
11030         len = 4;
11031         if (ring->id == RCS) {
11032                 len += 6;
11033                 /*
11034                  * On Gen 8, SRM is now taking an extra dword to accommodate
11035                  * 48bits addresses, and we need a NOOP for the batch size to
11036                  * stay even.
11037                  */
11038                 if (IS_GEN8(dev))
11039                         len += 2;
11040         }
11041
11042         /*
11043          * BSpec MI_DISPLAY_FLIP for IVB:
11044          * "The full packet must be contained within the same cache line."
11045          *
11046          * Currently the LRI+SRM+MI_DISPLAY_FLIP all fit within the same
11047          * cacheline, if we ever start emitting more commands before
11048          * the MI_DISPLAY_FLIP we may need to first emit everything else,
11049          * then do the cacheline alignment, and finally emit the
11050          * MI_DISPLAY_FLIP.
11051          */
11052         ret = intel_ring_cacheline_align(req);
11053         if (ret)
11054                 return ret;
11055
11056         ret = intel_ring_begin(req, len);
11057         if (ret)
11058                 return ret;
11059
11060         /* Unmask the flip-done completion message. Note that the bspec says that
11061          * we should do this for both the BCS and RCS, and that we must not unmask
11062          * more than one flip event at any time (or ensure that one flip message
11063          * can be sent by waiting for flip-done prior to queueing new flips).
11064          * Experimentation says that BCS works despite DERRMR masking all
11065          * flip-done completion events and that unmasking all planes at once
11066          * for the RCS also doesn't appear to drop events. Setting the DERRMR
11067          * to zero does lead to lockups within MI_DISPLAY_FLIP.
11068          */
11069         if (ring->id == RCS) {
11070                 intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
11071                 intel_ring_emit(ring, DERRMR);
11072                 intel_ring_emit(ring, ~(DERRMR_PIPEA_PRI_FLIP_DONE |
11073                                         DERRMR_PIPEB_PRI_FLIP_DONE |
11074                                         DERRMR_PIPEC_PRI_FLIP_DONE));
11075                 if (IS_GEN8(dev))
11076                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM_GEN8(1) |
11077                                               MI_SRM_LRM_GLOBAL_GTT);
11078                 else
11079                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM(1) |
11080                                               MI_SRM_LRM_GLOBAL_GTT);
11081                 intel_ring_emit(ring, DERRMR);
11082                 intel_ring_emit(ring, ring->scratch.gtt_offset + 256);
11083                 if (IS_GEN8(dev)) {
11084                         intel_ring_emit(ring, 0);
11085                         intel_ring_emit(ring, MI_NOOP);
11086                 }
11087         }
11088
11089         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 | plane_bit);
11090         intel_ring_emit(ring, (fb->pitches[0] | obj->tiling_mode));
11091         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
11092         intel_ring_emit(ring, (MI_NOOP));
11093
11094         intel_mark_page_flip_active(intel_crtc);
11095         return 0;
11096 }
11097
11098 static bool use_mmio_flip(struct intel_engine_cs *ring,
11099                           struct drm_i915_gem_object *obj)
11100 {
11101         /*
11102          * This is not being used for older platforms, because
11103          * non-availability of flip done interrupt forces us to use
11104          * CS flips. Older platforms derive flip done using some clever
11105          * tricks involving the flip_pending status bits and vblank irqs.
11106          * So using MMIO flips there would disrupt this mechanism.
11107          */
11108
11109         if (ring == NULL)
11110                 return true;
11111
11112         if (INTEL_INFO(ring->dev)->gen < 5)
11113                 return false;
11114
11115         if (i915.use_mmio_flip < 0)
11116                 return false;
11117         else if (i915.use_mmio_flip > 0)
11118                 return true;
11119         else if (i915.enable_execlists)
11120                 return true;
11121         else
11122                 return ring != i915_gem_request_get_ring(obj->last_write_req);
11123 }
11124
11125 static void skl_do_mmio_flip(struct intel_crtc *intel_crtc)
11126 {
11127         struct drm_device *dev = intel_crtc->base.dev;
11128         struct drm_i915_private *dev_priv = dev->dev_private;
11129         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
11130         const enum pipe pipe = intel_crtc->pipe;
11131         u32 ctl, stride;
11132
11133         ctl = I915_READ(PLANE_CTL(pipe, 0));
11134         ctl &= ~PLANE_CTL_TILED_MASK;
11135         switch (fb->modifier[0]) {
11136         case DRM_FORMAT_MOD_NONE:
11137                 break;
11138         case I915_FORMAT_MOD_X_TILED:
11139                 ctl |= PLANE_CTL_TILED_X;
11140                 break;
11141         case I915_FORMAT_MOD_Y_TILED:
11142                 ctl |= PLANE_CTL_TILED_Y;
11143                 break;
11144         case I915_FORMAT_MOD_Yf_TILED:
11145                 ctl |= PLANE_CTL_TILED_YF;
11146                 break;
11147         default:
11148                 MISSING_CASE(fb->modifier[0]);
11149         }
11150
11151         /*
11152          * The stride is either expressed as a multiple of 64 bytes chunks for
11153          * linear buffers or in number of tiles for tiled buffers.
11154          */
11155         stride = fb->pitches[0] /
11156                  intel_fb_stride_alignment(dev, fb->modifier[0],
11157                                            fb->pixel_format);
11158
11159         /*
11160          * Both PLANE_CTL and PLANE_STRIDE are not updated on vblank but on
11161          * PLANE_SURF updates, the update is then guaranteed to be atomic.
11162          */
11163         I915_WRITE(PLANE_CTL(pipe, 0), ctl);
11164         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
11165
11166         I915_WRITE(PLANE_SURF(pipe, 0), intel_crtc->unpin_work->gtt_offset);
11167         POSTING_READ(PLANE_SURF(pipe, 0));
11168 }
11169
11170 static void ilk_do_mmio_flip(struct intel_crtc *intel_crtc)
11171 {
11172         struct drm_device *dev = intel_crtc->base.dev;
11173         struct drm_i915_private *dev_priv = dev->dev_private;
11174         struct intel_framebuffer *intel_fb =
11175                 to_intel_framebuffer(intel_crtc->base.primary->fb);
11176         struct drm_i915_gem_object *obj = intel_fb->obj;
11177         u32 dspcntr;
11178         u32 reg;
11179
11180         reg = DSPCNTR(intel_crtc->plane);
11181         dspcntr = I915_READ(reg);
11182
11183         if (obj->tiling_mode != I915_TILING_NONE)
11184                 dspcntr |= DISPPLANE_TILED;
11185         else
11186                 dspcntr &= ~DISPPLANE_TILED;
11187
11188         I915_WRITE(reg, dspcntr);
11189
11190         I915_WRITE(DSPSURF(intel_crtc->plane),
11191                    intel_crtc->unpin_work->gtt_offset);
11192         POSTING_READ(DSPSURF(intel_crtc->plane));
11193
11194 }
11195
11196 /*
11197  * XXX: This is the temporary way to update the plane registers until we get
11198  * around to using the usual plane update functions for MMIO flips
11199  */
11200 static void intel_do_mmio_flip(struct intel_crtc *intel_crtc)
11201 {
11202         struct drm_device *dev = intel_crtc->base.dev;
11203         bool atomic_update;
11204         u32 start_vbl_count;
11205
11206         intel_mark_page_flip_active(intel_crtc);
11207
11208         atomic_update = intel_pipe_update_start(intel_crtc, &start_vbl_count);
11209
11210         if (INTEL_INFO(dev)->gen >= 9)
11211                 skl_do_mmio_flip(intel_crtc);
11212         else
11213                 /* use_mmio_flip() retricts MMIO flips to ilk+ */
11214                 ilk_do_mmio_flip(intel_crtc);
11215
11216         if (atomic_update)
11217                 intel_pipe_update_end(intel_crtc, start_vbl_count);
11218 }
11219
11220 static void intel_mmio_flip_work_func(struct work_struct *work)
11221 {
11222         struct intel_mmio_flip *mmio_flip =
11223                 container_of(work, struct intel_mmio_flip, work);
11224
11225         if (mmio_flip->req)
11226                 WARN_ON(__i915_wait_request(mmio_flip->req,
11227                                             mmio_flip->crtc->reset_counter,
11228                                             false, NULL,
11229                                             &mmio_flip->i915->rps.mmioflips));
11230
11231         intel_do_mmio_flip(mmio_flip->crtc);
11232
11233         i915_gem_request_unreference__unlocked(mmio_flip->req);
11234         kfree(mmio_flip);
11235 }
11236
11237 static int intel_queue_mmio_flip(struct drm_device *dev,
11238                                  struct drm_crtc *crtc,
11239                                  struct drm_framebuffer *fb,
11240                                  struct drm_i915_gem_object *obj,
11241                                  struct intel_engine_cs *ring,
11242                                  uint32_t flags)
11243 {
11244         struct intel_mmio_flip *mmio_flip;
11245
11246         mmio_flip = kmalloc(sizeof(*mmio_flip), GFP_KERNEL);
11247         if (mmio_flip == NULL)
11248                 return -ENOMEM;
11249
11250         mmio_flip->i915 = to_i915(dev);
11251         mmio_flip->req = i915_gem_request_reference(obj->last_write_req);
11252         mmio_flip->crtc = to_intel_crtc(crtc);
11253
11254         INIT_WORK(&mmio_flip->work, intel_mmio_flip_work_func);
11255         schedule_work(&mmio_flip->work);
11256
11257         return 0;
11258 }
11259
11260 static int intel_default_queue_flip(struct drm_device *dev,
11261                                     struct drm_crtc *crtc,
11262                                     struct drm_framebuffer *fb,
11263                                     struct drm_i915_gem_object *obj,
11264                                     struct drm_i915_gem_request *req,
11265                                     uint32_t flags)
11266 {
11267         return -ENODEV;
11268 }
11269
11270 static bool __intel_pageflip_stall_check(struct drm_device *dev,
11271                                          struct drm_crtc *crtc)
11272 {
11273         struct drm_i915_private *dev_priv = dev->dev_private;
11274         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11275         struct intel_unpin_work *work = intel_crtc->unpin_work;
11276         u32 addr;
11277
11278         if (atomic_read(&work->pending) >= INTEL_FLIP_COMPLETE)
11279                 return true;
11280
11281         if (!work->enable_stall_check)
11282                 return false;
11283
11284         if (work->flip_ready_vblank == 0) {
11285                 if (work->flip_queued_req &&
11286                     !i915_gem_request_completed(work->flip_queued_req, true))
11287                         return false;
11288
11289                 work->flip_ready_vblank = drm_crtc_vblank_count(crtc);
11290         }
11291
11292         if (drm_crtc_vblank_count(crtc) - work->flip_ready_vblank < 3)
11293                 return false;
11294
11295         /* Potential stall - if we see that the flip has happened,
11296          * assume a missed interrupt. */
11297         if (INTEL_INFO(dev)->gen >= 4)
11298                 addr = I915_HI_DISPBASE(I915_READ(DSPSURF(intel_crtc->plane)));
11299         else
11300                 addr = I915_READ(DSPADDR(intel_crtc->plane));
11301
11302         /* There is a potential issue here with a false positive after a flip
11303          * to the same address. We could address this by checking for a
11304          * non-incrementing frame counter.
11305          */
11306         return addr == work->gtt_offset;
11307 }
11308
11309 void intel_check_page_flip(struct drm_device *dev, int pipe)
11310 {
11311         struct drm_i915_private *dev_priv = dev->dev_private;
11312         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11313         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11314         struct intel_unpin_work *work;
11315
11316         WARN_ON(!in_interrupt());
11317
11318         if (crtc == NULL)
11319                 return;
11320
11321         spin_lock(&dev->event_lock);
11322         work = intel_crtc->unpin_work;
11323         if (work != NULL && __intel_pageflip_stall_check(dev, crtc)) {
11324                 WARN_ONCE(1, "Kicking stuck page flip: queued at %d, now %d\n",
11325                          work->flip_queued_vblank, drm_vblank_count(dev, pipe));
11326                 page_flip_completed(intel_crtc);
11327                 work = NULL;
11328         }
11329         if (work != NULL &&
11330             drm_vblank_count(dev, pipe) - work->flip_queued_vblank > 1)
11331                 intel_queue_rps_boost_for_request(dev, work->flip_queued_req);
11332         spin_unlock(&dev->event_lock);
11333 }
11334
11335 static int intel_crtc_page_flip(struct drm_crtc *crtc,
11336                                 struct drm_framebuffer *fb,
11337                                 struct drm_pending_vblank_event *event,
11338                                 uint32_t page_flip_flags)
11339 {
11340         struct drm_device *dev = crtc->dev;
11341         struct drm_i915_private *dev_priv = dev->dev_private;
11342         struct drm_framebuffer *old_fb = crtc->primary->fb;
11343         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
11344         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11345         struct drm_plane *primary = crtc->primary;
11346         enum pipe pipe = intel_crtc->pipe;
11347         struct intel_unpin_work *work;
11348         struct intel_engine_cs *ring;
11349         bool mmio_flip;
11350         struct drm_i915_gem_request *request = NULL;
11351         int ret;
11352
11353         /*
11354          * drm_mode_page_flip_ioctl() should already catch this, but double
11355          * check to be safe.  In the future we may enable pageflipping from
11356          * a disabled primary plane.
11357          */
11358         if (WARN_ON(intel_fb_obj(old_fb) == NULL))
11359                 return -EBUSY;
11360
11361         /* Can't change pixel format via MI display flips. */
11362         if (fb->pixel_format != crtc->primary->fb->pixel_format)
11363                 return -EINVAL;
11364
11365         /*
11366          * TILEOFF/LINOFF registers can't be changed via MI display flips.
11367          * Note that pitch changes could also affect these register.
11368          */
11369         if (INTEL_INFO(dev)->gen > 3 &&
11370             (fb->offsets[0] != crtc->primary->fb->offsets[0] ||
11371              fb->pitches[0] != crtc->primary->fb->pitches[0]))
11372                 return -EINVAL;
11373
11374         if (i915_terminally_wedged(&dev_priv->gpu_error))
11375                 goto out_hang;
11376
11377         work = kzalloc(sizeof(*work), GFP_KERNEL);
11378         if (work == NULL)
11379                 return -ENOMEM;
11380
11381         work->event = event;
11382         work->crtc = crtc;
11383         work->old_fb = old_fb;
11384         INIT_WORK(&work->work, intel_unpin_work_fn);
11385
11386         ret = drm_crtc_vblank_get(crtc);
11387         if (ret)
11388                 goto free_work;
11389
11390         /* We borrow the event spin lock for protecting unpin_work */
11391         spin_lock_irq(&dev->event_lock);
11392         if (intel_crtc->unpin_work) {
11393                 /* Before declaring the flip queue wedged, check if
11394                  * the hardware completed the operation behind our backs.
11395                  */
11396                 if (__intel_pageflip_stall_check(dev, crtc)) {
11397                         DRM_DEBUG_DRIVER("flip queue: previous flip completed, continuing\n");
11398                         page_flip_completed(intel_crtc);
11399                 } else {
11400                         DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
11401                         spin_unlock_irq(&dev->event_lock);
11402
11403                         drm_crtc_vblank_put(crtc);
11404                         kfree(work);
11405                         return -EBUSY;
11406                 }
11407         }
11408         intel_crtc->unpin_work = work;
11409         spin_unlock_irq(&dev->event_lock);
11410
11411         if (atomic_read(&intel_crtc->unpin_work_count) >= 2)
11412                 flush_workqueue(dev_priv->wq);
11413
11414         /* Reference the objects for the scheduled work. */
11415         drm_framebuffer_reference(work->old_fb);
11416         drm_gem_object_reference(&obj->base);
11417
11418         crtc->primary->fb = fb;
11419         update_state_fb(crtc->primary);
11420
11421         work->pending_flip_obj = obj;
11422
11423         ret = i915_mutex_lock_interruptible(dev);
11424         if (ret)
11425                 goto cleanup;
11426
11427         atomic_inc(&intel_crtc->unpin_work_count);
11428         intel_crtc->reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
11429
11430         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
11431                 work->flip_count = I915_READ(PIPE_FLIPCOUNT_GM45(pipe)) + 1;
11432
11433         if (IS_VALLEYVIEW(dev)) {
11434                 ring = &dev_priv->ring[BCS];
11435                 if (obj->tiling_mode != intel_fb_obj(work->old_fb)->tiling_mode)
11436                         /* vlv: DISPLAY_FLIP fails to change tiling */
11437                         ring = NULL;
11438         } else if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev)) {
11439                 ring = &dev_priv->ring[BCS];
11440         } else if (INTEL_INFO(dev)->gen >= 7) {
11441                 ring = i915_gem_request_get_ring(obj->last_write_req);
11442                 if (ring == NULL || ring->id != RCS)
11443                         ring = &dev_priv->ring[BCS];
11444         } else {
11445                 ring = &dev_priv->ring[RCS];
11446         }
11447
11448         mmio_flip = use_mmio_flip(ring, obj);
11449
11450         /* When using CS flips, we want to emit semaphores between rings.
11451          * However, when using mmio flips we will create a task to do the
11452          * synchronisation, so all we want here is to pin the framebuffer
11453          * into the display plane and skip any waits.
11454          */
11455         ret = intel_pin_and_fence_fb_obj(crtc->primary, fb,
11456                                          crtc->primary->state,
11457                                          mmio_flip ? i915_gem_request_get_ring(obj->last_write_req) : ring, &request);
11458         if (ret)
11459                 goto cleanup_pending;
11460
11461         work->gtt_offset = intel_plane_obj_offset(to_intel_plane(primary), obj)
11462                                                   + intel_crtc->dspaddr_offset;
11463
11464         if (mmio_flip) {
11465                 ret = intel_queue_mmio_flip(dev, crtc, fb, obj, ring,
11466                                             page_flip_flags);
11467                 if (ret)
11468                         goto cleanup_unpin;
11469
11470                 i915_gem_request_assign(&work->flip_queued_req,
11471                                         obj->last_write_req);
11472         } else {
11473                 if (!request) {
11474                         ret = i915_gem_request_alloc(ring, ring->default_context, &request);
11475                         if (ret)
11476                                 goto cleanup_unpin;
11477                 }
11478
11479                 ret = dev_priv->display.queue_flip(dev, crtc, fb, obj, request,
11480                                                    page_flip_flags);
11481                 if (ret)
11482                         goto cleanup_unpin;
11483
11484                 i915_gem_request_assign(&work->flip_queued_req, request);
11485         }
11486
11487         if (request)
11488                 i915_add_request_no_flush(request);
11489
11490         work->flip_queued_vblank = drm_crtc_vblank_count(crtc);
11491         work->enable_stall_check = true;
11492
11493         i915_gem_track_fb(intel_fb_obj(work->old_fb), obj,
11494                           to_intel_plane(primary)->frontbuffer_bit);
11495         mutex_unlock(&dev->struct_mutex);
11496
11497         intel_fbc_disable(dev_priv);
11498         intel_frontbuffer_flip_prepare(dev,
11499                                        to_intel_plane(primary)->frontbuffer_bit);
11500
11501         trace_i915_flip_request(intel_crtc->plane, obj);
11502
11503         return 0;
11504
11505 cleanup_unpin:
11506         intel_unpin_fb_obj(fb, crtc->primary->state);
11507 cleanup_pending:
11508         if (request)
11509                 i915_gem_request_cancel(request);
11510         atomic_dec(&intel_crtc->unpin_work_count);
11511         mutex_unlock(&dev->struct_mutex);
11512 cleanup:
11513         crtc->primary->fb = old_fb;
11514         update_state_fb(crtc->primary);
11515
11516         drm_gem_object_unreference_unlocked(&obj->base);
11517         drm_framebuffer_unreference(work->old_fb);
11518
11519         spin_lock_irq(&dev->event_lock);
11520         intel_crtc->unpin_work = NULL;
11521         spin_unlock_irq(&dev->event_lock);
11522
11523         drm_crtc_vblank_put(crtc);
11524 free_work:
11525         kfree(work);
11526
11527         if (ret == -EIO) {
11528                 struct drm_atomic_state *state;
11529                 struct drm_plane_state *plane_state;
11530
11531 out_hang:
11532                 state = drm_atomic_state_alloc(dev);
11533                 if (!state)
11534                         return -ENOMEM;
11535                 state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
11536
11537 retry:
11538                 plane_state = drm_atomic_get_plane_state(state, primary);
11539                 ret = PTR_ERR_OR_ZERO(plane_state);
11540                 if (!ret) {
11541                         drm_atomic_set_fb_for_plane(plane_state, fb);
11542
11543                         ret = drm_atomic_set_crtc_for_plane(plane_state, crtc);
11544                         if (!ret)
11545                                 ret = drm_atomic_commit(state);
11546                 }
11547
11548                 if (ret == -EDEADLK) {
11549                         drm_modeset_backoff(state->acquire_ctx);
11550                         drm_atomic_state_clear(state);
11551                         goto retry;
11552                 }
11553
11554                 if (ret)
11555                         drm_atomic_state_free(state);
11556
11557                 if (ret == 0 && event) {
11558                         spin_lock_irq(&dev->event_lock);
11559                         drm_send_vblank_event(dev, pipe, event);
11560                         spin_unlock_irq(&dev->event_lock);
11561                 }
11562         }
11563         return ret;
11564 }
11565
11566
11567 /**
11568  * intel_wm_need_update - Check whether watermarks need updating
11569  * @plane: drm plane
11570  * @state: new plane state
11571  *
11572  * Check current plane state versus the new one to determine whether
11573  * watermarks need to be recalculated.
11574  *
11575  * Returns true or false.
11576  */
11577 static bool intel_wm_need_update(struct drm_plane *plane,
11578                                  struct drm_plane_state *state)
11579 {
11580         /* Update watermarks on tiling changes. */
11581         if (!plane->state->fb || !state->fb ||
11582             plane->state->fb->modifier[0] != state->fb->modifier[0] ||
11583             plane->state->rotation != state->rotation)
11584                 return true;
11585
11586         if (plane->state->crtc_w != state->crtc_w)
11587                 return true;
11588
11589         return false;
11590 }
11591
11592 int intel_plane_atomic_calc_changes(struct drm_crtc_state *crtc_state,
11593                                     struct drm_plane_state *plane_state)
11594 {
11595         struct drm_crtc *crtc = crtc_state->crtc;
11596         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11597         struct drm_plane *plane = plane_state->plane;
11598         struct drm_device *dev = crtc->dev;
11599         struct drm_i915_private *dev_priv = dev->dev_private;
11600         struct intel_plane_state *old_plane_state =
11601                 to_intel_plane_state(plane->state);
11602         int idx = intel_crtc->base.base.id, ret;
11603         int i = drm_plane_index(plane);
11604         bool mode_changed = needs_modeset(crtc_state);
11605         bool was_crtc_enabled = crtc->state->active;
11606         bool is_crtc_enabled = crtc_state->active;
11607
11608         bool turn_off, turn_on, visible, was_visible;
11609         struct drm_framebuffer *fb = plane_state->fb;
11610
11611         if (crtc_state && INTEL_INFO(dev)->gen >= 9 &&
11612             plane->type != DRM_PLANE_TYPE_CURSOR) {
11613                 ret = skl_update_scaler_plane(
11614                         to_intel_crtc_state(crtc_state),
11615                         to_intel_plane_state(plane_state));
11616                 if (ret)
11617                         return ret;
11618         }
11619
11620         /*
11621          * Disabling a plane is always okay; we just need to update
11622          * fb tracking in a special way since cleanup_fb() won't
11623          * get called by the plane helpers.
11624          */
11625         if (old_plane_state->base.fb && !fb)
11626                 intel_crtc->atomic.disabled_planes |= 1 << i;
11627
11628         was_visible = old_plane_state->visible;
11629         visible = to_intel_plane_state(plane_state)->visible;
11630
11631         if (!was_crtc_enabled && WARN_ON(was_visible))
11632                 was_visible = false;
11633
11634         if (!is_crtc_enabled && WARN_ON(visible))
11635                 visible = false;
11636
11637         if (!was_visible && !visible)
11638                 return 0;
11639
11640         turn_off = was_visible && (!visible || mode_changed);
11641         turn_on = visible && (!was_visible || mode_changed);
11642
11643         DRM_DEBUG_ATOMIC("[CRTC:%i] has [PLANE:%i] with fb %i\n", idx,
11644                          plane->base.id, fb ? fb->base.id : -1);
11645
11646         DRM_DEBUG_ATOMIC("[PLANE:%i] visible %i -> %i, off %i, on %i, ms %i\n",
11647                          plane->base.id, was_visible, visible,
11648                          turn_off, turn_on, mode_changed);
11649
11650         if (turn_on) {
11651                 intel_crtc->atomic.update_wm_pre = true;
11652                 /* must disable cxsr around plane enable/disable */
11653                 if (plane->type != DRM_PLANE_TYPE_CURSOR) {
11654                         intel_crtc->atomic.disable_cxsr = true;
11655                         /* to potentially re-enable cxsr */
11656                         intel_crtc->atomic.wait_vblank = true;
11657                         intel_crtc->atomic.update_wm_post = true;
11658                 }
11659         } else if (turn_off) {
11660                 intel_crtc->atomic.update_wm_post = true;
11661                 /* must disable cxsr around plane enable/disable */
11662                 if (plane->type != DRM_PLANE_TYPE_CURSOR) {
11663                         if (is_crtc_enabled)
11664                                 intel_crtc->atomic.wait_vblank = true;
11665                         intel_crtc->atomic.disable_cxsr = true;
11666                 }
11667         } else if (intel_wm_need_update(plane, plane_state)) {
11668                 intel_crtc->atomic.update_wm_pre = true;
11669         }
11670
11671         if (visible)
11672                 intel_crtc->atomic.fb_bits |=
11673                         to_intel_plane(plane)->frontbuffer_bit;
11674
11675         switch (plane->type) {
11676         case DRM_PLANE_TYPE_PRIMARY:
11677                 intel_crtc->atomic.wait_for_flips = true;
11678                 intel_crtc->atomic.pre_disable_primary = turn_off;
11679                 intel_crtc->atomic.post_enable_primary = turn_on;
11680
11681                 if (turn_off) {
11682                         /*
11683                          * FIXME: Actually if we will still have any other
11684                          * plane enabled on the pipe we could let IPS enabled
11685                          * still, but for now lets consider that when we make
11686                          * primary invisible by setting DSPCNTR to 0 on
11687                          * update_primary_plane function IPS needs to be
11688                          * disable.
11689                          */
11690                         intel_crtc->atomic.disable_ips = true;
11691
11692                         intel_crtc->atomic.disable_fbc = true;
11693                 }
11694
11695                 /*
11696                  * FBC does not work on some platforms for rotated
11697                  * planes, so disable it when rotation is not 0 and
11698                  * update it when rotation is set back to 0.
11699                  *
11700                  * FIXME: This is redundant with the fbc update done in
11701                  * the primary plane enable function except that that
11702                  * one is done too late. We eventually need to unify
11703                  * this.
11704                  */
11705
11706                 if (visible &&
11707                     INTEL_INFO(dev)->gen <= 4 && !IS_G4X(dev) &&
11708                     dev_priv->fbc.crtc == intel_crtc &&
11709                     plane_state->rotation != BIT(DRM_ROTATE_0))
11710                         intel_crtc->atomic.disable_fbc = true;
11711
11712                 /*
11713                  * BDW signals flip done immediately if the plane
11714                  * is disabled, even if the plane enable is already
11715                  * armed to occur at the next vblank :(
11716                  */
11717                 if (turn_on && IS_BROADWELL(dev))
11718                         intel_crtc->atomic.wait_vblank = true;
11719
11720                 intel_crtc->atomic.update_fbc |= visible || mode_changed;
11721                 break;
11722         case DRM_PLANE_TYPE_CURSOR:
11723                 break;
11724         case DRM_PLANE_TYPE_OVERLAY:
11725                 if (turn_off && !mode_changed) {
11726                         intel_crtc->atomic.wait_vblank = true;
11727                         intel_crtc->atomic.update_sprite_watermarks |=
11728                                 1 << i;
11729                 }
11730         }
11731         return 0;
11732 }
11733
11734 static bool encoders_cloneable(const struct intel_encoder *a,
11735                                const struct intel_encoder *b)
11736 {
11737         /* masks could be asymmetric, so check both ways */
11738         return a == b || (a->cloneable & (1 << b->type) &&
11739                           b->cloneable & (1 << a->type));
11740 }
11741
11742 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
11743                                          struct intel_crtc *crtc,
11744                                          struct intel_encoder *encoder)
11745 {
11746         struct intel_encoder *source_encoder;
11747         struct drm_connector *connector;
11748         struct drm_connector_state *connector_state;
11749         int i;
11750
11751         for_each_connector_in_state(state, connector, connector_state, i) {
11752                 if (connector_state->crtc != &crtc->base)
11753                         continue;
11754
11755                 source_encoder =
11756                         to_intel_encoder(connector_state->best_encoder);
11757                 if (!encoders_cloneable(encoder, source_encoder))
11758                         return false;
11759         }
11760
11761         return true;
11762 }
11763
11764 static bool check_encoder_cloning(struct drm_atomic_state *state,
11765                                   struct intel_crtc *crtc)
11766 {
11767         struct intel_encoder *encoder;
11768         struct drm_connector *connector;
11769         struct drm_connector_state *connector_state;
11770         int i;
11771
11772         for_each_connector_in_state(state, connector, connector_state, i) {
11773                 if (connector_state->crtc != &crtc->base)
11774                         continue;
11775
11776                 encoder = to_intel_encoder(connector_state->best_encoder);
11777                 if (!check_single_encoder_cloning(state, crtc, encoder))
11778                         return false;
11779         }
11780
11781         return true;
11782 }
11783
11784 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
11785                                    struct drm_crtc_state *crtc_state)
11786 {
11787         struct drm_device *dev = crtc->dev;
11788         struct drm_i915_private *dev_priv = dev->dev_private;
11789         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11790         struct intel_crtc_state *pipe_config =
11791                 to_intel_crtc_state(crtc_state);
11792         struct drm_atomic_state *state = crtc_state->state;
11793         int ret, idx = crtc->base.id;
11794         bool mode_changed = needs_modeset(crtc_state);
11795
11796         if (mode_changed && !check_encoder_cloning(state, intel_crtc)) {
11797                 DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
11798                 return -EINVAL;
11799         }
11800
11801         I915_STATE_WARN(crtc->state->active != intel_crtc->active,
11802                 "[CRTC:%i] mismatch between state->active(%i) and crtc->active(%i)\n",
11803                 idx, crtc->state->active, intel_crtc->active);
11804
11805         if (mode_changed && !crtc_state->active)
11806                 intel_crtc->atomic.update_wm_post = true;
11807
11808         if (mode_changed && crtc_state->enable &&
11809             dev_priv->display.crtc_compute_clock &&
11810             !WARN_ON(pipe_config->shared_dpll != DPLL_ID_PRIVATE)) {
11811                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
11812                                                            pipe_config);
11813                 if (ret)
11814                         return ret;
11815         }
11816
11817         ret = 0;
11818         if (INTEL_INFO(dev)->gen >= 9) {
11819                 if (mode_changed)
11820                         ret = skl_update_scaler_crtc(pipe_config);
11821
11822                 if (!ret)
11823                         ret = intel_atomic_setup_scalers(dev, intel_crtc,
11824                                                          pipe_config);
11825         }
11826
11827         return ret;
11828 }
11829
11830 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
11831         .mode_set_base_atomic = intel_pipe_set_base_atomic,
11832         .load_lut = intel_crtc_load_lut,
11833         .atomic_begin = intel_begin_crtc_commit,
11834         .atomic_flush = intel_finish_crtc_commit,
11835         .atomic_check = intel_crtc_atomic_check,
11836 };
11837
11838 /**
11839  * intel_modeset_update_staged_output_state
11840  *
11841  * Updates the staged output configuration state, e.g. after we've read out the
11842  * current hw state.
11843  */
11844 static void intel_modeset_update_staged_output_state(struct drm_device *dev)
11845 {
11846         struct intel_crtc *crtc;
11847         struct intel_encoder *encoder;
11848         struct intel_connector *connector;
11849
11850         for_each_intel_connector(dev, connector) {
11851                 connector->new_encoder =
11852                         to_intel_encoder(connector->base.encoder);
11853         }
11854
11855         for_each_intel_encoder(dev, encoder) {
11856                 encoder->new_crtc =
11857                         to_intel_crtc(encoder->base.crtc);
11858         }
11859
11860         for_each_intel_crtc(dev, crtc) {
11861                 crtc->new_enabled = crtc->base.state->enable;
11862         }
11863 }
11864
11865 /* Transitional helper to copy current connector/encoder state to
11866  * connector->state. This is needed so that code that is partially
11867  * converted to atomic does the right thing.
11868  */
11869 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
11870 {
11871         struct intel_connector *connector;
11872
11873         for_each_intel_connector(dev, connector) {
11874                 if (connector->base.encoder) {
11875                         connector->base.state->best_encoder =
11876                                 connector->base.encoder;
11877                         connector->base.state->crtc =
11878                                 connector->base.encoder->crtc;
11879                 } else {
11880                         connector->base.state->best_encoder = NULL;
11881                         connector->base.state->crtc = NULL;
11882                 }
11883         }
11884 }
11885
11886 static void
11887 connected_sink_compute_bpp(struct intel_connector *connector,
11888                            struct intel_crtc_state *pipe_config)
11889 {
11890         int bpp = pipe_config->pipe_bpp;
11891
11892         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
11893                 connector->base.base.id,
11894                 connector->base.name);
11895
11896         /* Don't use an invalid EDID bpc value */
11897         if (connector->base.display_info.bpc &&
11898             connector->base.display_info.bpc * 3 < bpp) {
11899                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
11900                               bpp, connector->base.display_info.bpc*3);
11901                 pipe_config->pipe_bpp = connector->base.display_info.bpc*3;
11902         }
11903
11904         /* Clamp bpp to 8 on screens without EDID 1.4 */
11905         if (connector->base.display_info.bpc == 0 && bpp > 24) {
11906                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
11907                               bpp);
11908                 pipe_config->pipe_bpp = 24;
11909         }
11910 }
11911
11912 static int
11913 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
11914                           struct intel_crtc_state *pipe_config)
11915 {
11916         struct drm_device *dev = crtc->base.dev;
11917         struct drm_atomic_state *state;
11918         struct drm_connector *connector;
11919         struct drm_connector_state *connector_state;
11920         int bpp, i;
11921
11922         if ((IS_G4X(dev) || IS_VALLEYVIEW(dev)))
11923                 bpp = 10*3;
11924         else if (INTEL_INFO(dev)->gen >= 5)
11925                 bpp = 12*3;
11926         else
11927                 bpp = 8*3;
11928
11929
11930         pipe_config->pipe_bpp = bpp;
11931
11932         state = pipe_config->base.state;
11933
11934         /* Clamp display bpp to EDID value */
11935         for_each_connector_in_state(state, connector, connector_state, i) {
11936                 if (connector_state->crtc != &crtc->base)
11937                         continue;
11938
11939                 connected_sink_compute_bpp(to_intel_connector(connector),
11940                                            pipe_config);
11941         }
11942
11943         return bpp;
11944 }
11945
11946 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
11947 {
11948         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
11949                         "type: 0x%x flags: 0x%x\n",
11950                 mode->crtc_clock,
11951                 mode->crtc_hdisplay, mode->crtc_hsync_start,
11952                 mode->crtc_hsync_end, mode->crtc_htotal,
11953                 mode->crtc_vdisplay, mode->crtc_vsync_start,
11954                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
11955 }
11956
11957 static void intel_dump_pipe_config(struct intel_crtc *crtc,
11958                                    struct intel_crtc_state *pipe_config,
11959                                    const char *context)
11960 {
11961         struct drm_device *dev = crtc->base.dev;
11962         struct drm_plane *plane;
11963         struct intel_plane *intel_plane;
11964         struct intel_plane_state *state;
11965         struct drm_framebuffer *fb;
11966
11967         DRM_DEBUG_KMS("[CRTC:%d]%s config %p for pipe %c\n", crtc->base.base.id,
11968                       context, pipe_config, pipe_name(crtc->pipe));
11969
11970         DRM_DEBUG_KMS("cpu_transcoder: %c\n", transcoder_name(pipe_config->cpu_transcoder));
11971         DRM_DEBUG_KMS("pipe bpp: %i, dithering: %i\n",
11972                       pipe_config->pipe_bpp, pipe_config->dither);
11973         DRM_DEBUG_KMS("fdi/pch: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
11974                       pipe_config->has_pch_encoder,
11975                       pipe_config->fdi_lanes,
11976                       pipe_config->fdi_m_n.gmch_m, pipe_config->fdi_m_n.gmch_n,
11977                       pipe_config->fdi_m_n.link_m, pipe_config->fdi_m_n.link_n,
11978                       pipe_config->fdi_m_n.tu);
11979         DRM_DEBUG_KMS("dp: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
11980                       pipe_config->has_dp_encoder,
11981                       pipe_config->dp_m_n.gmch_m, pipe_config->dp_m_n.gmch_n,
11982                       pipe_config->dp_m_n.link_m, pipe_config->dp_m_n.link_n,
11983                       pipe_config->dp_m_n.tu);
11984
11985         DRM_DEBUG_KMS("dp: %i, gmch_m2: %u, gmch_n2: %u, link_m2: %u, link_n2: %u, tu2: %u\n",
11986                       pipe_config->has_dp_encoder,
11987                       pipe_config->dp_m2_n2.gmch_m,
11988                       pipe_config->dp_m2_n2.gmch_n,
11989                       pipe_config->dp_m2_n2.link_m,
11990                       pipe_config->dp_m2_n2.link_n,
11991                       pipe_config->dp_m2_n2.tu);
11992
11993         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
11994                       pipe_config->has_audio,
11995                       pipe_config->has_infoframe);
11996
11997         DRM_DEBUG_KMS("requested mode:\n");
11998         drm_mode_debug_printmodeline(&pipe_config->base.mode);
11999         DRM_DEBUG_KMS("adjusted mode:\n");
12000         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
12001         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
12002         DRM_DEBUG_KMS("port clock: %d\n", pipe_config->port_clock);
12003         DRM_DEBUG_KMS("pipe src size: %dx%d\n",
12004                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
12005         DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
12006                       crtc->num_scalers,
12007                       pipe_config->scaler_state.scaler_users,
12008                       pipe_config->scaler_state.scaler_id);
12009         DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
12010                       pipe_config->gmch_pfit.control,
12011                       pipe_config->gmch_pfit.pgm_ratios,
12012                       pipe_config->gmch_pfit.lvds_border_bits);
12013         DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
12014                       pipe_config->pch_pfit.pos,
12015                       pipe_config->pch_pfit.size,
12016                       pipe_config->pch_pfit.enabled ? "enabled" : "disabled");
12017         DRM_DEBUG_KMS("ips: %i\n", pipe_config->ips_enabled);
12018         DRM_DEBUG_KMS("double wide: %i\n", pipe_config->double_wide);
12019
12020         if (IS_BROXTON(dev)) {
12021                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: ebb0: 0x%x, ebb4: 0x%x,"
12022                               "pll0: 0x%x, pll1: 0x%x, pll2: 0x%x, pll3: 0x%x, "
12023                               "pll6: 0x%x, pll8: 0x%x, pll9: 0x%x, pll10: 0x%x, pcsdw12: 0x%x\n",
12024                               pipe_config->ddi_pll_sel,
12025                               pipe_config->dpll_hw_state.ebb0,
12026                               pipe_config->dpll_hw_state.ebb4,
12027                               pipe_config->dpll_hw_state.pll0,
12028                               pipe_config->dpll_hw_state.pll1,
12029                               pipe_config->dpll_hw_state.pll2,
12030                               pipe_config->dpll_hw_state.pll3,
12031                               pipe_config->dpll_hw_state.pll6,
12032                               pipe_config->dpll_hw_state.pll8,
12033                               pipe_config->dpll_hw_state.pll9,
12034                               pipe_config->dpll_hw_state.pll10,
12035                               pipe_config->dpll_hw_state.pcsdw12);
12036         } else if (IS_SKYLAKE(dev)) {
12037                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: "
12038                               "ctrl1: 0x%x, cfgcr1: 0x%x, cfgcr2: 0x%x\n",
12039                               pipe_config->ddi_pll_sel,
12040                               pipe_config->dpll_hw_state.ctrl1,
12041                               pipe_config->dpll_hw_state.cfgcr1,
12042                               pipe_config->dpll_hw_state.cfgcr2);
12043         } else if (HAS_DDI(dev)) {
12044                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: wrpll: 0x%x\n",
12045                               pipe_config->ddi_pll_sel,
12046                               pipe_config->dpll_hw_state.wrpll);
12047         } else {
12048                 DRM_DEBUG_KMS("dpll_hw_state: dpll: 0x%x, dpll_md: 0x%x, "
12049                               "fp0: 0x%x, fp1: 0x%x\n",
12050                               pipe_config->dpll_hw_state.dpll,
12051                               pipe_config->dpll_hw_state.dpll_md,
12052                               pipe_config->dpll_hw_state.fp0,
12053                               pipe_config->dpll_hw_state.fp1);
12054         }
12055
12056         DRM_DEBUG_KMS("planes on this crtc\n");
12057         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
12058                 intel_plane = to_intel_plane(plane);
12059                 if (intel_plane->pipe != crtc->pipe)
12060                         continue;
12061
12062                 state = to_intel_plane_state(plane->state);
12063                 fb = state->base.fb;
12064                 if (!fb) {
12065                         DRM_DEBUG_KMS("%s PLANE:%d plane: %u.%u idx: %d "
12066                                 "disabled, scaler_id = %d\n",
12067                                 plane->type == DRM_PLANE_TYPE_CURSOR ? "CURSOR" : "STANDARD",
12068                                 plane->base.id, intel_plane->pipe,
12069                                 (crtc->base.primary == plane) ? 0 : intel_plane->plane + 1,
12070                                 drm_plane_index(plane), state->scaler_id);
12071                         continue;
12072                 }
12073
12074                 DRM_DEBUG_KMS("%s PLANE:%d plane: %u.%u idx: %d enabled",
12075                         plane->type == DRM_PLANE_TYPE_CURSOR ? "CURSOR" : "STANDARD",
12076                         plane->base.id, intel_plane->pipe,
12077                         crtc->base.primary == plane ? 0 : intel_plane->plane + 1,
12078                         drm_plane_index(plane));
12079                 DRM_DEBUG_KMS("\tFB:%d, fb = %ux%u format = 0x%x",
12080                         fb->base.id, fb->width, fb->height, fb->pixel_format);
12081                 DRM_DEBUG_KMS("\tscaler:%d src (%u, %u) %ux%u dst (%u, %u) %ux%u\n",
12082                         state->scaler_id,
12083                         state->src.x1 >> 16, state->src.y1 >> 16,
12084                         drm_rect_width(&state->src) >> 16,
12085                         drm_rect_height(&state->src) >> 16,
12086                         state->dst.x1, state->dst.y1,
12087                         drm_rect_width(&state->dst), drm_rect_height(&state->dst));
12088         }
12089 }
12090
12091 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
12092 {
12093         struct drm_device *dev = state->dev;
12094         struct intel_encoder *encoder;
12095         struct drm_connector *connector;
12096         struct drm_connector_state *connector_state;
12097         unsigned int used_ports = 0;
12098         int i;
12099
12100         /*
12101          * Walk the connector list instead of the encoder
12102          * list to detect the problem on ddi platforms
12103          * where there's just one encoder per digital port.
12104          */
12105         for_each_connector_in_state(state, connector, connector_state, i) {
12106                 if (!connector_state->best_encoder)
12107                         continue;
12108
12109                 encoder = to_intel_encoder(connector_state->best_encoder);
12110
12111                 WARN_ON(!connector_state->crtc);
12112
12113                 switch (encoder->type) {
12114                         unsigned int port_mask;
12115                 case INTEL_OUTPUT_UNKNOWN:
12116                         if (WARN_ON(!HAS_DDI(dev)))
12117                                 break;
12118                 case INTEL_OUTPUT_DISPLAYPORT:
12119                 case INTEL_OUTPUT_HDMI:
12120                 case INTEL_OUTPUT_EDP:
12121                         port_mask = 1 << enc_to_dig_port(&encoder->base)->port;
12122
12123                         /* the same port mustn't appear more than once */
12124                         if (used_ports & port_mask)
12125                                 return false;
12126
12127                         used_ports |= port_mask;
12128                 default:
12129                         break;
12130                 }
12131         }
12132
12133         return true;
12134 }
12135
12136 static void
12137 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
12138 {
12139         struct drm_crtc_state tmp_state;
12140         struct intel_crtc_scaler_state scaler_state;
12141         struct intel_dpll_hw_state dpll_hw_state;
12142         enum intel_dpll_id shared_dpll;
12143         uint32_t ddi_pll_sel;
12144
12145         /* FIXME: before the switch to atomic started, a new pipe_config was
12146          * kzalloc'd. Code that depends on any field being zero should be
12147          * fixed, so that the crtc_state can be safely duplicated. For now,
12148          * only fields that are know to not cause problems are preserved. */
12149
12150         tmp_state = crtc_state->base;
12151         scaler_state = crtc_state->scaler_state;
12152         shared_dpll = crtc_state->shared_dpll;
12153         dpll_hw_state = crtc_state->dpll_hw_state;
12154         ddi_pll_sel = crtc_state->ddi_pll_sel;
12155
12156         memset(crtc_state, 0, sizeof *crtc_state);
12157
12158         crtc_state->base = tmp_state;
12159         crtc_state->scaler_state = scaler_state;
12160         crtc_state->shared_dpll = shared_dpll;
12161         crtc_state->dpll_hw_state = dpll_hw_state;
12162         crtc_state->ddi_pll_sel = ddi_pll_sel;
12163 }
12164
12165 static int
12166 intel_modeset_pipe_config(struct drm_crtc *crtc,
12167                           struct intel_crtc_state *pipe_config)
12168 {
12169         struct drm_atomic_state *state = pipe_config->base.state;
12170         struct intel_encoder *encoder;
12171         struct drm_connector *connector;
12172         struct drm_connector_state *connector_state;
12173         int base_bpp, ret = -EINVAL;
12174         int i;
12175         bool retry = true;
12176
12177         clear_intel_crtc_state(pipe_config);
12178
12179         pipe_config->cpu_transcoder =
12180                 (enum transcoder) to_intel_crtc(crtc)->pipe;
12181
12182         /*
12183          * Sanitize sync polarity flags based on requested ones. If neither
12184          * positive or negative polarity is requested, treat this as meaning
12185          * negative polarity.
12186          */
12187         if (!(pipe_config->base.adjusted_mode.flags &
12188               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
12189                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
12190
12191         if (!(pipe_config->base.adjusted_mode.flags &
12192               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
12193                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
12194
12195         /* Compute a starting value for pipe_config->pipe_bpp taking the source
12196          * plane pixel format and any sink constraints into account. Returns the
12197          * source plane bpp so that dithering can be selected on mismatches
12198          * after encoders and crtc also have had their say. */
12199         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
12200                                              pipe_config);
12201         if (base_bpp < 0)
12202                 goto fail;
12203
12204         /*
12205          * Determine the real pipe dimensions. Note that stereo modes can
12206          * increase the actual pipe size due to the frame doubling and
12207          * insertion of additional space for blanks between the frame. This
12208          * is stored in the crtc timings. We use the requested mode to do this
12209          * computation to clearly distinguish it from the adjusted mode, which
12210          * can be changed by the connectors in the below retry loop.
12211          */
12212         drm_crtc_get_hv_timing(&pipe_config->base.mode,
12213                                &pipe_config->pipe_src_w,
12214                                &pipe_config->pipe_src_h);
12215
12216 encoder_retry:
12217         /* Ensure the port clock defaults are reset when retrying. */
12218         pipe_config->port_clock = 0;
12219         pipe_config->pixel_multiplier = 1;
12220
12221         /* Fill in default crtc timings, allow encoders to overwrite them. */
12222         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
12223                               CRTC_STEREO_DOUBLE);
12224
12225         /* Pass our mode to the connectors and the CRTC to give them a chance to
12226          * adjust it according to limitations or connector properties, and also
12227          * a chance to reject the mode entirely.
12228          */
12229         for_each_connector_in_state(state, connector, connector_state, i) {
12230                 if (connector_state->crtc != crtc)
12231                         continue;
12232
12233                 encoder = to_intel_encoder(connector_state->best_encoder);
12234
12235                 if (!(encoder->compute_config(encoder, pipe_config))) {
12236                         DRM_DEBUG_KMS("Encoder config failure\n");
12237                         goto fail;
12238                 }
12239         }
12240
12241         /* Set default port clock if not overwritten by the encoder. Needs to be
12242          * done afterwards in case the encoder adjusts the mode. */
12243         if (!pipe_config->port_clock)
12244                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
12245                         * pipe_config->pixel_multiplier;
12246
12247         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
12248         if (ret < 0) {
12249                 DRM_DEBUG_KMS("CRTC fixup failed\n");
12250                 goto fail;
12251         }
12252
12253         if (ret == RETRY) {
12254                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
12255                         ret = -EINVAL;
12256                         goto fail;
12257                 }
12258
12259                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
12260                 retry = false;
12261                 goto encoder_retry;
12262         }
12263
12264         pipe_config->dither = pipe_config->pipe_bpp != base_bpp;
12265         DRM_DEBUG_KMS("plane bpp: %i, pipe bpp: %i, dithering: %i\n",
12266                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
12267
12268 fail:
12269         return ret;
12270 }
12271
12272 static bool intel_crtc_in_use(struct drm_crtc *crtc)
12273 {
12274         struct drm_encoder *encoder;
12275         struct drm_device *dev = crtc->dev;
12276
12277         list_for_each_entry(encoder, &dev->mode_config.encoder_list, head)
12278                 if (encoder->crtc == crtc)
12279                         return true;
12280
12281         return false;
12282 }
12283
12284 static void
12285 intel_modeset_update_state(struct drm_atomic_state *state)
12286 {
12287         struct drm_device *dev = state->dev;
12288         struct intel_encoder *intel_encoder;
12289         struct drm_crtc *crtc;
12290         struct drm_crtc_state *crtc_state;
12291         struct drm_connector *connector;
12292         int i;
12293
12294         intel_shared_dpll_commit(state);
12295
12296         for_each_intel_encoder(dev, intel_encoder) {
12297                 if (!intel_encoder->base.crtc)
12298                         continue;
12299
12300                 crtc = intel_encoder->base.crtc;
12301                 crtc_state = drm_atomic_get_existing_crtc_state(state, crtc);
12302                 if (!crtc_state || !needs_modeset(crtc->state))
12303                         continue;
12304
12305                 intel_encoder->connectors_active = false;
12306         }
12307
12308         drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
12309         intel_modeset_update_staged_output_state(state->dev);
12310
12311         /* Double check state. */
12312         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12313                 WARN_ON(crtc->state->enable != intel_crtc_in_use(crtc));
12314
12315                 to_intel_crtc(crtc)->config = to_intel_crtc_state(crtc->state);
12316
12317                 /* Update hwmode for vblank functions */
12318                 if (crtc->state->active)
12319                         crtc->hwmode = crtc->state->adjusted_mode;
12320                 else
12321                         crtc->hwmode.crtc_clock = 0;
12322         }
12323
12324         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
12325                 if (!connector->encoder || !connector->encoder->crtc)
12326                         continue;
12327
12328                 crtc = connector->encoder->crtc;
12329                 crtc_state = drm_atomic_get_existing_crtc_state(state, crtc);
12330                 if (!crtc_state || !needs_modeset(crtc->state))
12331                         continue;
12332
12333                 if (crtc->state->active) {
12334                         struct drm_property *dpms_property =
12335                                 dev->mode_config.dpms_property;
12336
12337                         connector->dpms = DRM_MODE_DPMS_ON;
12338                         drm_object_property_set_value(&connector->base, dpms_property, DRM_MODE_DPMS_ON);
12339
12340                         intel_encoder = to_intel_encoder(connector->encoder);
12341                         intel_encoder->connectors_active = true;
12342                 } else
12343                         connector->dpms = DRM_MODE_DPMS_OFF;
12344         }
12345 }
12346
12347 static bool intel_fuzzy_clock_check(int clock1, int clock2)
12348 {
12349         int diff;
12350
12351         if (clock1 == clock2)
12352                 return true;
12353
12354         if (!clock1 || !clock2)
12355                 return false;
12356
12357         diff = abs(clock1 - clock2);
12358
12359         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
12360                 return true;
12361
12362         return false;
12363 }
12364
12365 #define for_each_intel_crtc_masked(dev, mask, intel_crtc) \
12366         list_for_each_entry((intel_crtc), \
12367                             &(dev)->mode_config.crtc_list, \
12368                             base.head) \
12369                 if (mask & (1 <<(intel_crtc)->pipe))
12370
12371
12372 static bool
12373 intel_compare_m_n(unsigned int m, unsigned int n,
12374                   unsigned int m2, unsigned int n2,
12375                   bool exact)
12376 {
12377         if (m == m2 && n == n2)
12378                 return true;
12379
12380         if (exact || !m || !n || !m2 || !n2)
12381                 return false;
12382
12383         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
12384
12385         if (m > m2) {
12386                 while (m > m2) {
12387                         m2 <<= 1;
12388                         n2 <<= 1;
12389                 }
12390         } else if (m < m2) {
12391                 while (m < m2) {
12392                         m <<= 1;
12393                         n <<= 1;
12394                 }
12395         }
12396
12397         return m == m2 && n == n2;
12398 }
12399
12400 static bool
12401 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
12402                        struct intel_link_m_n *m2_n2,
12403                        bool adjust)
12404 {
12405         if (m_n->tu == m2_n2->tu &&
12406             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
12407                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
12408             intel_compare_m_n(m_n->link_m, m_n->link_n,
12409                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
12410                 if (adjust)
12411                         *m2_n2 = *m_n;
12412
12413                 return true;
12414         }
12415
12416         return false;
12417 }
12418
12419 static bool
12420 intel_pipe_config_compare(struct drm_device *dev,
12421                           struct intel_crtc_state *current_config,
12422                           struct intel_crtc_state *pipe_config,
12423                           bool adjust)
12424 {
12425         bool ret = true;
12426
12427 #define INTEL_ERR_OR_DBG_KMS(fmt, ...) \
12428         do { \
12429                 if (!adjust) \
12430                         DRM_ERROR(fmt, ##__VA_ARGS__); \
12431                 else \
12432                         DRM_DEBUG_KMS(fmt, ##__VA_ARGS__); \
12433         } while (0)
12434
12435 #define PIPE_CONF_CHECK_X(name) \
12436         if (current_config->name != pipe_config->name) { \
12437                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12438                           "(expected 0x%08x, found 0x%08x)\n", \
12439                           current_config->name, \
12440                           pipe_config->name); \
12441                 ret = false; \
12442         }
12443
12444 #define PIPE_CONF_CHECK_I(name) \
12445         if (current_config->name != pipe_config->name) { \
12446                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12447                           "(expected %i, found %i)\n", \
12448                           current_config->name, \
12449                           pipe_config->name); \
12450                 ret = false; \
12451         }
12452
12453 #define PIPE_CONF_CHECK_M_N(name) \
12454         if (!intel_compare_link_m_n(&current_config->name, \
12455                                     &pipe_config->name,\
12456                                     adjust)) { \
12457                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12458                           "(expected tu %i gmch %i/%i link %i/%i, " \
12459                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12460                           current_config->name.tu, \
12461                           current_config->name.gmch_m, \
12462                           current_config->name.gmch_n, \
12463                           current_config->name.link_m, \
12464                           current_config->name.link_n, \
12465                           pipe_config->name.tu, \
12466                           pipe_config->name.gmch_m, \
12467                           pipe_config->name.gmch_n, \
12468                           pipe_config->name.link_m, \
12469                           pipe_config->name.link_n); \
12470                 ret = false; \
12471         }
12472
12473 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) \
12474         if (!intel_compare_link_m_n(&current_config->name, \
12475                                     &pipe_config->name, adjust) && \
12476             !intel_compare_link_m_n(&current_config->alt_name, \
12477                                     &pipe_config->name, adjust)) { \
12478                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12479                           "(expected tu %i gmch %i/%i link %i/%i, " \
12480                           "or tu %i gmch %i/%i link %i/%i, " \
12481                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12482                           current_config->name.tu, \
12483                           current_config->name.gmch_m, \
12484                           current_config->name.gmch_n, \
12485                           current_config->name.link_m, \
12486                           current_config->name.link_n, \
12487                           current_config->alt_name.tu, \
12488                           current_config->alt_name.gmch_m, \
12489                           current_config->alt_name.gmch_n, \
12490                           current_config->alt_name.link_m, \
12491                           current_config->alt_name.link_n, \
12492                           pipe_config->name.tu, \
12493                           pipe_config->name.gmch_m, \
12494                           pipe_config->name.gmch_n, \
12495                           pipe_config->name.link_m, \
12496                           pipe_config->name.link_n); \
12497                 ret = false; \
12498         }
12499
12500 /* This is required for BDW+ where there is only one set of registers for
12501  * switching between high and low RR.
12502  * This macro can be used whenever a comparison has to be made between one
12503  * hw state and multiple sw state variables.
12504  */
12505 #define PIPE_CONF_CHECK_I_ALT(name, alt_name) \
12506         if ((current_config->name != pipe_config->name) && \
12507                 (current_config->alt_name != pipe_config->name)) { \
12508                         INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12509                                   "(expected %i or %i, found %i)\n", \
12510                                   current_config->name, \
12511                                   current_config->alt_name, \
12512                                   pipe_config->name); \
12513                         ret = false; \
12514         }
12515
12516 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
12517         if ((current_config->name ^ pipe_config->name) & (mask)) { \
12518                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name "(" #mask ") " \
12519                           "(expected %i, found %i)\n", \
12520                           current_config->name & (mask), \
12521                           pipe_config->name & (mask)); \
12522                 ret = false; \
12523         }
12524
12525 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
12526         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
12527                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12528                           "(expected %i, found %i)\n", \
12529                           current_config->name, \
12530                           pipe_config->name); \
12531                 ret = false; \
12532         }
12533
12534 #define PIPE_CONF_QUIRK(quirk)  \
12535         ((current_config->quirks | pipe_config->quirks) & (quirk))
12536
12537         PIPE_CONF_CHECK_I(cpu_transcoder);
12538
12539         PIPE_CONF_CHECK_I(has_pch_encoder);
12540         PIPE_CONF_CHECK_I(fdi_lanes);
12541         PIPE_CONF_CHECK_M_N(fdi_m_n);
12542
12543         PIPE_CONF_CHECK_I(has_dp_encoder);
12544
12545         if (INTEL_INFO(dev)->gen < 8) {
12546                 PIPE_CONF_CHECK_M_N(dp_m_n);
12547
12548                 PIPE_CONF_CHECK_I(has_drrs);
12549                 if (current_config->has_drrs)
12550                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
12551         } else
12552                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
12553
12554         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
12555         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
12556         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
12557         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
12558         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
12559         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
12560
12561         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
12562         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
12563         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
12564         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
12565         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
12566         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
12567
12568         PIPE_CONF_CHECK_I(pixel_multiplier);
12569         PIPE_CONF_CHECK_I(has_hdmi_sink);
12570         if ((INTEL_INFO(dev)->gen < 8 && !IS_HASWELL(dev)) ||
12571             IS_VALLEYVIEW(dev))
12572                 PIPE_CONF_CHECK_I(limited_color_range);
12573         PIPE_CONF_CHECK_I(has_infoframe);
12574
12575         PIPE_CONF_CHECK_I(has_audio);
12576
12577         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12578                               DRM_MODE_FLAG_INTERLACE);
12579
12580         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
12581                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12582                                       DRM_MODE_FLAG_PHSYNC);
12583                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12584                                       DRM_MODE_FLAG_NHSYNC);
12585                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12586                                       DRM_MODE_FLAG_PVSYNC);
12587                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12588                                       DRM_MODE_FLAG_NVSYNC);
12589         }
12590
12591         PIPE_CONF_CHECK_I(pipe_src_w);
12592         PIPE_CONF_CHECK_I(pipe_src_h);
12593
12594         /*
12595          * FIXME: BIOS likes to set up a cloned config with lvds+external
12596          * screen. Since we don't yet re-compute the pipe config when moving
12597          * just the lvds port away to another pipe the sw tracking won't match.
12598          *
12599          * Proper atomic modesets with recomputed global state will fix this.
12600          * Until then just don't check gmch state for inherited modes.
12601          */
12602         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_INHERITED_MODE)) {
12603                 PIPE_CONF_CHECK_I(gmch_pfit.control);
12604                 /* pfit ratios are autocomputed by the hw on gen4+ */
12605                 if (INTEL_INFO(dev)->gen < 4)
12606                         PIPE_CONF_CHECK_I(gmch_pfit.pgm_ratios);
12607                 PIPE_CONF_CHECK_I(gmch_pfit.lvds_border_bits);
12608         }
12609
12610         PIPE_CONF_CHECK_I(pch_pfit.enabled);
12611         if (current_config->pch_pfit.enabled) {
12612                 PIPE_CONF_CHECK_I(pch_pfit.pos);
12613                 PIPE_CONF_CHECK_I(pch_pfit.size);
12614         }
12615
12616         PIPE_CONF_CHECK_I(scaler_state.scaler_id);
12617
12618         /* BDW+ don't expose a synchronous way to read the state */
12619         if (IS_HASWELL(dev))
12620                 PIPE_CONF_CHECK_I(ips_enabled);
12621
12622         PIPE_CONF_CHECK_I(double_wide);
12623
12624         PIPE_CONF_CHECK_X(ddi_pll_sel);
12625
12626         PIPE_CONF_CHECK_I(shared_dpll);
12627         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
12628         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
12629         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
12630         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
12631         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
12632         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
12633         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
12634         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
12635
12636         if (IS_G4X(dev) || INTEL_INFO(dev)->gen >= 5)
12637                 PIPE_CONF_CHECK_I(pipe_bpp);
12638
12639         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
12640         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
12641
12642 #undef PIPE_CONF_CHECK_X
12643 #undef PIPE_CONF_CHECK_I
12644 #undef PIPE_CONF_CHECK_I_ALT
12645 #undef PIPE_CONF_CHECK_FLAGS
12646 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
12647 #undef PIPE_CONF_QUIRK
12648 #undef INTEL_ERR_OR_DBG_KMS
12649
12650         return ret;
12651 }
12652
12653 static void check_wm_state(struct drm_device *dev)
12654 {
12655         struct drm_i915_private *dev_priv = dev->dev_private;
12656         struct skl_ddb_allocation hw_ddb, *sw_ddb;
12657         struct intel_crtc *intel_crtc;
12658         int plane;
12659
12660         if (INTEL_INFO(dev)->gen < 9)
12661                 return;
12662
12663         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
12664         sw_ddb = &dev_priv->wm.skl_hw.ddb;
12665
12666         for_each_intel_crtc(dev, intel_crtc) {
12667                 struct skl_ddb_entry *hw_entry, *sw_entry;
12668                 const enum pipe pipe = intel_crtc->pipe;
12669
12670                 if (!intel_crtc->active)
12671                         continue;
12672
12673                 /* planes */
12674                 for_each_plane(dev_priv, pipe, plane) {
12675                         hw_entry = &hw_ddb.plane[pipe][plane];
12676                         sw_entry = &sw_ddb->plane[pipe][plane];
12677
12678                         if (skl_ddb_entry_equal(hw_entry, sw_entry))
12679                                 continue;
12680
12681                         DRM_ERROR("mismatch in DDB state pipe %c plane %d "
12682                                   "(expected (%u,%u), found (%u,%u))\n",
12683                                   pipe_name(pipe), plane + 1,
12684                                   sw_entry->start, sw_entry->end,
12685                                   hw_entry->start, hw_entry->end);
12686                 }
12687
12688                 /* cursor */
12689                 hw_entry = &hw_ddb.cursor[pipe];
12690                 sw_entry = &sw_ddb->cursor[pipe];
12691
12692                 if (skl_ddb_entry_equal(hw_entry, sw_entry))
12693                         continue;
12694
12695                 DRM_ERROR("mismatch in DDB state pipe %c cursor "
12696                           "(expected (%u,%u), found (%u,%u))\n",
12697                           pipe_name(pipe),
12698                           sw_entry->start, sw_entry->end,
12699                           hw_entry->start, hw_entry->end);
12700         }
12701 }
12702
12703 static void
12704 check_connector_state(struct drm_device *dev)
12705 {
12706         struct intel_connector *connector;
12707
12708         for_each_intel_connector(dev, connector) {
12709                 /* This also checks the encoder/connector hw state with the
12710                  * ->get_hw_state callbacks. */
12711                 intel_connector_check_state(connector);
12712
12713                 I915_STATE_WARN(&connector->new_encoder->base != connector->base.encoder,
12714                      "connector's staged encoder doesn't match current encoder\n");
12715         }
12716 }
12717
12718 static void
12719 check_encoder_state(struct drm_device *dev)
12720 {
12721         struct intel_encoder *encoder;
12722         struct intel_connector *connector;
12723
12724         for_each_intel_encoder(dev, encoder) {
12725                 bool enabled = false;
12726                 bool active = false;
12727                 enum pipe pipe, tracked_pipe;
12728
12729                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
12730                               encoder->base.base.id,
12731                               encoder->base.name);
12732
12733                 I915_STATE_WARN(&encoder->new_crtc->base != encoder->base.crtc,
12734                      "encoder's stage crtc doesn't match current crtc\n");
12735                 I915_STATE_WARN(encoder->connectors_active && !encoder->base.crtc,
12736                      "encoder's active_connectors set, but no crtc\n");
12737
12738                 for_each_intel_connector(dev, connector) {
12739                         if (connector->base.encoder != &encoder->base)
12740                                 continue;
12741                         enabled = true;
12742                         if (connector->base.dpms != DRM_MODE_DPMS_OFF)
12743                                 active = true;
12744                 }
12745                 /*
12746                  * for MST connectors if we unplug the connector is gone
12747                  * away but the encoder is still connected to a crtc
12748                  * until a modeset happens in response to the hotplug.
12749                  */
12750                 if (!enabled && encoder->base.encoder_type == DRM_MODE_ENCODER_DPMST)
12751                         continue;
12752
12753                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
12754                      "encoder's enabled state mismatch "
12755                      "(expected %i, found %i)\n",
12756                      !!encoder->base.crtc, enabled);
12757                 I915_STATE_WARN(active && !encoder->base.crtc,
12758                      "active encoder with no crtc\n");
12759
12760                 I915_STATE_WARN(encoder->connectors_active != active,
12761                      "encoder's computed active state doesn't match tracked active state "
12762                      "(expected %i, found %i)\n", active, encoder->connectors_active);
12763
12764                 active = encoder->get_hw_state(encoder, &pipe);
12765                 I915_STATE_WARN(active != encoder->connectors_active,
12766                      "encoder's hw state doesn't match sw tracking "
12767                      "(expected %i, found %i)\n",
12768                      encoder->connectors_active, active);
12769
12770                 if (!encoder->base.crtc)
12771                         continue;
12772
12773                 tracked_pipe = to_intel_crtc(encoder->base.crtc)->pipe;
12774                 I915_STATE_WARN(active && pipe != tracked_pipe,
12775                      "active encoder's pipe doesn't match"
12776                      "(expected %i, found %i)\n",
12777                      tracked_pipe, pipe);
12778
12779         }
12780 }
12781
12782 static void
12783 check_crtc_state(struct drm_device *dev)
12784 {
12785         struct drm_i915_private *dev_priv = dev->dev_private;
12786         struct intel_crtc *crtc;
12787         struct intel_encoder *encoder;
12788         struct intel_crtc_state pipe_config;
12789
12790         for_each_intel_crtc(dev, crtc) {
12791                 bool enabled = false;
12792                 bool active = false;
12793
12794                 memset(&pipe_config, 0, sizeof(pipe_config));
12795
12796                 DRM_DEBUG_KMS("[CRTC:%d]\n",
12797                               crtc->base.base.id);
12798
12799                 I915_STATE_WARN(crtc->active && !crtc->base.state->enable,
12800                      "active crtc, but not enabled in sw tracking\n");
12801
12802                 for_each_intel_encoder(dev, encoder) {
12803                         if (encoder->base.crtc != &crtc->base)
12804                                 continue;
12805                         enabled = true;
12806                         if (encoder->connectors_active)
12807                                 active = true;
12808                 }
12809
12810                 I915_STATE_WARN(active != crtc->active,
12811                      "crtc's computed active state doesn't match tracked active state "
12812                      "(expected %i, found %i)\n", active, crtc->active);
12813                 I915_STATE_WARN(enabled != crtc->base.state->enable,
12814                      "crtc's computed enabled state doesn't match tracked enabled state "
12815                      "(expected %i, found %i)\n", enabled,
12816                                 crtc->base.state->enable);
12817
12818                 active = dev_priv->display.get_pipe_config(crtc,
12819                                                            &pipe_config);
12820
12821                 /* hw state is inconsistent with the pipe quirk */
12822                 if ((crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
12823                     (crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
12824                         active = crtc->active;
12825
12826                 for_each_intel_encoder(dev, encoder) {
12827                         enum pipe pipe;
12828                         if (encoder->base.crtc != &crtc->base)
12829                                 continue;
12830                         if (encoder->get_hw_state(encoder, &pipe))
12831                                 encoder->get_config(encoder, &pipe_config);
12832                 }
12833
12834                 I915_STATE_WARN(crtc->active != active,
12835                      "crtc active state doesn't match with hw state "
12836                      "(expected %i, found %i)\n", crtc->active, active);
12837
12838                 I915_STATE_WARN(crtc->active != crtc->base.state->active,
12839                      "transitional active state does not match atomic hw state "
12840                      "(expected %i, found %i)\n", crtc->base.state->active, crtc->active);
12841
12842                 if (!active)
12843                         continue;
12844
12845                 if (!intel_pipe_config_compare(dev, crtc->config,
12846                                                &pipe_config, false)) {
12847                         I915_STATE_WARN(1, "pipe state doesn't match!\n");
12848                         intel_dump_pipe_config(crtc, &pipe_config,
12849                                                "[hw state]");
12850                         intel_dump_pipe_config(crtc, crtc->config,
12851                                                "[sw state]");
12852                 }
12853         }
12854 }
12855
12856 static void
12857 check_shared_dpll_state(struct drm_device *dev)
12858 {
12859         struct drm_i915_private *dev_priv = dev->dev_private;
12860         struct intel_crtc *crtc;
12861         struct intel_dpll_hw_state dpll_hw_state;
12862         int i;
12863
12864         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
12865                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
12866                 int enabled_crtcs = 0, active_crtcs = 0;
12867                 bool active;
12868
12869                 memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
12870
12871                 DRM_DEBUG_KMS("%s\n", pll->name);
12872
12873                 active = pll->get_hw_state(dev_priv, pll, &dpll_hw_state);
12874
12875                 I915_STATE_WARN(pll->active > hweight32(pll->config.crtc_mask),
12876                      "more active pll users than references: %i vs %i\n",
12877                      pll->active, hweight32(pll->config.crtc_mask));
12878                 I915_STATE_WARN(pll->active && !pll->on,
12879                      "pll in active use but not on in sw tracking\n");
12880                 I915_STATE_WARN(pll->on && !pll->active,
12881                      "pll in on but not on in use in sw tracking\n");
12882                 I915_STATE_WARN(pll->on != active,
12883                      "pll on state mismatch (expected %i, found %i)\n",
12884                      pll->on, active);
12885
12886                 for_each_intel_crtc(dev, crtc) {
12887                         if (crtc->base.state->enable && intel_crtc_to_shared_dpll(crtc) == pll)
12888                                 enabled_crtcs++;
12889                         if (crtc->active && intel_crtc_to_shared_dpll(crtc) == pll)
12890                                 active_crtcs++;
12891                 }
12892                 I915_STATE_WARN(pll->active != active_crtcs,
12893                      "pll active crtcs mismatch (expected %i, found %i)\n",
12894                      pll->active, active_crtcs);
12895                 I915_STATE_WARN(hweight32(pll->config.crtc_mask) != enabled_crtcs,
12896                      "pll enabled crtcs mismatch (expected %i, found %i)\n",
12897                      hweight32(pll->config.crtc_mask), enabled_crtcs);
12898
12899                 I915_STATE_WARN(pll->on && memcmp(&pll->config.hw_state, &dpll_hw_state,
12900                                        sizeof(dpll_hw_state)),
12901                      "pll hw state mismatch\n");
12902         }
12903 }
12904
12905 void
12906 intel_modeset_check_state(struct drm_device *dev)
12907 {
12908         check_wm_state(dev);
12909         check_connector_state(dev);
12910         check_encoder_state(dev);
12911         check_crtc_state(dev);
12912         check_shared_dpll_state(dev);
12913 }
12914
12915 void ironlake_check_encoder_dotclock(const struct intel_crtc_state *pipe_config,
12916                                      int dotclock)
12917 {
12918         /*
12919          * FDI already provided one idea for the dotclock.
12920          * Yell if the encoder disagrees.
12921          */
12922         WARN(!intel_fuzzy_clock_check(pipe_config->base.adjusted_mode.crtc_clock, dotclock),
12923              "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
12924              pipe_config->base.adjusted_mode.crtc_clock, dotclock);
12925 }
12926
12927 static void update_scanline_offset(struct intel_crtc *crtc)
12928 {
12929         struct drm_device *dev = crtc->base.dev;
12930
12931         /*
12932          * The scanline counter increments at the leading edge of hsync.
12933          *
12934          * On most platforms it starts counting from vtotal-1 on the
12935          * first active line. That means the scanline counter value is
12936          * always one less than what we would expect. Ie. just after
12937          * start of vblank, which also occurs at start of hsync (on the
12938          * last active line), the scanline counter will read vblank_start-1.
12939          *
12940          * On gen2 the scanline counter starts counting from 1 instead
12941          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
12942          * to keep the value positive), instead of adding one.
12943          *
12944          * On HSW+ the behaviour of the scanline counter depends on the output
12945          * type. For DP ports it behaves like most other platforms, but on HDMI
12946          * there's an extra 1 line difference. So we need to add two instead of
12947          * one to the value.
12948          */
12949         if (IS_GEN2(dev)) {
12950                 const struct drm_display_mode *mode = &crtc->config->base.adjusted_mode;
12951                 int vtotal;
12952
12953                 vtotal = mode->crtc_vtotal;
12954                 if (mode->flags & DRM_MODE_FLAG_INTERLACE)
12955                         vtotal /= 2;
12956
12957                 crtc->scanline_offset = vtotal - 1;
12958         } else if (HAS_DDI(dev) &&
12959                    intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI)) {
12960                 crtc->scanline_offset = 2;
12961         } else
12962                 crtc->scanline_offset = 1;
12963 }
12964
12965 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
12966 {
12967         struct drm_device *dev = state->dev;
12968         struct drm_i915_private *dev_priv = to_i915(dev);
12969         struct intel_shared_dpll_config *shared_dpll = NULL;
12970         struct intel_crtc *intel_crtc;
12971         struct intel_crtc_state *intel_crtc_state;
12972         struct drm_crtc *crtc;
12973         struct drm_crtc_state *crtc_state;
12974         int i;
12975
12976         if (!dev_priv->display.crtc_compute_clock)
12977                 return;
12978
12979         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12980                 int dpll;
12981
12982                 intel_crtc = to_intel_crtc(crtc);
12983                 intel_crtc_state = to_intel_crtc_state(crtc_state);
12984                 dpll = intel_crtc_state->shared_dpll;
12985
12986                 if (!needs_modeset(crtc_state) || dpll == DPLL_ID_PRIVATE)
12987                         continue;
12988
12989                 intel_crtc_state->shared_dpll = DPLL_ID_PRIVATE;
12990
12991                 if (!shared_dpll)
12992                         shared_dpll = intel_atomic_get_shared_dpll_state(state);
12993
12994                 shared_dpll[dpll].crtc_mask &= ~(1 << intel_crtc->pipe);
12995         }
12996 }
12997
12998 /*
12999  * This implements the workaround described in the "notes" section of the mode
13000  * set sequence documentation. When going from no pipes or single pipe to
13001  * multiple pipes, and planes are enabled after the pipe, we need to wait at
13002  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
13003  */
13004 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
13005 {
13006         struct drm_crtc_state *crtc_state;
13007         struct intel_crtc *intel_crtc;
13008         struct drm_crtc *crtc;
13009         struct intel_crtc_state *first_crtc_state = NULL;
13010         struct intel_crtc_state *other_crtc_state = NULL;
13011         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
13012         int i;
13013
13014         /* look at all crtc's that are going to be enabled in during modeset */
13015         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13016                 intel_crtc = to_intel_crtc(crtc);
13017
13018                 if (!crtc_state->active || !needs_modeset(crtc_state))
13019                         continue;
13020
13021                 if (first_crtc_state) {
13022                         other_crtc_state = to_intel_crtc_state(crtc_state);
13023                         break;
13024                 } else {
13025                         first_crtc_state = to_intel_crtc_state(crtc_state);
13026                         first_pipe = intel_crtc->pipe;
13027                 }
13028         }
13029
13030         /* No workaround needed? */
13031         if (!first_crtc_state)
13032                 return 0;
13033
13034         /* w/a possibly needed, check how many crtc's are already enabled. */
13035         for_each_intel_crtc(state->dev, intel_crtc) {
13036                 struct intel_crtc_state *pipe_config;
13037
13038                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
13039                 if (IS_ERR(pipe_config))
13040                         return PTR_ERR(pipe_config);
13041
13042                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
13043
13044                 if (!pipe_config->base.active ||
13045                     needs_modeset(&pipe_config->base))
13046                         continue;
13047
13048                 /* 2 or more enabled crtcs means no need for w/a */
13049                 if (enabled_pipe != INVALID_PIPE)
13050                         return 0;
13051
13052                 enabled_pipe = intel_crtc->pipe;
13053         }
13054
13055         if (enabled_pipe != INVALID_PIPE)
13056                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
13057         else if (other_crtc_state)
13058                 other_crtc_state->hsw_workaround_pipe = first_pipe;
13059
13060         return 0;
13061 }
13062
13063 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
13064 {
13065         struct drm_crtc *crtc;
13066         struct drm_crtc_state *crtc_state;
13067         int ret = 0;
13068
13069         /* add all active pipes to the state */
13070         for_each_crtc(state->dev, crtc) {
13071                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
13072                 if (IS_ERR(crtc_state))
13073                         return PTR_ERR(crtc_state);
13074
13075                 if (!crtc_state->active || needs_modeset(crtc_state))
13076                         continue;
13077
13078                 crtc_state->mode_changed = true;
13079
13080                 ret = drm_atomic_add_affected_connectors(state, crtc);
13081                 if (ret)
13082                         break;
13083
13084                 ret = drm_atomic_add_affected_planes(state, crtc);
13085                 if (ret)
13086                         break;
13087         }
13088
13089         return ret;
13090 }
13091
13092
13093 /* Code that should eventually be part of atomic_check() */
13094 static int intel_modeset_checks(struct drm_atomic_state *state)
13095 {
13096         struct drm_device *dev = state->dev;
13097         struct drm_i915_private *dev_priv = dev->dev_private;
13098         int ret;
13099
13100         if (!check_digital_port_conflicts(state)) {
13101                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
13102                 return -EINVAL;
13103         }
13104
13105         /*
13106          * See if the config requires any additional preparation, e.g.
13107          * to adjust global state with pipes off.  We need to do this
13108          * here so we can get the modeset_pipe updated config for the new
13109          * mode set on this crtc.  For other crtcs we need to use the
13110          * adjusted_mode bits in the crtc directly.
13111          */
13112         if (dev_priv->display.modeset_calc_cdclk) {
13113                 unsigned int cdclk;
13114
13115                 ret = dev_priv->display.modeset_calc_cdclk(state);
13116
13117                 cdclk = to_intel_atomic_state(state)->cdclk;
13118                 if (!ret && cdclk != dev_priv->cdclk_freq)
13119                         ret = intel_modeset_all_pipes(state);
13120
13121                 if (ret < 0)
13122                         return ret;
13123         } else
13124                 to_intel_atomic_state(state)->cdclk = dev_priv->cdclk_freq;
13125
13126         intel_modeset_clear_plls(state);
13127
13128         if (IS_HASWELL(dev))
13129                 return haswell_mode_set_planes_workaround(state);
13130
13131         return 0;
13132 }
13133
13134 static int
13135 intel_modeset_compute_config(struct drm_atomic_state *state)
13136 {
13137         struct drm_crtc *crtc;
13138         struct drm_crtc_state *crtc_state;
13139         int ret, i;
13140         bool any_ms = false;
13141
13142         ret = drm_atomic_helper_check_modeset(state->dev, state);
13143         if (ret)
13144                 return ret;
13145
13146         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13147                 struct intel_crtc_state *pipe_config =
13148                         to_intel_crtc_state(crtc_state);
13149                 bool modeset, recalc;
13150
13151                 if (!crtc_state->enable) {
13152                         if (needs_modeset(crtc_state))
13153                                 any_ms = true;
13154                         continue;
13155                 }
13156
13157                 modeset = needs_modeset(crtc_state);
13158                 recalc = pipe_config->quirks & PIPE_CONFIG_QUIRK_INHERITED_MODE;
13159
13160                 if (!modeset && !recalc)
13161                         continue;
13162
13163                 if (recalc) {
13164                         ret = drm_atomic_add_affected_connectors(state, crtc);
13165                         if (ret)
13166                                 return ret;
13167                 }
13168
13169                 ret = intel_modeset_pipe_config(crtc, pipe_config);
13170                 if (ret)
13171                         return ret;
13172
13173                 if (recalc && !intel_pipe_config_compare(state->dev,
13174                                         to_intel_crtc_state(crtc->state),
13175                                         pipe_config, true)) {
13176                         modeset = crtc_state->mode_changed = true;
13177
13178                         ret = drm_atomic_add_affected_planes(state, crtc);
13179                         if (ret)
13180                                 return ret;
13181                 }
13182
13183                 any_ms = modeset;
13184                 intel_dump_pipe_config(to_intel_crtc(crtc),
13185                                        pipe_config,
13186                                        modeset ? "[modeset]" : "[fastboot]");
13187         }
13188
13189         if (any_ms) {
13190                 ret = intel_modeset_checks(state);
13191
13192                 if (ret)
13193                         return ret;
13194         } else
13195                 to_intel_atomic_state(state)->cdclk =
13196                         to_i915(state->dev)->cdclk_freq;
13197
13198         return drm_atomic_helper_check_planes(state->dev, state);
13199 }
13200
13201 static int __intel_set_mode(struct drm_atomic_state *state)
13202 {
13203         struct drm_device *dev = state->dev;
13204         struct drm_i915_private *dev_priv = dev->dev_private;
13205         struct drm_crtc *crtc;
13206         struct drm_crtc_state *crtc_state;
13207         int ret = 0;
13208         int i;
13209         bool any_ms = false;
13210
13211         ret = drm_atomic_helper_prepare_planes(dev, state);
13212         if (ret)
13213                 return ret;
13214
13215         drm_atomic_helper_swap_state(dev, state);
13216
13217         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13218                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13219
13220                 if (!needs_modeset(crtc->state))
13221                         continue;
13222
13223                 any_ms = true;
13224                 intel_pre_plane_update(intel_crtc);
13225
13226                 if (crtc_state->active) {
13227                         intel_crtc_disable_planes(crtc, crtc_state->plane_mask);
13228                         dev_priv->display.crtc_disable(crtc);
13229                         intel_crtc->active = false;
13230                         intel_disable_shared_dpll(intel_crtc);
13231                 }
13232         }
13233
13234         /* Only after disabling all output pipelines that will be changed can we
13235          * update the the output configuration. */
13236         intel_modeset_update_state(state);
13237
13238         /* The state has been swaped above, so state actually contains the
13239          * old state now. */
13240         if (any_ms)
13241                 modeset_update_crtc_power_domains(state);
13242
13243         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
13244         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13245                 if (needs_modeset(crtc->state) && crtc->state->active) {
13246                         update_scanline_offset(to_intel_crtc(crtc));
13247                         dev_priv->display.crtc_enable(crtc);
13248                 }
13249
13250                 drm_atomic_helper_commit_planes_on_crtc(crtc_state);
13251         }
13252
13253         /* FIXME: add subpixel order */
13254
13255         drm_atomic_helper_cleanup_planes(dev, state);
13256
13257         drm_atomic_state_free(state);
13258
13259         return 0;
13260 }
13261
13262 static int intel_set_mode_checked(struct drm_atomic_state *state)
13263 {
13264         struct drm_device *dev = state->dev;
13265         int ret;
13266
13267         ret = __intel_set_mode(state);
13268         if (ret == 0)
13269                 intel_modeset_check_state(dev);
13270
13271         return ret;
13272 }
13273
13274 static int intel_set_mode(struct drm_atomic_state *state)
13275 {
13276         int ret;
13277
13278         ret = intel_modeset_compute_config(state);
13279         if (ret)
13280                 return ret;
13281
13282         return intel_set_mode_checked(state);
13283 }
13284
13285 void intel_crtc_restore_mode(struct drm_crtc *crtc)
13286 {
13287         struct drm_device *dev = crtc->dev;
13288         struct drm_atomic_state *state;
13289         struct intel_encoder *encoder;
13290         struct intel_connector *connector;
13291         struct drm_connector_state *connector_state;
13292         struct intel_crtc_state *crtc_state;
13293         int ret;
13294
13295         state = drm_atomic_state_alloc(dev);
13296         if (!state) {
13297                 DRM_DEBUG_KMS("[CRTC:%d] mode restore failed, out of memory",
13298                               crtc->base.id);
13299                 return;
13300         }
13301
13302         state->acquire_ctx = dev->mode_config.acquire_ctx;
13303
13304         /* The force restore path in the HW readout code relies on the staged
13305          * config still keeping the user requested config while the actual
13306          * state has been overwritten by the configuration read from HW. We
13307          * need to copy the staged config to the atomic state, otherwise the
13308          * mode set will just reapply the state the HW is already in. */
13309         for_each_intel_encoder(dev, encoder) {
13310                 if (&encoder->new_crtc->base != crtc)
13311                         continue;
13312
13313                 for_each_intel_connector(dev, connector) {
13314                         if (connector->new_encoder != encoder)
13315                                 continue;
13316
13317                         connector_state = drm_atomic_get_connector_state(state, &connector->base);
13318                         if (IS_ERR(connector_state)) {
13319                                 DRM_DEBUG_KMS("Failed to add [CONNECTOR:%d:%s] to state: %ld\n",
13320                                               connector->base.base.id,
13321                                               connector->base.name,
13322                                               PTR_ERR(connector_state));
13323                                 continue;
13324                         }
13325
13326                         connector_state->crtc = crtc;
13327                         connector_state->best_encoder = &encoder->base;
13328                 }
13329         }
13330
13331         crtc_state = intel_atomic_get_crtc_state(state, to_intel_crtc(crtc));
13332         if (IS_ERR(crtc_state)) {
13333                 DRM_DEBUG_KMS("Failed to add [CRTC:%d] to state: %ld\n",
13334                               crtc->base.id, PTR_ERR(crtc_state));
13335                 drm_atomic_state_free(state);
13336                 return;
13337         }
13338
13339         crtc_state->base.active = crtc_state->base.enable =
13340                 to_intel_crtc(crtc)->new_enabled;
13341
13342         drm_mode_copy(&crtc_state->base.mode, &crtc->mode);
13343
13344         intel_modeset_setup_plane_state(state, crtc, &crtc->mode,
13345                                         crtc->primary->fb, crtc->x, crtc->y);
13346
13347         ret = intel_set_mode(state);
13348         if (ret)
13349                 drm_atomic_state_free(state);
13350 }
13351
13352 #undef for_each_intel_crtc_masked
13353
13354 static bool intel_connector_in_mode_set(struct intel_connector *connector,
13355                                         struct drm_mode_set *set)
13356 {
13357         int ro;
13358
13359         for (ro = 0; ro < set->num_connectors; ro++)
13360                 if (set->connectors[ro] == &connector->base)
13361                         return true;
13362
13363         return false;
13364 }
13365
13366 static int
13367 intel_modeset_stage_output_state(struct drm_device *dev,
13368                                  struct drm_mode_set *set,
13369                                  struct drm_atomic_state *state)
13370 {
13371         struct intel_connector *connector;
13372         struct drm_connector *drm_connector;
13373         struct drm_connector_state *connector_state;
13374         struct drm_crtc *crtc;
13375         struct drm_crtc_state *crtc_state;
13376         int i, ret;
13377
13378         /* The upper layers ensure that we either disable a crtc or have a list
13379          * of connectors. For paranoia, double-check this. */
13380         WARN_ON(!set->fb && (set->num_connectors != 0));
13381         WARN_ON(set->fb && (set->num_connectors == 0));
13382
13383         for_each_intel_connector(dev, connector) {
13384                 bool in_mode_set = intel_connector_in_mode_set(connector, set);
13385
13386                 if (!in_mode_set && connector->base.state->crtc != set->crtc)
13387                         continue;
13388
13389                 connector_state =
13390                         drm_atomic_get_connector_state(state, &connector->base);
13391                 if (IS_ERR(connector_state))
13392                         return PTR_ERR(connector_state);
13393
13394                 if (in_mode_set) {
13395                         int pipe = to_intel_crtc(set->crtc)->pipe;
13396                         connector_state->best_encoder =
13397                                 &intel_find_encoder(connector, pipe)->base;
13398                 }
13399
13400                 if (connector->base.state->crtc != set->crtc)
13401                         continue;
13402
13403                 /* If we disable the crtc, disable all its connectors. Also, if
13404                  * the connector is on the changing crtc but not on the new
13405                  * connector list, disable it. */
13406                 if (!set->fb || !in_mode_set) {
13407                         connector_state->best_encoder = NULL;
13408
13409                         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] to [NOCRTC]\n",
13410                                 connector->base.base.id,
13411                                 connector->base.name);
13412                 }
13413         }
13414         /* connector->new_encoder is now updated for all connectors. */
13415
13416         for_each_connector_in_state(state, drm_connector, connector_state, i) {
13417                 connector = to_intel_connector(drm_connector);
13418
13419                 if (!connector_state->best_encoder) {
13420                         ret = drm_atomic_set_crtc_for_connector(connector_state,
13421                                                                 NULL);
13422                         if (ret)
13423                                 return ret;
13424
13425                         continue;
13426                 }
13427
13428                 if (intel_connector_in_mode_set(connector, set)) {
13429                         struct drm_crtc *crtc = connector->base.state->crtc;
13430
13431                         /* If this connector was in a previous crtc, add it
13432                          * to the state. We might need to disable it. */
13433                         if (crtc) {
13434                                 crtc_state =
13435                                         drm_atomic_get_crtc_state(state, crtc);
13436                                 if (IS_ERR(crtc_state))
13437                                         return PTR_ERR(crtc_state);
13438                         }
13439
13440                         ret = drm_atomic_set_crtc_for_connector(connector_state,
13441                                                                 set->crtc);
13442                         if (ret)
13443                                 return ret;
13444                 }
13445
13446                 /* Make sure the new CRTC will work with the encoder */
13447                 if (!drm_encoder_crtc_ok(connector_state->best_encoder,
13448                                          connector_state->crtc)) {
13449                         return -EINVAL;
13450                 }
13451
13452                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] to [CRTC:%d]\n",
13453                         connector->base.base.id,
13454                         connector->base.name,
13455                         connector_state->crtc->base.id);
13456
13457                 if (connector_state->best_encoder != &connector->encoder->base)
13458                         connector->encoder =
13459                                 to_intel_encoder(connector_state->best_encoder);
13460         }
13461
13462         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13463                 bool has_connectors;
13464
13465                 ret = drm_atomic_add_affected_connectors(state, crtc);
13466                 if (ret)
13467                         return ret;
13468
13469                 has_connectors = !!drm_atomic_connectors_for_crtc(state, crtc);
13470                 if (has_connectors != crtc_state->enable)
13471                         crtc_state->enable =
13472                         crtc_state->active = has_connectors;
13473         }
13474
13475         ret = intel_modeset_setup_plane_state(state, set->crtc, set->mode,
13476                                               set->fb, set->x, set->y);
13477         if (ret)
13478                 return ret;
13479
13480         crtc_state = drm_atomic_get_crtc_state(state, set->crtc);
13481         if (IS_ERR(crtc_state))
13482                 return PTR_ERR(crtc_state);
13483
13484         ret = drm_atomic_set_mode_for_crtc(crtc_state, set->mode);
13485         if (ret)
13486                 return ret;
13487
13488         if (set->num_connectors)
13489                 crtc_state->active = true;
13490
13491         return 0;
13492 }
13493
13494 static int intel_crtc_set_config(struct drm_mode_set *set)
13495 {
13496         struct drm_device *dev;
13497         struct drm_atomic_state *state = NULL;
13498         int ret;
13499
13500         BUG_ON(!set);
13501         BUG_ON(!set->crtc);
13502         BUG_ON(!set->crtc->helper_private);
13503
13504         /* Enforce sane interface api - has been abused by the fb helper. */
13505         BUG_ON(!set->mode && set->fb);
13506         BUG_ON(set->fb && set->num_connectors == 0);
13507
13508         if (set->fb) {
13509                 DRM_DEBUG_KMS("[CRTC:%d] [FB:%d] #connectors=%d (x y) (%i %i)\n",
13510                                 set->crtc->base.id, set->fb->base.id,
13511                                 (int)set->num_connectors, set->x, set->y);
13512         } else {
13513                 DRM_DEBUG_KMS("[CRTC:%d] [NOFB]\n", set->crtc->base.id);
13514         }
13515
13516         dev = set->crtc->dev;
13517
13518         state = drm_atomic_state_alloc(dev);
13519         if (!state)
13520                 return -ENOMEM;
13521
13522         state->acquire_ctx = dev->mode_config.acquire_ctx;
13523
13524         ret = intel_modeset_stage_output_state(dev, set, state);
13525         if (ret)
13526                 goto out;
13527
13528         ret = intel_modeset_compute_config(state);
13529         if (ret)
13530                 goto out;
13531
13532         intel_update_pipe_size(to_intel_crtc(set->crtc));
13533
13534         ret = intel_set_mode_checked(state);
13535         if (ret) {
13536                 DRM_DEBUG_KMS("failed to set mode on [CRTC:%d], err = %d\n",
13537                               set->crtc->base.id, ret);
13538         }
13539
13540 out:
13541         if (ret)
13542                 drm_atomic_state_free(state);
13543         return ret;
13544 }
13545
13546 static const struct drm_crtc_funcs intel_crtc_funcs = {
13547         .gamma_set = intel_crtc_gamma_set,
13548         .set_config = intel_crtc_set_config,
13549         .destroy = intel_crtc_destroy,
13550         .page_flip = intel_crtc_page_flip,
13551         .atomic_duplicate_state = intel_crtc_duplicate_state,
13552         .atomic_destroy_state = intel_crtc_destroy_state,
13553 };
13554
13555 static bool ibx_pch_dpll_get_hw_state(struct drm_i915_private *dev_priv,
13556                                       struct intel_shared_dpll *pll,
13557                                       struct intel_dpll_hw_state *hw_state)
13558 {
13559         uint32_t val;
13560
13561         if (!intel_display_power_is_enabled(dev_priv, POWER_DOMAIN_PLLS))
13562                 return false;
13563
13564         val = I915_READ(PCH_DPLL(pll->id));
13565         hw_state->dpll = val;
13566         hw_state->fp0 = I915_READ(PCH_FP0(pll->id));
13567         hw_state->fp1 = I915_READ(PCH_FP1(pll->id));
13568
13569         return val & DPLL_VCO_ENABLE;
13570 }
13571
13572 static void ibx_pch_dpll_mode_set(struct drm_i915_private *dev_priv,
13573                                   struct intel_shared_dpll *pll)
13574 {
13575         I915_WRITE(PCH_FP0(pll->id), pll->config.hw_state.fp0);
13576         I915_WRITE(PCH_FP1(pll->id), pll->config.hw_state.fp1);
13577 }
13578
13579 static void ibx_pch_dpll_enable(struct drm_i915_private *dev_priv,
13580                                 struct intel_shared_dpll *pll)
13581 {
13582         /* PCH refclock must be enabled first */
13583         ibx_assert_pch_refclk_enabled(dev_priv);
13584
13585         I915_WRITE(PCH_DPLL(pll->id), pll->config.hw_state.dpll);
13586
13587         /* Wait for the clocks to stabilize. */
13588         POSTING_READ(PCH_DPLL(pll->id));
13589         udelay(150);
13590
13591         /* The pixel multiplier can only be updated once the
13592          * DPLL is enabled and the clocks are stable.
13593          *
13594          * So write it again.
13595          */
13596         I915_WRITE(PCH_DPLL(pll->id), pll->config.hw_state.dpll);
13597         POSTING_READ(PCH_DPLL(pll->id));
13598         udelay(200);
13599 }
13600
13601 static void ibx_pch_dpll_disable(struct drm_i915_private *dev_priv,
13602                                  struct intel_shared_dpll *pll)
13603 {
13604         struct drm_device *dev = dev_priv->dev;
13605         struct intel_crtc *crtc;
13606
13607         /* Make sure no transcoder isn't still depending on us. */
13608         for_each_intel_crtc(dev, crtc) {
13609                 if (intel_crtc_to_shared_dpll(crtc) == pll)
13610                         assert_pch_transcoder_disabled(dev_priv, crtc->pipe);
13611         }
13612
13613         I915_WRITE(PCH_DPLL(pll->id), 0);
13614         POSTING_READ(PCH_DPLL(pll->id));
13615         udelay(200);
13616 }
13617
13618 static char *ibx_pch_dpll_names[] = {
13619         "PCH DPLL A",
13620         "PCH DPLL B",
13621 };
13622
13623 static void ibx_pch_dpll_init(struct drm_device *dev)
13624 {
13625         struct drm_i915_private *dev_priv = dev->dev_private;
13626         int i;
13627
13628         dev_priv->num_shared_dpll = 2;
13629
13630         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
13631                 dev_priv->shared_dplls[i].id = i;
13632                 dev_priv->shared_dplls[i].name = ibx_pch_dpll_names[i];
13633                 dev_priv->shared_dplls[i].mode_set = ibx_pch_dpll_mode_set;
13634                 dev_priv->shared_dplls[i].enable = ibx_pch_dpll_enable;
13635                 dev_priv->shared_dplls[i].disable = ibx_pch_dpll_disable;
13636                 dev_priv->shared_dplls[i].get_hw_state =
13637                         ibx_pch_dpll_get_hw_state;
13638         }
13639 }
13640
13641 static void intel_shared_dpll_init(struct drm_device *dev)
13642 {
13643         struct drm_i915_private *dev_priv = dev->dev_private;
13644
13645         intel_update_cdclk(dev);
13646
13647         if (HAS_DDI(dev))
13648                 intel_ddi_pll_init(dev);
13649         else if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
13650                 ibx_pch_dpll_init(dev);
13651         else
13652                 dev_priv->num_shared_dpll = 0;
13653
13654         BUG_ON(dev_priv->num_shared_dpll > I915_NUM_PLLS);
13655 }
13656
13657 /**
13658  * intel_prepare_plane_fb - Prepare fb for usage on plane
13659  * @plane: drm plane to prepare for
13660  * @fb: framebuffer to prepare for presentation
13661  *
13662  * Prepares a framebuffer for usage on a display plane.  Generally this
13663  * involves pinning the underlying object and updating the frontbuffer tracking
13664  * bits.  Some older platforms need special physical address handling for
13665  * cursor planes.
13666  *
13667  * Returns 0 on success, negative error code on failure.
13668  */
13669 int
13670 intel_prepare_plane_fb(struct drm_plane *plane,
13671                        struct drm_framebuffer *fb,
13672                        const struct drm_plane_state *new_state)
13673 {
13674         struct drm_device *dev = plane->dev;
13675         struct intel_plane *intel_plane = to_intel_plane(plane);
13676         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13677         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->fb);
13678         int ret = 0;
13679
13680         if (!obj)
13681                 return 0;
13682
13683         mutex_lock(&dev->struct_mutex);
13684
13685         if (plane->type == DRM_PLANE_TYPE_CURSOR &&
13686             INTEL_INFO(dev)->cursor_needs_physical) {
13687                 int align = IS_I830(dev) ? 16 * 1024 : 256;
13688                 ret = i915_gem_object_attach_phys(obj, align);
13689                 if (ret)
13690                         DRM_DEBUG_KMS("failed to attach phys object\n");
13691         } else {
13692                 ret = intel_pin_and_fence_fb_obj(plane, fb, new_state, NULL, NULL);
13693         }
13694
13695         if (ret == 0)
13696                 i915_gem_track_fb(old_obj, obj, intel_plane->frontbuffer_bit);
13697
13698         mutex_unlock(&dev->struct_mutex);
13699
13700         return ret;
13701 }
13702
13703 /**
13704  * intel_cleanup_plane_fb - Cleans up an fb after plane use
13705  * @plane: drm plane to clean up for
13706  * @fb: old framebuffer that was on plane
13707  *
13708  * Cleans up a framebuffer that has just been removed from a plane.
13709  */
13710 void
13711 intel_cleanup_plane_fb(struct drm_plane *plane,
13712                        struct drm_framebuffer *fb,
13713                        const struct drm_plane_state *old_state)
13714 {
13715         struct drm_device *dev = plane->dev;
13716         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13717
13718         if (WARN_ON(!obj))
13719                 return;
13720
13721         if (plane->type != DRM_PLANE_TYPE_CURSOR ||
13722             !INTEL_INFO(dev)->cursor_needs_physical) {
13723                 mutex_lock(&dev->struct_mutex);
13724                 intel_unpin_fb_obj(fb, old_state);
13725                 mutex_unlock(&dev->struct_mutex);
13726         }
13727 }
13728
13729 int
13730 skl_max_scale(struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state)
13731 {
13732         int max_scale;
13733         struct drm_device *dev;
13734         struct drm_i915_private *dev_priv;
13735         int crtc_clock, cdclk;
13736
13737         if (!intel_crtc || !crtc_state)
13738                 return DRM_PLANE_HELPER_NO_SCALING;
13739
13740         dev = intel_crtc->base.dev;
13741         dev_priv = dev->dev_private;
13742         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
13743         cdclk = to_intel_atomic_state(crtc_state->base.state)->cdclk;
13744
13745         if (!crtc_clock || !cdclk)
13746                 return DRM_PLANE_HELPER_NO_SCALING;
13747
13748         /*
13749          * skl max scale is lower of:
13750          *    close to 3 but not 3, -1 is for that purpose
13751          *            or
13752          *    cdclk/crtc_clock
13753          */
13754         max_scale = min((1 << 16) * 3 - 1, (1 << 8) * ((cdclk << 8) / crtc_clock));
13755
13756         return max_scale;
13757 }
13758
13759 static int
13760 intel_check_primary_plane(struct drm_plane *plane,
13761                           struct intel_crtc_state *crtc_state,
13762                           struct intel_plane_state *state)
13763 {
13764         struct drm_crtc *crtc = state->base.crtc;
13765         struct drm_framebuffer *fb = state->base.fb;
13766         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
13767         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
13768         bool can_position = false;
13769
13770         /* use scaler when colorkey is not required */
13771         if (INTEL_INFO(plane->dev)->gen >= 9 &&
13772             state->ckey.flags == I915_SET_COLORKEY_NONE) {
13773                 min_scale = 1;
13774                 max_scale = skl_max_scale(to_intel_crtc(crtc), crtc_state);
13775                 can_position = true;
13776         }
13777
13778         return drm_plane_helper_check_update(plane, crtc, fb, &state->src,
13779                                              &state->dst, &state->clip,
13780                                              min_scale, max_scale,
13781                                              can_position, true,
13782                                              &state->visible);
13783 }
13784
13785 static void
13786 intel_commit_primary_plane(struct drm_plane *plane,
13787                            struct intel_plane_state *state)
13788 {
13789         struct drm_crtc *crtc = state->base.crtc;
13790         struct drm_framebuffer *fb = state->base.fb;
13791         struct drm_device *dev = plane->dev;
13792         struct drm_i915_private *dev_priv = dev->dev_private;
13793         struct intel_crtc *intel_crtc;
13794         struct drm_rect *src = &state->src;
13795
13796         crtc = crtc ? crtc : plane->crtc;
13797         intel_crtc = to_intel_crtc(crtc);
13798
13799         plane->fb = fb;
13800         crtc->x = src->x1 >> 16;
13801         crtc->y = src->y1 >> 16;
13802
13803         if (!crtc->state->active)
13804                 return;
13805
13806         if (state->visible)
13807                 /* FIXME: kill this fastboot hack */
13808                 intel_update_pipe_size(intel_crtc);
13809
13810         dev_priv->display.update_primary_plane(crtc, fb, crtc->x, crtc->y);
13811 }
13812
13813 static void
13814 intel_disable_primary_plane(struct drm_plane *plane,
13815                             struct drm_crtc *crtc)
13816 {
13817         struct drm_device *dev = plane->dev;
13818         struct drm_i915_private *dev_priv = dev->dev_private;
13819
13820         dev_priv->display.update_primary_plane(crtc, NULL, 0, 0);
13821 }
13822
13823 static void intel_begin_crtc_commit(struct drm_crtc *crtc)
13824 {
13825         struct drm_device *dev = crtc->dev;
13826         struct drm_i915_private *dev_priv = dev->dev_private;
13827         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13828
13829         if (!needs_modeset(crtc->state))
13830                 intel_pre_plane_update(intel_crtc);
13831
13832         if (intel_crtc->atomic.update_wm_pre)
13833                 intel_update_watermarks(crtc);
13834
13835         intel_runtime_pm_get(dev_priv);
13836
13837         /* Perform vblank evasion around commit operation */
13838         if (crtc->state->active)
13839                 intel_crtc->atomic.evade =
13840                         intel_pipe_update_start(intel_crtc,
13841                                                 &intel_crtc->atomic.start_vbl_count);
13842
13843         if (!needs_modeset(crtc->state) && INTEL_INFO(dev)->gen >= 9)
13844                 skl_detach_scalers(intel_crtc);
13845 }
13846
13847 static void intel_finish_crtc_commit(struct drm_crtc *crtc)
13848 {
13849         struct drm_device *dev = crtc->dev;
13850         struct drm_i915_private *dev_priv = dev->dev_private;
13851         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13852
13853         if (intel_crtc->atomic.evade)
13854                 intel_pipe_update_end(intel_crtc,
13855                                       intel_crtc->atomic.start_vbl_count);
13856
13857         intel_runtime_pm_put(dev_priv);
13858
13859         intel_post_plane_update(intel_crtc);
13860 }
13861
13862 /**
13863  * intel_plane_destroy - destroy a plane
13864  * @plane: plane to destroy
13865  *
13866  * Common destruction function for all types of planes (primary, cursor,
13867  * sprite).
13868  */
13869 void intel_plane_destroy(struct drm_plane *plane)
13870 {
13871         struct intel_plane *intel_plane = to_intel_plane(plane);
13872         drm_plane_cleanup(plane);
13873         kfree(intel_plane);
13874 }
13875
13876 const struct drm_plane_funcs intel_plane_funcs = {
13877         .update_plane = drm_atomic_helper_update_plane,
13878         .disable_plane = drm_atomic_helper_disable_plane,
13879         .destroy = intel_plane_destroy,
13880         .set_property = drm_atomic_helper_plane_set_property,
13881         .atomic_get_property = intel_plane_atomic_get_property,
13882         .atomic_set_property = intel_plane_atomic_set_property,
13883         .atomic_duplicate_state = intel_plane_duplicate_state,
13884         .atomic_destroy_state = intel_plane_destroy_state,
13885
13886 };
13887
13888 static struct drm_plane *intel_primary_plane_create(struct drm_device *dev,
13889                                                     int pipe)
13890 {
13891         struct intel_plane *primary;
13892         struct intel_plane_state *state;
13893         const uint32_t *intel_primary_formats;
13894         int num_formats;
13895
13896         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
13897         if (primary == NULL)
13898                 return NULL;
13899
13900         state = intel_create_plane_state(&primary->base);
13901         if (!state) {
13902                 kfree(primary);
13903                 return NULL;
13904         }
13905         primary->base.state = &state->base;
13906
13907         primary->can_scale = false;
13908         primary->max_downscale = 1;
13909         if (INTEL_INFO(dev)->gen >= 9) {
13910                 primary->can_scale = true;
13911                 state->scaler_id = -1;
13912         }
13913         primary->pipe = pipe;
13914         primary->plane = pipe;
13915         primary->frontbuffer_bit = INTEL_FRONTBUFFER_PRIMARY(pipe);
13916         primary->check_plane = intel_check_primary_plane;
13917         primary->commit_plane = intel_commit_primary_plane;
13918         primary->disable_plane = intel_disable_primary_plane;
13919         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4)
13920                 primary->plane = !pipe;
13921
13922         if (INTEL_INFO(dev)->gen >= 9) {
13923                 intel_primary_formats = skl_primary_formats;
13924                 num_formats = ARRAY_SIZE(skl_primary_formats);
13925         } else if (INTEL_INFO(dev)->gen >= 4) {
13926                 intel_primary_formats = i965_primary_formats;
13927                 num_formats = ARRAY_SIZE(i965_primary_formats);
13928         } else {
13929                 intel_primary_formats = i8xx_primary_formats;
13930                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
13931         }
13932
13933         drm_universal_plane_init(dev, &primary->base, 0,
13934                                  &intel_plane_funcs,
13935                                  intel_primary_formats, num_formats,
13936                                  DRM_PLANE_TYPE_PRIMARY);
13937
13938         if (INTEL_INFO(dev)->gen >= 4)
13939                 intel_create_rotation_property(dev, primary);
13940
13941         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
13942
13943         return &primary->base;
13944 }
13945
13946 void intel_create_rotation_property(struct drm_device *dev, struct intel_plane *plane)
13947 {
13948         if (!dev->mode_config.rotation_property) {
13949                 unsigned long flags = BIT(DRM_ROTATE_0) |
13950                         BIT(DRM_ROTATE_180);
13951
13952                 if (INTEL_INFO(dev)->gen >= 9)
13953                         flags |= BIT(DRM_ROTATE_90) | BIT(DRM_ROTATE_270);
13954
13955                 dev->mode_config.rotation_property =
13956                         drm_mode_create_rotation_property(dev, flags);
13957         }
13958         if (dev->mode_config.rotation_property)
13959                 drm_object_attach_property(&plane->base.base,
13960                                 dev->mode_config.rotation_property,
13961                                 plane->base.state->rotation);
13962 }
13963
13964 static int
13965 intel_check_cursor_plane(struct drm_plane *plane,
13966                          struct intel_crtc_state *crtc_state,
13967                          struct intel_plane_state *state)
13968 {
13969         struct drm_crtc *crtc = crtc_state->base.crtc;
13970         struct drm_framebuffer *fb = state->base.fb;
13971         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13972         unsigned stride;
13973         int ret;
13974
13975         ret = drm_plane_helper_check_update(plane, crtc, fb, &state->src,
13976                                             &state->dst, &state->clip,
13977                                             DRM_PLANE_HELPER_NO_SCALING,
13978                                             DRM_PLANE_HELPER_NO_SCALING,
13979                                             true, true, &state->visible);
13980         if (ret)
13981                 return ret;
13982
13983         /* if we want to turn off the cursor ignore width and height */
13984         if (!obj)
13985                 return 0;
13986
13987         /* Check for which cursor types we support */
13988         if (!cursor_size_ok(plane->dev, state->base.crtc_w, state->base.crtc_h)) {
13989                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
13990                           state->base.crtc_w, state->base.crtc_h);
13991                 return -EINVAL;
13992         }
13993
13994         stride = roundup_pow_of_two(state->base.crtc_w) * 4;
13995         if (obj->base.size < stride * state->base.crtc_h) {
13996                 DRM_DEBUG_KMS("buffer is too small\n");
13997                 return -ENOMEM;
13998         }
13999
14000         if (fb->modifier[0] != DRM_FORMAT_MOD_NONE) {
14001                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
14002                 return -EINVAL;
14003         }
14004
14005         return 0;
14006 }
14007
14008 static void
14009 intel_disable_cursor_plane(struct drm_plane *plane,
14010                            struct drm_crtc *crtc)
14011 {
14012         intel_crtc_update_cursor(crtc, false);
14013 }
14014
14015 static void
14016 intel_commit_cursor_plane(struct drm_plane *plane,
14017                           struct intel_plane_state *state)
14018 {
14019         struct drm_crtc *crtc = state->base.crtc;
14020         struct drm_device *dev = plane->dev;
14021         struct intel_crtc *intel_crtc;
14022         struct drm_i915_gem_object *obj = intel_fb_obj(state->base.fb);
14023         uint32_t addr;
14024
14025         crtc = crtc ? crtc : plane->crtc;
14026         intel_crtc = to_intel_crtc(crtc);
14027
14028         plane->fb = state->base.fb;
14029         crtc->cursor_x = state->base.crtc_x;
14030         crtc->cursor_y = state->base.crtc_y;
14031
14032         if (intel_crtc->cursor_bo == obj)
14033                 goto update;
14034
14035         if (!obj)
14036                 addr = 0;
14037         else if (!INTEL_INFO(dev)->cursor_needs_physical)
14038                 addr = i915_gem_obj_ggtt_offset(obj);
14039         else
14040                 addr = obj->phys_handle->busaddr;
14041
14042         intel_crtc->cursor_addr = addr;
14043         intel_crtc->cursor_bo = obj;
14044
14045 update:
14046         if (crtc->state->active)
14047                 intel_crtc_update_cursor(crtc, state->visible);
14048 }
14049
14050 static struct drm_plane *intel_cursor_plane_create(struct drm_device *dev,
14051                                                    int pipe)
14052 {
14053         struct intel_plane *cursor;
14054         struct intel_plane_state *state;
14055
14056         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
14057         if (cursor == NULL)
14058                 return NULL;
14059
14060         state = intel_create_plane_state(&cursor->base);
14061         if (!state) {
14062                 kfree(cursor);
14063                 return NULL;
14064         }
14065         cursor->base.state = &state->base;
14066
14067         cursor->can_scale = false;
14068         cursor->max_downscale = 1;
14069         cursor->pipe = pipe;
14070         cursor->plane = pipe;
14071         cursor->frontbuffer_bit = INTEL_FRONTBUFFER_CURSOR(pipe);
14072         cursor->check_plane = intel_check_cursor_plane;
14073         cursor->commit_plane = intel_commit_cursor_plane;
14074         cursor->disable_plane = intel_disable_cursor_plane;
14075
14076         drm_universal_plane_init(dev, &cursor->base, 0,
14077                                  &intel_plane_funcs,
14078                                  intel_cursor_formats,
14079                                  ARRAY_SIZE(intel_cursor_formats),
14080                                  DRM_PLANE_TYPE_CURSOR);
14081
14082         if (INTEL_INFO(dev)->gen >= 4) {
14083                 if (!dev->mode_config.rotation_property)
14084                         dev->mode_config.rotation_property =
14085                                 drm_mode_create_rotation_property(dev,
14086                                                         BIT(DRM_ROTATE_0) |
14087                                                         BIT(DRM_ROTATE_180));
14088                 if (dev->mode_config.rotation_property)
14089                         drm_object_attach_property(&cursor->base.base,
14090                                 dev->mode_config.rotation_property,
14091                                 state->base.rotation);
14092         }
14093
14094         if (INTEL_INFO(dev)->gen >=9)
14095                 state->scaler_id = -1;
14096
14097         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
14098
14099         return &cursor->base;
14100 }
14101
14102 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
14103         struct intel_crtc_state *crtc_state)
14104 {
14105         int i;
14106         struct intel_scaler *intel_scaler;
14107         struct intel_crtc_scaler_state *scaler_state = &crtc_state->scaler_state;
14108
14109         for (i = 0; i < intel_crtc->num_scalers; i++) {
14110                 intel_scaler = &scaler_state->scalers[i];
14111                 intel_scaler->in_use = 0;
14112                 intel_scaler->mode = PS_SCALER_MODE_DYN;
14113         }
14114
14115         scaler_state->scaler_id = -1;
14116 }
14117
14118 static void intel_crtc_init(struct drm_device *dev, int pipe)
14119 {
14120         struct drm_i915_private *dev_priv = dev->dev_private;
14121         struct intel_crtc *intel_crtc;
14122         struct intel_crtc_state *crtc_state = NULL;
14123         struct drm_plane *primary = NULL;
14124         struct drm_plane *cursor = NULL;
14125         int i, ret;
14126
14127         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
14128         if (intel_crtc == NULL)
14129                 return;
14130
14131         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
14132         if (!crtc_state)
14133                 goto fail;
14134         intel_crtc->config = crtc_state;
14135         intel_crtc->base.state = &crtc_state->base;
14136         crtc_state->base.crtc = &intel_crtc->base;
14137
14138         /* initialize shared scalers */
14139         if (INTEL_INFO(dev)->gen >= 9) {
14140                 if (pipe == PIPE_C)
14141                         intel_crtc->num_scalers = 1;
14142                 else
14143                         intel_crtc->num_scalers = SKL_NUM_SCALERS;
14144
14145                 skl_init_scalers(dev, intel_crtc, crtc_state);
14146         }
14147
14148         primary = intel_primary_plane_create(dev, pipe);
14149         if (!primary)
14150                 goto fail;
14151
14152         cursor = intel_cursor_plane_create(dev, pipe);
14153         if (!cursor)
14154                 goto fail;
14155
14156         ret = drm_crtc_init_with_planes(dev, &intel_crtc->base, primary,
14157                                         cursor, &intel_crtc_funcs);
14158         if (ret)
14159                 goto fail;
14160
14161         drm_mode_crtc_set_gamma_size(&intel_crtc->base, 256);
14162         for (i = 0; i < 256; i++) {
14163                 intel_crtc->lut_r[i] = i;
14164                 intel_crtc->lut_g[i] = i;
14165                 intel_crtc->lut_b[i] = i;
14166         }
14167
14168         /*
14169          * On gen2/3 only plane A can do fbc, but the panel fitter and lvds port
14170          * is hooked to pipe B. Hence we want plane A feeding pipe B.
14171          */
14172         intel_crtc->pipe = pipe;
14173         intel_crtc->plane = pipe;
14174         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4) {
14175                 DRM_DEBUG_KMS("swapping pipes & planes for FBC\n");
14176                 intel_crtc->plane = !pipe;
14177         }
14178
14179         intel_crtc->cursor_base = ~0;
14180         intel_crtc->cursor_cntl = ~0;
14181         intel_crtc->cursor_size = ~0;
14182
14183         intel_crtc->wm.cxsr_allowed = true;
14184
14185         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
14186                dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
14187         dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = &intel_crtc->base;
14188         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = &intel_crtc->base;
14189
14190         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
14191
14192         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
14193         return;
14194
14195 fail:
14196         if (primary)
14197                 drm_plane_cleanup(primary);
14198         if (cursor)
14199                 drm_plane_cleanup(cursor);
14200         kfree(crtc_state);
14201         kfree(intel_crtc);
14202 }
14203
14204 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
14205 {
14206         struct drm_encoder *encoder = connector->base.encoder;
14207         struct drm_device *dev = connector->base.dev;
14208
14209         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
14210
14211         if (!encoder || WARN_ON(!encoder->crtc))
14212                 return INVALID_PIPE;
14213
14214         return to_intel_crtc(encoder->crtc)->pipe;
14215 }
14216
14217 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
14218                                 struct drm_file *file)
14219 {
14220         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
14221         struct drm_crtc *drmmode_crtc;
14222         struct intel_crtc *crtc;
14223
14224         drmmode_crtc = drm_crtc_find(dev, pipe_from_crtc_id->crtc_id);
14225
14226         if (!drmmode_crtc) {
14227                 DRM_ERROR("no such CRTC id\n");
14228                 return -ENOENT;
14229         }
14230
14231         crtc = to_intel_crtc(drmmode_crtc);
14232         pipe_from_crtc_id->pipe = crtc->pipe;
14233
14234         return 0;
14235 }
14236
14237 static int intel_encoder_clones(struct intel_encoder *encoder)
14238 {
14239         struct drm_device *dev = encoder->base.dev;
14240         struct intel_encoder *source_encoder;
14241         int index_mask = 0;
14242         int entry = 0;
14243
14244         for_each_intel_encoder(dev, source_encoder) {
14245                 if (encoders_cloneable(encoder, source_encoder))
14246                         index_mask |= (1 << entry);
14247
14248                 entry++;
14249         }
14250
14251         return index_mask;
14252 }
14253
14254 static bool has_edp_a(struct drm_device *dev)
14255 {
14256         struct drm_i915_private *dev_priv = dev->dev_private;
14257
14258         if (!IS_MOBILE(dev))
14259                 return false;
14260
14261         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
14262                 return false;
14263
14264         if (IS_GEN5(dev) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
14265                 return false;
14266
14267         return true;
14268 }
14269
14270 static bool intel_crt_present(struct drm_device *dev)
14271 {
14272         struct drm_i915_private *dev_priv = dev->dev_private;
14273
14274         if (INTEL_INFO(dev)->gen >= 9)
14275                 return false;
14276
14277         if (IS_HSW_ULT(dev) || IS_BDW_ULT(dev))
14278                 return false;
14279
14280         if (IS_CHERRYVIEW(dev))
14281                 return false;
14282
14283         if (IS_VALLEYVIEW(dev) && !dev_priv->vbt.int_crt_support)
14284                 return false;
14285
14286         return true;
14287 }
14288
14289 static void intel_setup_outputs(struct drm_device *dev)
14290 {
14291         struct drm_i915_private *dev_priv = dev->dev_private;
14292         struct intel_encoder *encoder;
14293         bool dpd_is_edp = false;
14294
14295         intel_lvds_init(dev);
14296
14297         if (intel_crt_present(dev))
14298                 intel_crt_init(dev);
14299
14300         if (IS_BROXTON(dev)) {
14301                 /*
14302                  * FIXME: Broxton doesn't support port detection via the
14303                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
14304                  * detect the ports.
14305                  */
14306                 intel_ddi_init(dev, PORT_A);
14307                 intel_ddi_init(dev, PORT_B);
14308                 intel_ddi_init(dev, PORT_C);
14309         } else if (HAS_DDI(dev)) {
14310                 int found;
14311
14312                 /*
14313                  * Haswell uses DDI functions to detect digital outputs.
14314                  * On SKL pre-D0 the strap isn't connected, so we assume
14315                  * it's there.
14316                  */
14317                 found = I915_READ(DDI_BUF_CTL_A) & DDI_INIT_DISPLAY_DETECTED;
14318                 /* WaIgnoreDDIAStrap: skl */
14319                 if (found ||
14320                     (IS_SKYLAKE(dev) && INTEL_REVID(dev) < SKL_REVID_D0))
14321                         intel_ddi_init(dev, PORT_A);
14322
14323                 /* DDI B, C and D detection is indicated by the SFUSE_STRAP
14324                  * register */
14325                 found = I915_READ(SFUSE_STRAP);
14326
14327                 if (found & SFUSE_STRAP_DDIB_DETECTED)
14328                         intel_ddi_init(dev, PORT_B);
14329                 if (found & SFUSE_STRAP_DDIC_DETECTED)
14330                         intel_ddi_init(dev, PORT_C);
14331                 if (found & SFUSE_STRAP_DDID_DETECTED)
14332                         intel_ddi_init(dev, PORT_D);
14333         } else if (HAS_PCH_SPLIT(dev)) {
14334                 int found;
14335                 dpd_is_edp = intel_dp_is_edp(dev, PORT_D);
14336
14337                 if (has_edp_a(dev))
14338                         intel_dp_init(dev, DP_A, PORT_A);
14339
14340                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
14341                         /* PCH SDVOB multiplex with HDMIB */
14342                         found = intel_sdvo_init(dev, PCH_SDVOB, true);
14343                         if (!found)
14344                                 intel_hdmi_init(dev, PCH_HDMIB, PORT_B);
14345                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
14346                                 intel_dp_init(dev, PCH_DP_B, PORT_B);
14347                 }
14348
14349                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
14350                         intel_hdmi_init(dev, PCH_HDMIC, PORT_C);
14351
14352                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
14353                         intel_hdmi_init(dev, PCH_HDMID, PORT_D);
14354
14355                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
14356                         intel_dp_init(dev, PCH_DP_C, PORT_C);
14357
14358                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
14359                         intel_dp_init(dev, PCH_DP_D, PORT_D);
14360         } else if (IS_VALLEYVIEW(dev)) {
14361                 /*
14362                  * The DP_DETECTED bit is the latched state of the DDC
14363                  * SDA pin at boot. However since eDP doesn't require DDC
14364                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
14365                  * eDP ports may have been muxed to an alternate function.
14366                  * Thus we can't rely on the DP_DETECTED bit alone to detect
14367                  * eDP ports. Consult the VBT as well as DP_DETECTED to
14368                  * detect eDP ports.
14369                  */
14370                 if (I915_READ(VLV_DISPLAY_BASE + GEN4_HDMIB) & SDVO_DETECTED &&
14371                     !intel_dp_is_edp(dev, PORT_B))
14372                         intel_hdmi_init(dev, VLV_DISPLAY_BASE + GEN4_HDMIB,
14373                                         PORT_B);
14374                 if (I915_READ(VLV_DISPLAY_BASE + DP_B) & DP_DETECTED ||
14375                     intel_dp_is_edp(dev, PORT_B))
14376                         intel_dp_init(dev, VLV_DISPLAY_BASE + DP_B, PORT_B);
14377
14378                 if (I915_READ(VLV_DISPLAY_BASE + GEN4_HDMIC) & SDVO_DETECTED &&
14379                     !intel_dp_is_edp(dev, PORT_C))
14380                         intel_hdmi_init(dev, VLV_DISPLAY_BASE + GEN4_HDMIC,
14381                                         PORT_C);
14382                 if (I915_READ(VLV_DISPLAY_BASE + DP_C) & DP_DETECTED ||
14383                     intel_dp_is_edp(dev, PORT_C))
14384                         intel_dp_init(dev, VLV_DISPLAY_BASE + DP_C, PORT_C);
14385
14386                 if (IS_CHERRYVIEW(dev)) {
14387                         if (I915_READ(VLV_DISPLAY_BASE + CHV_HDMID) & SDVO_DETECTED)
14388                                 intel_hdmi_init(dev, VLV_DISPLAY_BASE + CHV_HDMID,
14389                                                 PORT_D);
14390                         /* eDP not supported on port D, so don't check VBT */
14391                         if (I915_READ(VLV_DISPLAY_BASE + DP_D) & DP_DETECTED)
14392                                 intel_dp_init(dev, VLV_DISPLAY_BASE + DP_D, PORT_D);
14393                 }
14394
14395                 intel_dsi_init(dev);
14396         } else if (!IS_GEN2(dev) && !IS_PINEVIEW(dev)) {
14397                 bool found = false;
14398
14399                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14400                         DRM_DEBUG_KMS("probing SDVOB\n");
14401                         found = intel_sdvo_init(dev, GEN3_SDVOB, true);
14402                         if (!found && IS_G4X(dev)) {
14403                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
14404                                 intel_hdmi_init(dev, GEN4_HDMIB, PORT_B);
14405                         }
14406
14407                         if (!found && IS_G4X(dev))
14408                                 intel_dp_init(dev, DP_B, PORT_B);
14409                 }
14410
14411                 /* Before G4X SDVOC doesn't have its own detect register */
14412
14413                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14414                         DRM_DEBUG_KMS("probing SDVOC\n");
14415                         found = intel_sdvo_init(dev, GEN3_SDVOC, false);
14416                 }
14417
14418                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
14419
14420                         if (IS_G4X(dev)) {
14421                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
14422                                 intel_hdmi_init(dev, GEN4_HDMIC, PORT_C);
14423                         }
14424                         if (IS_G4X(dev))
14425                                 intel_dp_init(dev, DP_C, PORT_C);
14426                 }
14427
14428                 if (IS_G4X(dev) &&
14429                     (I915_READ(DP_D) & DP_DETECTED))
14430                         intel_dp_init(dev, DP_D, PORT_D);
14431         } else if (IS_GEN2(dev))
14432                 intel_dvo_init(dev);
14433
14434         if (SUPPORTS_TV(dev))
14435                 intel_tv_init(dev);
14436
14437         intel_psr_init(dev);
14438
14439         for_each_intel_encoder(dev, encoder) {
14440                 encoder->base.possible_crtcs = encoder->crtc_mask;
14441                 encoder->base.possible_clones =
14442                         intel_encoder_clones(encoder);
14443         }
14444
14445         intel_init_pch_refclk(dev);
14446
14447         drm_helper_move_panel_connectors_to_head(dev);
14448 }
14449
14450 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
14451 {
14452         struct drm_device *dev = fb->dev;
14453         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14454
14455         drm_framebuffer_cleanup(fb);
14456         mutex_lock(&dev->struct_mutex);
14457         WARN_ON(!intel_fb->obj->framebuffer_references--);
14458         drm_gem_object_unreference(&intel_fb->obj->base);
14459         mutex_unlock(&dev->struct_mutex);
14460         kfree(intel_fb);
14461 }
14462
14463 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
14464                                                 struct drm_file *file,
14465                                                 unsigned int *handle)
14466 {
14467         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14468         struct drm_i915_gem_object *obj = intel_fb->obj;
14469
14470         return drm_gem_handle_create(file, &obj->base, handle);
14471 }
14472
14473 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
14474                                         struct drm_file *file,
14475                                         unsigned flags, unsigned color,
14476                                         struct drm_clip_rect *clips,
14477                                         unsigned num_clips)
14478 {
14479         struct drm_device *dev = fb->dev;
14480         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14481         struct drm_i915_gem_object *obj = intel_fb->obj;
14482
14483         mutex_lock(&dev->struct_mutex);
14484         intel_fb_obj_flush(obj, false, ORIGIN_GTT);
14485         mutex_unlock(&dev->struct_mutex);
14486
14487         return 0;
14488 }
14489
14490 static const struct drm_framebuffer_funcs intel_fb_funcs = {
14491         .destroy = intel_user_framebuffer_destroy,
14492         .create_handle = intel_user_framebuffer_create_handle,
14493         .dirty = intel_user_framebuffer_dirty,
14494 };
14495
14496 static
14497 u32 intel_fb_pitch_limit(struct drm_device *dev, uint64_t fb_modifier,
14498                          uint32_t pixel_format)
14499 {
14500         u32 gen = INTEL_INFO(dev)->gen;
14501
14502         if (gen >= 9) {
14503                 /* "The stride in bytes must not exceed the of the size of 8K
14504                  *  pixels and 32K bytes."
14505                  */
14506                  return min(8192*drm_format_plane_cpp(pixel_format, 0), 32768);
14507         } else if (gen >= 5 && !IS_VALLEYVIEW(dev)) {
14508                 return 32*1024;
14509         } else if (gen >= 4) {
14510                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14511                         return 16*1024;
14512                 else
14513                         return 32*1024;
14514         } else if (gen >= 3) {
14515                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14516                         return 8*1024;
14517                 else
14518                         return 16*1024;
14519         } else {
14520                 /* XXX DSPC is limited to 4k tiled */
14521                 return 8*1024;
14522         }
14523 }
14524
14525 static int intel_framebuffer_init(struct drm_device *dev,
14526                                   struct intel_framebuffer *intel_fb,
14527                                   struct drm_mode_fb_cmd2 *mode_cmd,
14528                                   struct drm_i915_gem_object *obj)
14529 {
14530         unsigned int aligned_height;
14531         int ret;
14532         u32 pitch_limit, stride_alignment;
14533
14534         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
14535
14536         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
14537                 /* Enforce that fb modifier and tiling mode match, but only for
14538                  * X-tiled. This is needed for FBC. */
14539                 if (!!(obj->tiling_mode == I915_TILING_X) !=
14540                     !!(mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED)) {
14541                         DRM_DEBUG("tiling_mode doesn't match fb modifier\n");
14542                         return -EINVAL;
14543                 }
14544         } else {
14545                 if (obj->tiling_mode == I915_TILING_X)
14546                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
14547                 else if (obj->tiling_mode == I915_TILING_Y) {
14548                         DRM_DEBUG("No Y tiling for legacy addfb\n");
14549                         return -EINVAL;
14550                 }
14551         }
14552
14553         /* Passed in modifier sanity checking. */
14554         switch (mode_cmd->modifier[0]) {
14555         case I915_FORMAT_MOD_Y_TILED:
14556         case I915_FORMAT_MOD_Yf_TILED:
14557                 if (INTEL_INFO(dev)->gen < 9) {
14558                         DRM_DEBUG("Unsupported tiling 0x%llx!\n",
14559                                   mode_cmd->modifier[0]);
14560                         return -EINVAL;
14561                 }
14562         case DRM_FORMAT_MOD_NONE:
14563         case I915_FORMAT_MOD_X_TILED:
14564                 break;
14565         default:
14566                 DRM_DEBUG("Unsupported fb modifier 0x%llx!\n",
14567                           mode_cmd->modifier[0]);
14568                 return -EINVAL;
14569         }
14570
14571         stride_alignment = intel_fb_stride_alignment(dev, mode_cmd->modifier[0],
14572                                                      mode_cmd->pixel_format);
14573         if (mode_cmd->pitches[0] & (stride_alignment - 1)) {
14574                 DRM_DEBUG("pitch (%d) must be at least %u byte aligned\n",
14575                           mode_cmd->pitches[0], stride_alignment);
14576                 return -EINVAL;
14577         }
14578
14579         pitch_limit = intel_fb_pitch_limit(dev, mode_cmd->modifier[0],
14580                                            mode_cmd->pixel_format);
14581         if (mode_cmd->pitches[0] > pitch_limit) {
14582                 DRM_DEBUG("%s pitch (%u) must be at less than %d\n",
14583                           mode_cmd->modifier[0] != DRM_FORMAT_MOD_NONE ?
14584                           "tiled" : "linear",
14585                           mode_cmd->pitches[0], pitch_limit);
14586                 return -EINVAL;
14587         }
14588
14589         if (mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED &&
14590             mode_cmd->pitches[0] != obj->stride) {
14591                 DRM_DEBUG("pitch (%d) must match tiling stride (%d)\n",
14592                           mode_cmd->pitches[0], obj->stride);
14593                 return -EINVAL;
14594         }
14595
14596         /* Reject formats not supported by any plane early. */
14597         switch (mode_cmd->pixel_format) {
14598         case DRM_FORMAT_C8:
14599         case DRM_FORMAT_RGB565:
14600         case DRM_FORMAT_XRGB8888:
14601         case DRM_FORMAT_ARGB8888:
14602                 break;
14603         case DRM_FORMAT_XRGB1555:
14604                 if (INTEL_INFO(dev)->gen > 3) {
14605                         DRM_DEBUG("unsupported pixel format: %s\n",
14606                                   drm_get_format_name(mode_cmd->pixel_format));
14607                         return -EINVAL;
14608                 }
14609                 break;
14610         case DRM_FORMAT_ABGR8888:
14611                 if (!IS_VALLEYVIEW(dev) && INTEL_INFO(dev)->gen < 9) {
14612                         DRM_DEBUG("unsupported pixel format: %s\n",
14613                                   drm_get_format_name(mode_cmd->pixel_format));
14614                         return -EINVAL;
14615                 }
14616                 break;
14617         case DRM_FORMAT_XBGR8888:
14618         case DRM_FORMAT_XRGB2101010:
14619         case DRM_FORMAT_XBGR2101010:
14620                 if (INTEL_INFO(dev)->gen < 4) {
14621                         DRM_DEBUG("unsupported pixel format: %s\n",
14622                                   drm_get_format_name(mode_cmd->pixel_format));
14623                         return -EINVAL;
14624                 }
14625                 break;
14626         case DRM_FORMAT_ABGR2101010:
14627                 if (!IS_VALLEYVIEW(dev)) {
14628                         DRM_DEBUG("unsupported pixel format: %s\n",
14629                                   drm_get_format_name(mode_cmd->pixel_format));
14630                         return -EINVAL;
14631                 }
14632                 break;
14633         case DRM_FORMAT_YUYV:
14634         case DRM_FORMAT_UYVY:
14635         case DRM_FORMAT_YVYU:
14636         case DRM_FORMAT_VYUY:
14637                 if (INTEL_INFO(dev)->gen < 5) {
14638                         DRM_DEBUG("unsupported pixel format: %s\n",
14639                                   drm_get_format_name(mode_cmd->pixel_format));
14640                         return -EINVAL;
14641                 }
14642                 break;
14643         default:
14644                 DRM_DEBUG("unsupported pixel format: %s\n",
14645                           drm_get_format_name(mode_cmd->pixel_format));
14646                 return -EINVAL;
14647         }
14648
14649         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14650         if (mode_cmd->offsets[0] != 0)
14651                 return -EINVAL;
14652
14653         aligned_height = intel_fb_align_height(dev, mode_cmd->height,
14654                                                mode_cmd->pixel_format,
14655                                                mode_cmd->modifier[0]);
14656         /* FIXME drm helper for size checks (especially planar formats)? */
14657         if (obj->base.size < aligned_height * mode_cmd->pitches[0])
14658                 return -EINVAL;
14659
14660         drm_helper_mode_fill_fb_struct(&intel_fb->base, mode_cmd);
14661         intel_fb->obj = obj;
14662         intel_fb->obj->framebuffer_references++;
14663
14664         ret = drm_framebuffer_init(dev, &intel_fb->base, &intel_fb_funcs);
14665         if (ret) {
14666                 DRM_ERROR("framebuffer init failed %d\n", ret);
14667                 return ret;
14668         }
14669
14670         return 0;
14671 }
14672
14673 static struct drm_framebuffer *
14674 intel_user_framebuffer_create(struct drm_device *dev,
14675                               struct drm_file *filp,
14676                               struct drm_mode_fb_cmd2 *mode_cmd)
14677 {
14678         struct drm_i915_gem_object *obj;
14679
14680         obj = to_intel_bo(drm_gem_object_lookup(dev, filp,
14681                                                 mode_cmd->handles[0]));
14682         if (&obj->base == NULL)
14683                 return ERR_PTR(-ENOENT);
14684
14685         return intel_framebuffer_create(dev, mode_cmd, obj);
14686 }
14687
14688 #ifndef CONFIG_DRM_I915_FBDEV
14689 static inline void intel_fbdev_output_poll_changed(struct drm_device *dev)
14690 {
14691 }
14692 #endif
14693
14694 static const struct drm_mode_config_funcs intel_mode_funcs = {
14695         .fb_create = intel_user_framebuffer_create,
14696         .output_poll_changed = intel_fbdev_output_poll_changed,
14697         .atomic_check = intel_atomic_check,
14698         .atomic_commit = intel_atomic_commit,
14699         .atomic_state_alloc = intel_atomic_state_alloc,
14700         .atomic_state_clear = intel_atomic_state_clear,
14701 };
14702
14703 /* Set up chip specific display functions */
14704 static void intel_init_display(struct drm_device *dev)
14705 {
14706         struct drm_i915_private *dev_priv = dev->dev_private;
14707
14708         if (HAS_PCH_SPLIT(dev) || IS_G4X(dev))
14709                 dev_priv->display.find_dpll = g4x_find_best_dpll;
14710         else if (IS_CHERRYVIEW(dev))
14711                 dev_priv->display.find_dpll = chv_find_best_dpll;
14712         else if (IS_VALLEYVIEW(dev))
14713                 dev_priv->display.find_dpll = vlv_find_best_dpll;
14714         else if (IS_PINEVIEW(dev))
14715                 dev_priv->display.find_dpll = pnv_find_best_dpll;
14716         else
14717                 dev_priv->display.find_dpll = i9xx_find_best_dpll;
14718
14719         if (INTEL_INFO(dev)->gen >= 9) {
14720                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14721                 dev_priv->display.get_initial_plane_config =
14722                         skylake_get_initial_plane_config;
14723                 dev_priv->display.crtc_compute_clock =
14724                         haswell_crtc_compute_clock;
14725                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14726                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14727                 dev_priv->display.update_primary_plane =
14728                         skylake_update_primary_plane;
14729         } else if (HAS_DDI(dev)) {
14730                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14731                 dev_priv->display.get_initial_plane_config =
14732                         ironlake_get_initial_plane_config;
14733                 dev_priv->display.crtc_compute_clock =
14734                         haswell_crtc_compute_clock;
14735                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14736                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14737                 dev_priv->display.update_primary_plane =
14738                         ironlake_update_primary_plane;
14739         } else if (HAS_PCH_SPLIT(dev)) {
14740                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
14741                 dev_priv->display.get_initial_plane_config =
14742                         ironlake_get_initial_plane_config;
14743                 dev_priv->display.crtc_compute_clock =
14744                         ironlake_crtc_compute_clock;
14745                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
14746                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
14747                 dev_priv->display.update_primary_plane =
14748                         ironlake_update_primary_plane;
14749         } else if (IS_VALLEYVIEW(dev)) {
14750                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14751                 dev_priv->display.get_initial_plane_config =
14752                         i9xx_get_initial_plane_config;
14753                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14754                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14755                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14756                 dev_priv->display.update_primary_plane =
14757                         i9xx_update_primary_plane;
14758         } else {
14759                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14760                 dev_priv->display.get_initial_plane_config =
14761                         i9xx_get_initial_plane_config;
14762                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14763                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14764                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14765                 dev_priv->display.update_primary_plane =
14766                         i9xx_update_primary_plane;
14767         }
14768
14769         /* Returns the core display clock speed */
14770         if (IS_SKYLAKE(dev))
14771                 dev_priv->display.get_display_clock_speed =
14772                         skylake_get_display_clock_speed;
14773         else if (IS_BROXTON(dev))
14774                 dev_priv->display.get_display_clock_speed =
14775                         broxton_get_display_clock_speed;
14776         else if (IS_BROADWELL(dev))
14777                 dev_priv->display.get_display_clock_speed =
14778                         broadwell_get_display_clock_speed;
14779         else if (IS_HASWELL(dev))
14780                 dev_priv->display.get_display_clock_speed =
14781                         haswell_get_display_clock_speed;
14782         else if (IS_VALLEYVIEW(dev))
14783                 dev_priv->display.get_display_clock_speed =
14784                         valleyview_get_display_clock_speed;
14785         else if (IS_GEN5(dev))
14786                 dev_priv->display.get_display_clock_speed =
14787                         ilk_get_display_clock_speed;
14788         else if (IS_I945G(dev) || IS_BROADWATER(dev) ||
14789                  IS_GEN6(dev) || IS_IVYBRIDGE(dev))
14790                 dev_priv->display.get_display_clock_speed =
14791                         i945_get_display_clock_speed;
14792         else if (IS_GM45(dev))
14793                 dev_priv->display.get_display_clock_speed =
14794                         gm45_get_display_clock_speed;
14795         else if (IS_CRESTLINE(dev))
14796                 dev_priv->display.get_display_clock_speed =
14797                         i965gm_get_display_clock_speed;
14798         else if (IS_PINEVIEW(dev))
14799                 dev_priv->display.get_display_clock_speed =
14800                         pnv_get_display_clock_speed;
14801         else if (IS_G33(dev) || IS_G4X(dev))
14802                 dev_priv->display.get_display_clock_speed =
14803                         g33_get_display_clock_speed;
14804         else if (IS_I915G(dev))
14805                 dev_priv->display.get_display_clock_speed =
14806                         i915_get_display_clock_speed;
14807         else if (IS_I945GM(dev) || IS_845G(dev))
14808                 dev_priv->display.get_display_clock_speed =
14809                         i9xx_misc_get_display_clock_speed;
14810         else if (IS_PINEVIEW(dev))
14811                 dev_priv->display.get_display_clock_speed =
14812                         pnv_get_display_clock_speed;
14813         else if (IS_I915GM(dev))
14814                 dev_priv->display.get_display_clock_speed =
14815                         i915gm_get_display_clock_speed;
14816         else if (IS_I865G(dev))
14817                 dev_priv->display.get_display_clock_speed =
14818                         i865_get_display_clock_speed;
14819         else if (IS_I85X(dev))
14820                 dev_priv->display.get_display_clock_speed =
14821                         i85x_get_display_clock_speed;
14822         else { /* 830 */
14823                 WARN(!IS_I830(dev), "Unknown platform. Assuming 133 MHz CDCLK\n");
14824                 dev_priv->display.get_display_clock_speed =
14825                         i830_get_display_clock_speed;
14826         }
14827
14828         if (IS_GEN5(dev)) {
14829                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
14830         } else if (IS_GEN6(dev)) {
14831                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
14832         } else if (IS_IVYBRIDGE(dev)) {
14833                 /* FIXME: detect B0+ stepping and use auto training */
14834                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
14835         } else if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
14836                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
14837                 if (IS_BROADWELL(dev)) {
14838                         dev_priv->display.modeset_commit_cdclk =
14839                                 broadwell_modeset_commit_cdclk;
14840                         dev_priv->display.modeset_calc_cdclk =
14841                                 broadwell_modeset_calc_cdclk;
14842                 }
14843         } else if (IS_VALLEYVIEW(dev)) {
14844                 dev_priv->display.modeset_commit_cdclk =
14845                         valleyview_modeset_commit_cdclk;
14846                 dev_priv->display.modeset_calc_cdclk =
14847                         valleyview_modeset_calc_cdclk;
14848         } else if (IS_BROXTON(dev)) {
14849                 dev_priv->display.modeset_commit_cdclk =
14850                         broxton_modeset_commit_cdclk;
14851                 dev_priv->display.modeset_calc_cdclk =
14852                         broxton_modeset_calc_cdclk;
14853         }
14854
14855         switch (INTEL_INFO(dev)->gen) {
14856         case 2:
14857                 dev_priv->display.queue_flip = intel_gen2_queue_flip;
14858                 break;
14859
14860         case 3:
14861                 dev_priv->display.queue_flip = intel_gen3_queue_flip;
14862                 break;
14863
14864         case 4:
14865         case 5:
14866                 dev_priv->display.queue_flip = intel_gen4_queue_flip;
14867                 break;
14868
14869         case 6:
14870                 dev_priv->display.queue_flip = intel_gen6_queue_flip;
14871                 break;
14872         case 7:
14873         case 8: /* FIXME(BDW): Check that the gen8 RCS flip works. */
14874                 dev_priv->display.queue_flip = intel_gen7_queue_flip;
14875                 break;
14876         case 9:
14877                 /* Drop through - unsupported since execlist only. */
14878         default:
14879                 /* Default just returns -ENODEV to indicate unsupported */
14880                 dev_priv->display.queue_flip = intel_default_queue_flip;
14881         }
14882
14883         intel_panel_init_backlight_funcs(dev);
14884
14885         mutex_init(&dev_priv->pps_mutex);
14886 }
14887
14888 /*
14889  * Some BIOSes insist on assuming the GPU's pipe A is enabled at suspend,
14890  * resume, or other times.  This quirk makes sure that's the case for
14891  * affected systems.
14892  */
14893 static void quirk_pipea_force(struct drm_device *dev)
14894 {
14895         struct drm_i915_private *dev_priv = dev->dev_private;
14896
14897         dev_priv->quirks |= QUIRK_PIPEA_FORCE;
14898         DRM_INFO("applying pipe a force quirk\n");
14899 }
14900
14901 static void quirk_pipeb_force(struct drm_device *dev)
14902 {
14903         struct drm_i915_private *dev_priv = dev->dev_private;
14904
14905         dev_priv->quirks |= QUIRK_PIPEB_FORCE;
14906         DRM_INFO("applying pipe b force quirk\n");
14907 }
14908
14909 /*
14910  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
14911  */
14912 static void quirk_ssc_force_disable(struct drm_device *dev)
14913 {
14914         struct drm_i915_private *dev_priv = dev->dev_private;
14915         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
14916         DRM_INFO("applying lvds SSC disable quirk\n");
14917 }
14918
14919 /*
14920  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
14921  * brightness value
14922  */
14923 static void quirk_invert_brightness(struct drm_device *dev)
14924 {
14925         struct drm_i915_private *dev_priv = dev->dev_private;
14926         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
14927         DRM_INFO("applying inverted panel brightness quirk\n");
14928 }
14929
14930 /* Some VBT's incorrectly indicate no backlight is present */
14931 static void quirk_backlight_present(struct drm_device *dev)
14932 {
14933         struct drm_i915_private *dev_priv = dev->dev_private;
14934         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
14935         DRM_INFO("applying backlight present quirk\n");
14936 }
14937
14938 struct intel_quirk {
14939         int device;
14940         int subsystem_vendor;
14941         int subsystem_device;
14942         void (*hook)(struct drm_device *dev);
14943 };
14944
14945 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
14946 struct intel_dmi_quirk {
14947         void (*hook)(struct drm_device *dev);
14948         const struct dmi_system_id (*dmi_id_list)[];
14949 };
14950
14951 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
14952 {
14953         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
14954         return 1;
14955 }
14956
14957 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
14958         {
14959                 .dmi_id_list = &(const struct dmi_system_id[]) {
14960                         {
14961                                 .callback = intel_dmi_reverse_brightness,
14962                                 .ident = "NCR Corporation",
14963                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
14964                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
14965                                 },
14966                         },
14967                         { }  /* terminating entry */
14968                 },
14969                 .hook = quirk_invert_brightness,
14970         },
14971 };
14972
14973 static struct intel_quirk intel_quirks[] = {
14974         /* Toshiba Protege R-205, S-209 needs pipe A force quirk */
14975         { 0x2592, 0x1179, 0x0001, quirk_pipea_force },
14976
14977         /* ThinkPad T60 needs pipe A force quirk (bug #16494) */
14978         { 0x2782, 0x17aa, 0x201a, quirk_pipea_force },
14979
14980         /* 830 needs to leave pipe A & dpll A up */
14981         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipea_force },
14982
14983         /* 830 needs to leave pipe B & dpll B up */
14984         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipeb_force },
14985
14986         /* Lenovo U160 cannot use SSC on LVDS */
14987         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
14988
14989         /* Sony Vaio Y cannot use SSC on LVDS */
14990         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
14991
14992         /* Acer Aspire 5734Z must invert backlight brightness */
14993         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
14994
14995         /* Acer/eMachines G725 */
14996         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
14997
14998         /* Acer/eMachines e725 */
14999         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
15000
15001         /* Acer/Packard Bell NCL20 */
15002         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
15003
15004         /* Acer Aspire 4736Z */
15005         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
15006
15007         /* Acer Aspire 5336 */
15008         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
15009
15010         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
15011         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
15012
15013         /* Acer C720 Chromebook (Core i3 4005U) */
15014         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
15015
15016         /* Apple Macbook 2,1 (Core 2 T7400) */
15017         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
15018
15019         /* Toshiba CB35 Chromebook (Celeron 2955U) */
15020         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
15021
15022         /* HP Chromebook 14 (Celeron 2955U) */
15023         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
15024
15025         /* Dell Chromebook 11 */
15026         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
15027 };
15028
15029 static void intel_init_quirks(struct drm_device *dev)
15030 {
15031         struct pci_dev *d = dev->pdev;
15032         int i;
15033
15034         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
15035                 struct intel_quirk *q = &intel_quirks[i];
15036
15037                 if (d->device == q->device &&
15038                     (d->subsystem_vendor == q->subsystem_vendor ||
15039                      q->subsystem_vendor == PCI_ANY_ID) &&
15040                     (d->subsystem_device == q->subsystem_device ||
15041                      q->subsystem_device == PCI_ANY_ID))
15042                         q->hook(dev);
15043         }
15044         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
15045                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
15046                         intel_dmi_quirks[i].hook(dev);
15047         }
15048 }
15049
15050 /* Disable the VGA plane that we never use */
15051 static void i915_disable_vga(struct drm_device *dev)
15052 {
15053         struct drm_i915_private *dev_priv = dev->dev_private;
15054         u8 sr1;
15055         u32 vga_reg = i915_vgacntrl_reg(dev);
15056
15057         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
15058         vga_get_uninterruptible(dev->pdev, VGA_RSRC_LEGACY_IO);
15059         outb(SR01, VGA_SR_INDEX);
15060         sr1 = inb(VGA_SR_DATA);
15061         outb(sr1 | 1<<5, VGA_SR_DATA);
15062         vga_put(dev->pdev, VGA_RSRC_LEGACY_IO);
15063         udelay(300);
15064
15065         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
15066         POSTING_READ(vga_reg);
15067 }
15068
15069 void intel_modeset_init_hw(struct drm_device *dev)
15070 {
15071         intel_update_cdclk(dev);
15072         intel_prepare_ddi(dev);
15073         intel_init_clock_gating(dev);
15074         intel_enable_gt_powersave(dev);
15075 }
15076
15077 void intel_modeset_init(struct drm_device *dev)
15078 {
15079         struct drm_i915_private *dev_priv = dev->dev_private;
15080         int sprite, ret;
15081         enum pipe pipe;
15082         struct intel_crtc *crtc;
15083
15084         drm_mode_config_init(dev);
15085
15086         dev->mode_config.min_width = 0;
15087         dev->mode_config.min_height = 0;
15088
15089         dev->mode_config.preferred_depth = 24;
15090         dev->mode_config.prefer_shadow = 1;
15091
15092         dev->mode_config.allow_fb_modifiers = true;
15093
15094         dev->mode_config.funcs = &intel_mode_funcs;
15095
15096         intel_init_quirks(dev);
15097
15098         intel_init_pm(dev);
15099
15100         if (INTEL_INFO(dev)->num_pipes == 0)
15101                 return;
15102
15103         intel_init_display(dev);
15104         intel_init_audio(dev);
15105
15106         if (IS_GEN2(dev)) {
15107                 dev->mode_config.max_width = 2048;
15108                 dev->mode_config.max_height = 2048;
15109         } else if (IS_GEN3(dev)) {
15110                 dev->mode_config.max_width = 4096;
15111                 dev->mode_config.max_height = 4096;
15112         } else {
15113                 dev->mode_config.max_width = 8192;
15114                 dev->mode_config.max_height = 8192;
15115         }
15116
15117         if (IS_845G(dev) || IS_I865G(dev)) {
15118                 dev->mode_config.cursor_width = IS_845G(dev) ? 64 : 512;
15119                 dev->mode_config.cursor_height = 1023;
15120         } else if (IS_GEN2(dev)) {
15121                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
15122                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
15123         } else {
15124                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
15125                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
15126         }
15127
15128         dev->mode_config.fb_base = dev_priv->gtt.mappable_base;
15129
15130         DRM_DEBUG_KMS("%d display pipe%s available.\n",
15131                       INTEL_INFO(dev)->num_pipes,
15132                       INTEL_INFO(dev)->num_pipes > 1 ? "s" : "");
15133
15134         for_each_pipe(dev_priv, pipe) {
15135                 intel_crtc_init(dev, pipe);
15136                 for_each_sprite(dev_priv, pipe, sprite) {
15137                         ret = intel_plane_init(dev, pipe, sprite);
15138                         if (ret)
15139                                 DRM_DEBUG_KMS("pipe %c sprite %c init failed: %d\n",
15140                                               pipe_name(pipe), sprite_name(pipe, sprite), ret);
15141                 }
15142         }
15143
15144         intel_init_dpio(dev);
15145
15146         intel_shared_dpll_init(dev);
15147
15148         /* Just disable it once at startup */
15149         i915_disable_vga(dev);
15150         intel_setup_outputs(dev);
15151
15152         /* Just in case the BIOS is doing something questionable. */
15153         intel_fbc_disable(dev_priv);
15154
15155         drm_modeset_lock_all(dev);
15156         intel_modeset_setup_hw_state(dev, false);
15157         drm_modeset_unlock_all(dev);
15158
15159         for_each_intel_crtc(dev, crtc) {
15160                 struct intel_initial_plane_config plane_config = {};
15161
15162                 if (!crtc->active)
15163                         continue;
15164
15165                 /*
15166                  * Note that reserving the BIOS fb up front prevents us
15167                  * from stuffing other stolen allocations like the ring
15168                  * on top.  This prevents some ugliness at boot time, and
15169                  * can even allow for smooth boot transitions if the BIOS
15170                  * fb is large enough for the active pipe configuration.
15171                  */
15172                 dev_priv->display.get_initial_plane_config(crtc,
15173                                                            &plane_config);
15174
15175                 /*
15176                  * If the fb is shared between multiple heads, we'll
15177                  * just get the first one.
15178                  */
15179                 intel_find_initial_plane_obj(crtc, &plane_config);
15180         }
15181 }
15182
15183 static void intel_enable_pipe_a(struct drm_device *dev)
15184 {
15185         struct intel_connector *connector;
15186         struct drm_connector *crt = NULL;
15187         struct intel_load_detect_pipe load_detect_temp;
15188         struct drm_modeset_acquire_ctx *ctx = dev->mode_config.acquire_ctx;
15189
15190         /* We can't just switch on the pipe A, we need to set things up with a
15191          * proper mode and output configuration. As a gross hack, enable pipe A
15192          * by enabling the load detect pipe once. */
15193         for_each_intel_connector(dev, connector) {
15194                 if (connector->encoder->type == INTEL_OUTPUT_ANALOG) {
15195                         crt = &connector->base;
15196                         break;
15197                 }
15198         }
15199
15200         if (!crt)
15201                 return;
15202
15203         if (intel_get_load_detect_pipe(crt, NULL, &load_detect_temp, ctx))
15204                 intel_release_load_detect_pipe(crt, &load_detect_temp, ctx);
15205 }
15206
15207 static bool
15208 intel_check_plane_mapping(struct intel_crtc *crtc)
15209 {
15210         struct drm_device *dev = crtc->base.dev;
15211         struct drm_i915_private *dev_priv = dev->dev_private;
15212         u32 reg, val;
15213
15214         if (INTEL_INFO(dev)->num_pipes == 1)
15215                 return true;
15216
15217         reg = DSPCNTR(!crtc->plane);
15218         val = I915_READ(reg);
15219
15220         if ((val & DISPLAY_PLANE_ENABLE) &&
15221             (!!(val & DISPPLANE_SEL_PIPE_MASK) == crtc->pipe))
15222                 return false;
15223
15224         return true;
15225 }
15226
15227 static void intel_sanitize_crtc(struct intel_crtc *crtc)
15228 {
15229         struct drm_device *dev = crtc->base.dev;
15230         struct drm_i915_private *dev_priv = dev->dev_private;
15231         struct intel_encoder *encoder;
15232         u32 reg;
15233         bool enable;
15234
15235         /* Clear any frame start delays used for debugging left by the BIOS */
15236         reg = PIPECONF(crtc->config->cpu_transcoder);
15237         I915_WRITE(reg, I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
15238
15239         /* restore vblank interrupts to correct state */
15240         drm_crtc_vblank_reset(&crtc->base);
15241         if (crtc->active) {
15242                 update_scanline_offset(crtc);
15243                 drm_crtc_vblank_on(&crtc->base);
15244         }
15245
15246         /* We need to sanitize the plane -> pipe mapping first because this will
15247          * disable the crtc (and hence change the state) if it is wrong. Note
15248          * that gen4+ has a fixed plane -> pipe mapping.  */
15249         if (INTEL_INFO(dev)->gen < 4 && !intel_check_plane_mapping(crtc)) {
15250                 bool plane;
15251
15252                 DRM_DEBUG_KMS("[CRTC:%d] wrong plane connection detected!\n",
15253                               crtc->base.base.id);
15254
15255                 /* Pipe has the wrong plane attached and the plane is active.
15256                  * Temporarily change the plane mapping and disable everything
15257                  * ...  */
15258                 plane = crtc->plane;
15259                 to_intel_plane_state(crtc->base.primary->state)->visible = true;
15260                 crtc->plane = !plane;
15261                 intel_crtc_disable_noatomic(&crtc->base);
15262                 crtc->plane = plane;
15263         }
15264
15265         if (dev_priv->quirks & QUIRK_PIPEA_FORCE &&
15266             crtc->pipe == PIPE_A && !crtc->active) {
15267                 /* BIOS forgot to enable pipe A, this mostly happens after
15268                  * resume. Force-enable the pipe to fix this, the update_dpms
15269                  * call below we restore the pipe to the right state, but leave
15270                  * the required bits on. */
15271                 intel_enable_pipe_a(dev);
15272         }
15273
15274         /* Adjust the state of the output pipe according to whether we
15275          * have active connectors/encoders. */
15276         enable = false;
15277         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
15278                 enable |= encoder->connectors_active;
15279
15280         if (!enable)
15281                 intel_crtc_disable_noatomic(&crtc->base);
15282
15283         if (crtc->active != crtc->base.state->active) {
15284
15285                 /* This can happen either due to bugs in the get_hw_state
15286                  * functions or because of calls to intel_crtc_disable_noatomic,
15287                  * or because the pipe is force-enabled due to the
15288                  * pipe A quirk. */
15289                 DRM_DEBUG_KMS("[CRTC:%d] hw state adjusted, was %s, now %s\n",
15290                               crtc->base.base.id,
15291                               crtc->base.state->enable ? "enabled" : "disabled",
15292                               crtc->active ? "enabled" : "disabled");
15293
15294                 WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, NULL) < 0);
15295                 crtc->base.state->active = crtc->active;
15296                 crtc->base.enabled = crtc->active;
15297
15298                 /* Because we only establish the connector -> encoder ->
15299                  * crtc links if something is active, this means the
15300                  * crtc is now deactivated. Break the links. connector
15301                  * -> encoder links are only establish when things are
15302                  *  actually up, hence no need to break them. */
15303                 WARN_ON(crtc->active);
15304
15305                 for_each_encoder_on_crtc(dev, &crtc->base, encoder) {
15306                         WARN_ON(encoder->connectors_active);
15307                         encoder->base.crtc = NULL;
15308                 }
15309         }
15310
15311         if (crtc->active || HAS_GMCH_DISPLAY(dev)) {
15312                 /*
15313                  * We start out with underrun reporting disabled to avoid races.
15314                  * For correct bookkeeping mark this on active crtcs.
15315                  *
15316                  * Also on gmch platforms we dont have any hardware bits to
15317                  * disable the underrun reporting. Which means we need to start
15318                  * out with underrun reporting disabled also on inactive pipes,
15319                  * since otherwise we'll complain about the garbage we read when
15320                  * e.g. coming up after runtime pm.
15321                  *
15322                  * No protection against concurrent access is required - at
15323                  * worst a fifo underrun happens which also sets this to false.
15324                  */
15325                 crtc->cpu_fifo_underrun_disabled = true;
15326                 crtc->pch_fifo_underrun_disabled = true;
15327         }
15328 }
15329
15330 static void intel_sanitize_encoder(struct intel_encoder *encoder)
15331 {
15332         struct intel_connector *connector;
15333         struct drm_device *dev = encoder->base.dev;
15334
15335         /* We need to check both for a crtc link (meaning that the
15336          * encoder is active and trying to read from a pipe) and the
15337          * pipe itself being active. */
15338         bool has_active_crtc = encoder->base.crtc &&
15339                 to_intel_crtc(encoder->base.crtc)->active;
15340
15341         if (encoder->connectors_active && !has_active_crtc) {
15342                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
15343                               encoder->base.base.id,
15344                               encoder->base.name);
15345
15346                 /* Connector is active, but has no active pipe. This is
15347                  * fallout from our resume register restoring. Disable
15348                  * the encoder manually again. */
15349                 if (encoder->base.crtc) {
15350                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
15351                                       encoder->base.base.id,
15352                                       encoder->base.name);
15353                         encoder->disable(encoder);
15354                         if (encoder->post_disable)
15355                                 encoder->post_disable(encoder);
15356                 }
15357                 encoder->base.crtc = NULL;
15358                 encoder->connectors_active = false;
15359
15360                 /* Inconsistent output/port/pipe state happens presumably due to
15361                  * a bug in one of the get_hw_state functions. Or someplace else
15362                  * in our code, like the register restore mess on resume. Clamp
15363                  * things to off as a safer default. */
15364                 for_each_intel_connector(dev, connector) {
15365                         if (connector->encoder != encoder)
15366                                 continue;
15367                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15368                         connector->base.encoder = NULL;
15369                 }
15370         }
15371         /* Enabled encoders without active connectors will be fixed in
15372          * the crtc fixup. */
15373 }
15374
15375 void i915_redisable_vga_power_on(struct drm_device *dev)
15376 {
15377         struct drm_i915_private *dev_priv = dev->dev_private;
15378         u32 vga_reg = i915_vgacntrl_reg(dev);
15379
15380         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
15381                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
15382                 i915_disable_vga(dev);
15383         }
15384 }
15385
15386 void i915_redisable_vga(struct drm_device *dev)
15387 {
15388         struct drm_i915_private *dev_priv = dev->dev_private;
15389
15390         /* This function can be called both from intel_modeset_setup_hw_state or
15391          * at a very early point in our resume sequence, where the power well
15392          * structures are not yet restored. Since this function is at a very
15393          * paranoid "someone might have enabled VGA while we were not looking"
15394          * level, just check if the power well is enabled instead of trying to
15395          * follow the "don't touch the power well if we don't need it" policy
15396          * the rest of the driver uses. */
15397         if (!intel_display_power_is_enabled(dev_priv, POWER_DOMAIN_VGA))
15398                 return;
15399
15400         i915_redisable_vga_power_on(dev);
15401 }
15402
15403 static bool primary_get_hw_state(struct intel_crtc *crtc)
15404 {
15405         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
15406
15407         return !!(I915_READ(DSPCNTR(crtc->plane)) & DISPLAY_PLANE_ENABLE);
15408 }
15409
15410 static void readout_plane_state(struct intel_crtc *crtc,
15411                                 struct intel_crtc_state *crtc_state)
15412 {
15413         struct intel_plane *p;
15414         struct intel_plane_state *plane_state;
15415         bool active = crtc_state->base.active;
15416
15417         for_each_intel_plane(crtc->base.dev, p) {
15418                 if (crtc->pipe != p->pipe)
15419                         continue;
15420
15421                 plane_state = to_intel_plane_state(p->base.state);
15422
15423                 if (p->base.type == DRM_PLANE_TYPE_PRIMARY)
15424                         plane_state->visible = primary_get_hw_state(crtc);
15425                 else {
15426                         if (active)
15427                                 p->disable_plane(&p->base, &crtc->base);
15428
15429                         plane_state->visible = false;
15430                 }
15431         }
15432 }
15433
15434 static void intel_modeset_readout_hw_state(struct drm_device *dev)
15435 {
15436         struct drm_i915_private *dev_priv = dev->dev_private;
15437         enum pipe pipe;
15438         struct intel_crtc *crtc;
15439         struct intel_encoder *encoder;
15440         struct intel_connector *connector;
15441         int i;
15442
15443         for_each_intel_crtc(dev, crtc) {
15444                 __drm_atomic_helper_crtc_destroy_state(&crtc->base, crtc->base.state);
15445                 memset(crtc->config, 0, sizeof(*crtc->config));
15446                 crtc->config->base.crtc = &crtc->base;
15447
15448                 crtc->config->quirks |= PIPE_CONFIG_QUIRK_INHERITED_MODE;
15449
15450                 crtc->active = dev_priv->display.get_pipe_config(crtc,
15451                                                                  crtc->config);
15452
15453                 crtc->base.state->enable = crtc->active;
15454                 crtc->base.state->active = crtc->active;
15455                 crtc->base.enabled = crtc->active;
15456                 crtc->base.hwmode = crtc->config->base.adjusted_mode;
15457
15458                 readout_plane_state(crtc, to_intel_crtc_state(crtc->base.state));
15459
15460                 DRM_DEBUG_KMS("[CRTC:%d] hw state readout: %s\n",
15461                               crtc->base.base.id,
15462                               crtc->active ? "enabled" : "disabled");
15463         }
15464
15465         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15466                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15467
15468                 pll->on = pll->get_hw_state(dev_priv, pll,
15469                                             &pll->config.hw_state);
15470                 pll->active = 0;
15471                 pll->config.crtc_mask = 0;
15472                 for_each_intel_crtc(dev, crtc) {
15473                         if (crtc->active && intel_crtc_to_shared_dpll(crtc) == pll) {
15474                                 pll->active++;
15475                                 pll->config.crtc_mask |= 1 << crtc->pipe;
15476                         }
15477                 }
15478
15479                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15480                               pll->name, pll->config.crtc_mask, pll->on);
15481
15482                 if (pll->config.crtc_mask)
15483                         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
15484         }
15485
15486         for_each_intel_encoder(dev, encoder) {
15487                 pipe = 0;
15488
15489                 if (encoder->get_hw_state(encoder, &pipe)) {
15490                         crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
15491                         encoder->base.crtc = &crtc->base;
15492                         encoder->get_config(encoder, crtc->config);
15493                 } else {
15494                         encoder->base.crtc = NULL;
15495                 }
15496
15497                 encoder->connectors_active = false;
15498                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
15499                               encoder->base.base.id,
15500                               encoder->base.name,
15501                               encoder->base.crtc ? "enabled" : "disabled",
15502                               pipe_name(pipe));
15503         }
15504
15505         for_each_intel_connector(dev, connector) {
15506                 if (connector->get_hw_state(connector)) {
15507                         connector->base.dpms = DRM_MODE_DPMS_ON;
15508                         connector->encoder->connectors_active = true;
15509                         connector->base.encoder = &connector->encoder->base;
15510                 } else {
15511                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15512                         connector->base.encoder = NULL;
15513                 }
15514                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
15515                               connector->base.base.id,
15516                               connector->base.name,
15517                               connector->base.encoder ? "enabled" : "disabled");
15518         }
15519 }
15520
15521 /* Scan out the current hw modeset state, sanitizes it and maps it into the drm
15522  * and i915 state tracking structures. */
15523 void intel_modeset_setup_hw_state(struct drm_device *dev,
15524                                   bool force_restore)
15525 {
15526         struct drm_i915_private *dev_priv = dev->dev_private;
15527         enum pipe pipe;
15528         struct intel_crtc *crtc;
15529         struct intel_encoder *encoder;
15530         int i;
15531
15532         intel_modeset_readout_hw_state(dev);
15533
15534         /*
15535          * Now that we have the config, copy it to each CRTC struct
15536          * Note that this could go away if we move to using crtc_config
15537          * checking everywhere.
15538          */
15539         for_each_intel_crtc(dev, crtc) {
15540                 if (crtc->active && i915.fastboot) {
15541                         intel_mode_from_pipe_config(&crtc->base.mode,
15542                                                     crtc->config);
15543                         DRM_DEBUG_KMS("[CRTC:%d] found active mode: ",
15544                                       crtc->base.base.id);
15545                         drm_mode_debug_printmodeline(&crtc->base.mode);
15546                 }
15547         }
15548
15549         /* HW state is read out, now we need to sanitize this mess. */
15550         for_each_intel_encoder(dev, encoder) {
15551                 intel_sanitize_encoder(encoder);
15552         }
15553
15554         for_each_pipe(dev_priv, pipe) {
15555                 crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
15556                 intel_sanitize_crtc(crtc);
15557                 intel_dump_pipe_config(crtc, crtc->config,
15558                                        "[setup_hw_state]");
15559         }
15560
15561         intel_modeset_update_connector_atomic_state(dev);
15562
15563         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15564                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15565
15566                 if (!pll->on || pll->active)
15567                         continue;
15568
15569                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
15570
15571                 pll->disable(dev_priv, pll);
15572                 pll->on = false;
15573         }
15574
15575         if (IS_VALLEYVIEW(dev))
15576                 vlv_wm_get_hw_state(dev);
15577         else if (IS_GEN9(dev))
15578                 skl_wm_get_hw_state(dev);
15579         else if (HAS_PCH_SPLIT(dev))
15580                 ilk_wm_get_hw_state(dev);
15581
15582         if (force_restore) {
15583                 i915_redisable_vga(dev);
15584
15585                 /*
15586                  * We need to use raw interfaces for restoring state to avoid
15587                  * checking (bogus) intermediate states.
15588                  */
15589                 for_each_pipe(dev_priv, pipe) {
15590                         struct drm_crtc *crtc =
15591                                 dev_priv->pipe_to_crtc_mapping[pipe];
15592
15593                         intel_crtc_restore_mode(crtc);
15594                 }
15595         } else {
15596                 intel_modeset_update_staged_output_state(dev);
15597         }
15598
15599         intel_modeset_check_state(dev);
15600 }
15601
15602 void intel_modeset_gem_init(struct drm_device *dev)
15603 {
15604         struct drm_i915_private *dev_priv = dev->dev_private;
15605         struct drm_crtc *c;
15606         struct drm_i915_gem_object *obj;
15607         int ret;
15608
15609         mutex_lock(&dev->struct_mutex);
15610         intel_init_gt_powersave(dev);
15611         mutex_unlock(&dev->struct_mutex);
15612
15613         /*
15614          * There may be no VBT; and if the BIOS enabled SSC we can
15615          * just keep using it to avoid unnecessary flicker.  Whereas if the
15616          * BIOS isn't using it, don't assume it will work even if the VBT
15617          * indicates as much.
15618          */
15619         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
15620                 dev_priv->vbt.lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
15621                                                 DREF_SSC1_ENABLE);
15622
15623         intel_modeset_init_hw(dev);
15624
15625         intel_setup_overlay(dev);
15626
15627         /*
15628          * Make sure any fbs we allocated at startup are properly
15629          * pinned & fenced.  When we do the allocation it's too early
15630          * for this.
15631          */
15632         for_each_crtc(dev, c) {
15633                 obj = intel_fb_obj(c->primary->fb);
15634                 if (obj == NULL)
15635                         continue;
15636
15637                 mutex_lock(&dev->struct_mutex);
15638                 ret = intel_pin_and_fence_fb_obj(c->primary,
15639                                                  c->primary->fb,
15640                                                  c->primary->state,
15641                                                  NULL, NULL);
15642                 mutex_unlock(&dev->struct_mutex);
15643                 if (ret) {
15644                         DRM_ERROR("failed to pin boot fb on pipe %d\n",
15645                                   to_intel_crtc(c)->pipe);
15646                         drm_framebuffer_unreference(c->primary->fb);
15647                         c->primary->fb = NULL;
15648                         c->primary->crtc = c->primary->state->crtc = NULL;
15649                         update_state_fb(c->primary);
15650                         c->state->plane_mask &= ~(1 << drm_plane_index(c->primary));
15651                 }
15652         }
15653
15654         intel_backlight_register(dev);
15655 }
15656
15657 void intel_connector_unregister(struct intel_connector *intel_connector)
15658 {
15659         struct drm_connector *connector = &intel_connector->base;
15660
15661         intel_panel_destroy_backlight(connector);
15662         drm_connector_unregister(connector);
15663 }
15664
15665 void intel_modeset_cleanup(struct drm_device *dev)
15666 {
15667         struct drm_i915_private *dev_priv = dev->dev_private;
15668         struct drm_connector *connector;
15669
15670         intel_disable_gt_powersave(dev);
15671
15672         intel_backlight_unregister(dev);
15673
15674         /*
15675          * Interrupts and polling as the first thing to avoid creating havoc.
15676          * Too much stuff here (turning of connectors, ...) would
15677          * experience fancy races otherwise.
15678          */
15679         intel_irq_uninstall(dev_priv);
15680
15681         /*
15682          * Due to the hpd irq storm handling the hotplug work can re-arm the
15683          * poll handlers. Hence disable polling after hpd handling is shut down.
15684          */
15685         drm_kms_helper_poll_fini(dev);
15686
15687         intel_unregister_dsm_handler();
15688
15689         intel_fbc_disable(dev_priv);
15690
15691         /* flush any delayed tasks or pending work */
15692         flush_scheduled_work();
15693
15694         /* destroy the backlight and sysfs files before encoders/connectors */
15695         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
15696                 struct intel_connector *intel_connector;
15697
15698                 intel_connector = to_intel_connector(connector);
15699                 intel_connector->unregister(intel_connector);
15700         }
15701
15702         drm_mode_config_cleanup(dev);
15703
15704         intel_cleanup_overlay(dev);
15705
15706         mutex_lock(&dev->struct_mutex);
15707         intel_cleanup_gt_powersave(dev);
15708         mutex_unlock(&dev->struct_mutex);
15709 }
15710
15711 /*
15712  * Return which encoder is currently attached for connector.
15713  */
15714 struct drm_encoder *intel_best_encoder(struct drm_connector *connector)
15715 {
15716         return &intel_attached_encoder(connector)->base;
15717 }
15718
15719 void intel_connector_attach_encoder(struct intel_connector *connector,
15720                                     struct intel_encoder *encoder)
15721 {
15722         connector->encoder = encoder;
15723         drm_mode_connector_attach_encoder(&connector->base,
15724                                           &encoder->base);
15725 }
15726
15727 /*
15728  * set vga decode state - true == enable VGA decode
15729  */
15730 int intel_modeset_vga_set_state(struct drm_device *dev, bool state)
15731 {
15732         struct drm_i915_private *dev_priv = dev->dev_private;
15733         unsigned reg = INTEL_INFO(dev)->gen >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
15734         u16 gmch_ctrl;
15735
15736         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
15737                 DRM_ERROR("failed to read control word\n");
15738                 return -EIO;
15739         }
15740
15741         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
15742                 return 0;
15743
15744         if (state)
15745                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
15746         else
15747                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
15748
15749         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
15750                 DRM_ERROR("failed to write control word\n");
15751                 return -EIO;
15752         }
15753
15754         return 0;
15755 }
15756
15757 struct intel_display_error_state {
15758
15759         u32 power_well_driver;
15760
15761         int num_transcoders;
15762
15763         struct intel_cursor_error_state {
15764                 u32 control;
15765                 u32 position;
15766                 u32 base;
15767                 u32 size;
15768         } cursor[I915_MAX_PIPES];
15769
15770         struct intel_pipe_error_state {
15771                 bool power_domain_on;
15772                 u32 source;
15773                 u32 stat;
15774         } pipe[I915_MAX_PIPES];
15775
15776         struct intel_plane_error_state {
15777                 u32 control;
15778                 u32 stride;
15779                 u32 size;
15780                 u32 pos;
15781                 u32 addr;
15782                 u32 surface;
15783                 u32 tile_offset;
15784         } plane[I915_MAX_PIPES];
15785
15786         struct intel_transcoder_error_state {
15787                 bool power_domain_on;
15788                 enum transcoder cpu_transcoder;
15789
15790                 u32 conf;
15791
15792                 u32 htotal;
15793                 u32 hblank;
15794                 u32 hsync;
15795                 u32 vtotal;
15796                 u32 vblank;
15797                 u32 vsync;
15798         } transcoder[4];
15799 };
15800
15801 struct intel_display_error_state *
15802 intel_display_capture_error_state(struct drm_device *dev)
15803 {
15804         struct drm_i915_private *dev_priv = dev->dev_private;
15805         struct intel_display_error_state *error;
15806         int transcoders[] = {
15807                 TRANSCODER_A,
15808                 TRANSCODER_B,
15809                 TRANSCODER_C,
15810                 TRANSCODER_EDP,
15811         };
15812         int i;
15813
15814         if (INTEL_INFO(dev)->num_pipes == 0)
15815                 return NULL;
15816
15817         error = kzalloc(sizeof(*error), GFP_ATOMIC);
15818         if (error == NULL)
15819                 return NULL;
15820
15821         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
15822                 error->power_well_driver = I915_READ(HSW_PWR_WELL_DRIVER);
15823
15824         for_each_pipe(dev_priv, i) {
15825                 error->pipe[i].power_domain_on =
15826                         __intel_display_power_is_enabled(dev_priv,
15827                                                          POWER_DOMAIN_PIPE(i));
15828                 if (!error->pipe[i].power_domain_on)
15829                         continue;
15830
15831                 error->cursor[i].control = I915_READ(CURCNTR(i));
15832                 error->cursor[i].position = I915_READ(CURPOS(i));
15833                 error->cursor[i].base = I915_READ(CURBASE(i));
15834
15835                 error->plane[i].control = I915_READ(DSPCNTR(i));
15836                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
15837                 if (INTEL_INFO(dev)->gen <= 3) {
15838                         error->plane[i].size = I915_READ(DSPSIZE(i));
15839                         error->plane[i].pos = I915_READ(DSPPOS(i));
15840                 }
15841                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
15842                         error->plane[i].addr = I915_READ(DSPADDR(i));
15843                 if (INTEL_INFO(dev)->gen >= 4) {
15844                         error->plane[i].surface = I915_READ(DSPSURF(i));
15845                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
15846                 }
15847
15848                 error->pipe[i].source = I915_READ(PIPESRC(i));
15849
15850                 if (HAS_GMCH_DISPLAY(dev))
15851                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
15852         }
15853
15854         error->num_transcoders = INTEL_INFO(dev)->num_pipes;
15855         if (HAS_DDI(dev_priv->dev))
15856                 error->num_transcoders++; /* Account for eDP. */
15857
15858         for (i = 0; i < error->num_transcoders; i++) {
15859                 enum transcoder cpu_transcoder = transcoders[i];
15860
15861                 error->transcoder[i].power_domain_on =
15862                         __intel_display_power_is_enabled(dev_priv,
15863                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
15864                 if (!error->transcoder[i].power_domain_on)
15865                         continue;
15866
15867                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
15868
15869                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
15870                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
15871                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
15872                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
15873                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
15874                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
15875                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
15876         }
15877
15878         return error;
15879 }
15880
15881 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
15882
15883 void
15884 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
15885                                 struct drm_device *dev,
15886                                 struct intel_display_error_state *error)
15887 {
15888         struct drm_i915_private *dev_priv = dev->dev_private;
15889         int i;
15890
15891         if (!error)
15892                 return;
15893
15894         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev)->num_pipes);
15895         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
15896                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
15897                            error->power_well_driver);
15898         for_each_pipe(dev_priv, i) {
15899                 err_printf(m, "Pipe [%d]:\n", i);
15900                 err_printf(m, "  Power: %s\n",
15901                            error->pipe[i].power_domain_on ? "on" : "off");
15902                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
15903                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
15904
15905                 err_printf(m, "Plane [%d]:\n", i);
15906                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
15907                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
15908                 if (INTEL_INFO(dev)->gen <= 3) {
15909                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
15910                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
15911                 }
15912                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
15913                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
15914                 if (INTEL_INFO(dev)->gen >= 4) {
15915                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
15916                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
15917                 }
15918
15919                 err_printf(m, "Cursor [%d]:\n", i);
15920                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
15921                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
15922                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
15923         }
15924
15925         for (i = 0; i < error->num_transcoders; i++) {
15926                 err_printf(m, "CPU transcoder: %c\n",
15927                            transcoder_name(error->transcoder[i].cpu_transcoder));
15928                 err_printf(m, "  Power: %s\n",
15929                            error->transcoder[i].power_domain_on ? "on" : "off");
15930                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
15931                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
15932                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
15933                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
15934                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
15935                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
15936                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
15937         }
15938 }
15939
15940 void intel_modeset_preclose(struct drm_device *dev, struct drm_file *file)
15941 {
15942         struct intel_crtc *crtc;
15943
15944         for_each_intel_crtc(dev, crtc) {
15945                 struct intel_unpin_work *work;
15946
15947                 spin_lock_irq(&dev->event_lock);
15948
15949                 work = crtc->unpin_work;
15950
15951                 if (work && work->event &&
15952                     work->event->base.file_priv == file) {
15953                         kfree(work->event);
15954                         work->event = NULL;
15955                 }
15956
15957                 spin_unlock_irq(&dev->event_lock);
15958         }
15959 }