d7ad8449a9e14207f0ebe9db032f12e416799248
[firefly-linux-kernel-4.4.55.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 static void intel_crtc_enable_planes(struct drm_crtc *crtc);
113 static void intel_crtc_disable_planes(struct drm_crtc *crtc);
114
115 static struct intel_encoder *intel_find_encoder(struct intel_connector *connector, int pipe)
116 {
117         if (!connector->mst_port)
118                 return connector->encoder;
119         else
120                 return &connector->mst_port->mst_encoders[pipe]->base;
121 }
122
123 typedef struct {
124         int     min, max;
125 } intel_range_t;
126
127 typedef struct {
128         int     dot_limit;
129         int     p2_slow, p2_fast;
130 } intel_p2_t;
131
132 typedef struct intel_limit intel_limit_t;
133 struct intel_limit {
134         intel_range_t   dot, vco, n, m, m1, m2, p, p1;
135         intel_p2_t          p2;
136 };
137
138 int
139 intel_pch_rawclk(struct drm_device *dev)
140 {
141         struct drm_i915_private *dev_priv = dev->dev_private;
142
143         WARN_ON(!HAS_PCH_SPLIT(dev));
144
145         return I915_READ(PCH_RAWCLK_FREQ) & RAWCLK_FREQ_MASK;
146 }
147
148 static inline u32 /* units of 100MHz */
149 intel_fdi_link_freq(struct drm_device *dev)
150 {
151         if (IS_GEN5(dev)) {
152                 struct drm_i915_private *dev_priv = dev->dev_private;
153                 return (I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK) + 2;
154         } else
155                 return 27;
156 }
157
158 static const intel_limit_t intel_limits_i8xx_dac = {
159         .dot = { .min = 25000, .max = 350000 },
160         .vco = { .min = 908000, .max = 1512000 },
161         .n = { .min = 2, .max = 16 },
162         .m = { .min = 96, .max = 140 },
163         .m1 = { .min = 18, .max = 26 },
164         .m2 = { .min = 6, .max = 16 },
165         .p = { .min = 4, .max = 128 },
166         .p1 = { .min = 2, .max = 33 },
167         .p2 = { .dot_limit = 165000,
168                 .p2_slow = 4, .p2_fast = 2 },
169 };
170
171 static const intel_limit_t intel_limits_i8xx_dvo = {
172         .dot = { .min = 25000, .max = 350000 },
173         .vco = { .min = 908000, .max = 1512000 },
174         .n = { .min = 2, .max = 16 },
175         .m = { .min = 96, .max = 140 },
176         .m1 = { .min = 18, .max = 26 },
177         .m2 = { .min = 6, .max = 16 },
178         .p = { .min = 4, .max = 128 },
179         .p1 = { .min = 2, .max = 33 },
180         .p2 = { .dot_limit = 165000,
181                 .p2_slow = 4, .p2_fast = 4 },
182 };
183
184 static const intel_limit_t intel_limits_i8xx_lvds = {
185         .dot = { .min = 25000, .max = 350000 },
186         .vco = { .min = 908000, .max = 1512000 },
187         .n = { .min = 2, .max = 16 },
188         .m = { .min = 96, .max = 140 },
189         .m1 = { .min = 18, .max = 26 },
190         .m2 = { .min = 6, .max = 16 },
191         .p = { .min = 4, .max = 128 },
192         .p1 = { .min = 1, .max = 6 },
193         .p2 = { .dot_limit = 165000,
194                 .p2_slow = 14, .p2_fast = 7 },
195 };
196
197 static const intel_limit_t intel_limits_i9xx_sdvo = {
198         .dot = { .min = 20000, .max = 400000 },
199         .vco = { .min = 1400000, .max = 2800000 },
200         .n = { .min = 1, .max = 6 },
201         .m = { .min = 70, .max = 120 },
202         .m1 = { .min = 8, .max = 18 },
203         .m2 = { .min = 3, .max = 7 },
204         .p = { .min = 5, .max = 80 },
205         .p1 = { .min = 1, .max = 8 },
206         .p2 = { .dot_limit = 200000,
207                 .p2_slow = 10, .p2_fast = 5 },
208 };
209
210 static const intel_limit_t intel_limits_i9xx_lvds = {
211         .dot = { .min = 20000, .max = 400000 },
212         .vco = { .min = 1400000, .max = 2800000 },
213         .n = { .min = 1, .max = 6 },
214         .m = { .min = 70, .max = 120 },
215         .m1 = { .min = 8, .max = 18 },
216         .m2 = { .min = 3, .max = 7 },
217         .p = { .min = 7, .max = 98 },
218         .p1 = { .min = 1, .max = 8 },
219         .p2 = { .dot_limit = 112000,
220                 .p2_slow = 14, .p2_fast = 7 },
221 };
222
223
224 static const intel_limit_t intel_limits_g4x_sdvo = {
225         .dot = { .min = 25000, .max = 270000 },
226         .vco = { .min = 1750000, .max = 3500000},
227         .n = { .min = 1, .max = 4 },
228         .m = { .min = 104, .max = 138 },
229         .m1 = { .min = 17, .max = 23 },
230         .m2 = { .min = 5, .max = 11 },
231         .p = { .min = 10, .max = 30 },
232         .p1 = { .min = 1, .max = 3},
233         .p2 = { .dot_limit = 270000,
234                 .p2_slow = 10,
235                 .p2_fast = 10
236         },
237 };
238
239 static const intel_limit_t intel_limits_g4x_hdmi = {
240         .dot = { .min = 22000, .max = 400000 },
241         .vco = { .min = 1750000, .max = 3500000},
242         .n = { .min = 1, .max = 4 },
243         .m = { .min = 104, .max = 138 },
244         .m1 = { .min = 16, .max = 23 },
245         .m2 = { .min = 5, .max = 11 },
246         .p = { .min = 5, .max = 80 },
247         .p1 = { .min = 1, .max = 8},
248         .p2 = { .dot_limit = 165000,
249                 .p2_slow = 10, .p2_fast = 5 },
250 };
251
252 static const intel_limit_t intel_limits_g4x_single_channel_lvds = {
253         .dot = { .min = 20000, .max = 115000 },
254         .vco = { .min = 1750000, .max = 3500000 },
255         .n = { .min = 1, .max = 3 },
256         .m = { .min = 104, .max = 138 },
257         .m1 = { .min = 17, .max = 23 },
258         .m2 = { .min = 5, .max = 11 },
259         .p = { .min = 28, .max = 112 },
260         .p1 = { .min = 2, .max = 8 },
261         .p2 = { .dot_limit = 0,
262                 .p2_slow = 14, .p2_fast = 14
263         },
264 };
265
266 static const intel_limit_t intel_limits_g4x_dual_channel_lvds = {
267         .dot = { .min = 80000, .max = 224000 },
268         .vco = { .min = 1750000, .max = 3500000 },
269         .n = { .min = 1, .max = 3 },
270         .m = { .min = 104, .max = 138 },
271         .m1 = { .min = 17, .max = 23 },
272         .m2 = { .min = 5, .max = 11 },
273         .p = { .min = 14, .max = 42 },
274         .p1 = { .min = 2, .max = 6 },
275         .p2 = { .dot_limit = 0,
276                 .p2_slow = 7, .p2_fast = 7
277         },
278 };
279
280 static const intel_limit_t intel_limits_pineview_sdvo = {
281         .dot = { .min = 20000, .max = 400000},
282         .vco = { .min = 1700000, .max = 3500000 },
283         /* Pineview's Ncounter is a ring counter */
284         .n = { .min = 3, .max = 6 },
285         .m = { .min = 2, .max = 256 },
286         /* Pineview only has one combined m divider, which we treat as m2. */
287         .m1 = { .min = 0, .max = 0 },
288         .m2 = { .min = 0, .max = 254 },
289         .p = { .min = 5, .max = 80 },
290         .p1 = { .min = 1, .max = 8 },
291         .p2 = { .dot_limit = 200000,
292                 .p2_slow = 10, .p2_fast = 5 },
293 };
294
295 static const intel_limit_t intel_limits_pineview_lvds = {
296         .dot = { .min = 20000, .max = 400000 },
297         .vco = { .min = 1700000, .max = 3500000 },
298         .n = { .min = 3, .max = 6 },
299         .m = { .min = 2, .max = 256 },
300         .m1 = { .min = 0, .max = 0 },
301         .m2 = { .min = 0, .max = 254 },
302         .p = { .min = 7, .max = 112 },
303         .p1 = { .min = 1, .max = 8 },
304         .p2 = { .dot_limit = 112000,
305                 .p2_slow = 14, .p2_fast = 14 },
306 };
307
308 /* Ironlake / Sandybridge
309  *
310  * We calculate clock using (register_value + 2) for N/M1/M2, so here
311  * the range value for them is (actual_value - 2).
312  */
313 static const intel_limit_t intel_limits_ironlake_dac = {
314         .dot = { .min = 25000, .max = 350000 },
315         .vco = { .min = 1760000, .max = 3510000 },
316         .n = { .min = 1, .max = 5 },
317         .m = { .min = 79, .max = 127 },
318         .m1 = { .min = 12, .max = 22 },
319         .m2 = { .min = 5, .max = 9 },
320         .p = { .min = 5, .max = 80 },
321         .p1 = { .min = 1, .max = 8 },
322         .p2 = { .dot_limit = 225000,
323                 .p2_slow = 10, .p2_fast = 5 },
324 };
325
326 static const intel_limit_t intel_limits_ironlake_single_lvds = {
327         .dot = { .min = 25000, .max = 350000 },
328         .vco = { .min = 1760000, .max = 3510000 },
329         .n = { .min = 1, .max = 3 },
330         .m = { .min = 79, .max = 118 },
331         .m1 = { .min = 12, .max = 22 },
332         .m2 = { .min = 5, .max = 9 },
333         .p = { .min = 28, .max = 112 },
334         .p1 = { .min = 2, .max = 8 },
335         .p2 = { .dot_limit = 225000,
336                 .p2_slow = 14, .p2_fast = 14 },
337 };
338
339 static const intel_limit_t intel_limits_ironlake_dual_lvds = {
340         .dot = { .min = 25000, .max = 350000 },
341         .vco = { .min = 1760000, .max = 3510000 },
342         .n = { .min = 1, .max = 3 },
343         .m = { .min = 79, .max = 127 },
344         .m1 = { .min = 12, .max = 22 },
345         .m2 = { .min = 5, .max = 9 },
346         .p = { .min = 14, .max = 56 },
347         .p1 = { .min = 2, .max = 8 },
348         .p2 = { .dot_limit = 225000,
349                 .p2_slow = 7, .p2_fast = 7 },
350 };
351
352 /* LVDS 100mhz refclk limits. */
353 static const intel_limit_t intel_limits_ironlake_single_lvds_100m = {
354         .dot = { .min = 25000, .max = 350000 },
355         .vco = { .min = 1760000, .max = 3510000 },
356         .n = { .min = 1, .max = 2 },
357         .m = { .min = 79, .max = 126 },
358         .m1 = { .min = 12, .max = 22 },
359         .m2 = { .min = 5, .max = 9 },
360         .p = { .min = 28, .max = 112 },
361         .p1 = { .min = 2, .max = 8 },
362         .p2 = { .dot_limit = 225000,
363                 .p2_slow = 14, .p2_fast = 14 },
364 };
365
366 static const intel_limit_t intel_limits_ironlake_dual_lvds_100m = {
367         .dot = { .min = 25000, .max = 350000 },
368         .vco = { .min = 1760000, .max = 3510000 },
369         .n = { .min = 1, .max = 3 },
370         .m = { .min = 79, .max = 126 },
371         .m1 = { .min = 12, .max = 22 },
372         .m2 = { .min = 5, .max = 9 },
373         .p = { .min = 14, .max = 42 },
374         .p1 = { .min = 2, .max = 6 },
375         .p2 = { .dot_limit = 225000,
376                 .p2_slow = 7, .p2_fast = 7 },
377 };
378
379 static const intel_limit_t intel_limits_vlv = {
380          /*
381           * These are the data rate limits (measured in fast clocks)
382           * since those are the strictest limits we have. The fast
383           * clock and actual rate limits are more relaxed, so checking
384           * them would make no difference.
385           */
386         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
387         .vco = { .min = 4000000, .max = 6000000 },
388         .n = { .min = 1, .max = 7 },
389         .m1 = { .min = 2, .max = 3 },
390         .m2 = { .min = 11, .max = 156 },
391         .p1 = { .min = 2, .max = 3 },
392         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
393 };
394
395 static const intel_limit_t intel_limits_chv = {
396         /*
397          * These are the data rate limits (measured in fast clocks)
398          * since those are the strictest limits we have.  The fast
399          * clock and actual rate limits are more relaxed, so checking
400          * them would make no difference.
401          */
402         .dot = { .min = 25000 * 5, .max = 540000 * 5},
403         .vco = { .min = 4800000, .max = 6480000 },
404         .n = { .min = 1, .max = 1 },
405         .m1 = { .min = 2, .max = 2 },
406         .m2 = { .min = 24 << 22, .max = 175 << 22 },
407         .p1 = { .min = 2, .max = 4 },
408         .p2 = { .p2_slow = 1, .p2_fast = 14 },
409 };
410
411 static const intel_limit_t intel_limits_bxt = {
412         /* FIXME: find real dot limits */
413         .dot = { .min = 0, .max = INT_MAX },
414         .vco = { .min = 4800000, .max = 6480000 },
415         .n = { .min = 1, .max = 1 },
416         .m1 = { .min = 2, .max = 2 },
417         /* FIXME: find real m2 limits */
418         .m2 = { .min = 2 << 22, .max = 255 << 22 },
419         .p1 = { .min = 2, .max = 4 },
420         .p2 = { .p2_slow = 1, .p2_fast = 20 },
421 };
422
423 static void vlv_clock(int refclk, intel_clock_t *clock)
424 {
425         clock->m = clock->m1 * clock->m2;
426         clock->p = clock->p1 * clock->p2;
427         if (WARN_ON(clock->n == 0 || clock->p == 0))
428                 return;
429         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
430         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
431 }
432
433 static bool
434 needs_modeset(struct drm_crtc_state *state)
435 {
436         return state->mode_changed || state->active_changed;
437 }
438
439 /**
440  * Returns whether any output on the specified pipe is of the specified type
441  */
442 bool intel_pipe_has_type(struct intel_crtc *crtc, enum intel_output_type type)
443 {
444         struct drm_device *dev = crtc->base.dev;
445         struct intel_encoder *encoder;
446
447         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
448                 if (encoder->type == type)
449                         return true;
450
451         return false;
452 }
453
454 /**
455  * Returns whether any output on the specified pipe will have the specified
456  * type after a staged modeset is complete, i.e., the same as
457  * intel_pipe_has_type() but looking at encoder->new_crtc instead of
458  * encoder->crtc.
459  */
460 static bool intel_pipe_will_have_type(const struct intel_crtc_state *crtc_state,
461                                       int type)
462 {
463         struct drm_atomic_state *state = crtc_state->base.state;
464         struct drm_connector *connector;
465         struct drm_connector_state *connector_state;
466         struct intel_encoder *encoder;
467         int i, num_connectors = 0;
468
469         for_each_connector_in_state(state, connector, connector_state, i) {
470                 if (connector_state->crtc != crtc_state->base.crtc)
471                         continue;
472
473                 num_connectors++;
474
475                 encoder = to_intel_encoder(connector_state->best_encoder);
476                 if (encoder->type == type)
477                         return true;
478         }
479
480         WARN_ON(num_connectors == 0);
481
482         return false;
483 }
484
485 static const intel_limit_t *
486 intel_ironlake_limit(struct intel_crtc_state *crtc_state, int refclk)
487 {
488         struct drm_device *dev = crtc_state->base.crtc->dev;
489         const intel_limit_t *limit;
490
491         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
492                 if (intel_is_dual_link_lvds(dev)) {
493                         if (refclk == 100000)
494                                 limit = &intel_limits_ironlake_dual_lvds_100m;
495                         else
496                                 limit = &intel_limits_ironlake_dual_lvds;
497                 } else {
498                         if (refclk == 100000)
499                                 limit = &intel_limits_ironlake_single_lvds_100m;
500                         else
501                                 limit = &intel_limits_ironlake_single_lvds;
502                 }
503         } else
504                 limit = &intel_limits_ironlake_dac;
505
506         return limit;
507 }
508
509 static const intel_limit_t *
510 intel_g4x_limit(struct intel_crtc_state *crtc_state)
511 {
512         struct drm_device *dev = crtc_state->base.crtc->dev;
513         const intel_limit_t *limit;
514
515         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
516                 if (intel_is_dual_link_lvds(dev))
517                         limit = &intel_limits_g4x_dual_channel_lvds;
518                 else
519                         limit = &intel_limits_g4x_single_channel_lvds;
520         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_HDMI) ||
521                    intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
522                 limit = &intel_limits_g4x_hdmi;
523         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_SDVO)) {
524                 limit = &intel_limits_g4x_sdvo;
525         } else /* The option is for other outputs */
526                 limit = &intel_limits_i9xx_sdvo;
527
528         return limit;
529 }
530
531 static const intel_limit_t *
532 intel_limit(struct intel_crtc_state *crtc_state, int refclk)
533 {
534         struct drm_device *dev = crtc_state->base.crtc->dev;
535         const intel_limit_t *limit;
536
537         if (IS_BROXTON(dev))
538                 limit = &intel_limits_bxt;
539         else if (HAS_PCH_SPLIT(dev))
540                 limit = intel_ironlake_limit(crtc_state, refclk);
541         else if (IS_G4X(dev)) {
542                 limit = intel_g4x_limit(crtc_state);
543         } else if (IS_PINEVIEW(dev)) {
544                 if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
545                         limit = &intel_limits_pineview_lvds;
546                 else
547                         limit = &intel_limits_pineview_sdvo;
548         } else if (IS_CHERRYVIEW(dev)) {
549                 limit = &intel_limits_chv;
550         } else if (IS_VALLEYVIEW(dev)) {
551                 limit = &intel_limits_vlv;
552         } else if (!IS_GEN2(dev)) {
553                 if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
554                         limit = &intel_limits_i9xx_lvds;
555                 else
556                         limit = &intel_limits_i9xx_sdvo;
557         } else {
558                 if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
559                         limit = &intel_limits_i8xx_lvds;
560                 else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_DVO))
561                         limit = &intel_limits_i8xx_dvo;
562                 else
563                         limit = &intel_limits_i8xx_dac;
564         }
565         return limit;
566 }
567
568 /* m1 is reserved as 0 in Pineview, n is a ring counter */
569 static void pineview_clock(int refclk, intel_clock_t *clock)
570 {
571         clock->m = clock->m2 + 2;
572         clock->p = clock->p1 * clock->p2;
573         if (WARN_ON(clock->n == 0 || clock->p == 0))
574                 return;
575         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
576         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
577 }
578
579 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
580 {
581         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
582 }
583
584 static void i9xx_clock(int refclk, intel_clock_t *clock)
585 {
586         clock->m = i9xx_dpll_compute_m(clock);
587         clock->p = clock->p1 * clock->p2;
588         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
589                 return;
590         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
591         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
592 }
593
594 static void chv_clock(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;
600         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
601                         clock->n << 22);
602         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
603 }
604
605 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
606 /**
607  * Returns whether the given set of divisors are valid for a given refclk with
608  * the given connectors.
609  */
610
611 static bool intel_PLL_is_valid(struct drm_device *dev,
612                                const intel_limit_t *limit,
613                                const intel_clock_t *clock)
614 {
615         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
616                 INTELPllInvalid("n out of range\n");
617         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
618                 INTELPllInvalid("p1 out of range\n");
619         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
620                 INTELPllInvalid("m2 out of range\n");
621         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
622                 INTELPllInvalid("m1 out of range\n");
623
624         if (!IS_PINEVIEW(dev) && !IS_VALLEYVIEW(dev) && !IS_BROXTON(dev))
625                 if (clock->m1 <= clock->m2)
626                         INTELPllInvalid("m1 <= m2\n");
627
628         if (!IS_VALLEYVIEW(dev) && !IS_BROXTON(dev)) {
629                 if (clock->p < limit->p.min || limit->p.max < clock->p)
630                         INTELPllInvalid("p out of range\n");
631                 if (clock->m < limit->m.min || limit->m.max < clock->m)
632                         INTELPllInvalid("m out of range\n");
633         }
634
635         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
636                 INTELPllInvalid("vco out of range\n");
637         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
638          * connector, etc., rather than just a single range.
639          */
640         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
641                 INTELPllInvalid("dot out of range\n");
642
643         return true;
644 }
645
646 static bool
647 i9xx_find_best_dpll(const intel_limit_t *limit,
648                     struct intel_crtc_state *crtc_state,
649                     int target, int refclk, intel_clock_t *match_clock,
650                     intel_clock_t *best_clock)
651 {
652         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
653         struct drm_device *dev = crtc->base.dev;
654         intel_clock_t clock;
655         int err = target;
656
657         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
658                 /*
659                  * For LVDS just rely on its current settings for dual-channel.
660                  * We haven't figured out how to reliably set up different
661                  * single/dual channel state, if we even can.
662                  */
663                 if (intel_is_dual_link_lvds(dev))
664                         clock.p2 = limit->p2.p2_fast;
665                 else
666                         clock.p2 = limit->p2.p2_slow;
667         } else {
668                 if (target < limit->p2.dot_limit)
669                         clock.p2 = limit->p2.p2_slow;
670                 else
671                         clock.p2 = limit->p2.p2_fast;
672         }
673
674         memset(best_clock, 0, sizeof(*best_clock));
675
676         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
677              clock.m1++) {
678                 for (clock.m2 = limit->m2.min;
679                      clock.m2 <= limit->m2.max; clock.m2++) {
680                         if (clock.m2 >= clock.m1)
681                                 break;
682                         for (clock.n = limit->n.min;
683                              clock.n <= limit->n.max; clock.n++) {
684                                 for (clock.p1 = limit->p1.min;
685                                         clock.p1 <= limit->p1.max; clock.p1++) {
686                                         int this_err;
687
688                                         i9xx_clock(refclk, &clock);
689                                         if (!intel_PLL_is_valid(dev, limit,
690                                                                 &clock))
691                                                 continue;
692                                         if (match_clock &&
693                                             clock.p != match_clock->p)
694                                                 continue;
695
696                                         this_err = abs(clock.dot - target);
697                                         if (this_err < err) {
698                                                 *best_clock = clock;
699                                                 err = this_err;
700                                         }
701                                 }
702                         }
703                 }
704         }
705
706         return (err != target);
707 }
708
709 static bool
710 pnv_find_best_dpll(const intel_limit_t *limit,
711                    struct intel_crtc_state *crtc_state,
712                    int target, int refclk, intel_clock_t *match_clock,
713                    intel_clock_t *best_clock)
714 {
715         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
716         struct drm_device *dev = crtc->base.dev;
717         intel_clock_t clock;
718         int err = target;
719
720         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
721                 /*
722                  * For LVDS just rely on its current settings for dual-channel.
723                  * We haven't figured out how to reliably set up different
724                  * single/dual channel state, if we even can.
725                  */
726                 if (intel_is_dual_link_lvds(dev))
727                         clock.p2 = limit->p2.p2_fast;
728                 else
729                         clock.p2 = limit->p2.p2_slow;
730         } else {
731                 if (target < limit->p2.dot_limit)
732                         clock.p2 = limit->p2.p2_slow;
733                 else
734                         clock.p2 = limit->p2.p2_fast;
735         }
736
737         memset(best_clock, 0, sizeof(*best_clock));
738
739         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
740              clock.m1++) {
741                 for (clock.m2 = limit->m2.min;
742                      clock.m2 <= limit->m2.max; clock.m2++) {
743                         for (clock.n = limit->n.min;
744                              clock.n <= limit->n.max; clock.n++) {
745                                 for (clock.p1 = limit->p1.min;
746                                         clock.p1 <= limit->p1.max; clock.p1++) {
747                                         int this_err;
748
749                                         pineview_clock(refclk, &clock);
750                                         if (!intel_PLL_is_valid(dev, limit,
751                                                                 &clock))
752                                                 continue;
753                                         if (match_clock &&
754                                             clock.p != match_clock->p)
755                                                 continue;
756
757                                         this_err = abs(clock.dot - target);
758                                         if (this_err < err) {
759                                                 *best_clock = clock;
760                                                 err = this_err;
761                                         }
762                                 }
763                         }
764                 }
765         }
766
767         return (err != target);
768 }
769
770 static bool
771 g4x_find_best_dpll(const intel_limit_t *limit,
772                    struct intel_crtc_state *crtc_state,
773                    int target, int refclk, intel_clock_t *match_clock,
774                    intel_clock_t *best_clock)
775 {
776         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
777         struct drm_device *dev = crtc->base.dev;
778         intel_clock_t clock;
779         int max_n;
780         bool found;
781         /* approximately equals target * 0.00585 */
782         int err_most = (target >> 8) + (target >> 9);
783         found = false;
784
785         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
786                 if (intel_is_dual_link_lvds(dev))
787                         clock.p2 = limit->p2.p2_fast;
788                 else
789                         clock.p2 = limit->p2.p2_slow;
790         } else {
791                 if (target < limit->p2.dot_limit)
792                         clock.p2 = limit->p2.p2_slow;
793                 else
794                         clock.p2 = limit->p2.p2_fast;
795         }
796
797         memset(best_clock, 0, sizeof(*best_clock));
798         max_n = limit->n.max;
799         /* based on hardware requirement, prefer smaller n to precision */
800         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
801                 /* based on hardware requirement, prefere larger m1,m2 */
802                 for (clock.m1 = limit->m1.max;
803                      clock.m1 >= limit->m1.min; clock.m1--) {
804                         for (clock.m2 = limit->m2.max;
805                              clock.m2 >= limit->m2.min; clock.m2--) {
806                                 for (clock.p1 = limit->p1.max;
807                                      clock.p1 >= limit->p1.min; clock.p1--) {
808                                         int this_err;
809
810                                         i9xx_clock(refclk, &clock);
811                                         if (!intel_PLL_is_valid(dev, limit,
812                                                                 &clock))
813                                                 continue;
814
815                                         this_err = abs(clock.dot - target);
816                                         if (this_err < err_most) {
817                                                 *best_clock = clock;
818                                                 err_most = this_err;
819                                                 max_n = clock.n;
820                                                 found = true;
821                                         }
822                                 }
823                         }
824                 }
825         }
826         return found;
827 }
828
829 /*
830  * Check if the calculated PLL configuration is more optimal compared to the
831  * best configuration and error found so far. Return the calculated error.
832  */
833 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
834                                const intel_clock_t *calculated_clock,
835                                const intel_clock_t *best_clock,
836                                unsigned int best_error_ppm,
837                                unsigned int *error_ppm)
838 {
839         /*
840          * For CHV ignore the error and consider only the P value.
841          * Prefer a bigger P value based on HW requirements.
842          */
843         if (IS_CHERRYVIEW(dev)) {
844                 *error_ppm = 0;
845
846                 return calculated_clock->p > best_clock->p;
847         }
848
849         if (WARN_ON_ONCE(!target_freq))
850                 return false;
851
852         *error_ppm = div_u64(1000000ULL *
853                                 abs(target_freq - calculated_clock->dot),
854                              target_freq);
855         /*
856          * Prefer a better P value over a better (smaller) error if the error
857          * is small. Ensure this preference for future configurations too by
858          * setting the error to 0.
859          */
860         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
861                 *error_ppm = 0;
862
863                 return true;
864         }
865
866         return *error_ppm + 10 < best_error_ppm;
867 }
868
869 static bool
870 vlv_find_best_dpll(const intel_limit_t *limit,
871                    struct intel_crtc_state *crtc_state,
872                    int target, int refclk, intel_clock_t *match_clock,
873                    intel_clock_t *best_clock)
874 {
875         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
876         struct drm_device *dev = crtc->base.dev;
877         intel_clock_t clock;
878         unsigned int bestppm = 1000000;
879         /* min update 19.2 MHz */
880         int max_n = min(limit->n.max, refclk / 19200);
881         bool found = false;
882
883         target *= 5; /* fast clock */
884
885         memset(best_clock, 0, sizeof(*best_clock));
886
887         /* based on hardware requirement, prefer smaller n to precision */
888         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
889                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
890                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
891                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
892                                 clock.p = clock.p1 * clock.p2;
893                                 /* based on hardware requirement, prefer bigger m1,m2 values */
894                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
895                                         unsigned int ppm;
896
897                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
898                                                                      refclk * clock.m1);
899
900                                         vlv_clock(refclk, &clock);
901
902                                         if (!intel_PLL_is_valid(dev, limit,
903                                                                 &clock))
904                                                 continue;
905
906                                         if (!vlv_PLL_is_optimal(dev, target,
907                                                                 &clock,
908                                                                 best_clock,
909                                                                 bestppm, &ppm))
910                                                 continue;
911
912                                         *best_clock = clock;
913                                         bestppm = ppm;
914                                         found = true;
915                                 }
916                         }
917                 }
918         }
919
920         return found;
921 }
922
923 static bool
924 chv_find_best_dpll(const intel_limit_t *limit,
925                    struct intel_crtc_state *crtc_state,
926                    int target, int refclk, intel_clock_t *match_clock,
927                    intel_clock_t *best_clock)
928 {
929         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
930         struct drm_device *dev = crtc->base.dev;
931         unsigned int best_error_ppm;
932         intel_clock_t clock;
933         uint64_t m2;
934         int found = false;
935
936         memset(best_clock, 0, sizeof(*best_clock));
937         best_error_ppm = 1000000;
938
939         /*
940          * Based on hardware doc, the n always set to 1, and m1 always
941          * set to 2.  If requires to support 200Mhz refclk, we need to
942          * revisit this because n may not 1 anymore.
943          */
944         clock.n = 1, clock.m1 = 2;
945         target *= 5;    /* fast clock */
946
947         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
948                 for (clock.p2 = limit->p2.p2_fast;
949                                 clock.p2 >= limit->p2.p2_slow;
950                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
951                         unsigned int error_ppm;
952
953                         clock.p = clock.p1 * clock.p2;
954
955                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
956                                         clock.n) << 22, refclk * clock.m1);
957
958                         if (m2 > INT_MAX/clock.m1)
959                                 continue;
960
961                         clock.m2 = m2;
962
963                         chv_clock(refclk, &clock);
964
965                         if (!intel_PLL_is_valid(dev, limit, &clock))
966                                 continue;
967
968                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
969                                                 best_error_ppm, &error_ppm))
970                                 continue;
971
972                         *best_clock = clock;
973                         best_error_ppm = error_ppm;
974                         found = true;
975                 }
976         }
977
978         return found;
979 }
980
981 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state, int target_clock,
982                         intel_clock_t *best_clock)
983 {
984         int refclk = i9xx_get_refclk(crtc_state, 0);
985
986         return chv_find_best_dpll(intel_limit(crtc_state, refclk), crtc_state,
987                                   target_clock, refclk, NULL, best_clock);
988 }
989
990 bool intel_crtc_active(struct drm_crtc *crtc)
991 {
992         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
993
994         /* Be paranoid as we can arrive here with only partial
995          * state retrieved from the hardware during setup.
996          *
997          * We can ditch the adjusted_mode.crtc_clock check as soon
998          * as Haswell has gained clock readout/fastboot support.
999          *
1000          * We can ditch the crtc->primary->fb check as soon as we can
1001          * properly reconstruct framebuffers.
1002          *
1003          * FIXME: The intel_crtc->active here should be switched to
1004          * crtc->state->active once we have proper CRTC states wired up
1005          * for atomic.
1006          */
1007         return intel_crtc->active && crtc->primary->state->fb &&
1008                 intel_crtc->config->base.adjusted_mode.crtc_clock;
1009 }
1010
1011 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
1012                                              enum pipe pipe)
1013 {
1014         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1015         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1016
1017         return intel_crtc->config->cpu_transcoder;
1018 }
1019
1020 static bool pipe_dsl_stopped(struct drm_device *dev, enum pipe pipe)
1021 {
1022         struct drm_i915_private *dev_priv = dev->dev_private;
1023         u32 reg = PIPEDSL(pipe);
1024         u32 line1, line2;
1025         u32 line_mask;
1026
1027         if (IS_GEN2(dev))
1028                 line_mask = DSL_LINEMASK_GEN2;
1029         else
1030                 line_mask = DSL_LINEMASK_GEN3;
1031
1032         line1 = I915_READ(reg) & line_mask;
1033         mdelay(5);
1034         line2 = I915_READ(reg) & line_mask;
1035
1036         return line1 == line2;
1037 }
1038
1039 /*
1040  * intel_wait_for_pipe_off - wait for pipe to turn off
1041  * @crtc: crtc whose pipe to wait for
1042  *
1043  * After disabling a pipe, we can't wait for vblank in the usual way,
1044  * spinning on the vblank interrupt status bit, since we won't actually
1045  * see an interrupt when the pipe is disabled.
1046  *
1047  * On Gen4 and above:
1048  *   wait for the pipe register state bit to turn off
1049  *
1050  * Otherwise:
1051  *   wait for the display line value to settle (it usually
1052  *   ends up stopping at the start of the next frame).
1053  *
1054  */
1055 static void intel_wait_for_pipe_off(struct intel_crtc *crtc)
1056 {
1057         struct drm_device *dev = crtc->base.dev;
1058         struct drm_i915_private *dev_priv = dev->dev_private;
1059         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1060         enum pipe pipe = crtc->pipe;
1061
1062         if (INTEL_INFO(dev)->gen >= 4) {
1063                 int reg = PIPECONF(cpu_transcoder);
1064
1065                 /* Wait for the Pipe State to go off */
1066                 if (wait_for((I915_READ(reg) & I965_PIPECONF_ACTIVE) == 0,
1067                              100))
1068                         WARN(1, "pipe_off wait timed out\n");
1069         } else {
1070                 /* Wait for the display line to settle */
1071                 if (wait_for(pipe_dsl_stopped(dev, pipe), 100))
1072                         WARN(1, "pipe_off wait timed out\n");
1073         }
1074 }
1075
1076 /*
1077  * ibx_digital_port_connected - is the specified port connected?
1078  * @dev_priv: i915 private structure
1079  * @port: the port to test
1080  *
1081  * Returns true if @port is connected, false otherwise.
1082  */
1083 bool ibx_digital_port_connected(struct drm_i915_private *dev_priv,
1084                                 struct intel_digital_port *port)
1085 {
1086         u32 bit;
1087
1088         if (HAS_PCH_IBX(dev_priv->dev)) {
1089                 switch (port->port) {
1090                 case PORT_B:
1091                         bit = SDE_PORTB_HOTPLUG;
1092                         break;
1093                 case PORT_C:
1094                         bit = SDE_PORTC_HOTPLUG;
1095                         break;
1096                 case PORT_D:
1097                         bit = SDE_PORTD_HOTPLUG;
1098                         break;
1099                 default:
1100                         return true;
1101                 }
1102         } else {
1103                 switch (port->port) {
1104                 case PORT_B:
1105                         bit = SDE_PORTB_HOTPLUG_CPT;
1106                         break;
1107                 case PORT_C:
1108                         bit = SDE_PORTC_HOTPLUG_CPT;
1109                         break;
1110                 case PORT_D:
1111                         bit = SDE_PORTD_HOTPLUG_CPT;
1112                         break;
1113                 default:
1114                         return true;
1115                 }
1116         }
1117
1118         return I915_READ(SDEISR) & bit;
1119 }
1120
1121 static const char *state_string(bool enabled)
1122 {
1123         return enabled ? "on" : "off";
1124 }
1125
1126 /* Only for pre-ILK configs */
1127 void assert_pll(struct drm_i915_private *dev_priv,
1128                 enum pipe pipe, bool state)
1129 {
1130         int reg;
1131         u32 val;
1132         bool cur_state;
1133
1134         reg = DPLL(pipe);
1135         val = I915_READ(reg);
1136         cur_state = !!(val & DPLL_VCO_ENABLE);
1137         I915_STATE_WARN(cur_state != state,
1138              "PLL state assertion failure (expected %s, current %s)\n",
1139              state_string(state), state_string(cur_state));
1140 }
1141
1142 /* XXX: the dsi pll is shared between MIPI DSI ports */
1143 static void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1144 {
1145         u32 val;
1146         bool cur_state;
1147
1148         mutex_lock(&dev_priv->sb_lock);
1149         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1150         mutex_unlock(&dev_priv->sb_lock);
1151
1152         cur_state = val & DSI_PLL_VCO_EN;
1153         I915_STATE_WARN(cur_state != state,
1154              "DSI PLL state assertion failure (expected %s, current %s)\n",
1155              state_string(state), state_string(cur_state));
1156 }
1157 #define assert_dsi_pll_enabled(d) assert_dsi_pll(d, true)
1158 #define assert_dsi_pll_disabled(d) assert_dsi_pll(d, false)
1159
1160 struct intel_shared_dpll *
1161 intel_crtc_to_shared_dpll(struct intel_crtc *crtc)
1162 {
1163         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
1164
1165         if (crtc->config->shared_dpll < 0)
1166                 return NULL;
1167
1168         return &dev_priv->shared_dplls[crtc->config->shared_dpll];
1169 }
1170
1171 /* For ILK+ */
1172 void assert_shared_dpll(struct drm_i915_private *dev_priv,
1173                         struct intel_shared_dpll *pll,
1174                         bool state)
1175 {
1176         bool cur_state;
1177         struct intel_dpll_hw_state hw_state;
1178
1179         if (WARN (!pll,
1180                   "asserting DPLL %s with no DPLL\n", state_string(state)))
1181                 return;
1182
1183         cur_state = pll->get_hw_state(dev_priv, pll, &hw_state);
1184         I915_STATE_WARN(cur_state != state,
1185              "%s assertion failure (expected %s, current %s)\n",
1186              pll->name, state_string(state), state_string(cur_state));
1187 }
1188
1189 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1190                           enum pipe pipe, bool state)
1191 {
1192         int reg;
1193         u32 val;
1194         bool cur_state;
1195         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1196                                                                       pipe);
1197
1198         if (HAS_DDI(dev_priv->dev)) {
1199                 /* DDI does not have a specific FDI_TX register */
1200                 reg = TRANS_DDI_FUNC_CTL(cpu_transcoder);
1201                 val = I915_READ(reg);
1202                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1203         } else {
1204                 reg = FDI_TX_CTL(pipe);
1205                 val = I915_READ(reg);
1206                 cur_state = !!(val & FDI_TX_ENABLE);
1207         }
1208         I915_STATE_WARN(cur_state != state,
1209              "FDI TX state assertion failure (expected %s, current %s)\n",
1210              state_string(state), state_string(cur_state));
1211 }
1212 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1213 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1214
1215 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1216                           enum pipe pipe, bool state)
1217 {
1218         int reg;
1219         u32 val;
1220         bool cur_state;
1221
1222         reg = FDI_RX_CTL(pipe);
1223         val = I915_READ(reg);
1224         cur_state = !!(val & FDI_RX_ENABLE);
1225         I915_STATE_WARN(cur_state != state,
1226              "FDI RX state assertion failure (expected %s, current %s)\n",
1227              state_string(state), state_string(cur_state));
1228 }
1229 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1230 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1231
1232 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1233                                       enum pipe pipe)
1234 {
1235         int reg;
1236         u32 val;
1237
1238         /* ILK FDI PLL is always enabled */
1239         if (INTEL_INFO(dev_priv->dev)->gen == 5)
1240                 return;
1241
1242         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1243         if (HAS_DDI(dev_priv->dev))
1244                 return;
1245
1246         reg = FDI_TX_CTL(pipe);
1247         val = I915_READ(reg);
1248         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1249 }
1250
1251 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1252                        enum pipe pipe, bool state)
1253 {
1254         int reg;
1255         u32 val;
1256         bool cur_state;
1257
1258         reg = FDI_RX_CTL(pipe);
1259         val = I915_READ(reg);
1260         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1261         I915_STATE_WARN(cur_state != state,
1262              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1263              state_string(state), state_string(cur_state));
1264 }
1265
1266 void assert_panel_unlocked(struct drm_i915_private *dev_priv,
1267                            enum pipe pipe)
1268 {
1269         struct drm_device *dev = dev_priv->dev;
1270         int pp_reg;
1271         u32 val;
1272         enum pipe panel_pipe = PIPE_A;
1273         bool locked = true;
1274
1275         if (WARN_ON(HAS_DDI(dev)))
1276                 return;
1277
1278         if (HAS_PCH_SPLIT(dev)) {
1279                 u32 port_sel;
1280
1281                 pp_reg = PCH_PP_CONTROL;
1282                 port_sel = I915_READ(PCH_PP_ON_DELAYS) & PANEL_PORT_SELECT_MASK;
1283
1284                 if (port_sel == PANEL_PORT_SELECT_LVDS &&
1285                     I915_READ(PCH_LVDS) & LVDS_PIPEB_SELECT)
1286                         panel_pipe = PIPE_B;
1287                 /* XXX: else fix for eDP */
1288         } else if (IS_VALLEYVIEW(dev)) {
1289                 /* presumably write lock depends on pipe, not port select */
1290                 pp_reg = VLV_PIPE_PP_CONTROL(pipe);
1291                 panel_pipe = pipe;
1292         } else {
1293                 pp_reg = PP_CONTROL;
1294                 if (I915_READ(LVDS) & LVDS_PIPEB_SELECT)
1295                         panel_pipe = PIPE_B;
1296         }
1297
1298         val = I915_READ(pp_reg);
1299         if (!(val & PANEL_POWER_ON) ||
1300             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1301                 locked = false;
1302
1303         I915_STATE_WARN(panel_pipe == pipe && locked,
1304              "panel assertion failure, pipe %c regs locked\n",
1305              pipe_name(pipe));
1306 }
1307
1308 static void assert_cursor(struct drm_i915_private *dev_priv,
1309                           enum pipe pipe, bool state)
1310 {
1311         struct drm_device *dev = dev_priv->dev;
1312         bool cur_state;
1313
1314         if (IS_845G(dev) || IS_I865G(dev))
1315                 cur_state = I915_READ(_CURACNTR) & CURSOR_ENABLE;
1316         else
1317                 cur_state = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
1318
1319         I915_STATE_WARN(cur_state != state,
1320              "cursor on pipe %c assertion failure (expected %s, current %s)\n",
1321              pipe_name(pipe), state_string(state), state_string(cur_state));
1322 }
1323 #define assert_cursor_enabled(d, p) assert_cursor(d, p, true)
1324 #define assert_cursor_disabled(d, p) assert_cursor(d, p, false)
1325
1326 void assert_pipe(struct drm_i915_private *dev_priv,
1327                  enum pipe pipe, bool state)
1328 {
1329         int reg;
1330         u32 val;
1331         bool cur_state;
1332         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1333                                                                       pipe);
1334
1335         /* if we need the pipe quirk it must be always on */
1336         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1337             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1338                 state = true;
1339
1340         if (!intel_display_power_is_enabled(dev_priv,
1341                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder))) {
1342                 cur_state = false;
1343         } else {
1344                 reg = PIPECONF(cpu_transcoder);
1345                 val = I915_READ(reg);
1346                 cur_state = !!(val & PIPECONF_ENABLE);
1347         }
1348
1349         I915_STATE_WARN(cur_state != state,
1350              "pipe %c assertion failure (expected %s, current %s)\n",
1351              pipe_name(pipe), state_string(state), state_string(cur_state));
1352 }
1353
1354 static void assert_plane(struct drm_i915_private *dev_priv,
1355                          enum plane plane, bool state)
1356 {
1357         int reg;
1358         u32 val;
1359         bool cur_state;
1360
1361         reg = DSPCNTR(plane);
1362         val = I915_READ(reg);
1363         cur_state = !!(val & DISPLAY_PLANE_ENABLE);
1364         I915_STATE_WARN(cur_state != state,
1365              "plane %c assertion failure (expected %s, current %s)\n",
1366              plane_name(plane), state_string(state), state_string(cur_state));
1367 }
1368
1369 #define assert_plane_enabled(d, p) assert_plane(d, p, true)
1370 #define assert_plane_disabled(d, p) assert_plane(d, p, false)
1371
1372 static void assert_planes_disabled(struct drm_i915_private *dev_priv,
1373                                    enum pipe pipe)
1374 {
1375         struct drm_device *dev = dev_priv->dev;
1376         int reg, i;
1377         u32 val;
1378         int cur_pipe;
1379
1380         /* Primary planes are fixed to pipes on gen4+ */
1381         if (INTEL_INFO(dev)->gen >= 4) {
1382                 reg = DSPCNTR(pipe);
1383                 val = I915_READ(reg);
1384                 I915_STATE_WARN(val & DISPLAY_PLANE_ENABLE,
1385                      "plane %c assertion failure, should be disabled but not\n",
1386                      plane_name(pipe));
1387                 return;
1388         }
1389
1390         /* Need to check both planes against the pipe */
1391         for_each_pipe(dev_priv, i) {
1392                 reg = DSPCNTR(i);
1393                 val = I915_READ(reg);
1394                 cur_pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
1395                         DISPPLANE_SEL_PIPE_SHIFT;
1396                 I915_STATE_WARN((val & DISPLAY_PLANE_ENABLE) && pipe == cur_pipe,
1397                      "plane %c assertion failure, should be off on pipe %c but is still active\n",
1398                      plane_name(i), pipe_name(pipe));
1399         }
1400 }
1401
1402 static void assert_sprites_disabled(struct drm_i915_private *dev_priv,
1403                                     enum pipe pipe)
1404 {
1405         struct drm_device *dev = dev_priv->dev;
1406         int reg, sprite;
1407         u32 val;
1408
1409         if (INTEL_INFO(dev)->gen >= 9) {
1410                 for_each_sprite(dev_priv, pipe, sprite) {
1411                         val = I915_READ(PLANE_CTL(pipe, sprite));
1412                         I915_STATE_WARN(val & PLANE_CTL_ENABLE,
1413                              "plane %d assertion failure, should be off on pipe %c but is still active\n",
1414                              sprite, pipe_name(pipe));
1415                 }
1416         } else if (IS_VALLEYVIEW(dev)) {
1417                 for_each_sprite(dev_priv, pipe, sprite) {
1418                         reg = SPCNTR(pipe, sprite);
1419                         val = I915_READ(reg);
1420                         I915_STATE_WARN(val & SP_ENABLE,
1421                              "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1422                              sprite_name(pipe, sprite), pipe_name(pipe));
1423                 }
1424         } else if (INTEL_INFO(dev)->gen >= 7) {
1425                 reg = SPRCTL(pipe);
1426                 val = I915_READ(reg);
1427                 I915_STATE_WARN(val & SPRITE_ENABLE,
1428                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1429                      plane_name(pipe), pipe_name(pipe));
1430         } else if (INTEL_INFO(dev)->gen >= 5) {
1431                 reg = DVSCNTR(pipe);
1432                 val = I915_READ(reg);
1433                 I915_STATE_WARN(val & DVS_ENABLE,
1434                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1435                      plane_name(pipe), pipe_name(pipe));
1436         }
1437 }
1438
1439 static void assert_vblank_disabled(struct drm_crtc *crtc)
1440 {
1441         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1442                 drm_crtc_vblank_put(crtc);
1443 }
1444
1445 static void ibx_assert_pch_refclk_enabled(struct drm_i915_private *dev_priv)
1446 {
1447         u32 val;
1448         bool enabled;
1449
1450         I915_STATE_WARN_ON(!(HAS_PCH_IBX(dev_priv->dev) || HAS_PCH_CPT(dev_priv->dev)));
1451
1452         val = I915_READ(PCH_DREF_CONTROL);
1453         enabled = !!(val & (DREF_SSC_SOURCE_MASK | DREF_NONSPREAD_SOURCE_MASK |
1454                             DREF_SUPERSPREAD_SOURCE_MASK));
1455         I915_STATE_WARN(!enabled, "PCH refclk assertion failure, should be active but is disabled\n");
1456 }
1457
1458 static void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1459                                            enum pipe pipe)
1460 {
1461         int reg;
1462         u32 val;
1463         bool enabled;
1464
1465         reg = PCH_TRANSCONF(pipe);
1466         val = I915_READ(reg);
1467         enabled = !!(val & TRANS_ENABLE);
1468         I915_STATE_WARN(enabled,
1469              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1470              pipe_name(pipe));
1471 }
1472
1473 static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1474                             enum pipe pipe, u32 port_sel, u32 val)
1475 {
1476         if ((val & DP_PORT_EN) == 0)
1477                 return false;
1478
1479         if (HAS_PCH_CPT(dev_priv->dev)) {
1480                 u32     trans_dp_ctl_reg = TRANS_DP_CTL(pipe);
1481                 u32     trans_dp_ctl = I915_READ(trans_dp_ctl_reg);
1482                 if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1483                         return false;
1484         } else if (IS_CHERRYVIEW(dev_priv->dev)) {
1485                 if ((val & DP_PIPE_MASK_CHV) != DP_PIPE_SELECT_CHV(pipe))
1486                         return false;
1487         } else {
1488                 if ((val & DP_PIPE_MASK) != (pipe << 30))
1489                         return false;
1490         }
1491         return true;
1492 }
1493
1494 static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1495                               enum pipe pipe, u32 val)
1496 {
1497         if ((val & SDVO_ENABLE) == 0)
1498                 return false;
1499
1500         if (HAS_PCH_CPT(dev_priv->dev)) {
1501                 if ((val & SDVO_PIPE_SEL_MASK_CPT) != SDVO_PIPE_SEL_CPT(pipe))
1502                         return false;
1503         } else if (IS_CHERRYVIEW(dev_priv->dev)) {
1504                 if ((val & SDVO_PIPE_SEL_MASK_CHV) != SDVO_PIPE_SEL_CHV(pipe))
1505                         return false;
1506         } else {
1507                 if ((val & SDVO_PIPE_SEL_MASK) != SDVO_PIPE_SEL(pipe))
1508                         return false;
1509         }
1510         return true;
1511 }
1512
1513 static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1514                               enum pipe pipe, u32 val)
1515 {
1516         if ((val & LVDS_PORT_EN) == 0)
1517                 return false;
1518
1519         if (HAS_PCH_CPT(dev_priv->dev)) {
1520                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1521                         return false;
1522         } else {
1523                 if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1524                         return false;
1525         }
1526         return true;
1527 }
1528
1529 static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1530                               enum pipe pipe, u32 val)
1531 {
1532         if ((val & ADPA_DAC_ENABLE) == 0)
1533                 return false;
1534         if (HAS_PCH_CPT(dev_priv->dev)) {
1535                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1536                         return false;
1537         } else {
1538                 if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1539                         return false;
1540         }
1541         return true;
1542 }
1543
1544 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1545                                    enum pipe pipe, int reg, u32 port_sel)
1546 {
1547         u32 val = I915_READ(reg);
1548         I915_STATE_WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1549              "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1550              reg, pipe_name(pipe));
1551
1552         I915_STATE_WARN(HAS_PCH_IBX(dev_priv->dev) && (val & DP_PORT_EN) == 0
1553              && (val & DP_PIPEB_SELECT),
1554              "IBX PCH dp port still using transcoder B\n");
1555 }
1556
1557 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1558                                      enum pipe pipe, int reg)
1559 {
1560         u32 val = I915_READ(reg);
1561         I915_STATE_WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1562              "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1563              reg, pipe_name(pipe));
1564
1565         I915_STATE_WARN(HAS_PCH_IBX(dev_priv->dev) && (val & SDVO_ENABLE) == 0
1566              && (val & SDVO_PIPE_B_SELECT),
1567              "IBX PCH hdmi port still using transcoder B\n");
1568 }
1569
1570 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1571                                       enum pipe pipe)
1572 {
1573         int reg;
1574         u32 val;
1575
1576         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1577         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1578         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1579
1580         reg = PCH_ADPA;
1581         val = I915_READ(reg);
1582         I915_STATE_WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1583              "PCH VGA enabled on transcoder %c, should be disabled\n",
1584              pipe_name(pipe));
1585
1586         reg = PCH_LVDS;
1587         val = I915_READ(reg);
1588         I915_STATE_WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1589              "PCH LVDS enabled on transcoder %c, should be disabled\n",
1590              pipe_name(pipe));
1591
1592         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIB);
1593         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIC);
1594         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMID);
1595 }
1596
1597 static void intel_init_dpio(struct drm_device *dev)
1598 {
1599         struct drm_i915_private *dev_priv = dev->dev_private;
1600
1601         if (!IS_VALLEYVIEW(dev))
1602                 return;
1603
1604         /*
1605          * IOSF_PORT_DPIO is used for VLV x2 PHY (DP/HDMI B and C),
1606          * CHV x1 PHY (DP/HDMI D)
1607          * IOSF_PORT_DPIO_2 is used for CHV x2 PHY (DP/HDMI B and C)
1608          */
1609         if (IS_CHERRYVIEW(dev)) {
1610                 DPIO_PHY_IOSF_PORT(DPIO_PHY0) = IOSF_PORT_DPIO_2;
1611                 DPIO_PHY_IOSF_PORT(DPIO_PHY1) = IOSF_PORT_DPIO;
1612         } else {
1613                 DPIO_PHY_IOSF_PORT(DPIO_PHY0) = IOSF_PORT_DPIO;
1614         }
1615 }
1616
1617 static void vlv_enable_pll(struct intel_crtc *crtc,
1618                            const struct intel_crtc_state *pipe_config)
1619 {
1620         struct drm_device *dev = crtc->base.dev;
1621         struct drm_i915_private *dev_priv = dev->dev_private;
1622         int reg = DPLL(crtc->pipe);
1623         u32 dpll = pipe_config->dpll_hw_state.dpll;
1624
1625         assert_pipe_disabled(dev_priv, crtc->pipe);
1626
1627         /* No really, not for ILK+ */
1628         BUG_ON(!IS_VALLEYVIEW(dev_priv->dev));
1629
1630         /* PLL is protected by panel, make sure we can write it */
1631         if (IS_MOBILE(dev_priv->dev))
1632                 assert_panel_unlocked(dev_priv, crtc->pipe);
1633
1634         I915_WRITE(reg, dpll);
1635         POSTING_READ(reg);
1636         udelay(150);
1637
1638         if (wait_for(((I915_READ(reg) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1639                 DRM_ERROR("DPLL %d failed to lock\n", crtc->pipe);
1640
1641         I915_WRITE(DPLL_MD(crtc->pipe), pipe_config->dpll_hw_state.dpll_md);
1642         POSTING_READ(DPLL_MD(crtc->pipe));
1643
1644         /* We do this three times for luck */
1645         I915_WRITE(reg, dpll);
1646         POSTING_READ(reg);
1647         udelay(150); /* wait for warmup */
1648         I915_WRITE(reg, dpll);
1649         POSTING_READ(reg);
1650         udelay(150); /* wait for warmup */
1651         I915_WRITE(reg, dpll);
1652         POSTING_READ(reg);
1653         udelay(150); /* wait for warmup */
1654 }
1655
1656 static void chv_enable_pll(struct intel_crtc *crtc,
1657                            const struct intel_crtc_state *pipe_config)
1658 {
1659         struct drm_device *dev = crtc->base.dev;
1660         struct drm_i915_private *dev_priv = dev->dev_private;
1661         int pipe = crtc->pipe;
1662         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1663         u32 tmp;
1664
1665         assert_pipe_disabled(dev_priv, crtc->pipe);
1666
1667         BUG_ON(!IS_CHERRYVIEW(dev_priv->dev));
1668
1669         mutex_lock(&dev_priv->sb_lock);
1670
1671         /* Enable back the 10bit clock to display controller */
1672         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1673         tmp |= DPIO_DCLKP_EN;
1674         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1675
1676         mutex_unlock(&dev_priv->sb_lock);
1677
1678         /*
1679          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1680          */
1681         udelay(1);
1682
1683         /* Enable PLL */
1684         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1685
1686         /* Check PLL is locked */
1687         if (wait_for(((I915_READ(DPLL(pipe)) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1688                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1689
1690         /* not sure when this should be written */
1691         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1692         POSTING_READ(DPLL_MD(pipe));
1693 }
1694
1695 static int intel_num_dvo_pipes(struct drm_device *dev)
1696 {
1697         struct intel_crtc *crtc;
1698         int count = 0;
1699
1700         for_each_intel_crtc(dev, crtc)
1701                 count += crtc->base.state->active &&
1702                         intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO);
1703
1704         return count;
1705 }
1706
1707 static void i9xx_enable_pll(struct intel_crtc *crtc)
1708 {
1709         struct drm_device *dev = crtc->base.dev;
1710         struct drm_i915_private *dev_priv = dev->dev_private;
1711         int reg = DPLL(crtc->pipe);
1712         u32 dpll = crtc->config->dpll_hw_state.dpll;
1713
1714         assert_pipe_disabled(dev_priv, crtc->pipe);
1715
1716         /* No really, not for ILK+ */
1717         BUG_ON(INTEL_INFO(dev)->gen >= 5);
1718
1719         /* PLL is protected by panel, make sure we can write it */
1720         if (IS_MOBILE(dev) && !IS_I830(dev))
1721                 assert_panel_unlocked(dev_priv, crtc->pipe);
1722
1723         /* Enable DVO 2x clock on both PLLs if necessary */
1724         if (IS_I830(dev) && intel_num_dvo_pipes(dev) > 0) {
1725                 /*
1726                  * It appears to be important that we don't enable this
1727                  * for the current pipe before otherwise configuring the
1728                  * PLL. No idea how this should be handled if multiple
1729                  * DVO outputs are enabled simultaneosly.
1730                  */
1731                 dpll |= DPLL_DVO_2X_MODE;
1732                 I915_WRITE(DPLL(!crtc->pipe),
1733                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1734         }
1735
1736         /* Wait for the clocks to stabilize. */
1737         POSTING_READ(reg);
1738         udelay(150);
1739
1740         if (INTEL_INFO(dev)->gen >= 4) {
1741                 I915_WRITE(DPLL_MD(crtc->pipe),
1742                            crtc->config->dpll_hw_state.dpll_md);
1743         } else {
1744                 /* The pixel multiplier can only be updated once the
1745                  * DPLL is enabled and the clocks are stable.
1746                  *
1747                  * So write it again.
1748                  */
1749                 I915_WRITE(reg, dpll);
1750         }
1751
1752         /* We do this three times for luck */
1753         I915_WRITE(reg, dpll);
1754         POSTING_READ(reg);
1755         udelay(150); /* wait for warmup */
1756         I915_WRITE(reg, dpll);
1757         POSTING_READ(reg);
1758         udelay(150); /* wait for warmup */
1759         I915_WRITE(reg, dpll);
1760         POSTING_READ(reg);
1761         udelay(150); /* wait for warmup */
1762 }
1763
1764 /**
1765  * i9xx_disable_pll - disable a PLL
1766  * @dev_priv: i915 private structure
1767  * @pipe: pipe PLL to disable
1768  *
1769  * Disable the PLL for @pipe, making sure the pipe is off first.
1770  *
1771  * Note!  This is for pre-ILK only.
1772  */
1773 static void i9xx_disable_pll(struct intel_crtc *crtc)
1774 {
1775         struct drm_device *dev = crtc->base.dev;
1776         struct drm_i915_private *dev_priv = dev->dev_private;
1777         enum pipe pipe = crtc->pipe;
1778
1779         /* Disable DVO 2x clock on both PLLs if necessary */
1780         if (IS_I830(dev) &&
1781             intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO) &&
1782             !intel_num_dvo_pipes(dev)) {
1783                 I915_WRITE(DPLL(PIPE_B),
1784                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1785                 I915_WRITE(DPLL(PIPE_A),
1786                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1787         }
1788
1789         /* Don't disable pipe or pipe PLLs if needed */
1790         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1791             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1792                 return;
1793
1794         /* Make sure the pipe isn't still relying on us */
1795         assert_pipe_disabled(dev_priv, pipe);
1796
1797         I915_WRITE(DPLL(pipe), 0);
1798         POSTING_READ(DPLL(pipe));
1799 }
1800
1801 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1802 {
1803         u32 val = 0;
1804
1805         /* Make sure the pipe isn't still relying on us */
1806         assert_pipe_disabled(dev_priv, pipe);
1807
1808         /*
1809          * Leave integrated clock source and reference clock enabled for pipe B.
1810          * The latter is needed for VGA hotplug / manual detection.
1811          */
1812         if (pipe == PIPE_B)
1813                 val = DPLL_INTEGRATED_CRI_CLK_VLV | DPLL_REFA_CLK_ENABLE_VLV;
1814         I915_WRITE(DPLL(pipe), val);
1815         POSTING_READ(DPLL(pipe));
1816
1817 }
1818
1819 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1820 {
1821         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1822         u32 val;
1823
1824         /* Make sure the pipe isn't still relying on us */
1825         assert_pipe_disabled(dev_priv, pipe);
1826
1827         /* Set PLL en = 0 */
1828         val = DPLL_SSC_REF_CLOCK_CHV | DPLL_REFA_CLK_ENABLE_VLV;
1829         if (pipe != PIPE_A)
1830                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1831         I915_WRITE(DPLL(pipe), val);
1832         POSTING_READ(DPLL(pipe));
1833
1834         mutex_lock(&dev_priv->sb_lock);
1835
1836         /* Disable 10bit clock to display controller */
1837         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1838         val &= ~DPIO_DCLKP_EN;
1839         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1840
1841         /* disable left/right clock distribution */
1842         if (pipe != PIPE_B) {
1843                 val = vlv_dpio_read(dev_priv, pipe, _CHV_CMN_DW5_CH0);
1844                 val &= ~(CHV_BUFLEFTENA1_MASK | CHV_BUFRIGHTENA1_MASK);
1845                 vlv_dpio_write(dev_priv, pipe, _CHV_CMN_DW5_CH0, val);
1846         } else {
1847                 val = vlv_dpio_read(dev_priv, pipe, _CHV_CMN_DW1_CH1);
1848                 val &= ~(CHV_BUFLEFTENA2_MASK | CHV_BUFRIGHTENA2_MASK);
1849                 vlv_dpio_write(dev_priv, pipe, _CHV_CMN_DW1_CH1, val);
1850         }
1851
1852         mutex_unlock(&dev_priv->sb_lock);
1853 }
1854
1855 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1856                          struct intel_digital_port *dport,
1857                          unsigned int expected_mask)
1858 {
1859         u32 port_mask;
1860         int dpll_reg;
1861
1862         switch (dport->port) {
1863         case PORT_B:
1864                 port_mask = DPLL_PORTB_READY_MASK;
1865                 dpll_reg = DPLL(0);
1866                 break;
1867         case PORT_C:
1868                 port_mask = DPLL_PORTC_READY_MASK;
1869                 dpll_reg = DPLL(0);
1870                 expected_mask <<= 4;
1871                 break;
1872         case PORT_D:
1873                 port_mask = DPLL_PORTD_READY_MASK;
1874                 dpll_reg = DPIO_PHY_STATUS;
1875                 break;
1876         default:
1877                 BUG();
1878         }
1879
1880         if (wait_for((I915_READ(dpll_reg) & port_mask) == expected_mask, 1000))
1881                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1882                      port_name(dport->port), I915_READ(dpll_reg) & port_mask, expected_mask);
1883 }
1884
1885 static void intel_prepare_shared_dpll(struct intel_crtc *crtc)
1886 {
1887         struct drm_device *dev = crtc->base.dev;
1888         struct drm_i915_private *dev_priv = dev->dev_private;
1889         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1890
1891         if (WARN_ON(pll == NULL))
1892                 return;
1893
1894         WARN_ON(!pll->config.crtc_mask);
1895         if (pll->active == 0) {
1896                 DRM_DEBUG_DRIVER("setting up %s\n", pll->name);
1897                 WARN_ON(pll->on);
1898                 assert_shared_dpll_disabled(dev_priv, pll);
1899
1900                 pll->mode_set(dev_priv, pll);
1901         }
1902 }
1903
1904 /**
1905  * intel_enable_shared_dpll - enable PCH PLL
1906  * @dev_priv: i915 private structure
1907  * @pipe: pipe PLL to enable
1908  *
1909  * The PCH PLL needs to be enabled before the PCH transcoder, since it
1910  * drives the transcoder clock.
1911  */
1912 static void intel_enable_shared_dpll(struct intel_crtc *crtc)
1913 {
1914         struct drm_device *dev = crtc->base.dev;
1915         struct drm_i915_private *dev_priv = dev->dev_private;
1916         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1917
1918         if (WARN_ON(pll == NULL))
1919                 return;
1920
1921         if (WARN_ON(pll->config.crtc_mask == 0))
1922                 return;
1923
1924         DRM_DEBUG_KMS("enable %s (active %d, on? %d) for crtc %d\n",
1925                       pll->name, pll->active, pll->on,
1926                       crtc->base.base.id);
1927
1928         if (pll->active++) {
1929                 WARN_ON(!pll->on);
1930                 assert_shared_dpll_enabled(dev_priv, pll);
1931                 return;
1932         }
1933         WARN_ON(pll->on);
1934
1935         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
1936
1937         DRM_DEBUG_KMS("enabling %s\n", pll->name);
1938         pll->enable(dev_priv, pll);
1939         pll->on = true;
1940 }
1941
1942 static void intel_disable_shared_dpll(struct intel_crtc *crtc)
1943 {
1944         struct drm_device *dev = crtc->base.dev;
1945         struct drm_i915_private *dev_priv = dev->dev_private;
1946         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1947
1948         /* PCH only available on ILK+ */
1949         BUG_ON(INTEL_INFO(dev)->gen < 5);
1950         if (WARN_ON(pll == NULL))
1951                return;
1952
1953         if (WARN_ON(pll->config.crtc_mask == 0))
1954                 return;
1955
1956         DRM_DEBUG_KMS("disable %s (active %d, on? %d) for crtc %d\n",
1957                       pll->name, pll->active, pll->on,
1958                       crtc->base.base.id);
1959
1960         if (WARN_ON(pll->active == 0)) {
1961                 assert_shared_dpll_disabled(dev_priv, pll);
1962                 return;
1963         }
1964
1965         assert_shared_dpll_enabled(dev_priv, pll);
1966         WARN_ON(!pll->on);
1967         if (--pll->active)
1968                 return;
1969
1970         DRM_DEBUG_KMS("disabling %s\n", pll->name);
1971         pll->disable(dev_priv, pll);
1972         pll->on = false;
1973
1974         intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS);
1975 }
1976
1977 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1978                                            enum pipe pipe)
1979 {
1980         struct drm_device *dev = dev_priv->dev;
1981         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1982         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1983         uint32_t reg, val, pipeconf_val;
1984
1985         /* PCH only available on ILK+ */
1986         BUG_ON(!HAS_PCH_SPLIT(dev));
1987
1988         /* Make sure PCH DPLL is enabled */
1989         assert_shared_dpll_enabled(dev_priv,
1990                                    intel_crtc_to_shared_dpll(intel_crtc));
1991
1992         /* FDI must be feeding us bits for PCH ports */
1993         assert_fdi_tx_enabled(dev_priv, pipe);
1994         assert_fdi_rx_enabled(dev_priv, pipe);
1995
1996         if (HAS_PCH_CPT(dev)) {
1997                 /* Workaround: Set the timing override bit before enabling the
1998                  * pch transcoder. */
1999                 reg = TRANS_CHICKEN2(pipe);
2000                 val = I915_READ(reg);
2001                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
2002                 I915_WRITE(reg, val);
2003         }
2004
2005         reg = PCH_TRANSCONF(pipe);
2006         val = I915_READ(reg);
2007         pipeconf_val = I915_READ(PIPECONF(pipe));
2008
2009         if (HAS_PCH_IBX(dev_priv->dev)) {
2010                 /*
2011                  * Make the BPC in transcoder be consistent with
2012                  * that in pipeconf reg. For HDMI we must use 8bpc
2013                  * here for both 8bpc and 12bpc.
2014                  */
2015                 val &= ~PIPECONF_BPC_MASK;
2016                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_HDMI))
2017                         val |= PIPECONF_8BPC;
2018                 else
2019                         val |= pipeconf_val & PIPECONF_BPC_MASK;
2020         }
2021
2022         val &= ~TRANS_INTERLACE_MASK;
2023         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
2024                 if (HAS_PCH_IBX(dev_priv->dev) &&
2025                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
2026                         val |= TRANS_LEGACY_INTERLACED_ILK;
2027                 else
2028                         val |= TRANS_INTERLACED;
2029         else
2030                 val |= TRANS_PROGRESSIVE;
2031
2032         I915_WRITE(reg, val | TRANS_ENABLE);
2033         if (wait_for(I915_READ(reg) & TRANS_STATE_ENABLE, 100))
2034                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
2035 }
2036
2037 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
2038                                       enum transcoder cpu_transcoder)
2039 {
2040         u32 val, pipeconf_val;
2041
2042         /* PCH only available on ILK+ */
2043         BUG_ON(!HAS_PCH_SPLIT(dev_priv->dev));
2044
2045         /* FDI must be feeding us bits for PCH ports */
2046         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
2047         assert_fdi_rx_enabled(dev_priv, TRANSCODER_A);
2048
2049         /* Workaround: set timing override bit. */
2050         val = I915_READ(_TRANSA_CHICKEN2);
2051         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
2052         I915_WRITE(_TRANSA_CHICKEN2, val);
2053
2054         val = TRANS_ENABLE;
2055         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
2056
2057         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
2058             PIPECONF_INTERLACED_ILK)
2059                 val |= TRANS_INTERLACED;
2060         else
2061                 val |= TRANS_PROGRESSIVE;
2062
2063         I915_WRITE(LPT_TRANSCONF, val);
2064         if (wait_for(I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE, 100))
2065                 DRM_ERROR("Failed to enable PCH transcoder\n");
2066 }
2067
2068 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
2069                                             enum pipe pipe)
2070 {
2071         struct drm_device *dev = dev_priv->dev;
2072         uint32_t reg, val;
2073
2074         /* FDI relies on the transcoder */
2075         assert_fdi_tx_disabled(dev_priv, pipe);
2076         assert_fdi_rx_disabled(dev_priv, pipe);
2077
2078         /* Ports must be off as well */
2079         assert_pch_ports_disabled(dev_priv, pipe);
2080
2081         reg = PCH_TRANSCONF(pipe);
2082         val = I915_READ(reg);
2083         val &= ~TRANS_ENABLE;
2084         I915_WRITE(reg, val);
2085         /* wait for PCH transcoder off, transcoder state */
2086         if (wait_for((I915_READ(reg) & TRANS_STATE_ENABLE) == 0, 50))
2087                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
2088
2089         if (!HAS_PCH_IBX(dev)) {
2090                 /* Workaround: Clear the timing override chicken bit again. */
2091                 reg = TRANS_CHICKEN2(pipe);
2092                 val = I915_READ(reg);
2093                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
2094                 I915_WRITE(reg, val);
2095         }
2096 }
2097
2098 static void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
2099 {
2100         u32 val;
2101
2102         val = I915_READ(LPT_TRANSCONF);
2103         val &= ~TRANS_ENABLE;
2104         I915_WRITE(LPT_TRANSCONF, val);
2105         /* wait for PCH transcoder off, transcoder state */
2106         if (wait_for((I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE) == 0, 50))
2107                 DRM_ERROR("Failed to disable PCH transcoder\n");
2108
2109         /* Workaround: clear timing override bit. */
2110         val = I915_READ(_TRANSA_CHICKEN2);
2111         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
2112         I915_WRITE(_TRANSA_CHICKEN2, val);
2113 }
2114
2115 /**
2116  * intel_enable_pipe - enable a pipe, asserting requirements
2117  * @crtc: crtc responsible for the pipe
2118  *
2119  * Enable @crtc's pipe, making sure that various hardware specific requirements
2120  * are met, if applicable, e.g. PLL enabled, LVDS pairs enabled, etc.
2121  */
2122 static void intel_enable_pipe(struct intel_crtc *crtc)
2123 {
2124         struct drm_device *dev = crtc->base.dev;
2125         struct drm_i915_private *dev_priv = dev->dev_private;
2126         enum pipe pipe = crtc->pipe;
2127         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
2128                                                                       pipe);
2129         enum pipe pch_transcoder;
2130         int reg;
2131         u32 val;
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         /*
2193          * Make sure planes won't keep trying to pump pixels to us,
2194          * or we might hang the display.
2195          */
2196         assert_planes_disabled(dev_priv, pipe);
2197         assert_cursor_disabled(dev_priv, pipe);
2198         assert_sprites_disabled(dev_priv, pipe);
2199
2200         reg = PIPECONF(cpu_transcoder);
2201         val = I915_READ(reg);
2202         if ((val & PIPECONF_ENABLE) == 0)
2203                 return;
2204
2205         /*
2206          * Double wide has implications for planes
2207          * so best keep it disabled when not needed.
2208          */
2209         if (crtc->config->double_wide)
2210                 val &= ~PIPECONF_DOUBLE_WIDE;
2211
2212         /* Don't disable pipe or pipe PLLs if needed */
2213         if (!(pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) &&
2214             !(pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
2215                 val &= ~PIPECONF_ENABLE;
2216
2217         I915_WRITE(reg, val);
2218         if ((val & PIPECONF_ENABLE) == 0)
2219                 intel_wait_for_pipe_off(crtc);
2220 }
2221
2222 /**
2223  * intel_enable_primary_hw_plane - enable the primary plane on a given pipe
2224  * @plane:  plane to be enabled
2225  * @crtc: crtc for the plane
2226  *
2227  * Enable @plane on @crtc, making sure that the pipe is running first.
2228  */
2229 static void intel_enable_primary_hw_plane(struct drm_plane *plane,
2230                                           struct drm_crtc *crtc)
2231 {
2232         struct drm_device *dev = plane->dev;
2233         struct drm_i915_private *dev_priv = dev->dev_private;
2234         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2235
2236         /* If the pipe isn't enabled, we can't pump pixels and may hang */
2237         assert_pipe_enabled(dev_priv, intel_crtc->pipe);
2238         to_intel_plane_state(plane->state)->visible = true;
2239
2240         dev_priv->display.update_primary_plane(crtc, plane->fb,
2241                                                crtc->x, crtc->y);
2242 }
2243
2244 static bool need_vtd_wa(struct drm_device *dev)
2245 {
2246 #ifdef CONFIG_INTEL_IOMMU
2247         if (INTEL_INFO(dev)->gen >= 6 && intel_iommu_gfx_mapped)
2248                 return true;
2249 #endif
2250         return false;
2251 }
2252
2253 unsigned int
2254 intel_tile_height(struct drm_device *dev, uint32_t pixel_format,
2255                   uint64_t fb_format_modifier)
2256 {
2257         unsigned int tile_height;
2258         uint32_t pixel_bytes;
2259
2260         switch (fb_format_modifier) {
2261         case DRM_FORMAT_MOD_NONE:
2262                 tile_height = 1;
2263                 break;
2264         case I915_FORMAT_MOD_X_TILED:
2265                 tile_height = IS_GEN2(dev) ? 16 : 8;
2266                 break;
2267         case I915_FORMAT_MOD_Y_TILED:
2268                 tile_height = 32;
2269                 break;
2270         case I915_FORMAT_MOD_Yf_TILED:
2271                 pixel_bytes = drm_format_plane_cpp(pixel_format, 0);
2272                 switch (pixel_bytes) {
2273                 default:
2274                 case 1:
2275                         tile_height = 64;
2276                         break;
2277                 case 2:
2278                 case 4:
2279                         tile_height = 32;
2280                         break;
2281                 case 8:
2282                         tile_height = 16;
2283                         break;
2284                 case 16:
2285                         WARN_ONCE(1,
2286                                   "128-bit pixels are not supported for display!");
2287                         tile_height = 16;
2288                         break;
2289                 }
2290                 break;
2291         default:
2292                 MISSING_CASE(fb_format_modifier);
2293                 tile_height = 1;
2294                 break;
2295         }
2296
2297         return tile_height;
2298 }
2299
2300 unsigned int
2301 intel_fb_align_height(struct drm_device *dev, unsigned int height,
2302                       uint32_t pixel_format, uint64_t fb_format_modifier)
2303 {
2304         return ALIGN(height, intel_tile_height(dev, pixel_format,
2305                                                fb_format_modifier));
2306 }
2307
2308 static int
2309 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view, struct drm_framebuffer *fb,
2310                         const struct drm_plane_state *plane_state)
2311 {
2312         struct intel_rotation_info *info = &view->rotation_info;
2313
2314         *view = i915_ggtt_view_normal;
2315
2316         if (!plane_state)
2317                 return 0;
2318
2319         if (!intel_rotation_90_or_270(plane_state->rotation))
2320                 return 0;
2321
2322         *view = i915_ggtt_view_rotated;
2323
2324         info->height = fb->height;
2325         info->pixel_format = fb->pixel_format;
2326         info->pitch = fb->pitches[0];
2327         info->fb_modifier = fb->modifier[0];
2328
2329         return 0;
2330 }
2331
2332 static unsigned int intel_linear_alignment(struct drm_i915_private *dev_priv)
2333 {
2334         if (INTEL_INFO(dev_priv)->gen >= 9)
2335                 return 256 * 1024;
2336         else if (IS_BROADWATER(dev_priv) || IS_CRESTLINE(dev_priv) ||
2337                  IS_VALLEYVIEW(dev_priv))
2338                 return 128 * 1024;
2339         else if (INTEL_INFO(dev_priv)->gen >= 4)
2340                 return 4 * 1024;
2341         else
2342                 return 0;
2343 }
2344
2345 int
2346 intel_pin_and_fence_fb_obj(struct drm_plane *plane,
2347                            struct drm_framebuffer *fb,
2348                            const struct drm_plane_state *plane_state,
2349                            struct intel_engine_cs *pipelined)
2350 {
2351         struct drm_device *dev = fb->dev;
2352         struct drm_i915_private *dev_priv = dev->dev_private;
2353         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2354         struct i915_ggtt_view view;
2355         u32 alignment;
2356         int ret;
2357
2358         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2359
2360         switch (fb->modifier[0]) {
2361         case DRM_FORMAT_MOD_NONE:
2362                 alignment = intel_linear_alignment(dev_priv);
2363                 break;
2364         case I915_FORMAT_MOD_X_TILED:
2365                 if (INTEL_INFO(dev)->gen >= 9)
2366                         alignment = 256 * 1024;
2367                 else {
2368                         /* pin() will align the object as required by fence */
2369                         alignment = 0;
2370                 }
2371                 break;
2372         case I915_FORMAT_MOD_Y_TILED:
2373         case I915_FORMAT_MOD_Yf_TILED:
2374                 if (WARN_ONCE(INTEL_INFO(dev)->gen < 9,
2375                           "Y tiling bo slipped through, driver bug!\n"))
2376                         return -EINVAL;
2377                 alignment = 1 * 1024 * 1024;
2378                 break;
2379         default:
2380                 MISSING_CASE(fb->modifier[0]);
2381                 return -EINVAL;
2382         }
2383
2384         ret = intel_fill_fb_ggtt_view(&view, fb, plane_state);
2385         if (ret)
2386                 return ret;
2387
2388         /* Note that the w/a also requires 64 PTE of padding following the
2389          * bo. We currently fill all unused PTE with the shadow page and so
2390          * we should always have valid PTE following the scanout preventing
2391          * the VT-d warning.
2392          */
2393         if (need_vtd_wa(dev) && alignment < 256 * 1024)
2394                 alignment = 256 * 1024;
2395
2396         /*
2397          * Global gtt pte registers are special registers which actually forward
2398          * writes to a chunk of system memory. Which means that there is no risk
2399          * that the register values disappear as soon as we call
2400          * intel_runtime_pm_put(), so it is correct to wrap only the
2401          * pin/unpin/fence and not more.
2402          */
2403         intel_runtime_pm_get(dev_priv);
2404
2405         dev_priv->mm.interruptible = false;
2406         ret = i915_gem_object_pin_to_display_plane(obj, alignment, pipelined,
2407                                                    &view);
2408         if (ret)
2409                 goto err_interruptible;
2410
2411         /* Install a fence for tiled scan-out. Pre-i965 always needs a
2412          * fence, whereas 965+ only requires a fence if using
2413          * framebuffer compression.  For simplicity, we always install
2414          * a fence as the cost is not that onerous.
2415          */
2416         ret = i915_gem_object_get_fence(obj);
2417         if (ret)
2418                 goto err_unpin;
2419
2420         i915_gem_object_pin_fence(obj);
2421
2422         dev_priv->mm.interruptible = true;
2423         intel_runtime_pm_put(dev_priv);
2424         return 0;
2425
2426 err_unpin:
2427         i915_gem_object_unpin_from_display_plane(obj, &view);
2428 err_interruptible:
2429         dev_priv->mm.interruptible = true;
2430         intel_runtime_pm_put(dev_priv);
2431         return ret;
2432 }
2433
2434 static void intel_unpin_fb_obj(struct drm_framebuffer *fb,
2435                                const struct drm_plane_state *plane_state)
2436 {
2437         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2438         struct i915_ggtt_view view;
2439         int ret;
2440
2441         WARN_ON(!mutex_is_locked(&obj->base.dev->struct_mutex));
2442
2443         ret = intel_fill_fb_ggtt_view(&view, fb, plane_state);
2444         WARN_ONCE(ret, "Couldn't get view from plane state!");
2445
2446         i915_gem_object_unpin_fence(obj);
2447         i915_gem_object_unpin_from_display_plane(obj, &view);
2448 }
2449
2450 /* Computes the linear offset to the base tile and adjusts x, y. bytes per pixel
2451  * is assumed to be a power-of-two. */
2452 unsigned long intel_gen4_compute_page_offset(struct drm_i915_private *dev_priv,
2453                                              int *x, int *y,
2454                                              unsigned int tiling_mode,
2455                                              unsigned int cpp,
2456                                              unsigned int pitch)
2457 {
2458         if (tiling_mode != I915_TILING_NONE) {
2459                 unsigned int tile_rows, tiles;
2460
2461                 tile_rows = *y / 8;
2462                 *y %= 8;
2463
2464                 tiles = *x / (512/cpp);
2465                 *x %= 512/cpp;
2466
2467                 return tile_rows * pitch * 8 + tiles * 4096;
2468         } else {
2469                 unsigned int alignment = intel_linear_alignment(dev_priv) - 1;
2470                 unsigned int offset;
2471
2472                 offset = *y * pitch + *x * cpp;
2473                 *y = (offset & alignment) / pitch;
2474                 *x = ((offset & alignment) - *y * pitch) / cpp;
2475                 return offset & ~alignment;
2476         }
2477 }
2478
2479 static int i9xx_format_to_fourcc(int format)
2480 {
2481         switch (format) {
2482         case DISPPLANE_8BPP:
2483                 return DRM_FORMAT_C8;
2484         case DISPPLANE_BGRX555:
2485                 return DRM_FORMAT_XRGB1555;
2486         case DISPPLANE_BGRX565:
2487                 return DRM_FORMAT_RGB565;
2488         default:
2489         case DISPPLANE_BGRX888:
2490                 return DRM_FORMAT_XRGB8888;
2491         case DISPPLANE_RGBX888:
2492                 return DRM_FORMAT_XBGR8888;
2493         case DISPPLANE_BGRX101010:
2494                 return DRM_FORMAT_XRGB2101010;
2495         case DISPPLANE_RGBX101010:
2496                 return DRM_FORMAT_XBGR2101010;
2497         }
2498 }
2499
2500 static int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2501 {
2502         switch (format) {
2503         case PLANE_CTL_FORMAT_RGB_565:
2504                 return DRM_FORMAT_RGB565;
2505         default:
2506         case PLANE_CTL_FORMAT_XRGB_8888:
2507                 if (rgb_order) {
2508                         if (alpha)
2509                                 return DRM_FORMAT_ABGR8888;
2510                         else
2511                                 return DRM_FORMAT_XBGR8888;
2512                 } else {
2513                         if (alpha)
2514                                 return DRM_FORMAT_ARGB8888;
2515                         else
2516                                 return DRM_FORMAT_XRGB8888;
2517                 }
2518         case PLANE_CTL_FORMAT_XRGB_2101010:
2519                 if (rgb_order)
2520                         return DRM_FORMAT_XBGR2101010;
2521                 else
2522                         return DRM_FORMAT_XRGB2101010;
2523         }
2524 }
2525
2526 static bool
2527 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2528                               struct intel_initial_plane_config *plane_config)
2529 {
2530         struct drm_device *dev = crtc->base.dev;
2531         struct drm_i915_gem_object *obj = NULL;
2532         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2533         struct drm_framebuffer *fb = &plane_config->fb->base;
2534         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2535         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2536                                     PAGE_SIZE);
2537
2538         size_aligned -= base_aligned;
2539
2540         if (plane_config->size == 0)
2541                 return false;
2542
2543         obj = i915_gem_object_create_stolen_for_preallocated(dev,
2544                                                              base_aligned,
2545                                                              base_aligned,
2546                                                              size_aligned);
2547         if (!obj)
2548                 return false;
2549
2550         obj->tiling_mode = plane_config->tiling;
2551         if (obj->tiling_mode == I915_TILING_X)
2552                 obj->stride = fb->pitches[0];
2553
2554         mode_cmd.pixel_format = fb->pixel_format;
2555         mode_cmd.width = fb->width;
2556         mode_cmd.height = fb->height;
2557         mode_cmd.pitches[0] = fb->pitches[0];
2558         mode_cmd.modifier[0] = fb->modifier[0];
2559         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2560
2561         mutex_lock(&dev->struct_mutex);
2562         if (intel_framebuffer_init(dev, to_intel_framebuffer(fb),
2563                                    &mode_cmd, obj)) {
2564                 DRM_DEBUG_KMS("intel fb init failed\n");
2565                 goto out_unref_obj;
2566         }
2567         mutex_unlock(&dev->struct_mutex);
2568
2569         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2570         return true;
2571
2572 out_unref_obj:
2573         drm_gem_object_unreference(&obj->base);
2574         mutex_unlock(&dev->struct_mutex);
2575         return false;
2576 }
2577
2578 /* Update plane->state->fb to match plane->fb after driver-internal updates */
2579 static void
2580 update_state_fb(struct drm_plane *plane)
2581 {
2582         if (plane->fb == plane->state->fb)
2583                 return;
2584
2585         if (plane->state->fb)
2586                 drm_framebuffer_unreference(plane->state->fb);
2587         plane->state->fb = plane->fb;
2588         if (plane->state->fb)
2589                 drm_framebuffer_reference(plane->state->fb);
2590 }
2591
2592 static void
2593 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2594                              struct intel_initial_plane_config *plane_config)
2595 {
2596         struct drm_device *dev = intel_crtc->base.dev;
2597         struct drm_i915_private *dev_priv = dev->dev_private;
2598         struct drm_crtc *c;
2599         struct intel_crtc *i;
2600         struct drm_i915_gem_object *obj;
2601         struct drm_plane *primary = intel_crtc->base.primary;
2602         struct drm_framebuffer *fb;
2603
2604         if (!plane_config->fb)
2605                 return;
2606
2607         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2608                 fb = &plane_config->fb->base;
2609                 goto valid_fb;
2610         }
2611
2612         kfree(plane_config->fb);
2613
2614         /*
2615          * Failed to alloc the obj, check to see if we should share
2616          * an fb with another CRTC instead
2617          */
2618         for_each_crtc(dev, c) {
2619                 i = to_intel_crtc(c);
2620
2621                 if (c == &intel_crtc->base)
2622                         continue;
2623
2624                 if (!i->active)
2625                         continue;
2626
2627                 fb = c->primary->fb;
2628                 if (!fb)
2629                         continue;
2630
2631                 obj = intel_fb_obj(fb);
2632                 if (i915_gem_obj_ggtt_offset(obj) == plane_config->base) {
2633                         drm_framebuffer_reference(fb);
2634                         goto valid_fb;
2635                 }
2636         }
2637
2638         return;
2639
2640 valid_fb:
2641         obj = intel_fb_obj(fb);
2642         if (obj->tiling_mode != I915_TILING_NONE)
2643                 dev_priv->preserve_bios_swizzle = true;
2644
2645         primary->fb = fb;
2646         primary->crtc = primary->state->crtc = &intel_crtc->base;
2647         update_state_fb(primary);
2648         intel_crtc->base.state->plane_mask |= (1 << drm_plane_index(primary));
2649         obj->frontbuffer_bits |= INTEL_FRONTBUFFER_PRIMARY(intel_crtc->pipe);
2650 }
2651
2652 static void i9xx_update_primary_plane(struct drm_crtc *crtc,
2653                                       struct drm_framebuffer *fb,
2654                                       int x, int y)
2655 {
2656         struct drm_device *dev = crtc->dev;
2657         struct drm_i915_private *dev_priv = dev->dev_private;
2658         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2659         struct drm_plane *primary = crtc->primary;
2660         bool visible = to_intel_plane_state(primary->state)->visible;
2661         struct drm_i915_gem_object *obj;
2662         int plane = intel_crtc->plane;
2663         unsigned long linear_offset;
2664         u32 dspcntr;
2665         u32 reg = DSPCNTR(plane);
2666         int pixel_size;
2667
2668         if (!visible || !fb) {
2669                 I915_WRITE(reg, 0);
2670                 if (INTEL_INFO(dev)->gen >= 4)
2671                         I915_WRITE(DSPSURF(plane), 0);
2672                 else
2673                         I915_WRITE(DSPADDR(plane), 0);
2674                 POSTING_READ(reg);
2675                 return;
2676         }
2677
2678         obj = intel_fb_obj(fb);
2679         if (WARN_ON(obj == NULL))
2680                 return;
2681
2682         pixel_size = drm_format_plane_cpp(fb->pixel_format, 0);
2683
2684         dspcntr = DISPPLANE_GAMMA_ENABLE;
2685
2686         dspcntr |= DISPLAY_PLANE_ENABLE;
2687
2688         if (INTEL_INFO(dev)->gen < 4) {
2689                 if (intel_crtc->pipe == PIPE_B)
2690                         dspcntr |= DISPPLANE_SEL_PIPE_B;
2691
2692                 /* pipesrc and dspsize control the size that is scaled from,
2693                  * which should always be the user's requested size.
2694                  */
2695                 I915_WRITE(DSPSIZE(plane),
2696                            ((intel_crtc->config->pipe_src_h - 1) << 16) |
2697                            (intel_crtc->config->pipe_src_w - 1));
2698                 I915_WRITE(DSPPOS(plane), 0);
2699         } else if (IS_CHERRYVIEW(dev) && plane == PLANE_B) {
2700                 I915_WRITE(PRIMSIZE(plane),
2701                            ((intel_crtc->config->pipe_src_h - 1) << 16) |
2702                            (intel_crtc->config->pipe_src_w - 1));
2703                 I915_WRITE(PRIMPOS(plane), 0);
2704                 I915_WRITE(PRIMCNSTALPHA(plane), 0);
2705         }
2706
2707         switch (fb->pixel_format) {
2708         case DRM_FORMAT_C8:
2709                 dspcntr |= DISPPLANE_8BPP;
2710                 break;
2711         case DRM_FORMAT_XRGB1555:
2712                 dspcntr |= DISPPLANE_BGRX555;
2713                 break;
2714         case DRM_FORMAT_RGB565:
2715                 dspcntr |= DISPPLANE_BGRX565;
2716                 break;
2717         case DRM_FORMAT_XRGB8888:
2718                 dspcntr |= DISPPLANE_BGRX888;
2719                 break;
2720         case DRM_FORMAT_XBGR8888:
2721                 dspcntr |= DISPPLANE_RGBX888;
2722                 break;
2723         case DRM_FORMAT_XRGB2101010:
2724                 dspcntr |= DISPPLANE_BGRX101010;
2725                 break;
2726         case DRM_FORMAT_XBGR2101010:
2727                 dspcntr |= DISPPLANE_RGBX101010;
2728                 break;
2729         default:
2730                 BUG();
2731         }
2732
2733         if (INTEL_INFO(dev)->gen >= 4 &&
2734             obj->tiling_mode != I915_TILING_NONE)
2735                 dspcntr |= DISPPLANE_TILED;
2736
2737         if (IS_G4X(dev))
2738                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2739
2740         linear_offset = y * fb->pitches[0] + x * pixel_size;
2741
2742         if (INTEL_INFO(dev)->gen >= 4) {
2743                 intel_crtc->dspaddr_offset =
2744                         intel_gen4_compute_page_offset(dev_priv,
2745                                                        &x, &y, obj->tiling_mode,
2746                                                        pixel_size,
2747                                                        fb->pitches[0]);
2748                 linear_offset -= intel_crtc->dspaddr_offset;
2749         } else {
2750                 intel_crtc->dspaddr_offset = linear_offset;
2751         }
2752
2753         if (crtc->primary->state->rotation == BIT(DRM_ROTATE_180)) {
2754                 dspcntr |= DISPPLANE_ROTATE_180;
2755
2756                 x += (intel_crtc->config->pipe_src_w - 1);
2757                 y += (intel_crtc->config->pipe_src_h - 1);
2758
2759                 /* Finding the last pixel of the last line of the display
2760                 data and adding to linear_offset*/
2761                 linear_offset +=
2762                         (intel_crtc->config->pipe_src_h - 1) * fb->pitches[0] +
2763                         (intel_crtc->config->pipe_src_w - 1) * pixel_size;
2764         }
2765
2766         I915_WRITE(reg, dspcntr);
2767
2768         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2769         if (INTEL_INFO(dev)->gen >= 4) {
2770                 I915_WRITE(DSPSURF(plane),
2771                            i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2772                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2773                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2774         } else
2775                 I915_WRITE(DSPADDR(plane), i915_gem_obj_ggtt_offset(obj) + linear_offset);
2776         POSTING_READ(reg);
2777 }
2778
2779 static void ironlake_update_primary_plane(struct drm_crtc *crtc,
2780                                           struct drm_framebuffer *fb,
2781                                           int x, int y)
2782 {
2783         struct drm_device *dev = crtc->dev;
2784         struct drm_i915_private *dev_priv = dev->dev_private;
2785         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2786         struct drm_plane *primary = crtc->primary;
2787         bool visible = to_intel_plane_state(primary->state)->visible;
2788         struct drm_i915_gem_object *obj;
2789         int plane = intel_crtc->plane;
2790         unsigned long linear_offset;
2791         u32 dspcntr;
2792         u32 reg = DSPCNTR(plane);
2793         int pixel_size;
2794
2795         if (!visible || !fb) {
2796                 I915_WRITE(reg, 0);
2797                 I915_WRITE(DSPSURF(plane), 0);
2798                 POSTING_READ(reg);
2799                 return;
2800         }
2801
2802         obj = intel_fb_obj(fb);
2803         if (WARN_ON(obj == NULL))
2804                 return;
2805
2806         pixel_size = drm_format_plane_cpp(fb->pixel_format, 0);
2807
2808         dspcntr = DISPPLANE_GAMMA_ENABLE;
2809
2810         dspcntr |= DISPLAY_PLANE_ENABLE;
2811
2812         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
2813                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
2814
2815         switch (fb->pixel_format) {
2816         case DRM_FORMAT_C8:
2817                 dspcntr |= DISPPLANE_8BPP;
2818                 break;
2819         case DRM_FORMAT_RGB565:
2820                 dspcntr |= DISPPLANE_BGRX565;
2821                 break;
2822         case DRM_FORMAT_XRGB8888:
2823                 dspcntr |= DISPPLANE_BGRX888;
2824                 break;
2825         case DRM_FORMAT_XBGR8888:
2826                 dspcntr |= DISPPLANE_RGBX888;
2827                 break;
2828         case DRM_FORMAT_XRGB2101010:
2829                 dspcntr |= DISPPLANE_BGRX101010;
2830                 break;
2831         case DRM_FORMAT_XBGR2101010:
2832                 dspcntr |= DISPPLANE_RGBX101010;
2833                 break;
2834         default:
2835                 BUG();
2836         }
2837
2838         if (obj->tiling_mode != I915_TILING_NONE)
2839                 dspcntr |= DISPPLANE_TILED;
2840
2841         if (!IS_HASWELL(dev) && !IS_BROADWELL(dev))
2842                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2843
2844         linear_offset = y * fb->pitches[0] + x * pixel_size;
2845         intel_crtc->dspaddr_offset =
2846                 intel_gen4_compute_page_offset(dev_priv,
2847                                                &x, &y, obj->tiling_mode,
2848                                                pixel_size,
2849                                                fb->pitches[0]);
2850         linear_offset -= intel_crtc->dspaddr_offset;
2851         if (crtc->primary->state->rotation == BIT(DRM_ROTATE_180)) {
2852                 dspcntr |= DISPPLANE_ROTATE_180;
2853
2854                 if (!IS_HASWELL(dev) && !IS_BROADWELL(dev)) {
2855                         x += (intel_crtc->config->pipe_src_w - 1);
2856                         y += (intel_crtc->config->pipe_src_h - 1);
2857
2858                         /* Finding the last pixel of the last line of the display
2859                         data and adding to linear_offset*/
2860                         linear_offset +=
2861                                 (intel_crtc->config->pipe_src_h - 1) * fb->pitches[0] +
2862                                 (intel_crtc->config->pipe_src_w - 1) * pixel_size;
2863                 }
2864         }
2865
2866         I915_WRITE(reg, dspcntr);
2867
2868         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2869         I915_WRITE(DSPSURF(plane),
2870                    i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2871         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
2872                 I915_WRITE(DSPOFFSET(plane), (y << 16) | x);
2873         } else {
2874                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2875                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2876         }
2877         POSTING_READ(reg);
2878 }
2879
2880 u32 intel_fb_stride_alignment(struct drm_device *dev, uint64_t fb_modifier,
2881                               uint32_t pixel_format)
2882 {
2883         u32 bits_per_pixel = drm_format_plane_cpp(pixel_format, 0) * 8;
2884
2885         /*
2886          * The stride is either expressed as a multiple of 64 bytes
2887          * chunks for linear buffers or in number of tiles for tiled
2888          * buffers.
2889          */
2890         switch (fb_modifier) {
2891         case DRM_FORMAT_MOD_NONE:
2892                 return 64;
2893         case I915_FORMAT_MOD_X_TILED:
2894                 if (INTEL_INFO(dev)->gen == 2)
2895                         return 128;
2896                 return 512;
2897         case I915_FORMAT_MOD_Y_TILED:
2898                 /* No need to check for old gens and Y tiling since this is
2899                  * about the display engine and those will be blocked before
2900                  * we get here.
2901                  */
2902                 return 128;
2903         case I915_FORMAT_MOD_Yf_TILED:
2904                 if (bits_per_pixel == 8)
2905                         return 64;
2906                 else
2907                         return 128;
2908         default:
2909                 MISSING_CASE(fb_modifier);
2910                 return 64;
2911         }
2912 }
2913
2914 unsigned long intel_plane_obj_offset(struct intel_plane *intel_plane,
2915                                      struct drm_i915_gem_object *obj)
2916 {
2917         const struct i915_ggtt_view *view = &i915_ggtt_view_normal;
2918
2919         if (intel_rotation_90_or_270(intel_plane->base.state->rotation))
2920                 view = &i915_ggtt_view_rotated;
2921
2922         return i915_gem_obj_ggtt_offset_view(obj, view);
2923 }
2924
2925 /*
2926  * This function detaches (aka. unbinds) unused scalers in hardware
2927  */
2928 void skl_detach_scalers(struct intel_crtc *intel_crtc)
2929 {
2930         struct drm_device *dev;
2931         struct drm_i915_private *dev_priv;
2932         struct intel_crtc_scaler_state *scaler_state;
2933         int i;
2934
2935         if (!intel_crtc || !intel_crtc->config)
2936                 return;
2937
2938         dev = intel_crtc->base.dev;
2939         dev_priv = dev->dev_private;
2940         scaler_state = &intel_crtc->config->scaler_state;
2941
2942         /* loop through and disable scalers that aren't in use */
2943         for (i = 0; i < intel_crtc->num_scalers; i++) {
2944                 if (!scaler_state->scalers[i].in_use) {
2945                         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, i), 0);
2946                         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, i), 0);
2947                         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, i), 0);
2948                         DRM_DEBUG_KMS("CRTC:%d Disabled scaler id %u.%u\n",
2949                                 intel_crtc->base.base.id, intel_crtc->pipe, i);
2950                 }
2951         }
2952 }
2953
2954 u32 skl_plane_ctl_format(uint32_t pixel_format)
2955 {
2956         switch (pixel_format) {
2957         case DRM_FORMAT_C8:
2958                 return PLANE_CTL_FORMAT_INDEXED;
2959         case DRM_FORMAT_RGB565:
2960                 return PLANE_CTL_FORMAT_RGB_565;
2961         case DRM_FORMAT_XBGR8888:
2962                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
2963         case DRM_FORMAT_XRGB8888:
2964                 return PLANE_CTL_FORMAT_XRGB_8888;
2965         /*
2966          * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
2967          * to be already pre-multiplied. We need to add a knob (or a different
2968          * DRM_FORMAT) for user-space to configure that.
2969          */
2970         case DRM_FORMAT_ABGR8888:
2971                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX |
2972                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
2973         case DRM_FORMAT_ARGB8888:
2974                 return PLANE_CTL_FORMAT_XRGB_8888 |
2975                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
2976         case DRM_FORMAT_XRGB2101010:
2977                 return PLANE_CTL_FORMAT_XRGB_2101010;
2978         case DRM_FORMAT_XBGR2101010:
2979                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
2980         case DRM_FORMAT_YUYV:
2981                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
2982         case DRM_FORMAT_YVYU:
2983                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
2984         case DRM_FORMAT_UYVY:
2985                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
2986         case DRM_FORMAT_VYUY:
2987                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
2988         default:
2989                 MISSING_CASE(pixel_format);
2990         }
2991
2992         return 0;
2993 }
2994
2995 u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
2996 {
2997         switch (fb_modifier) {
2998         case DRM_FORMAT_MOD_NONE:
2999                 break;
3000         case I915_FORMAT_MOD_X_TILED:
3001                 return PLANE_CTL_TILED_X;
3002         case I915_FORMAT_MOD_Y_TILED:
3003                 return PLANE_CTL_TILED_Y;
3004         case I915_FORMAT_MOD_Yf_TILED:
3005                 return PLANE_CTL_TILED_YF;
3006         default:
3007                 MISSING_CASE(fb_modifier);
3008         }
3009
3010         return 0;
3011 }
3012
3013 u32 skl_plane_ctl_rotation(unsigned int rotation)
3014 {
3015         switch (rotation) {
3016         case BIT(DRM_ROTATE_0):
3017                 break;
3018         /*
3019          * DRM_ROTATE_ is counter clockwise to stay compatible with Xrandr
3020          * while i915 HW rotation is clockwise, thats why this swapping.
3021          */
3022         case BIT(DRM_ROTATE_90):
3023                 return PLANE_CTL_ROTATE_270;
3024         case BIT(DRM_ROTATE_180):
3025                 return PLANE_CTL_ROTATE_180;
3026         case BIT(DRM_ROTATE_270):
3027                 return PLANE_CTL_ROTATE_90;
3028         default:
3029                 MISSING_CASE(rotation);
3030         }
3031
3032         return 0;
3033 }
3034
3035 static void skylake_update_primary_plane(struct drm_crtc *crtc,
3036                                          struct drm_framebuffer *fb,
3037                                          int x, int y)
3038 {
3039         struct drm_device *dev = crtc->dev;
3040         struct drm_i915_private *dev_priv = dev->dev_private;
3041         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3042         struct drm_plane *plane = crtc->primary;
3043         bool visible = to_intel_plane_state(plane->state)->visible;
3044         struct drm_i915_gem_object *obj;
3045         int pipe = intel_crtc->pipe;
3046         u32 plane_ctl, stride_div, stride;
3047         u32 tile_height, plane_offset, plane_size;
3048         unsigned int rotation;
3049         int x_offset, y_offset;
3050         unsigned long surf_addr;
3051         struct intel_crtc_state *crtc_state = intel_crtc->config;
3052         struct intel_plane_state *plane_state;
3053         int src_x = 0, src_y = 0, src_w = 0, src_h = 0;
3054         int dst_x = 0, dst_y = 0, dst_w = 0, dst_h = 0;
3055         int scaler_id = -1;
3056
3057         plane_state = to_intel_plane_state(plane->state);
3058
3059         if (!visible || !fb) {
3060                 I915_WRITE(PLANE_CTL(pipe, 0), 0);
3061                 I915_WRITE(PLANE_SURF(pipe, 0), 0);
3062                 POSTING_READ(PLANE_CTL(pipe, 0));
3063                 return;
3064         }
3065
3066         plane_ctl = PLANE_CTL_ENABLE |
3067                     PLANE_CTL_PIPE_GAMMA_ENABLE |
3068                     PLANE_CTL_PIPE_CSC_ENABLE;
3069
3070         plane_ctl |= skl_plane_ctl_format(fb->pixel_format);
3071         plane_ctl |= skl_plane_ctl_tiling(fb->modifier[0]);
3072         plane_ctl |= PLANE_CTL_PLANE_GAMMA_DISABLE;
3073
3074         rotation = plane->state->rotation;
3075         plane_ctl |= skl_plane_ctl_rotation(rotation);
3076
3077         obj = intel_fb_obj(fb);
3078         stride_div = intel_fb_stride_alignment(dev, fb->modifier[0],
3079                                                fb->pixel_format);
3080         surf_addr = intel_plane_obj_offset(to_intel_plane(plane), obj);
3081
3082         /*
3083          * FIXME: intel_plane_state->src, dst aren't set when transitional
3084          * update_plane helpers are called from legacy paths.
3085          * Once full atomic crtc is available, below check can be avoided.
3086          */
3087         if (drm_rect_width(&plane_state->src)) {
3088                 scaler_id = plane_state->scaler_id;
3089                 src_x = plane_state->src.x1 >> 16;
3090                 src_y = plane_state->src.y1 >> 16;
3091                 src_w = drm_rect_width(&plane_state->src) >> 16;
3092                 src_h = drm_rect_height(&plane_state->src) >> 16;
3093                 dst_x = plane_state->dst.x1;
3094                 dst_y = plane_state->dst.y1;
3095                 dst_w = drm_rect_width(&plane_state->dst);
3096                 dst_h = drm_rect_height(&plane_state->dst);
3097
3098                 WARN_ON(x != src_x || y != src_y);
3099         } else {
3100                 src_w = intel_crtc->config->pipe_src_w;
3101                 src_h = intel_crtc->config->pipe_src_h;
3102         }
3103
3104         if (intel_rotation_90_or_270(rotation)) {
3105                 /* stride = Surface height in tiles */
3106                 tile_height = intel_tile_height(dev, fb->pixel_format,
3107                                                 fb->modifier[0]);
3108                 stride = DIV_ROUND_UP(fb->height, tile_height);
3109                 x_offset = stride * tile_height - y - src_h;
3110                 y_offset = x;
3111                 plane_size = (src_w - 1) << 16 | (src_h - 1);
3112         } else {
3113                 stride = fb->pitches[0] / stride_div;
3114                 x_offset = x;
3115                 y_offset = y;
3116                 plane_size = (src_h - 1) << 16 | (src_w - 1);
3117         }
3118         plane_offset = y_offset << 16 | x_offset;
3119
3120         I915_WRITE(PLANE_CTL(pipe, 0), plane_ctl);
3121         I915_WRITE(PLANE_OFFSET(pipe, 0), plane_offset);
3122         I915_WRITE(PLANE_SIZE(pipe, 0), plane_size);
3123         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
3124
3125         if (scaler_id >= 0) {
3126                 uint32_t ps_ctrl = 0;
3127
3128                 WARN_ON(!dst_w || !dst_h);
3129                 ps_ctrl = PS_SCALER_EN | PS_PLANE_SEL(0) |
3130                         crtc_state->scaler_state.scalers[scaler_id].mode;
3131                 I915_WRITE(SKL_PS_CTRL(pipe, scaler_id), ps_ctrl);
3132                 I915_WRITE(SKL_PS_PWR_GATE(pipe, scaler_id), 0);
3133                 I915_WRITE(SKL_PS_WIN_POS(pipe, scaler_id), (dst_x << 16) | dst_y);
3134                 I915_WRITE(SKL_PS_WIN_SZ(pipe, scaler_id), (dst_w << 16) | dst_h);
3135                 I915_WRITE(PLANE_POS(pipe, 0), 0);
3136         } else {
3137                 I915_WRITE(PLANE_POS(pipe, 0), (dst_y << 16) | dst_x);
3138         }
3139
3140         I915_WRITE(PLANE_SURF(pipe, 0), surf_addr);
3141
3142         POSTING_READ(PLANE_SURF(pipe, 0));
3143 }
3144
3145 /* Assume fb object is pinned & idle & fenced and just update base pointers */
3146 static int
3147 intel_pipe_set_base_atomic(struct drm_crtc *crtc, struct drm_framebuffer *fb,
3148                            int x, int y, enum mode_set_atomic state)
3149 {
3150         struct drm_device *dev = crtc->dev;
3151         struct drm_i915_private *dev_priv = dev->dev_private;
3152
3153         if (dev_priv->display.disable_fbc)
3154                 dev_priv->display.disable_fbc(dev);
3155
3156         dev_priv->display.update_primary_plane(crtc, fb, x, y);
3157
3158         return 0;
3159 }
3160
3161 static void intel_complete_page_flips(struct drm_device *dev)
3162 {
3163         struct drm_crtc *crtc;
3164
3165         for_each_crtc(dev, crtc) {
3166                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3167                 enum plane plane = intel_crtc->plane;
3168
3169                 intel_prepare_page_flip(dev, plane);
3170                 intel_finish_page_flip_plane(dev, plane);
3171         }
3172 }
3173
3174 static void intel_update_primary_planes(struct drm_device *dev)
3175 {
3176         struct drm_i915_private *dev_priv = dev->dev_private;
3177         struct drm_crtc *crtc;
3178
3179         for_each_crtc(dev, crtc) {
3180                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3181
3182                 drm_modeset_lock(&crtc->mutex, NULL);
3183                 /*
3184                  * FIXME: Once we have proper support for primary planes (and
3185                  * disabling them without disabling the entire crtc) allow again
3186                  * a NULL crtc->primary->fb.
3187                  */
3188                 if (intel_crtc->active && crtc->primary->fb)
3189                         dev_priv->display.update_primary_plane(crtc,
3190                                                                crtc->primary->fb,
3191                                                                crtc->x,
3192                                                                crtc->y);
3193                 drm_modeset_unlock(&crtc->mutex);
3194         }
3195 }
3196
3197 void intel_prepare_reset(struct drm_device *dev)
3198 {
3199         /* no reset support for gen2 */
3200         if (IS_GEN2(dev))
3201                 return;
3202
3203         /* reset doesn't touch the display */
3204         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
3205                 return;
3206
3207         drm_modeset_lock_all(dev);
3208         /*
3209          * Disabling the crtcs gracefully seems nicer. Also the
3210          * g33 docs say we should at least disable all the planes.
3211          */
3212         intel_display_suspend(dev);
3213 }
3214
3215 void intel_finish_reset(struct drm_device *dev)
3216 {
3217         struct drm_i915_private *dev_priv = to_i915(dev);
3218
3219         /*
3220          * Flips in the rings will be nuked by the reset,
3221          * so complete all pending flips so that user space
3222          * will get its events and not get stuck.
3223          */
3224         intel_complete_page_flips(dev);
3225
3226         /* no reset support for gen2 */
3227         if (IS_GEN2(dev))
3228                 return;
3229
3230         /* reset doesn't touch the display */
3231         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev)) {
3232                 /*
3233                  * Flips in the rings have been nuked by the reset,
3234                  * so update the base address of all primary
3235                  * planes to the the last fb to make sure we're
3236                  * showing the correct fb after a reset.
3237                  */
3238                 intel_update_primary_planes(dev);
3239                 return;
3240         }
3241
3242         /*
3243          * The display has been reset as well,
3244          * so need a full re-initialization.
3245          */
3246         intel_runtime_pm_disable_interrupts(dev_priv);
3247         intel_runtime_pm_enable_interrupts(dev_priv);
3248
3249         intel_modeset_init_hw(dev);
3250
3251         spin_lock_irq(&dev_priv->irq_lock);
3252         if (dev_priv->display.hpd_irq_setup)
3253                 dev_priv->display.hpd_irq_setup(dev);
3254         spin_unlock_irq(&dev_priv->irq_lock);
3255
3256         intel_modeset_setup_hw_state(dev, true);
3257
3258         intel_hpd_init(dev_priv);
3259
3260         drm_modeset_unlock_all(dev);
3261 }
3262
3263 static void
3264 intel_finish_fb(struct drm_framebuffer *old_fb)
3265 {
3266         struct drm_i915_gem_object *obj = intel_fb_obj(old_fb);
3267         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
3268         bool was_interruptible = dev_priv->mm.interruptible;
3269         int ret;
3270
3271         /* Big Hammer, we also need to ensure that any pending
3272          * MI_WAIT_FOR_EVENT inside a user batch buffer on the
3273          * current scanout is retired before unpinning the old
3274          * framebuffer. Note that we rely on userspace rendering
3275          * into the buffer attached to the pipe they are waiting
3276          * on. If not, userspace generates a GPU hang with IPEHR
3277          * point to the MI_WAIT_FOR_EVENT.
3278          *
3279          * This should only fail upon a hung GPU, in which case we
3280          * can safely continue.
3281          */
3282         dev_priv->mm.interruptible = false;
3283         ret = i915_gem_object_wait_rendering(obj, true);
3284         dev_priv->mm.interruptible = was_interruptible;
3285
3286         WARN_ON(ret);
3287 }
3288
3289 static bool intel_crtc_has_pending_flip(struct drm_crtc *crtc)
3290 {
3291         struct drm_device *dev = crtc->dev;
3292         struct drm_i915_private *dev_priv = dev->dev_private;
3293         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3294         bool pending;
3295
3296         if (i915_reset_in_progress(&dev_priv->gpu_error) ||
3297             intel_crtc->reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
3298                 return false;
3299
3300         spin_lock_irq(&dev->event_lock);
3301         pending = to_intel_crtc(crtc)->unpin_work != NULL;
3302         spin_unlock_irq(&dev->event_lock);
3303
3304         return pending;
3305 }
3306
3307 static void intel_update_pipe_size(struct intel_crtc *crtc)
3308 {
3309         struct drm_device *dev = crtc->base.dev;
3310         struct drm_i915_private *dev_priv = dev->dev_private;
3311         const struct drm_display_mode *adjusted_mode;
3312
3313         if (!i915.fastboot)
3314                 return;
3315
3316         /*
3317          * Update pipe size and adjust fitter if needed: the reason for this is
3318          * that in compute_mode_changes we check the native mode (not the pfit
3319          * mode) to see if we can flip rather than do a full mode set. In the
3320          * fastboot case, we'll flip, but if we don't update the pipesrc and
3321          * pfit state, we'll end up with a big fb scanned out into the wrong
3322          * sized surface.
3323          *
3324          * To fix this properly, we need to hoist the checks up into
3325          * compute_mode_changes (or above), check the actual pfit state and
3326          * whether the platform allows pfit disable with pipe active, and only
3327          * then update the pipesrc and pfit state, even on the flip path.
3328          */
3329
3330         adjusted_mode = &crtc->config->base.adjusted_mode;
3331
3332         I915_WRITE(PIPESRC(crtc->pipe),
3333                    ((adjusted_mode->crtc_hdisplay - 1) << 16) |
3334                    (adjusted_mode->crtc_vdisplay - 1));
3335         if (!crtc->config->pch_pfit.enabled &&
3336             (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS) ||
3337              intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP))) {
3338                 I915_WRITE(PF_CTL(crtc->pipe), 0);
3339                 I915_WRITE(PF_WIN_POS(crtc->pipe), 0);
3340                 I915_WRITE(PF_WIN_SZ(crtc->pipe), 0);
3341         }
3342         crtc->config->pipe_src_w = adjusted_mode->crtc_hdisplay;
3343         crtc->config->pipe_src_h = adjusted_mode->crtc_vdisplay;
3344 }
3345
3346 static void intel_fdi_normal_train(struct drm_crtc *crtc)
3347 {
3348         struct drm_device *dev = crtc->dev;
3349         struct drm_i915_private *dev_priv = dev->dev_private;
3350         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3351         int pipe = intel_crtc->pipe;
3352         u32 reg, temp;
3353
3354         /* enable normal train */
3355         reg = FDI_TX_CTL(pipe);
3356         temp = I915_READ(reg);
3357         if (IS_IVYBRIDGE(dev)) {
3358                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3359                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3360         } else {
3361                 temp &= ~FDI_LINK_TRAIN_NONE;
3362                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3363         }
3364         I915_WRITE(reg, temp);
3365
3366         reg = FDI_RX_CTL(pipe);
3367         temp = I915_READ(reg);
3368         if (HAS_PCH_CPT(dev)) {
3369                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3370                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3371         } else {
3372                 temp &= ~FDI_LINK_TRAIN_NONE;
3373                 temp |= FDI_LINK_TRAIN_NONE;
3374         }
3375         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3376
3377         /* wait one idle pattern time */
3378         POSTING_READ(reg);
3379         udelay(1000);
3380
3381         /* IVB wants error correction enabled */
3382         if (IS_IVYBRIDGE(dev))
3383                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3384                            FDI_FE_ERRC_ENABLE);
3385 }
3386
3387 /* The FDI link training functions for ILK/Ibexpeak. */
3388 static void ironlake_fdi_link_train(struct drm_crtc *crtc)
3389 {
3390         struct drm_device *dev = crtc->dev;
3391         struct drm_i915_private *dev_priv = dev->dev_private;
3392         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3393         int pipe = intel_crtc->pipe;
3394         u32 reg, temp, tries;
3395
3396         /* FDI needs bits from pipe first */
3397         assert_pipe_enabled(dev_priv, pipe);
3398
3399         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3400            for train result */
3401         reg = FDI_RX_IMR(pipe);
3402         temp = I915_READ(reg);
3403         temp &= ~FDI_RX_SYMBOL_LOCK;
3404         temp &= ~FDI_RX_BIT_LOCK;
3405         I915_WRITE(reg, temp);
3406         I915_READ(reg);
3407         udelay(150);
3408
3409         /* enable CPU FDI TX and PCH FDI RX */
3410         reg = FDI_TX_CTL(pipe);
3411         temp = I915_READ(reg);
3412         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3413         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3414         temp &= ~FDI_LINK_TRAIN_NONE;
3415         temp |= FDI_LINK_TRAIN_PATTERN_1;
3416         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3417
3418         reg = FDI_RX_CTL(pipe);
3419         temp = I915_READ(reg);
3420         temp &= ~FDI_LINK_TRAIN_NONE;
3421         temp |= FDI_LINK_TRAIN_PATTERN_1;
3422         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3423
3424         POSTING_READ(reg);
3425         udelay(150);
3426
3427         /* Ironlake workaround, enable clock pointer after FDI enable*/
3428         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3429         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3430                    FDI_RX_PHASE_SYNC_POINTER_EN);
3431
3432         reg = FDI_RX_IIR(pipe);
3433         for (tries = 0; tries < 5; tries++) {
3434                 temp = I915_READ(reg);
3435                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3436
3437                 if ((temp & FDI_RX_BIT_LOCK)) {
3438                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3439                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3440                         break;
3441                 }
3442         }
3443         if (tries == 5)
3444                 DRM_ERROR("FDI train 1 fail!\n");
3445
3446         /* Train 2 */
3447         reg = FDI_TX_CTL(pipe);
3448         temp = I915_READ(reg);
3449         temp &= ~FDI_LINK_TRAIN_NONE;
3450         temp |= FDI_LINK_TRAIN_PATTERN_2;
3451         I915_WRITE(reg, temp);
3452
3453         reg = FDI_RX_CTL(pipe);
3454         temp = I915_READ(reg);
3455         temp &= ~FDI_LINK_TRAIN_NONE;
3456         temp |= FDI_LINK_TRAIN_PATTERN_2;
3457         I915_WRITE(reg, temp);
3458
3459         POSTING_READ(reg);
3460         udelay(150);
3461
3462         reg = FDI_RX_IIR(pipe);
3463         for (tries = 0; tries < 5; tries++) {
3464                 temp = I915_READ(reg);
3465                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3466
3467                 if (temp & FDI_RX_SYMBOL_LOCK) {
3468                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3469                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3470                         break;
3471                 }
3472         }
3473         if (tries == 5)
3474                 DRM_ERROR("FDI train 2 fail!\n");
3475
3476         DRM_DEBUG_KMS("FDI train done\n");
3477
3478 }
3479
3480 static const int snb_b_fdi_train_param[] = {
3481         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3482         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3483         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3484         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3485 };
3486
3487 /* The FDI link training functions for SNB/Cougarpoint. */
3488 static void gen6_fdi_link_train(struct drm_crtc *crtc)
3489 {
3490         struct drm_device *dev = crtc->dev;
3491         struct drm_i915_private *dev_priv = dev->dev_private;
3492         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3493         int pipe = intel_crtc->pipe;
3494         u32 reg, temp, i, retry;
3495
3496         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3497            for train result */
3498         reg = FDI_RX_IMR(pipe);
3499         temp = I915_READ(reg);
3500         temp &= ~FDI_RX_SYMBOL_LOCK;
3501         temp &= ~FDI_RX_BIT_LOCK;
3502         I915_WRITE(reg, temp);
3503
3504         POSTING_READ(reg);
3505         udelay(150);
3506
3507         /* enable CPU FDI TX and PCH FDI RX */
3508         reg = FDI_TX_CTL(pipe);
3509         temp = I915_READ(reg);
3510         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3511         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3512         temp &= ~FDI_LINK_TRAIN_NONE;
3513         temp |= FDI_LINK_TRAIN_PATTERN_1;
3514         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3515         /* SNB-B */
3516         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3517         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3518
3519         I915_WRITE(FDI_RX_MISC(pipe),
3520                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3521
3522         reg = FDI_RX_CTL(pipe);
3523         temp = I915_READ(reg);
3524         if (HAS_PCH_CPT(dev)) {
3525                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3526                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3527         } else {
3528                 temp &= ~FDI_LINK_TRAIN_NONE;
3529                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3530         }
3531         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3532
3533         POSTING_READ(reg);
3534         udelay(150);
3535
3536         for (i = 0; i < 4; i++) {
3537                 reg = FDI_TX_CTL(pipe);
3538                 temp = I915_READ(reg);
3539                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3540                 temp |= snb_b_fdi_train_param[i];
3541                 I915_WRITE(reg, temp);
3542
3543                 POSTING_READ(reg);
3544                 udelay(500);
3545
3546                 for (retry = 0; retry < 5; retry++) {
3547                         reg = FDI_RX_IIR(pipe);
3548                         temp = I915_READ(reg);
3549                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3550                         if (temp & FDI_RX_BIT_LOCK) {
3551                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3552                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
3553                                 break;
3554                         }
3555                         udelay(50);
3556                 }
3557                 if (retry < 5)
3558                         break;
3559         }
3560         if (i == 4)
3561                 DRM_ERROR("FDI train 1 fail!\n");
3562
3563         /* Train 2 */
3564         reg = FDI_TX_CTL(pipe);
3565         temp = I915_READ(reg);
3566         temp &= ~FDI_LINK_TRAIN_NONE;
3567         temp |= FDI_LINK_TRAIN_PATTERN_2;
3568         if (IS_GEN6(dev)) {
3569                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3570                 /* SNB-B */
3571                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3572         }
3573         I915_WRITE(reg, temp);
3574
3575         reg = FDI_RX_CTL(pipe);
3576         temp = I915_READ(reg);
3577         if (HAS_PCH_CPT(dev)) {
3578                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3579                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3580         } else {
3581                 temp &= ~FDI_LINK_TRAIN_NONE;
3582                 temp |= FDI_LINK_TRAIN_PATTERN_2;
3583         }
3584         I915_WRITE(reg, temp);
3585
3586         POSTING_READ(reg);
3587         udelay(150);
3588
3589         for (i = 0; i < 4; i++) {
3590                 reg = FDI_TX_CTL(pipe);
3591                 temp = I915_READ(reg);
3592                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3593                 temp |= snb_b_fdi_train_param[i];
3594                 I915_WRITE(reg, temp);
3595
3596                 POSTING_READ(reg);
3597                 udelay(500);
3598
3599                 for (retry = 0; retry < 5; retry++) {
3600                         reg = FDI_RX_IIR(pipe);
3601                         temp = I915_READ(reg);
3602                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3603                         if (temp & FDI_RX_SYMBOL_LOCK) {
3604                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3605                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
3606                                 break;
3607                         }
3608                         udelay(50);
3609                 }
3610                 if (retry < 5)
3611                         break;
3612         }
3613         if (i == 4)
3614                 DRM_ERROR("FDI train 2 fail!\n");
3615
3616         DRM_DEBUG_KMS("FDI train done.\n");
3617 }
3618
3619 /* Manual link training for Ivy Bridge A0 parts */
3620 static void ivb_manual_fdi_link_train(struct drm_crtc *crtc)
3621 {
3622         struct drm_device *dev = crtc->dev;
3623         struct drm_i915_private *dev_priv = dev->dev_private;
3624         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3625         int pipe = intel_crtc->pipe;
3626         u32 reg, temp, i, j;
3627
3628         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3629            for train result */
3630         reg = FDI_RX_IMR(pipe);
3631         temp = I915_READ(reg);
3632         temp &= ~FDI_RX_SYMBOL_LOCK;
3633         temp &= ~FDI_RX_BIT_LOCK;
3634         I915_WRITE(reg, temp);
3635
3636         POSTING_READ(reg);
3637         udelay(150);
3638
3639         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
3640                       I915_READ(FDI_RX_IIR(pipe)));
3641
3642         /* Try each vswing and preemphasis setting twice before moving on */
3643         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
3644                 /* disable first in case we need to retry */
3645                 reg = FDI_TX_CTL(pipe);
3646                 temp = I915_READ(reg);
3647                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
3648                 temp &= ~FDI_TX_ENABLE;
3649                 I915_WRITE(reg, temp);
3650
3651                 reg = FDI_RX_CTL(pipe);
3652                 temp = I915_READ(reg);
3653                 temp &= ~FDI_LINK_TRAIN_AUTO;
3654                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3655                 temp &= ~FDI_RX_ENABLE;
3656                 I915_WRITE(reg, temp);
3657
3658                 /* enable CPU FDI TX and PCH FDI RX */
3659                 reg = FDI_TX_CTL(pipe);
3660                 temp = I915_READ(reg);
3661                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
3662                 temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3663                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
3664                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3665                 temp |= snb_b_fdi_train_param[j/2];
3666                 temp |= FDI_COMPOSITE_SYNC;
3667                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
3668
3669                 I915_WRITE(FDI_RX_MISC(pipe),
3670                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3671
3672                 reg = FDI_RX_CTL(pipe);
3673                 temp = I915_READ(reg);
3674                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3675                 temp |= FDI_COMPOSITE_SYNC;
3676                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
3677
3678                 POSTING_READ(reg);
3679                 udelay(1); /* should be 0.5us */
3680
3681                 for (i = 0; i < 4; i++) {
3682                         reg = FDI_RX_IIR(pipe);
3683                         temp = I915_READ(reg);
3684                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3685
3686                         if (temp & FDI_RX_BIT_LOCK ||
3687                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
3688                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3689                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
3690                                               i);
3691                                 break;
3692                         }
3693                         udelay(1); /* should be 0.5us */
3694                 }
3695                 if (i == 4) {
3696                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
3697                         continue;
3698                 }
3699
3700                 /* Train 2 */
3701                 reg = FDI_TX_CTL(pipe);
3702                 temp = I915_READ(reg);
3703                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3704                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
3705                 I915_WRITE(reg, temp);
3706
3707                 reg = FDI_RX_CTL(pipe);
3708                 temp = I915_READ(reg);
3709                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3710                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3711                 I915_WRITE(reg, temp);
3712
3713                 POSTING_READ(reg);
3714                 udelay(2); /* should be 1.5us */
3715
3716                 for (i = 0; i < 4; i++) {
3717                         reg = FDI_RX_IIR(pipe);
3718                         temp = I915_READ(reg);
3719                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3720
3721                         if (temp & FDI_RX_SYMBOL_LOCK ||
3722                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
3723                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3724                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
3725                                               i);
3726                                 goto train_done;
3727                         }
3728                         udelay(2); /* should be 1.5us */
3729                 }
3730                 if (i == 4)
3731                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
3732         }
3733
3734 train_done:
3735         DRM_DEBUG_KMS("FDI train done.\n");
3736 }
3737
3738 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
3739 {
3740         struct drm_device *dev = intel_crtc->base.dev;
3741         struct drm_i915_private *dev_priv = dev->dev_private;
3742         int pipe = intel_crtc->pipe;
3743         u32 reg, temp;
3744
3745
3746         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
3747         reg = FDI_RX_CTL(pipe);
3748         temp = I915_READ(reg);
3749         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
3750         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3751         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3752         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
3753
3754         POSTING_READ(reg);
3755         udelay(200);
3756
3757         /* Switch from Rawclk to PCDclk */
3758         temp = I915_READ(reg);
3759         I915_WRITE(reg, temp | FDI_PCDCLK);
3760
3761         POSTING_READ(reg);
3762         udelay(200);
3763
3764         /* Enable CPU FDI TX PLL, always on for Ironlake */
3765         reg = FDI_TX_CTL(pipe);
3766         temp = I915_READ(reg);
3767         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
3768                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
3769
3770                 POSTING_READ(reg);
3771                 udelay(100);
3772         }
3773 }
3774
3775 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
3776 {
3777         struct drm_device *dev = intel_crtc->base.dev;
3778         struct drm_i915_private *dev_priv = dev->dev_private;
3779         int pipe = intel_crtc->pipe;
3780         u32 reg, temp;
3781
3782         /* Switch from PCDclk to Rawclk */
3783         reg = FDI_RX_CTL(pipe);
3784         temp = I915_READ(reg);
3785         I915_WRITE(reg, temp & ~FDI_PCDCLK);
3786
3787         /* Disable CPU FDI TX PLL */
3788         reg = FDI_TX_CTL(pipe);
3789         temp = I915_READ(reg);
3790         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
3791
3792         POSTING_READ(reg);
3793         udelay(100);
3794
3795         reg = FDI_RX_CTL(pipe);
3796         temp = I915_READ(reg);
3797         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
3798
3799         /* Wait for the clocks to turn off. */
3800         POSTING_READ(reg);
3801         udelay(100);
3802 }
3803
3804 static void ironlake_fdi_disable(struct drm_crtc *crtc)
3805 {
3806         struct drm_device *dev = crtc->dev;
3807         struct drm_i915_private *dev_priv = dev->dev_private;
3808         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3809         int pipe = intel_crtc->pipe;
3810         u32 reg, temp;
3811
3812         /* disable CPU FDI tx and PCH FDI rx */
3813         reg = FDI_TX_CTL(pipe);
3814         temp = I915_READ(reg);
3815         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
3816         POSTING_READ(reg);
3817
3818         reg = FDI_RX_CTL(pipe);
3819         temp = I915_READ(reg);
3820         temp &= ~(0x7 << 16);
3821         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3822         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
3823
3824         POSTING_READ(reg);
3825         udelay(100);
3826
3827         /* Ironlake workaround, disable clock pointer after downing FDI */
3828         if (HAS_PCH_IBX(dev))
3829                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3830
3831         /* still set train pattern 1 */
3832         reg = FDI_TX_CTL(pipe);
3833         temp = I915_READ(reg);
3834         temp &= ~FDI_LINK_TRAIN_NONE;
3835         temp |= FDI_LINK_TRAIN_PATTERN_1;
3836         I915_WRITE(reg, temp);
3837
3838         reg = FDI_RX_CTL(pipe);
3839         temp = I915_READ(reg);
3840         if (HAS_PCH_CPT(dev)) {
3841                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3842                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3843         } else {
3844                 temp &= ~FDI_LINK_TRAIN_NONE;
3845                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3846         }
3847         /* BPC in FDI rx is consistent with that in PIPECONF */
3848         temp &= ~(0x07 << 16);
3849         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3850         I915_WRITE(reg, temp);
3851
3852         POSTING_READ(reg);
3853         udelay(100);
3854 }
3855
3856 bool intel_has_pending_fb_unpin(struct drm_device *dev)
3857 {
3858         struct intel_crtc *crtc;
3859
3860         /* Note that we don't need to be called with mode_config.lock here
3861          * as our list of CRTC objects is static for the lifetime of the
3862          * device and so cannot disappear as we iterate. Similarly, we can
3863          * happily treat the predicates as racy, atomic checks as userspace
3864          * cannot claim and pin a new fb without at least acquring the
3865          * struct_mutex and so serialising with us.
3866          */
3867         for_each_intel_crtc(dev, crtc) {
3868                 if (atomic_read(&crtc->unpin_work_count) == 0)
3869                         continue;
3870
3871                 if (crtc->unpin_work)
3872                         intel_wait_for_vblank(dev, crtc->pipe);
3873
3874                 return true;
3875         }
3876
3877         return false;
3878 }
3879
3880 static void page_flip_completed(struct intel_crtc *intel_crtc)
3881 {
3882         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
3883         struct intel_unpin_work *work = intel_crtc->unpin_work;
3884
3885         /* ensure that the unpin work is consistent wrt ->pending. */
3886         smp_rmb();
3887         intel_crtc->unpin_work = NULL;
3888
3889         if (work->event)
3890                 drm_send_vblank_event(intel_crtc->base.dev,
3891                                       intel_crtc->pipe,
3892                                       work->event);
3893
3894         drm_crtc_vblank_put(&intel_crtc->base);
3895
3896         wake_up_all(&dev_priv->pending_flip_queue);
3897         queue_work(dev_priv->wq, &work->work);
3898
3899         trace_i915_flip_complete(intel_crtc->plane,
3900                                  work->pending_flip_obj);
3901 }
3902
3903 void intel_crtc_wait_for_pending_flips(struct drm_crtc *crtc)
3904 {
3905         struct drm_device *dev = crtc->dev;
3906         struct drm_i915_private *dev_priv = dev->dev_private;
3907
3908         WARN_ON(waitqueue_active(&dev_priv->pending_flip_queue));
3909         if (WARN_ON(wait_event_timeout(dev_priv->pending_flip_queue,
3910                                        !intel_crtc_has_pending_flip(crtc),
3911                                        60*HZ) == 0)) {
3912                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3913
3914                 spin_lock_irq(&dev->event_lock);
3915                 if (intel_crtc->unpin_work) {
3916                         WARN_ONCE(1, "Removing stuck page flip\n");
3917                         page_flip_completed(intel_crtc);
3918                 }
3919                 spin_unlock_irq(&dev->event_lock);
3920         }
3921
3922         if (crtc->primary->fb) {
3923                 mutex_lock(&dev->struct_mutex);
3924                 intel_finish_fb(crtc->primary->fb);
3925                 mutex_unlock(&dev->struct_mutex);
3926         }
3927 }
3928
3929 /* Program iCLKIP clock to the desired frequency */
3930 static void lpt_program_iclkip(struct drm_crtc *crtc)
3931 {
3932         struct drm_device *dev = crtc->dev;
3933         struct drm_i915_private *dev_priv = dev->dev_private;
3934         int clock = to_intel_crtc(crtc)->config->base.adjusted_mode.crtc_clock;
3935         u32 divsel, phaseinc, auxdiv, phasedir = 0;
3936         u32 temp;
3937
3938         mutex_lock(&dev_priv->sb_lock);
3939
3940         /* It is necessary to ungate the pixclk gate prior to programming
3941          * the divisors, and gate it back when it is done.
3942          */
3943         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
3944
3945         /* Disable SSCCTL */
3946         intel_sbi_write(dev_priv, SBI_SSCCTL6,
3947                         intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK) |
3948                                 SBI_SSCCTL_DISABLE,
3949                         SBI_ICLK);
3950
3951         /* 20MHz is a corner case which is out of range for the 7-bit divisor */
3952         if (clock == 20000) {
3953                 auxdiv = 1;
3954                 divsel = 0x41;
3955                 phaseinc = 0x20;
3956         } else {
3957                 /* The iCLK virtual clock root frequency is in MHz,
3958                  * but the adjusted_mode->crtc_clock in in KHz. To get the
3959                  * divisors, it is necessary to divide one by another, so we
3960                  * convert the virtual clock precision to KHz here for higher
3961                  * precision.
3962                  */
3963                 u32 iclk_virtual_root_freq = 172800 * 1000;
3964                 u32 iclk_pi_range = 64;
3965                 u32 desired_divisor, msb_divisor_value, pi_value;
3966
3967                 desired_divisor = (iclk_virtual_root_freq / clock);
3968                 msb_divisor_value = desired_divisor / iclk_pi_range;
3969                 pi_value = desired_divisor % iclk_pi_range;
3970
3971                 auxdiv = 0;
3972                 divsel = msb_divisor_value - 2;
3973                 phaseinc = pi_value;
3974         }
3975
3976         /* This should not happen with any sane values */
3977         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
3978                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
3979         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
3980                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
3981
3982         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
3983                         clock,
3984                         auxdiv,
3985                         divsel,
3986                         phasedir,
3987                         phaseinc);
3988
3989         /* Program SSCDIVINTPHASE6 */
3990         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
3991         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
3992         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
3993         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
3994         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
3995         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
3996         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
3997         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
3998
3999         /* Program SSCAUXDIV */
4000         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4001         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
4002         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
4003         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
4004
4005         /* Enable modulator and associated divider */
4006         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4007         temp &= ~SBI_SSCCTL_DISABLE;
4008         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4009
4010         /* Wait for initialization time */
4011         udelay(24);
4012
4013         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
4014
4015         mutex_unlock(&dev_priv->sb_lock);
4016 }
4017
4018 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
4019                                                 enum pipe pch_transcoder)
4020 {
4021         struct drm_device *dev = crtc->base.dev;
4022         struct drm_i915_private *dev_priv = dev->dev_private;
4023         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
4024
4025         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
4026                    I915_READ(HTOTAL(cpu_transcoder)));
4027         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4028                    I915_READ(HBLANK(cpu_transcoder)));
4029         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4030                    I915_READ(HSYNC(cpu_transcoder)));
4031
4032         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4033                    I915_READ(VTOTAL(cpu_transcoder)));
4034         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4035                    I915_READ(VBLANK(cpu_transcoder)));
4036         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4037                    I915_READ(VSYNC(cpu_transcoder)));
4038         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4039                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4040 }
4041
4042 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4043 {
4044         struct drm_i915_private *dev_priv = dev->dev_private;
4045         uint32_t temp;
4046
4047         temp = I915_READ(SOUTH_CHICKEN1);
4048         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4049                 return;
4050
4051         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4052         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4053
4054         temp &= ~FDI_BC_BIFURCATION_SELECT;
4055         if (enable)
4056                 temp |= FDI_BC_BIFURCATION_SELECT;
4057
4058         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4059         I915_WRITE(SOUTH_CHICKEN1, temp);
4060         POSTING_READ(SOUTH_CHICKEN1);
4061 }
4062
4063 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4064 {
4065         struct drm_device *dev = intel_crtc->base.dev;
4066
4067         switch (intel_crtc->pipe) {
4068         case PIPE_A:
4069                 break;
4070         case PIPE_B:
4071                 if (intel_crtc->config->fdi_lanes > 2)
4072                         cpt_set_fdi_bc_bifurcation(dev, false);
4073                 else
4074                         cpt_set_fdi_bc_bifurcation(dev, true);
4075
4076                 break;
4077         case PIPE_C:
4078                 cpt_set_fdi_bc_bifurcation(dev, true);
4079
4080                 break;
4081         default:
4082                 BUG();
4083         }
4084 }
4085
4086 /*
4087  * Enable PCH resources required for PCH ports:
4088  *   - PCH PLLs
4089  *   - FDI training & RX/TX
4090  *   - update transcoder timings
4091  *   - DP transcoding bits
4092  *   - transcoder
4093  */
4094 static void ironlake_pch_enable(struct drm_crtc *crtc)
4095 {
4096         struct drm_device *dev = crtc->dev;
4097         struct drm_i915_private *dev_priv = dev->dev_private;
4098         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4099         int pipe = intel_crtc->pipe;
4100         u32 reg, temp;
4101
4102         assert_pch_transcoder_disabled(dev_priv, pipe);
4103
4104         if (IS_IVYBRIDGE(dev))
4105                 ivybridge_update_fdi_bc_bifurcation(intel_crtc);
4106
4107         /* Write the TU size bits before fdi link training, so that error
4108          * detection works. */
4109         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4110                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4111
4112         /* For PCH output, training FDI link */
4113         dev_priv->display.fdi_link_train(crtc);
4114
4115         /* We need to program the right clock selection before writing the pixel
4116          * mutliplier into the DPLL. */
4117         if (HAS_PCH_CPT(dev)) {
4118                 u32 sel;
4119
4120                 temp = I915_READ(PCH_DPLL_SEL);
4121                 temp |= TRANS_DPLL_ENABLE(pipe);
4122                 sel = TRANS_DPLLB_SEL(pipe);
4123                 if (intel_crtc->config->shared_dpll == DPLL_ID_PCH_PLL_B)
4124                         temp |= sel;
4125                 else
4126                         temp &= ~sel;
4127                 I915_WRITE(PCH_DPLL_SEL, temp);
4128         }
4129
4130         /* XXX: pch pll's can be enabled any time before we enable the PCH
4131          * transcoder, and we actually should do this to not upset any PCH
4132          * transcoder that already use the clock when we share it.
4133          *
4134          * Note that enable_shared_dpll tries to do the right thing, but
4135          * get_shared_dpll unconditionally resets the pll - we need that to have
4136          * the right LVDS enable sequence. */
4137         intel_enable_shared_dpll(intel_crtc);
4138
4139         /* set transcoder timing, panel must allow it */
4140         assert_panel_unlocked(dev_priv, pipe);
4141         ironlake_pch_transcoder_set_timings(intel_crtc, pipe);
4142
4143         intel_fdi_normal_train(crtc);
4144
4145         /* For PCH DP, enable TRANS_DP_CTL */
4146         if (HAS_PCH_CPT(dev) && intel_crtc->config->has_dp_encoder) {
4147                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4148                 reg = TRANS_DP_CTL(pipe);
4149                 temp = I915_READ(reg);
4150                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4151                           TRANS_DP_SYNC_MASK |
4152                           TRANS_DP_BPC_MASK);
4153                 temp |= TRANS_DP_OUTPUT_ENABLE;
4154                 temp |= bpc << 9; /* same format but at 11:9 */
4155
4156                 if (crtc->mode.flags & DRM_MODE_FLAG_PHSYNC)
4157                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4158                 if (crtc->mode.flags & DRM_MODE_FLAG_PVSYNC)
4159                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4160
4161                 switch (intel_trans_dp_port_sel(crtc)) {
4162                 case PCH_DP_B:
4163                         temp |= TRANS_DP_PORT_SEL_B;
4164                         break;
4165                 case PCH_DP_C:
4166                         temp |= TRANS_DP_PORT_SEL_C;
4167                         break;
4168                 case PCH_DP_D:
4169                         temp |= TRANS_DP_PORT_SEL_D;
4170                         break;
4171                 default:
4172                         BUG();
4173                 }
4174
4175                 I915_WRITE(reg, temp);
4176         }
4177
4178         ironlake_enable_pch_transcoder(dev_priv, pipe);
4179 }
4180
4181 static void lpt_pch_enable(struct drm_crtc *crtc)
4182 {
4183         struct drm_device *dev = crtc->dev;
4184         struct drm_i915_private *dev_priv = dev->dev_private;
4185         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4186         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4187
4188         assert_pch_transcoder_disabled(dev_priv, TRANSCODER_A);
4189
4190         lpt_program_iclkip(crtc);
4191
4192         /* Set transcoder timing. */
4193         ironlake_pch_transcoder_set_timings(intel_crtc, PIPE_A);
4194
4195         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4196 }
4197
4198 struct intel_shared_dpll *intel_get_shared_dpll(struct intel_crtc *crtc,
4199                                                 struct intel_crtc_state *crtc_state)
4200 {
4201         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
4202         struct intel_shared_dpll *pll;
4203         struct intel_shared_dpll_config *shared_dpll;
4204         enum intel_dpll_id i;
4205
4206         shared_dpll = intel_atomic_get_shared_dpll_state(crtc_state->base.state);
4207
4208         if (HAS_PCH_IBX(dev_priv->dev)) {
4209                 /* Ironlake PCH has a fixed PLL->PCH pipe mapping. */
4210                 i = (enum intel_dpll_id) crtc->pipe;
4211                 pll = &dev_priv->shared_dplls[i];
4212
4213                 DRM_DEBUG_KMS("CRTC:%d using pre-allocated %s\n",
4214                               crtc->base.base.id, pll->name);
4215
4216                 WARN_ON(shared_dpll[i].crtc_mask);
4217
4218                 goto found;
4219         }
4220
4221         if (IS_BROXTON(dev_priv->dev)) {
4222                 /* PLL is attached to port in bxt */
4223                 struct intel_encoder *encoder;
4224                 struct intel_digital_port *intel_dig_port;
4225
4226                 encoder = intel_ddi_get_crtc_new_encoder(crtc_state);
4227                 if (WARN_ON(!encoder))
4228                         return NULL;
4229
4230                 intel_dig_port = enc_to_dig_port(&encoder->base);
4231                 /* 1:1 mapping between ports and PLLs */
4232                 i = (enum intel_dpll_id)intel_dig_port->port;
4233                 pll = &dev_priv->shared_dplls[i];
4234                 DRM_DEBUG_KMS("CRTC:%d using pre-allocated %s\n",
4235                         crtc->base.base.id, pll->name);
4236                 WARN_ON(shared_dpll[i].crtc_mask);
4237
4238                 goto found;
4239         }
4240
4241         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4242                 pll = &dev_priv->shared_dplls[i];
4243
4244                 /* Only want to check enabled timings first */
4245                 if (shared_dpll[i].crtc_mask == 0)
4246                         continue;
4247
4248                 if (memcmp(&crtc_state->dpll_hw_state,
4249                            &shared_dpll[i].hw_state,
4250                            sizeof(crtc_state->dpll_hw_state)) == 0) {
4251                         DRM_DEBUG_KMS("CRTC:%d sharing existing %s (crtc mask 0x%08x, ative %d)\n",
4252                                       crtc->base.base.id, pll->name,
4253                                       shared_dpll[i].crtc_mask,
4254                                       pll->active);
4255                         goto found;
4256                 }
4257         }
4258
4259         /* Ok no matching timings, maybe there's a free one? */
4260         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4261                 pll = &dev_priv->shared_dplls[i];
4262                 if (shared_dpll[i].crtc_mask == 0) {
4263                         DRM_DEBUG_KMS("CRTC:%d allocated %s\n",
4264                                       crtc->base.base.id, pll->name);
4265                         goto found;
4266                 }
4267         }
4268
4269         return NULL;
4270
4271 found:
4272         if (shared_dpll[i].crtc_mask == 0)
4273                 shared_dpll[i].hw_state =
4274                         crtc_state->dpll_hw_state;
4275
4276         crtc_state->shared_dpll = i;
4277         DRM_DEBUG_DRIVER("using %s for pipe %c\n", pll->name,
4278                          pipe_name(crtc->pipe));
4279
4280         shared_dpll[i].crtc_mask |= 1 << crtc->pipe;
4281
4282         return pll;
4283 }
4284
4285 static void intel_shared_dpll_commit(struct drm_atomic_state *state)
4286 {
4287         struct drm_i915_private *dev_priv = to_i915(state->dev);
4288         struct intel_shared_dpll_config *shared_dpll;
4289         struct intel_shared_dpll *pll;
4290         enum intel_dpll_id i;
4291
4292         if (!to_intel_atomic_state(state)->dpll_set)
4293                 return;
4294
4295         shared_dpll = to_intel_atomic_state(state)->shared_dpll;
4296         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4297                 pll = &dev_priv->shared_dplls[i];
4298                 pll->config = shared_dpll[i];
4299         }
4300 }
4301
4302 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4303 {
4304         struct drm_i915_private *dev_priv = dev->dev_private;
4305         int dslreg = PIPEDSL(pipe);
4306         u32 temp;
4307
4308         temp = I915_READ(dslreg);
4309         udelay(500);
4310         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4311                 if (wait_for(I915_READ(dslreg) != temp, 5))
4312                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4313         }
4314 }
4315
4316 static int
4317 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4318                   unsigned scaler_user, int *scaler_id, unsigned int rotation,
4319                   int src_w, int src_h, int dst_w, int dst_h)
4320 {
4321         struct intel_crtc_scaler_state *scaler_state =
4322                 &crtc_state->scaler_state;
4323         struct intel_crtc *intel_crtc =
4324                 to_intel_crtc(crtc_state->base.crtc);
4325         int need_scaling;
4326
4327         need_scaling = intel_rotation_90_or_270(rotation) ?
4328                 (src_h != dst_w || src_w != dst_h):
4329                 (src_w != dst_w || src_h != dst_h);
4330
4331         /*
4332          * if plane is being disabled or scaler is no more required or force detach
4333          *  - free scaler binded to this plane/crtc
4334          *  - in order to do this, update crtc->scaler_usage
4335          *
4336          * Here scaler state in crtc_state is set free so that
4337          * scaler can be assigned to other user. Actual register
4338          * update to free the scaler is done in plane/panel-fit programming.
4339          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4340          */
4341         if (force_detach || !need_scaling) {
4342                 if (*scaler_id >= 0) {
4343                         scaler_state->scaler_users &= ~(1 << scaler_user);
4344                         scaler_state->scalers[*scaler_id].in_use = 0;
4345
4346                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4347                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4348                                 intel_crtc->pipe, scaler_user, *scaler_id,
4349                                 scaler_state->scaler_users);
4350                         *scaler_id = -1;
4351                 }
4352                 return 0;
4353         }
4354
4355         /* range checks */
4356         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4357                 dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4358
4359                 src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4360                 dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H) {
4361                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4362                         "size is out of scaler range\n",
4363                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4364                 return -EINVAL;
4365         }
4366
4367         /* mark this plane as a scaler user in crtc_state */
4368         scaler_state->scaler_users |= (1 << scaler_user);
4369         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4370                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4371                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4372                 scaler_state->scaler_users);
4373
4374         return 0;
4375 }
4376
4377 /**
4378  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4379  *
4380  * @state: crtc's scaler state
4381  * @force_detach: whether to forcibly disable scaler
4382  *
4383  * Return
4384  *     0 - scaler_usage updated successfully
4385  *    error - requested scaling cannot be supported or other error condition
4386  */
4387 int skl_update_scaler_crtc(struct intel_crtc_state *state, int force_detach)
4388 {
4389         struct intel_crtc *intel_crtc = to_intel_crtc(state->base.crtc);
4390         struct drm_display_mode *adjusted_mode =
4391                 &state->base.adjusted_mode;
4392
4393         DRM_DEBUG_KMS("Updating scaler for [CRTC:%i] scaler_user index %u.%u\n",
4394                       intel_crtc->base.base.id, intel_crtc->pipe, SKL_CRTC_INDEX);
4395
4396         return skl_update_scaler(state, force_detach, SKL_CRTC_INDEX,
4397                 &state->scaler_state.scaler_id, DRM_ROTATE_0,
4398                 state->pipe_src_w, state->pipe_src_h,
4399                 adjusted_mode->hdisplay, adjusted_mode->hdisplay);
4400 }
4401
4402 /**
4403  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4404  *
4405  * @state: crtc's scaler state
4406  * @plane_state: atomic plane state to update
4407  *
4408  * Return
4409  *     0 - scaler_usage updated successfully
4410  *    error - requested scaling cannot be supported or other error condition
4411  */
4412 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4413                                    struct intel_plane_state *plane_state)
4414 {
4415
4416         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
4417         struct intel_plane *intel_plane =
4418                 to_intel_plane(plane_state->base.plane);
4419         struct drm_framebuffer *fb = plane_state->base.fb;
4420         int ret;
4421
4422         bool force_detach = !fb || !plane_state->visible;
4423
4424         DRM_DEBUG_KMS("Updating scaler for [PLANE:%d] scaler_user index %u.%u\n",
4425                       intel_plane->base.base.id, intel_crtc->pipe,
4426                       drm_plane_index(&intel_plane->base));
4427
4428         ret = skl_update_scaler(crtc_state, force_detach,
4429                                 drm_plane_index(&intel_plane->base),
4430                                 &plane_state->scaler_id,
4431                                 plane_state->base.rotation,
4432                                 drm_rect_width(&plane_state->src) >> 16,
4433                                 drm_rect_height(&plane_state->src) >> 16,
4434                                 drm_rect_width(&plane_state->dst),
4435                                 drm_rect_height(&plane_state->dst));
4436
4437         if (ret || plane_state->scaler_id < 0)
4438                 return ret;
4439
4440         /* check colorkey */
4441         if (WARN_ON(intel_plane->ckey.flags != I915_SET_COLORKEY_NONE)) {
4442                 DRM_DEBUG_KMS("[PLANE:%d] scaling with color key not allowed",
4443                         intel_plane->base.base.id);
4444                 return -EINVAL;
4445         }
4446
4447         /* Check src format */
4448         switch (fb->pixel_format) {
4449         case DRM_FORMAT_RGB565:
4450         case DRM_FORMAT_XBGR8888:
4451         case DRM_FORMAT_XRGB8888:
4452         case DRM_FORMAT_ABGR8888:
4453         case DRM_FORMAT_ARGB8888:
4454         case DRM_FORMAT_XRGB2101010:
4455         case DRM_FORMAT_XBGR2101010:
4456         case DRM_FORMAT_YUYV:
4457         case DRM_FORMAT_YVYU:
4458         case DRM_FORMAT_UYVY:
4459         case DRM_FORMAT_VYUY:
4460                 break;
4461         default:
4462                 DRM_DEBUG_KMS("[PLANE:%d] FB:%d unsupported scaling format 0x%x\n",
4463                         intel_plane->base.base.id, fb->base.id, fb->pixel_format);
4464                 return -EINVAL;
4465         }
4466
4467         return 0;
4468 }
4469
4470 static void skylake_pfit_update(struct intel_crtc *crtc, int enable)
4471 {
4472         struct drm_device *dev = crtc->base.dev;
4473         struct drm_i915_private *dev_priv = dev->dev_private;
4474         int pipe = crtc->pipe;
4475         struct intel_crtc_scaler_state *scaler_state =
4476                 &crtc->config->scaler_state;
4477
4478         DRM_DEBUG_KMS("for crtc_state = %p\n", crtc->config);
4479
4480         /* To update pfit, first update scaler state */
4481         skl_update_scaler_crtc(crtc->config, !enable);
4482         intel_atomic_setup_scalers(crtc->base.dev, crtc, crtc->config);
4483         skl_detach_scalers(crtc);
4484         if (!enable)
4485                 return;
4486
4487         if (crtc->config->pch_pfit.enabled) {
4488                 int id;
4489
4490                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0)) {
4491                         DRM_ERROR("Requesting pfit without getting a scaler first\n");
4492                         return;
4493                 }
4494
4495                 id = scaler_state->scaler_id;
4496                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4497                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4498                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
4499                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
4500
4501                 DRM_DEBUG_KMS("for crtc_state = %p scaler_id = %d\n", crtc->config, id);
4502         }
4503 }
4504
4505 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4506 {
4507         struct drm_device *dev = crtc->base.dev;
4508         struct drm_i915_private *dev_priv = dev->dev_private;
4509         int pipe = crtc->pipe;
4510
4511         if (crtc->config->pch_pfit.enabled) {
4512                 /* Force use of hard-coded filter coefficients
4513                  * as some pre-programmed values are broken,
4514                  * e.g. x201.
4515                  */
4516                 if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev))
4517                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4518                                                  PF_PIPE_SEL_IVB(pipe));
4519                 else
4520                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4521                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4522                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4523         }
4524 }
4525
4526 static void intel_enable_sprite_planes(struct drm_crtc *crtc)
4527 {
4528         struct drm_device *dev = crtc->dev;
4529         enum pipe pipe = to_intel_crtc(crtc)->pipe;
4530         struct drm_plane *plane;
4531         struct intel_plane *intel_plane;
4532
4533         drm_for_each_legacy_plane(plane, &dev->mode_config.plane_list) {
4534                 intel_plane = to_intel_plane(plane);
4535                 if (intel_plane->pipe == pipe)
4536                         intel_plane_restore(&intel_plane->base);
4537         }
4538 }
4539
4540 void hsw_enable_ips(struct intel_crtc *crtc)
4541 {
4542         struct drm_device *dev = crtc->base.dev;
4543         struct drm_i915_private *dev_priv = dev->dev_private;
4544
4545         if (!crtc->config->ips_enabled)
4546                 return;
4547
4548         /* We can only enable IPS after we enable a plane and wait for a vblank */
4549         intel_wait_for_vblank(dev, crtc->pipe);
4550
4551         assert_plane_enabled(dev_priv, crtc->plane);
4552         if (IS_BROADWELL(dev)) {
4553                 mutex_lock(&dev_priv->rps.hw_lock);
4554                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0xc0000000));
4555                 mutex_unlock(&dev_priv->rps.hw_lock);
4556                 /* Quoting Art Runyan: "its not safe to expect any particular
4557                  * value in IPS_CTL bit 31 after enabling IPS through the
4558                  * mailbox." Moreover, the mailbox may return a bogus state,
4559                  * so we need to just enable it and continue on.
4560                  */
4561         } else {
4562                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4563                 /* The bit only becomes 1 in the next vblank, so this wait here
4564                  * is essentially intel_wait_for_vblank. If we don't have this
4565                  * and don't wait for vblanks until the end of crtc_enable, then
4566                  * the HW state readout code will complain that the expected
4567                  * IPS_CTL value is not the one we read. */
4568                 if (wait_for(I915_READ_NOTRACE(IPS_CTL) & IPS_ENABLE, 50))
4569                         DRM_ERROR("Timed out waiting for IPS enable\n");
4570         }
4571 }
4572
4573 void hsw_disable_ips(struct intel_crtc *crtc)
4574 {
4575         struct drm_device *dev = crtc->base.dev;
4576         struct drm_i915_private *dev_priv = dev->dev_private;
4577
4578         if (!crtc->config->ips_enabled)
4579                 return;
4580
4581         assert_plane_enabled(dev_priv, crtc->plane);
4582         if (IS_BROADWELL(dev)) {
4583                 mutex_lock(&dev_priv->rps.hw_lock);
4584                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4585                 mutex_unlock(&dev_priv->rps.hw_lock);
4586                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4587                 if (wait_for((I915_READ(IPS_CTL) & IPS_ENABLE) == 0, 42))
4588                         DRM_ERROR("Timed out waiting for IPS disable\n");
4589         } else {
4590                 I915_WRITE(IPS_CTL, 0);
4591                 POSTING_READ(IPS_CTL);
4592         }
4593
4594         /* We need to wait for a vblank before we can disable the plane. */
4595         intel_wait_for_vblank(dev, crtc->pipe);
4596 }
4597
4598 /** Loads the palette/gamma unit for the CRTC with the prepared values */
4599 static void intel_crtc_load_lut(struct drm_crtc *crtc)
4600 {
4601         struct drm_device *dev = crtc->dev;
4602         struct drm_i915_private *dev_priv = dev->dev_private;
4603         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4604         enum pipe pipe = intel_crtc->pipe;
4605         int palreg = PALETTE(pipe);
4606         int i;
4607         bool reenable_ips = false;
4608
4609         /* The clocks have to be on to load the palette. */
4610         if (!crtc->state->active)
4611                 return;
4612
4613         if (HAS_GMCH_DISPLAY(dev_priv->dev)) {
4614                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_DSI))
4615                         assert_dsi_pll_enabled(dev_priv);
4616                 else
4617                         assert_pll_enabled(dev_priv, pipe);
4618         }
4619
4620         /* use legacy palette for Ironlake */
4621         if (!HAS_GMCH_DISPLAY(dev))
4622                 palreg = LGC_PALETTE(pipe);
4623
4624         /* Workaround : Do not read or write the pipe palette/gamma data while
4625          * GAMMA_MODE is configured for split gamma and IPS_CTL has IPS enabled.
4626          */
4627         if (IS_HASWELL(dev) && intel_crtc->config->ips_enabled &&
4628             ((I915_READ(GAMMA_MODE(pipe)) & GAMMA_MODE_MODE_MASK) ==
4629              GAMMA_MODE_MODE_SPLIT)) {
4630                 hsw_disable_ips(intel_crtc);
4631                 reenable_ips = true;
4632         }
4633
4634         for (i = 0; i < 256; i++) {
4635                 I915_WRITE(palreg + 4 * i,
4636                            (intel_crtc->lut_r[i] << 16) |
4637                            (intel_crtc->lut_g[i] << 8) |
4638                            intel_crtc->lut_b[i]);
4639         }
4640
4641         if (reenable_ips)
4642                 hsw_enable_ips(intel_crtc);
4643 }
4644
4645 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
4646 {
4647         if (intel_crtc->overlay) {
4648                 struct drm_device *dev = intel_crtc->base.dev;
4649                 struct drm_i915_private *dev_priv = dev->dev_private;
4650
4651                 mutex_lock(&dev->struct_mutex);
4652                 dev_priv->mm.interruptible = false;
4653                 (void) intel_overlay_switch_off(intel_crtc->overlay);
4654                 dev_priv->mm.interruptible = true;
4655                 mutex_unlock(&dev->struct_mutex);
4656         }
4657
4658         /* Let userspace switch the overlay on again. In most cases userspace
4659          * has to recompute where to put it anyway.
4660          */
4661 }
4662
4663 /**
4664  * intel_post_enable_primary - Perform operations after enabling primary plane
4665  * @crtc: the CRTC whose primary plane was just enabled
4666  *
4667  * Performs potentially sleeping operations that must be done after the primary
4668  * plane is enabled, such as updating FBC and IPS.  Note that this may be
4669  * called due to an explicit primary plane update, or due to an implicit
4670  * re-enable that is caused when a sprite plane is updated to no longer
4671  * completely hide the primary plane.
4672  */
4673 static void
4674 intel_post_enable_primary(struct drm_crtc *crtc)
4675 {
4676         struct drm_device *dev = crtc->dev;
4677         struct drm_i915_private *dev_priv = dev->dev_private;
4678         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4679         int pipe = intel_crtc->pipe;
4680
4681         /*
4682          * BDW signals flip done immediately if the plane
4683          * is disabled, even if the plane enable is already
4684          * armed to occur at the next vblank :(
4685          */
4686         if (IS_BROADWELL(dev))
4687                 intel_wait_for_vblank(dev, pipe);
4688
4689         /*
4690          * FIXME IPS should be fine as long as one plane is
4691          * enabled, but in practice it seems to have problems
4692          * when going from primary only to sprite only and vice
4693          * versa.
4694          */
4695         hsw_enable_ips(intel_crtc);
4696
4697         mutex_lock(&dev->struct_mutex);
4698         intel_fbc_update(dev);
4699         mutex_unlock(&dev->struct_mutex);
4700
4701         /*
4702          * Gen2 reports pipe underruns whenever all planes are disabled.
4703          * So don't enable underrun reporting before at least some planes
4704          * are enabled.
4705          * FIXME: Need to fix the logic to work when we turn off all planes
4706          * but leave the pipe running.
4707          */
4708         if (IS_GEN2(dev))
4709                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4710
4711         /* Underruns don't raise interrupts, so check manually. */
4712         if (HAS_GMCH_DISPLAY(dev))
4713                 i9xx_check_fifo_underruns(dev_priv);
4714 }
4715
4716 /**
4717  * intel_pre_disable_primary - Perform operations before disabling primary plane
4718  * @crtc: the CRTC whose primary plane is to be disabled
4719  *
4720  * Performs potentially sleeping operations that must be done before the
4721  * primary plane is disabled, such as updating FBC and IPS.  Note that this may
4722  * be called due to an explicit primary plane update, or due to an implicit
4723  * disable that is caused when a sprite plane completely hides the primary
4724  * plane.
4725  */
4726 static void
4727 intel_pre_disable_primary(struct drm_crtc *crtc)
4728 {
4729         struct drm_device *dev = crtc->dev;
4730         struct drm_i915_private *dev_priv = dev->dev_private;
4731         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4732         int pipe = intel_crtc->pipe;
4733
4734         /*
4735          * Gen2 reports pipe underruns whenever all planes are disabled.
4736          * So diasble underrun reporting before all the planes get disabled.
4737          * FIXME: Need to fix the logic to work when we turn off all planes
4738          * but leave the pipe running.
4739          */
4740         if (IS_GEN2(dev))
4741                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4742
4743         /*
4744          * Vblank time updates from the shadow to live plane control register
4745          * are blocked if the memory self-refresh mode is active at that
4746          * moment. So to make sure the plane gets truly disabled, disable
4747          * first the self-refresh mode. The self-refresh enable bit in turn
4748          * will be checked/applied by the HW only at the next frame start
4749          * event which is after the vblank start event, so we need to have a
4750          * wait-for-vblank between disabling the plane and the pipe.
4751          */
4752         if (HAS_GMCH_DISPLAY(dev))
4753                 intel_set_memory_cxsr(dev_priv, false);
4754
4755         mutex_lock(&dev->struct_mutex);
4756         if (dev_priv->fbc.crtc == intel_crtc)
4757                 intel_fbc_disable(dev);
4758         mutex_unlock(&dev->struct_mutex);
4759
4760         /*
4761          * FIXME IPS should be fine as long as one plane is
4762          * enabled, but in practice it seems to have problems
4763          * when going from primary only to sprite only and vice
4764          * versa.
4765          */
4766         hsw_disable_ips(intel_crtc);
4767 }
4768
4769 static void intel_crtc_enable_planes(struct drm_crtc *crtc)
4770 {
4771         struct drm_device *dev = crtc->dev;
4772         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4773         int pipe = intel_crtc->pipe;
4774
4775         intel_enable_primary_hw_plane(crtc->primary, crtc);
4776         intel_enable_sprite_planes(crtc);
4777         if (to_intel_plane_state(crtc->cursor->state)->visible)
4778                 intel_crtc_update_cursor(crtc, true);
4779
4780         intel_post_enable_primary(crtc);
4781
4782         /*
4783          * FIXME: Once we grow proper nuclear flip support out of this we need
4784          * to compute the mask of flip planes precisely. For the time being
4785          * consider this a flip to a NULL plane.
4786          */
4787         intel_frontbuffer_flip(dev, INTEL_FRONTBUFFER_ALL_MASK(pipe));
4788 }
4789
4790 static void intel_crtc_disable_planes(struct drm_crtc *crtc)
4791 {
4792         struct drm_device *dev = crtc->dev;
4793         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4794         struct intel_plane *intel_plane;
4795         int pipe = intel_crtc->pipe;
4796
4797         intel_crtc_wait_for_pending_flips(crtc);
4798
4799         intel_pre_disable_primary(crtc);
4800
4801         intel_crtc_dpms_overlay_disable(intel_crtc);
4802         for_each_intel_plane(dev, intel_plane) {
4803                 if (intel_plane->pipe == pipe) {
4804                         struct drm_crtc *from = intel_plane->base.crtc;
4805
4806                         intel_plane->disable_plane(&intel_plane->base,
4807                                                    from ?: crtc, true);
4808                 }
4809         }
4810
4811         /*
4812          * FIXME: Once we grow proper nuclear flip support out of this we need
4813          * to compute the mask of flip planes precisely. For the time being
4814          * consider this a flip to a NULL plane.
4815          */
4816         intel_frontbuffer_flip(dev, INTEL_FRONTBUFFER_ALL_MASK(pipe));
4817 }
4818
4819 static void ironlake_crtc_enable(struct drm_crtc *crtc)
4820 {
4821         struct drm_device *dev = crtc->dev;
4822         struct drm_i915_private *dev_priv = dev->dev_private;
4823         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4824         struct intel_encoder *encoder;
4825         int pipe = intel_crtc->pipe;
4826
4827         if (WARN_ON(intel_crtc->active))
4828                 return;
4829
4830         if (intel_crtc->config->has_pch_encoder)
4831                 intel_prepare_shared_dpll(intel_crtc);
4832
4833         if (intel_crtc->config->has_dp_encoder)
4834                 intel_dp_set_m_n(intel_crtc, M1_N1);
4835
4836         intel_set_pipe_timings(intel_crtc);
4837
4838         if (intel_crtc->config->has_pch_encoder) {
4839                 intel_cpu_transcoder_set_m_n(intel_crtc,
4840                                      &intel_crtc->config->fdi_m_n, NULL);
4841         }
4842
4843         ironlake_set_pipeconf(crtc);
4844
4845         intel_crtc->active = true;
4846
4847         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4848         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
4849
4850         for_each_encoder_on_crtc(dev, crtc, encoder)
4851                 if (encoder->pre_enable)
4852                         encoder->pre_enable(encoder);
4853
4854         if (intel_crtc->config->has_pch_encoder) {
4855                 /* Note: FDI PLL enabling _must_ be done before we enable the
4856                  * cpu pipes, hence this is separate from all the other fdi/pch
4857                  * enabling. */
4858                 ironlake_fdi_pll_enable(intel_crtc);
4859         } else {
4860                 assert_fdi_tx_disabled(dev_priv, pipe);
4861                 assert_fdi_rx_disabled(dev_priv, pipe);
4862         }
4863
4864         ironlake_pfit_enable(intel_crtc);
4865
4866         /*
4867          * On ILK+ LUT must be loaded before the pipe is running but with
4868          * clocks enabled
4869          */
4870         intel_crtc_load_lut(crtc);
4871
4872         intel_update_watermarks(crtc);
4873         intel_enable_pipe(intel_crtc);
4874
4875         if (intel_crtc->config->has_pch_encoder)
4876                 ironlake_pch_enable(crtc);
4877
4878         assert_vblank_disabled(crtc);
4879         drm_crtc_vblank_on(crtc);
4880
4881         for_each_encoder_on_crtc(dev, crtc, encoder)
4882                 encoder->enable(encoder);
4883
4884         if (HAS_PCH_CPT(dev))
4885                 cpt_verify_modeset(dev, intel_crtc->pipe);
4886 }
4887
4888 /* IPS only exists on ULT machines and is tied to pipe A. */
4889 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
4890 {
4891         return HAS_IPS(crtc->base.dev) && crtc->pipe == PIPE_A;
4892 }
4893
4894 static void haswell_crtc_enable(struct drm_crtc *crtc)
4895 {
4896         struct drm_device *dev = crtc->dev;
4897         struct drm_i915_private *dev_priv = dev->dev_private;
4898         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4899         struct intel_encoder *encoder;
4900         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
4901         struct intel_crtc_state *pipe_config =
4902                 to_intel_crtc_state(crtc->state);
4903
4904         if (WARN_ON(intel_crtc->active))
4905                 return;
4906
4907         if (intel_crtc_to_shared_dpll(intel_crtc))
4908                 intel_enable_shared_dpll(intel_crtc);
4909
4910         if (intel_crtc->config->has_dp_encoder)
4911                 intel_dp_set_m_n(intel_crtc, M1_N1);
4912
4913         intel_set_pipe_timings(intel_crtc);
4914
4915         if (intel_crtc->config->cpu_transcoder != TRANSCODER_EDP) {
4916                 I915_WRITE(PIPE_MULT(intel_crtc->config->cpu_transcoder),
4917                            intel_crtc->config->pixel_multiplier - 1);
4918         }
4919
4920         if (intel_crtc->config->has_pch_encoder) {
4921                 intel_cpu_transcoder_set_m_n(intel_crtc,
4922                                      &intel_crtc->config->fdi_m_n, NULL);
4923         }
4924
4925         haswell_set_pipeconf(crtc);
4926
4927         intel_set_pipe_csc(crtc);
4928
4929         intel_crtc->active = true;
4930
4931         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4932         for_each_encoder_on_crtc(dev, crtc, encoder)
4933                 if (encoder->pre_enable)
4934                         encoder->pre_enable(encoder);
4935
4936         if (intel_crtc->config->has_pch_encoder) {
4937                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4938                                                       true);
4939                 dev_priv->display.fdi_link_train(crtc);
4940         }
4941
4942         intel_ddi_enable_pipe_clock(intel_crtc);
4943
4944         if (INTEL_INFO(dev)->gen == 9)
4945                 skylake_pfit_update(intel_crtc, 1);
4946         else if (INTEL_INFO(dev)->gen < 9)
4947                 ironlake_pfit_enable(intel_crtc);
4948         else
4949                 MISSING_CASE(INTEL_INFO(dev)->gen);
4950
4951         /*
4952          * On ILK+ LUT must be loaded before the pipe is running but with
4953          * clocks enabled
4954          */
4955         intel_crtc_load_lut(crtc);
4956
4957         intel_ddi_set_pipe_settings(crtc);
4958         intel_ddi_enable_transcoder_func(crtc);
4959
4960         intel_update_watermarks(crtc);
4961         intel_enable_pipe(intel_crtc);
4962
4963         if (intel_crtc->config->has_pch_encoder)
4964                 lpt_pch_enable(crtc);
4965
4966         if (intel_crtc->config->dp_encoder_is_mst)
4967                 intel_ddi_set_vc_payload_alloc(crtc, true);
4968
4969         assert_vblank_disabled(crtc);
4970         drm_crtc_vblank_on(crtc);
4971
4972         for_each_encoder_on_crtc(dev, crtc, encoder) {
4973                 encoder->enable(encoder);
4974                 intel_opregion_notify_encoder(encoder, true);
4975         }
4976
4977         /* If we change the relative order between pipe/planes enabling, we need
4978          * to change the workaround. */
4979         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
4980         if (IS_HASWELL(dev) && hsw_workaround_pipe != INVALID_PIPE) {
4981                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
4982                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
4983         }
4984 }
4985
4986 static void ironlake_pfit_disable(struct intel_crtc *crtc)
4987 {
4988         struct drm_device *dev = crtc->base.dev;
4989         struct drm_i915_private *dev_priv = dev->dev_private;
4990         int pipe = crtc->pipe;
4991
4992         /* To avoid upsetting the power well on haswell only disable the pfit if
4993          * it's in use. The hw state code will make sure we get this right. */
4994         if (crtc->config->pch_pfit.enabled) {
4995                 I915_WRITE(PF_CTL(pipe), 0);
4996                 I915_WRITE(PF_WIN_POS(pipe), 0);
4997                 I915_WRITE(PF_WIN_SZ(pipe), 0);
4998         }
4999 }
5000
5001 static void ironlake_crtc_disable(struct drm_crtc *crtc)
5002 {
5003         struct drm_device *dev = crtc->dev;
5004         struct drm_i915_private *dev_priv = dev->dev_private;
5005         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5006         struct intel_encoder *encoder;
5007         int pipe = intel_crtc->pipe;
5008         u32 reg, temp;
5009
5010         if (WARN_ON(!intel_crtc->active))
5011                 return;
5012
5013         for_each_encoder_on_crtc(dev, crtc, encoder)
5014                 encoder->disable(encoder);
5015
5016         drm_crtc_vblank_off(crtc);
5017         assert_vblank_disabled(crtc);
5018
5019         if (intel_crtc->config->has_pch_encoder)
5020                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5021
5022         intel_disable_pipe(intel_crtc);
5023
5024         ironlake_pfit_disable(intel_crtc);
5025
5026         if (intel_crtc->config->has_pch_encoder)
5027                 ironlake_fdi_disable(crtc);
5028
5029         for_each_encoder_on_crtc(dev, crtc, encoder)
5030                 if (encoder->post_disable)
5031                         encoder->post_disable(encoder);
5032
5033         if (intel_crtc->config->has_pch_encoder) {
5034                 ironlake_disable_pch_transcoder(dev_priv, pipe);
5035
5036                 if (HAS_PCH_CPT(dev)) {
5037                         /* disable TRANS_DP_CTL */
5038                         reg = TRANS_DP_CTL(pipe);
5039                         temp = I915_READ(reg);
5040                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5041                                   TRANS_DP_PORT_SEL_MASK);
5042                         temp |= TRANS_DP_PORT_SEL_NONE;
5043                         I915_WRITE(reg, temp);
5044
5045                         /* disable DPLL_SEL */
5046                         temp = I915_READ(PCH_DPLL_SEL);
5047                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5048                         I915_WRITE(PCH_DPLL_SEL, temp);
5049                 }
5050
5051                 /* disable PCH DPLL */
5052                 intel_disable_shared_dpll(intel_crtc);
5053
5054                 ironlake_fdi_pll_disable(intel_crtc);
5055         }
5056
5057         intel_crtc->active = false;
5058         intel_update_watermarks(crtc);
5059
5060         mutex_lock(&dev->struct_mutex);
5061         intel_fbc_update(dev);
5062         mutex_unlock(&dev->struct_mutex);
5063 }
5064
5065 static void haswell_crtc_disable(struct drm_crtc *crtc)
5066 {
5067         struct drm_device *dev = crtc->dev;
5068         struct drm_i915_private *dev_priv = dev->dev_private;
5069         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5070         struct intel_encoder *encoder;
5071         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5072
5073         if (WARN_ON(!intel_crtc->active))
5074                 return;
5075
5076         for_each_encoder_on_crtc(dev, crtc, encoder) {
5077                 intel_opregion_notify_encoder(encoder, false);
5078                 encoder->disable(encoder);
5079         }
5080
5081         drm_crtc_vblank_off(crtc);
5082         assert_vblank_disabled(crtc);
5083
5084         if (intel_crtc->config->has_pch_encoder)
5085                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5086                                                       false);
5087         intel_disable_pipe(intel_crtc);
5088
5089         if (intel_crtc->config->dp_encoder_is_mst)
5090                 intel_ddi_set_vc_payload_alloc(crtc, false);
5091
5092         intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
5093
5094         if (INTEL_INFO(dev)->gen == 9)
5095                 skylake_pfit_update(intel_crtc, 0);
5096         else if (INTEL_INFO(dev)->gen < 9)
5097                 ironlake_pfit_disable(intel_crtc);
5098         else
5099                 MISSING_CASE(INTEL_INFO(dev)->gen);
5100
5101         intel_ddi_disable_pipe_clock(intel_crtc);
5102
5103         if (intel_crtc->config->has_pch_encoder) {
5104                 lpt_disable_pch_transcoder(dev_priv);
5105                 intel_ddi_fdi_disable(crtc);
5106         }
5107
5108         for_each_encoder_on_crtc(dev, crtc, encoder)
5109                 if (encoder->post_disable)
5110                         encoder->post_disable(encoder);
5111
5112         intel_crtc->active = false;
5113         intel_update_watermarks(crtc);
5114
5115         mutex_lock(&dev->struct_mutex);
5116         intel_fbc_update(dev);
5117         mutex_unlock(&dev->struct_mutex);
5118
5119         if (intel_crtc_to_shared_dpll(intel_crtc))
5120                 intel_disable_shared_dpll(intel_crtc);
5121 }
5122
5123 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5124 {
5125         struct drm_device *dev = crtc->base.dev;
5126         struct drm_i915_private *dev_priv = dev->dev_private;
5127         struct intel_crtc_state *pipe_config = crtc->config;
5128
5129         if (!pipe_config->gmch_pfit.control)
5130                 return;
5131
5132         /*
5133          * The panel fitter should only be adjusted whilst the pipe is disabled,
5134          * according to register description and PRM.
5135          */
5136         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5137         assert_pipe_disabled(dev_priv, crtc->pipe);
5138
5139         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5140         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5141
5142         /* Border color in case we don't scale up to the full screen. Black by
5143          * default, change to something else for debugging. */
5144         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5145 }
5146
5147 static enum intel_display_power_domain port_to_power_domain(enum port port)
5148 {
5149         switch (port) {
5150         case PORT_A:
5151                 return POWER_DOMAIN_PORT_DDI_A_4_LANES;
5152         case PORT_B:
5153                 return POWER_DOMAIN_PORT_DDI_B_4_LANES;
5154         case PORT_C:
5155                 return POWER_DOMAIN_PORT_DDI_C_4_LANES;
5156         case PORT_D:
5157                 return POWER_DOMAIN_PORT_DDI_D_4_LANES;
5158         default:
5159                 WARN_ON_ONCE(1);
5160                 return POWER_DOMAIN_PORT_OTHER;
5161         }
5162 }
5163
5164 #define for_each_power_domain(domain, mask)                             \
5165         for ((domain) = 0; (domain) < POWER_DOMAIN_NUM; (domain)++)     \
5166                 if ((1 << (domain)) & (mask))
5167
5168 enum intel_display_power_domain
5169 intel_display_port_power_domain(struct intel_encoder *intel_encoder)
5170 {
5171         struct drm_device *dev = intel_encoder->base.dev;
5172         struct intel_digital_port *intel_dig_port;
5173
5174         switch (intel_encoder->type) {
5175         case INTEL_OUTPUT_UNKNOWN:
5176                 /* Only DDI platforms should ever use this output type */
5177                 WARN_ON_ONCE(!HAS_DDI(dev));
5178         case INTEL_OUTPUT_DISPLAYPORT:
5179         case INTEL_OUTPUT_HDMI:
5180         case INTEL_OUTPUT_EDP:
5181                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5182                 return port_to_power_domain(intel_dig_port->port);
5183         case INTEL_OUTPUT_DP_MST:
5184                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5185                 return port_to_power_domain(intel_dig_port->port);
5186         case INTEL_OUTPUT_ANALOG:
5187                 return POWER_DOMAIN_PORT_CRT;
5188         case INTEL_OUTPUT_DSI:
5189                 return POWER_DOMAIN_PORT_DSI;
5190         default:
5191                 return POWER_DOMAIN_PORT_OTHER;
5192         }
5193 }
5194
5195 static unsigned long get_crtc_power_domains(struct drm_crtc *crtc)
5196 {
5197         struct drm_device *dev = crtc->dev;
5198         struct intel_encoder *intel_encoder;
5199         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5200         enum pipe pipe = intel_crtc->pipe;
5201         unsigned long mask;
5202         enum transcoder transcoder;
5203
5204         transcoder = intel_pipe_to_cpu_transcoder(dev->dev_private, pipe);
5205
5206         mask = BIT(POWER_DOMAIN_PIPE(pipe));
5207         mask |= BIT(POWER_DOMAIN_TRANSCODER(transcoder));
5208         if (intel_crtc->config->pch_pfit.enabled ||
5209             intel_crtc->config->pch_pfit.force_thru)
5210                 mask |= BIT(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5211
5212         for_each_encoder_on_crtc(dev, crtc, intel_encoder)
5213                 mask |= BIT(intel_display_port_power_domain(intel_encoder));
5214
5215         return mask;
5216 }
5217
5218 static void modeset_update_crtc_power_domains(struct drm_atomic_state *state)
5219 {
5220         struct drm_device *dev = state->dev;
5221         struct drm_i915_private *dev_priv = dev->dev_private;
5222         unsigned long pipe_domains[I915_MAX_PIPES] = { 0, };
5223         struct intel_crtc *crtc;
5224
5225         /*
5226          * First get all needed power domains, then put all unneeded, to avoid
5227          * any unnecessary toggling of the power wells.
5228          */
5229         for_each_intel_crtc(dev, crtc) {
5230                 enum intel_display_power_domain domain;
5231
5232                 if (!crtc->base.state->enable)
5233                         continue;
5234
5235                 pipe_domains[crtc->pipe] = get_crtc_power_domains(&crtc->base);
5236
5237                 for_each_power_domain(domain, pipe_domains[crtc->pipe])
5238                         intel_display_power_get(dev_priv, domain);
5239         }
5240
5241         if (dev_priv->display.modeset_global_resources)
5242                 dev_priv->display.modeset_global_resources(state);
5243
5244         for_each_intel_crtc(dev, crtc) {
5245                 enum intel_display_power_domain domain;
5246
5247                 for_each_power_domain(domain, crtc->enabled_power_domains)
5248                         intel_display_power_put(dev_priv, domain);
5249
5250                 crtc->enabled_power_domains = pipe_domains[crtc->pipe];
5251         }
5252
5253         intel_display_set_init_power(dev_priv, false);
5254 }
5255
5256 static void intel_update_max_cdclk(struct drm_device *dev)
5257 {
5258         struct drm_i915_private *dev_priv = dev->dev_private;
5259
5260         if (IS_SKYLAKE(dev)) {
5261                 u32 limit = I915_READ(SKL_DFSM) & SKL_DFSM_CDCLK_LIMIT_MASK;
5262
5263                 if (limit == SKL_DFSM_CDCLK_LIMIT_675)
5264                         dev_priv->max_cdclk_freq = 675000;
5265                 else if (limit == SKL_DFSM_CDCLK_LIMIT_540)
5266                         dev_priv->max_cdclk_freq = 540000;
5267                 else if (limit == SKL_DFSM_CDCLK_LIMIT_450)
5268                         dev_priv->max_cdclk_freq = 450000;
5269                 else
5270                         dev_priv->max_cdclk_freq = 337500;
5271         } else if (IS_BROADWELL(dev))  {
5272                 /*
5273                  * FIXME with extra cooling we can allow
5274                  * 540 MHz for ULX and 675 Mhz for ULT.
5275                  * How can we know if extra cooling is
5276                  * available? PCI ID, VTB, something else?
5277                  */
5278                 if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
5279                         dev_priv->max_cdclk_freq = 450000;
5280                 else if (IS_BDW_ULX(dev))
5281                         dev_priv->max_cdclk_freq = 450000;
5282                 else if (IS_BDW_ULT(dev))
5283                         dev_priv->max_cdclk_freq = 540000;
5284                 else
5285                         dev_priv->max_cdclk_freq = 675000;
5286         } else if (IS_CHERRYVIEW(dev)) {
5287                 dev_priv->max_cdclk_freq = 320000;
5288         } else if (IS_VALLEYVIEW(dev)) {
5289                 dev_priv->max_cdclk_freq = 400000;
5290         } else {
5291                 /* otherwise assume cdclk is fixed */
5292                 dev_priv->max_cdclk_freq = dev_priv->cdclk_freq;
5293         }
5294
5295         DRM_DEBUG_DRIVER("Max CD clock rate: %d kHz\n",
5296                          dev_priv->max_cdclk_freq);
5297 }
5298
5299 static void intel_update_cdclk(struct drm_device *dev)
5300 {
5301         struct drm_i915_private *dev_priv = dev->dev_private;
5302
5303         dev_priv->cdclk_freq = dev_priv->display.get_display_clock_speed(dev);
5304         DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz\n",
5305                          dev_priv->cdclk_freq);
5306
5307         /*
5308          * Program the gmbus_freq based on the cdclk frequency.
5309          * BSpec erroneously claims we should aim for 4MHz, but
5310          * in fact 1MHz is the correct frequency.
5311          */
5312         if (IS_VALLEYVIEW(dev)) {
5313                 /*
5314                  * Program the gmbus_freq based on the cdclk frequency.
5315                  * BSpec erroneously claims we should aim for 4MHz, but
5316                  * in fact 1MHz is the correct frequency.
5317                  */
5318                 I915_WRITE(GMBUSFREQ_VLV, DIV_ROUND_UP(dev_priv->cdclk_freq, 1000));
5319         }
5320
5321         if (dev_priv->max_cdclk_freq == 0)
5322                 intel_update_max_cdclk(dev);
5323 }
5324
5325 static void broxton_set_cdclk(struct drm_device *dev, int frequency)
5326 {
5327         struct drm_i915_private *dev_priv = dev->dev_private;
5328         uint32_t divider;
5329         uint32_t ratio;
5330         uint32_t current_freq;
5331         int ret;
5332
5333         /* frequency = 19.2MHz * ratio / 2 / div{1,1.5,2,4} */
5334         switch (frequency) {
5335         case 144000:
5336                 divider = BXT_CDCLK_CD2X_DIV_SEL_4;
5337                 ratio = BXT_DE_PLL_RATIO(60);
5338                 break;
5339         case 288000:
5340                 divider = BXT_CDCLK_CD2X_DIV_SEL_2;
5341                 ratio = BXT_DE_PLL_RATIO(60);
5342                 break;
5343         case 384000:
5344                 divider = BXT_CDCLK_CD2X_DIV_SEL_1_5;
5345                 ratio = BXT_DE_PLL_RATIO(60);
5346                 break;
5347         case 576000:
5348                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5349                 ratio = BXT_DE_PLL_RATIO(60);
5350                 break;
5351         case 624000:
5352                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5353                 ratio = BXT_DE_PLL_RATIO(65);
5354                 break;
5355         case 19200:
5356                 /*
5357                  * Bypass frequency with DE PLL disabled. Init ratio, divider
5358                  * to suppress GCC warning.
5359                  */
5360                 ratio = 0;
5361                 divider = 0;
5362                 break;
5363         default:
5364                 DRM_ERROR("unsupported CDCLK freq %d", frequency);
5365
5366                 return;
5367         }
5368
5369         mutex_lock(&dev_priv->rps.hw_lock);
5370         /* Inform power controller of upcoming frequency change */
5371         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5372                                       0x80000000);
5373         mutex_unlock(&dev_priv->rps.hw_lock);
5374
5375         if (ret) {
5376                 DRM_ERROR("PCode CDCLK freq change notify failed (err %d, freq %d)\n",
5377                           ret, frequency);
5378                 return;
5379         }
5380
5381         current_freq = I915_READ(CDCLK_CTL) & CDCLK_FREQ_DECIMAL_MASK;
5382         /* convert from .1 fixpoint MHz with -1MHz offset to kHz */
5383         current_freq = current_freq * 500 + 1000;
5384
5385         /*
5386          * DE PLL has to be disabled when
5387          * - setting to 19.2MHz (bypass, PLL isn't used)
5388          * - before setting to 624MHz (PLL needs toggling)
5389          * - before setting to any frequency from 624MHz (PLL needs toggling)
5390          */
5391         if (frequency == 19200 || frequency == 624000 ||
5392             current_freq == 624000) {
5393                 I915_WRITE(BXT_DE_PLL_ENABLE, ~BXT_DE_PLL_PLL_ENABLE);
5394                 /* Timeout 200us */
5395                 if (wait_for(!(I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_LOCK),
5396                              1))
5397                         DRM_ERROR("timout waiting for DE PLL unlock\n");
5398         }
5399
5400         if (frequency != 19200) {
5401                 uint32_t val;
5402
5403                 val = I915_READ(BXT_DE_PLL_CTL);
5404                 val &= ~BXT_DE_PLL_RATIO_MASK;
5405                 val |= ratio;
5406                 I915_WRITE(BXT_DE_PLL_CTL, val);
5407
5408                 I915_WRITE(BXT_DE_PLL_ENABLE, BXT_DE_PLL_PLL_ENABLE);
5409                 /* Timeout 200us */
5410                 if (wait_for(I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_LOCK, 1))
5411                         DRM_ERROR("timeout waiting for DE PLL lock\n");
5412
5413                 val = I915_READ(CDCLK_CTL);
5414                 val &= ~BXT_CDCLK_CD2X_DIV_SEL_MASK;
5415                 val |= divider;
5416                 /*
5417                  * Disable SSA Precharge when CD clock frequency < 500 MHz,
5418                  * enable otherwise.
5419                  */
5420                 val &= ~BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5421                 if (frequency >= 500000)
5422                         val |= BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5423
5424                 val &= ~CDCLK_FREQ_DECIMAL_MASK;
5425                 /* convert from kHz to .1 fixpoint MHz with -1MHz offset */
5426                 val |= (frequency - 1000) / 500;
5427                 I915_WRITE(CDCLK_CTL, val);
5428         }
5429
5430         mutex_lock(&dev_priv->rps.hw_lock);
5431         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5432                                       DIV_ROUND_UP(frequency, 25000));
5433         mutex_unlock(&dev_priv->rps.hw_lock);
5434
5435         if (ret) {
5436                 DRM_ERROR("PCode CDCLK freq set failed, (err %d, freq %d)\n",
5437                           ret, frequency);
5438                 return;
5439         }
5440
5441         intel_update_cdclk(dev);
5442 }
5443
5444 void broxton_init_cdclk(struct drm_device *dev)
5445 {
5446         struct drm_i915_private *dev_priv = dev->dev_private;
5447         uint32_t val;
5448
5449         /*
5450          * NDE_RSTWRN_OPT RST PCH Handshake En must always be 0b on BXT
5451          * or else the reset will hang because there is no PCH to respond.
5452          * Move the handshake programming to initialization sequence.
5453          * Previously was left up to BIOS.
5454          */
5455         val = I915_READ(HSW_NDE_RSTWRN_OPT);
5456         val &= ~RESET_PCH_HANDSHAKE_ENABLE;
5457         I915_WRITE(HSW_NDE_RSTWRN_OPT, val);
5458
5459         /* Enable PG1 for cdclk */
5460         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
5461
5462         /* check if cd clock is enabled */
5463         if (I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_PLL_ENABLE) {
5464                 DRM_DEBUG_KMS("Display already initialized\n");
5465                 return;
5466         }
5467
5468         /*
5469          * FIXME:
5470          * - The initial CDCLK needs to be read from VBT.
5471          *   Need to make this change after VBT has changes for BXT.
5472          * - check if setting the max (or any) cdclk freq is really necessary
5473          *   here, it belongs to modeset time
5474          */
5475         broxton_set_cdclk(dev, 624000);
5476
5477         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) | DBUF_POWER_REQUEST);
5478         POSTING_READ(DBUF_CTL);
5479
5480         udelay(10);
5481
5482         if (!(I915_READ(DBUF_CTL) & DBUF_POWER_STATE))
5483                 DRM_ERROR("DBuf power enable timeout!\n");
5484 }
5485
5486 void broxton_uninit_cdclk(struct drm_device *dev)
5487 {
5488         struct drm_i915_private *dev_priv = dev->dev_private;
5489
5490         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) & ~DBUF_POWER_REQUEST);
5491         POSTING_READ(DBUF_CTL);
5492
5493         udelay(10);
5494
5495         if (I915_READ(DBUF_CTL) & DBUF_POWER_STATE)
5496                 DRM_ERROR("DBuf power disable timeout!\n");
5497
5498         /* Set minimum (bypass) frequency, in effect turning off the DE PLL */
5499         broxton_set_cdclk(dev, 19200);
5500
5501         intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS);
5502 }
5503
5504 static const struct skl_cdclk_entry {
5505         unsigned int freq;
5506         unsigned int vco;
5507 } skl_cdclk_frequencies[] = {
5508         { .freq = 308570, .vco = 8640 },
5509         { .freq = 337500, .vco = 8100 },
5510         { .freq = 432000, .vco = 8640 },
5511         { .freq = 450000, .vco = 8100 },
5512         { .freq = 540000, .vco = 8100 },
5513         { .freq = 617140, .vco = 8640 },
5514         { .freq = 675000, .vco = 8100 },
5515 };
5516
5517 static unsigned int skl_cdclk_decimal(unsigned int freq)
5518 {
5519         return (freq - 1000) / 500;
5520 }
5521
5522 static unsigned int skl_cdclk_get_vco(unsigned int freq)
5523 {
5524         unsigned int i;
5525
5526         for (i = 0; i < ARRAY_SIZE(skl_cdclk_frequencies); i++) {
5527                 const struct skl_cdclk_entry *e = &skl_cdclk_frequencies[i];
5528
5529                 if (e->freq == freq)
5530                         return e->vco;
5531         }
5532
5533         return 8100;
5534 }
5535
5536 static void
5537 skl_dpll0_enable(struct drm_i915_private *dev_priv, unsigned int required_vco)
5538 {
5539         unsigned int min_freq;
5540         u32 val;
5541
5542         /* select the minimum CDCLK before enabling DPLL 0 */
5543         val = I915_READ(CDCLK_CTL);
5544         val &= ~CDCLK_FREQ_SEL_MASK | ~CDCLK_FREQ_DECIMAL_MASK;
5545         val |= CDCLK_FREQ_337_308;
5546
5547         if (required_vco == 8640)
5548                 min_freq = 308570;
5549         else
5550                 min_freq = 337500;
5551
5552         val = CDCLK_FREQ_337_308 | skl_cdclk_decimal(min_freq);
5553
5554         I915_WRITE(CDCLK_CTL, val);
5555         POSTING_READ(CDCLK_CTL);
5556
5557         /*
5558          * We always enable DPLL0 with the lowest link rate possible, but still
5559          * taking into account the VCO required to operate the eDP panel at the
5560          * desired frequency. The usual DP link rates operate with a VCO of
5561          * 8100 while the eDP 1.4 alternate link rates need a VCO of 8640.
5562          * The modeset code is responsible for the selection of the exact link
5563          * rate later on, with the constraint of choosing a frequency that
5564          * works with required_vco.
5565          */
5566         val = I915_READ(DPLL_CTRL1);
5567
5568         val &= ~(DPLL_CTRL1_HDMI_MODE(SKL_DPLL0) | DPLL_CTRL1_SSC(SKL_DPLL0) |
5569                  DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0));
5570         val |= DPLL_CTRL1_OVERRIDE(SKL_DPLL0);
5571         if (required_vco == 8640)
5572                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1080,
5573                                             SKL_DPLL0);
5574         else
5575                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_810,
5576                                             SKL_DPLL0);
5577
5578         I915_WRITE(DPLL_CTRL1, val);
5579         POSTING_READ(DPLL_CTRL1);
5580
5581         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) | LCPLL_PLL_ENABLE);
5582
5583         if (wait_for(I915_READ(LCPLL1_CTL) & LCPLL_PLL_LOCK, 5))
5584                 DRM_ERROR("DPLL0 not locked\n");
5585 }
5586
5587 static bool skl_cdclk_pcu_ready(struct drm_i915_private *dev_priv)
5588 {
5589         int ret;
5590         u32 val;
5591
5592         /* inform PCU we want to change CDCLK */
5593         val = SKL_CDCLK_PREPARE_FOR_CHANGE;
5594         mutex_lock(&dev_priv->rps.hw_lock);
5595         ret = sandybridge_pcode_read(dev_priv, SKL_PCODE_CDCLK_CONTROL, &val);
5596         mutex_unlock(&dev_priv->rps.hw_lock);
5597
5598         return ret == 0 && (val & SKL_CDCLK_READY_FOR_CHANGE);
5599 }
5600
5601 static bool skl_cdclk_wait_for_pcu_ready(struct drm_i915_private *dev_priv)
5602 {
5603         unsigned int i;
5604
5605         for (i = 0; i < 15; i++) {
5606                 if (skl_cdclk_pcu_ready(dev_priv))
5607                         return true;
5608                 udelay(10);
5609         }
5610
5611         return false;
5612 }
5613
5614 static void skl_set_cdclk(struct drm_i915_private *dev_priv, unsigned int freq)
5615 {
5616         struct drm_device *dev = dev_priv->dev;
5617         u32 freq_select, pcu_ack;
5618
5619         DRM_DEBUG_DRIVER("Changing CDCLK to %dKHz\n", freq);
5620
5621         if (!skl_cdclk_wait_for_pcu_ready(dev_priv)) {
5622                 DRM_ERROR("failed to inform PCU about cdclk change\n");
5623                 return;
5624         }
5625
5626         /* set CDCLK_CTL */
5627         switch(freq) {
5628         case 450000:
5629         case 432000:
5630                 freq_select = CDCLK_FREQ_450_432;
5631                 pcu_ack = 1;
5632                 break;
5633         case 540000:
5634                 freq_select = CDCLK_FREQ_540;
5635                 pcu_ack = 2;
5636                 break;
5637         case 308570:
5638         case 337500:
5639         default:
5640                 freq_select = CDCLK_FREQ_337_308;
5641                 pcu_ack = 0;
5642                 break;
5643         case 617140:
5644         case 675000:
5645                 freq_select = CDCLK_FREQ_675_617;
5646                 pcu_ack = 3;
5647                 break;
5648         }
5649
5650         I915_WRITE(CDCLK_CTL, freq_select | skl_cdclk_decimal(freq));
5651         POSTING_READ(CDCLK_CTL);
5652
5653         /* inform PCU of the change */
5654         mutex_lock(&dev_priv->rps.hw_lock);
5655         sandybridge_pcode_write(dev_priv, SKL_PCODE_CDCLK_CONTROL, pcu_ack);
5656         mutex_unlock(&dev_priv->rps.hw_lock);
5657
5658         intel_update_cdclk(dev);
5659 }
5660
5661 void skl_uninit_cdclk(struct drm_i915_private *dev_priv)
5662 {
5663         /* disable DBUF power */
5664         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) & ~DBUF_POWER_REQUEST);
5665         POSTING_READ(DBUF_CTL);
5666
5667         udelay(10);
5668
5669         if (I915_READ(DBUF_CTL) & DBUF_POWER_STATE)
5670                 DRM_ERROR("DBuf power disable timeout\n");
5671
5672         /* disable DPLL0 */
5673         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) & ~LCPLL_PLL_ENABLE);
5674         if (wait_for(!(I915_READ(LCPLL1_CTL) & LCPLL_PLL_LOCK), 1))
5675                 DRM_ERROR("Couldn't disable DPLL0\n");
5676
5677         intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS);
5678 }
5679
5680 void skl_init_cdclk(struct drm_i915_private *dev_priv)
5681 {
5682         u32 val;
5683         unsigned int required_vco;
5684
5685         /* enable PCH reset handshake */
5686         val = I915_READ(HSW_NDE_RSTWRN_OPT);
5687         I915_WRITE(HSW_NDE_RSTWRN_OPT, val | RESET_PCH_HANDSHAKE_ENABLE);
5688
5689         /* enable PG1 and Misc I/O */
5690         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
5691
5692         /* DPLL0 already enabed !? */
5693         if (I915_READ(LCPLL1_CTL) & LCPLL_PLL_ENABLE) {
5694                 DRM_DEBUG_DRIVER("DPLL0 already running\n");
5695                 return;
5696         }
5697
5698         /* enable DPLL0 */
5699         required_vco = skl_cdclk_get_vco(dev_priv->skl_boot_cdclk);
5700         skl_dpll0_enable(dev_priv, required_vco);
5701
5702         /* set CDCLK to the frequency the BIOS chose */
5703         skl_set_cdclk(dev_priv, dev_priv->skl_boot_cdclk);
5704
5705         /* enable DBUF power */
5706         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) | DBUF_POWER_REQUEST);
5707         POSTING_READ(DBUF_CTL);
5708
5709         udelay(10);
5710
5711         if (!(I915_READ(DBUF_CTL) & DBUF_POWER_STATE))
5712                 DRM_ERROR("DBuf power enable timeout\n");
5713 }
5714
5715 /* returns HPLL frequency in kHz */
5716 static int valleyview_get_vco(struct drm_i915_private *dev_priv)
5717 {
5718         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
5719
5720         /* Obtain SKU information */
5721         mutex_lock(&dev_priv->sb_lock);
5722         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
5723                 CCK_FUSE_HPLL_FREQ_MASK;
5724         mutex_unlock(&dev_priv->sb_lock);
5725
5726         return vco_freq[hpll_freq] * 1000;
5727 }
5728
5729 /* Adjust CDclk dividers to allow high res or save power if possible */
5730 static void valleyview_set_cdclk(struct drm_device *dev, int cdclk)
5731 {
5732         struct drm_i915_private *dev_priv = dev->dev_private;
5733         u32 val, cmd;
5734
5735         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5736                                         != dev_priv->cdclk_freq);
5737
5738         if (cdclk >= 320000) /* jump to highest voltage for 400MHz too */
5739                 cmd = 2;
5740         else if (cdclk == 266667)
5741                 cmd = 1;
5742         else
5743                 cmd = 0;
5744
5745         mutex_lock(&dev_priv->rps.hw_lock);
5746         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5747         val &= ~DSPFREQGUAR_MASK;
5748         val |= (cmd << DSPFREQGUAR_SHIFT);
5749         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5750         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5751                       DSPFREQSTAT_MASK) == (cmd << DSPFREQSTAT_SHIFT),
5752                      50)) {
5753                 DRM_ERROR("timed out waiting for CDclk change\n");
5754         }
5755         mutex_unlock(&dev_priv->rps.hw_lock);
5756
5757         mutex_lock(&dev_priv->sb_lock);
5758
5759         if (cdclk == 400000) {
5760                 u32 divider;
5761
5762                 divider = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5763
5764                 /* adjust cdclk divider */
5765                 val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
5766                 val &= ~DISPLAY_FREQUENCY_VALUES;
5767                 val |= divider;
5768                 vlv_cck_write(dev_priv, CCK_DISPLAY_CLOCK_CONTROL, val);
5769
5770                 if (wait_for((vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL) &
5771                               DISPLAY_FREQUENCY_STATUS) == (divider << DISPLAY_FREQUENCY_STATUS_SHIFT),
5772                              50))
5773                         DRM_ERROR("timed out waiting for CDclk change\n");
5774         }
5775
5776         /* adjust self-refresh exit latency value */
5777         val = vlv_bunit_read(dev_priv, BUNIT_REG_BISOC);
5778         val &= ~0x7f;
5779
5780         /*
5781          * For high bandwidth configs, we set a higher latency in the bunit
5782          * so that the core display fetch happens in time to avoid underruns.
5783          */
5784         if (cdclk == 400000)
5785                 val |= 4500 / 250; /* 4.5 usec */
5786         else
5787                 val |= 3000 / 250; /* 3.0 usec */
5788         vlv_bunit_write(dev_priv, BUNIT_REG_BISOC, val);
5789
5790         mutex_unlock(&dev_priv->sb_lock);
5791
5792         intel_update_cdclk(dev);
5793 }
5794
5795 static void cherryview_set_cdclk(struct drm_device *dev, int cdclk)
5796 {
5797         struct drm_i915_private *dev_priv = dev->dev_private;
5798         u32 val, cmd;
5799
5800         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5801                                                 != dev_priv->cdclk_freq);
5802
5803         switch (cdclk) {
5804         case 333333:
5805         case 320000:
5806         case 266667:
5807         case 200000:
5808                 break;
5809         default:
5810                 MISSING_CASE(cdclk);
5811                 return;
5812         }
5813
5814         /*
5815          * Specs are full of misinformation, but testing on actual
5816          * hardware has shown that we just need to write the desired
5817          * CCK divider into the Punit register.
5818          */
5819         cmd = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5820
5821         mutex_lock(&dev_priv->rps.hw_lock);
5822         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5823         val &= ~DSPFREQGUAR_MASK_CHV;
5824         val |= (cmd << DSPFREQGUAR_SHIFT_CHV);
5825         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5826         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5827                       DSPFREQSTAT_MASK_CHV) == (cmd << DSPFREQSTAT_SHIFT_CHV),
5828                      50)) {
5829                 DRM_ERROR("timed out waiting for CDclk change\n");
5830         }
5831         mutex_unlock(&dev_priv->rps.hw_lock);
5832
5833         intel_update_cdclk(dev);
5834 }
5835
5836 static int valleyview_calc_cdclk(struct drm_i915_private *dev_priv,
5837                                  int max_pixclk)
5838 {
5839         int freq_320 = (dev_priv->hpll_freq <<  1) % 320000 != 0 ? 333333 : 320000;
5840         int limit = IS_CHERRYVIEW(dev_priv) ? 95 : 90;
5841
5842         /*
5843          * Really only a few cases to deal with, as only 4 CDclks are supported:
5844          *   200MHz
5845          *   267MHz
5846          *   320/333MHz (depends on HPLL freq)
5847          *   400MHz (VLV only)
5848          * So we check to see whether we're above 90% (VLV) or 95% (CHV)
5849          * of the lower bin and adjust if needed.
5850          *
5851          * We seem to get an unstable or solid color picture at 200MHz.
5852          * Not sure what's wrong. For now use 200MHz only when all pipes
5853          * are off.
5854          */
5855         if (!IS_CHERRYVIEW(dev_priv) &&
5856             max_pixclk > freq_320*limit/100)
5857                 return 400000;
5858         else if (max_pixclk > 266667*limit/100)
5859                 return freq_320;
5860         else if (max_pixclk > 0)
5861                 return 266667;
5862         else
5863                 return 200000;
5864 }
5865
5866 static int broxton_calc_cdclk(struct drm_i915_private *dev_priv,
5867                               int max_pixclk)
5868 {
5869         /*
5870          * FIXME:
5871          * - remove the guardband, it's not needed on BXT
5872          * - set 19.2MHz bypass frequency if there are no active pipes
5873          */
5874         if (max_pixclk > 576000*9/10)
5875                 return 624000;
5876         else if (max_pixclk > 384000*9/10)
5877                 return 576000;
5878         else if (max_pixclk > 288000*9/10)
5879                 return 384000;
5880         else if (max_pixclk > 144000*9/10)
5881                 return 288000;
5882         else
5883                 return 144000;
5884 }
5885
5886 /* Compute the max pixel clock for new configuration. Uses atomic state if
5887  * that's non-NULL, look at current state otherwise. */
5888 static int intel_mode_max_pixclk(struct drm_device *dev,
5889                                  struct drm_atomic_state *state)
5890 {
5891         struct intel_crtc *intel_crtc;
5892         struct intel_crtc_state *crtc_state;
5893         int max_pixclk = 0;
5894
5895         for_each_intel_crtc(dev, intel_crtc) {
5896                 if (state)
5897                         crtc_state =
5898                                 intel_atomic_get_crtc_state(state, intel_crtc);
5899                 else
5900                         crtc_state = intel_crtc->config;
5901                 if (IS_ERR(crtc_state))
5902                         return PTR_ERR(crtc_state);
5903
5904                 if (!crtc_state->base.enable)
5905                         continue;
5906
5907                 max_pixclk = max(max_pixclk,
5908                                  crtc_state->base.adjusted_mode.crtc_clock);
5909         }
5910
5911         return max_pixclk;
5912 }
5913
5914 static int valleyview_modeset_global_pipes(struct drm_atomic_state *state)
5915 {
5916         struct drm_i915_private *dev_priv = to_i915(state->dev);
5917         struct drm_crtc *crtc;
5918         struct drm_crtc_state *crtc_state;
5919         int max_pixclk = intel_mode_max_pixclk(state->dev, state);
5920         int cdclk, ret = 0;
5921
5922         if (max_pixclk < 0)
5923                 return max_pixclk;
5924
5925         if (IS_VALLEYVIEW(dev_priv))
5926                 cdclk = valleyview_calc_cdclk(dev_priv, max_pixclk);
5927         else
5928                 cdclk = broxton_calc_cdclk(dev_priv, max_pixclk);
5929
5930         if (cdclk == dev_priv->cdclk_freq)
5931                 return 0;
5932
5933         /* add all active pipes to the state */
5934         for_each_crtc(state->dev, crtc) {
5935                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
5936                 if (IS_ERR(crtc_state))
5937                         return PTR_ERR(crtc_state);
5938
5939                 if (!crtc_state->active || needs_modeset(crtc_state))
5940                         continue;
5941
5942                 crtc_state->mode_changed = true;
5943
5944                 ret = drm_atomic_add_affected_connectors(state, crtc);
5945                 if (ret)
5946                         break;
5947
5948                 ret = drm_atomic_add_affected_planes(state, crtc);
5949                 if (ret)
5950                         break;
5951         }
5952
5953         return ret;
5954 }
5955
5956 static void vlv_program_pfi_credits(struct drm_i915_private *dev_priv)
5957 {
5958         unsigned int credits, default_credits;
5959
5960         if (IS_CHERRYVIEW(dev_priv))
5961                 default_credits = PFI_CREDIT(12);
5962         else
5963                 default_credits = PFI_CREDIT(8);
5964
5965         if (DIV_ROUND_CLOSEST(dev_priv->cdclk_freq, 1000) >= dev_priv->rps.cz_freq) {
5966                 /* CHV suggested value is 31 or 63 */
5967                 if (IS_CHERRYVIEW(dev_priv))
5968                         credits = PFI_CREDIT_63;
5969                 else
5970                         credits = PFI_CREDIT(15);
5971         } else {
5972                 credits = default_credits;
5973         }
5974
5975         /*
5976          * WA - write default credits before re-programming
5977          * FIXME: should we also set the resend bit here?
5978          */
5979         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
5980                    default_credits);
5981
5982         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
5983                    credits | PFI_CREDIT_RESEND);
5984
5985         /*
5986          * FIXME is this guaranteed to clear
5987          * immediately or should we poll for it?
5988          */
5989         WARN_ON(I915_READ(GCI_CONTROL) & PFI_CREDIT_RESEND);
5990 }
5991
5992 static void valleyview_modeset_global_resources(struct drm_atomic_state *old_state)
5993 {
5994         struct drm_device *dev = old_state->dev;
5995         struct drm_i915_private *dev_priv = dev->dev_private;
5996         int max_pixclk = intel_mode_max_pixclk(dev, NULL);
5997         int req_cdclk;
5998
5999         /* The path in intel_mode_max_pixclk() with a NULL atomic state should
6000          * never fail. */
6001         if (WARN_ON(max_pixclk < 0))
6002                 return;
6003
6004         req_cdclk = valleyview_calc_cdclk(dev_priv, max_pixclk);
6005
6006         if (req_cdclk != dev_priv->cdclk_freq) {
6007                 /*
6008                  * FIXME: We can end up here with all power domains off, yet
6009                  * with a CDCLK frequency other than the minimum. To account
6010                  * for this take the PIPE-A power domain, which covers the HW
6011                  * blocks needed for the following programming. This can be
6012                  * removed once it's guaranteed that we get here either with
6013                  * the minimum CDCLK set, or the required power domains
6014                  * enabled.
6015                  */
6016                 intel_display_power_get(dev_priv, POWER_DOMAIN_PIPE_A);
6017
6018                 if (IS_CHERRYVIEW(dev))
6019                         cherryview_set_cdclk(dev, req_cdclk);
6020                 else
6021                         valleyview_set_cdclk(dev, req_cdclk);
6022
6023                 vlv_program_pfi_credits(dev_priv);
6024
6025                 intel_display_power_put(dev_priv, POWER_DOMAIN_PIPE_A);
6026         }
6027 }
6028
6029 static void valleyview_crtc_enable(struct drm_crtc *crtc)
6030 {
6031         struct drm_device *dev = crtc->dev;
6032         struct drm_i915_private *dev_priv = to_i915(dev);
6033         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6034         struct intel_encoder *encoder;
6035         int pipe = intel_crtc->pipe;
6036         bool is_dsi;
6037
6038         if (WARN_ON(intel_crtc->active))
6039                 return;
6040
6041         is_dsi = intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_DSI);
6042
6043         if (!is_dsi) {
6044                 if (IS_CHERRYVIEW(dev))
6045                         chv_prepare_pll(intel_crtc, intel_crtc->config);
6046                 else
6047                         vlv_prepare_pll(intel_crtc, intel_crtc->config);
6048         }
6049
6050         if (intel_crtc->config->has_dp_encoder)
6051                 intel_dp_set_m_n(intel_crtc, M1_N1);
6052
6053         intel_set_pipe_timings(intel_crtc);
6054
6055         if (IS_CHERRYVIEW(dev) && pipe == PIPE_B) {
6056                 struct drm_i915_private *dev_priv = dev->dev_private;
6057
6058                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6059                 I915_WRITE(CHV_CANVAS(pipe), 0);
6060         }
6061
6062         i9xx_set_pipeconf(intel_crtc);
6063
6064         intel_crtc->active = true;
6065
6066         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6067
6068         for_each_encoder_on_crtc(dev, crtc, encoder)
6069                 if (encoder->pre_pll_enable)
6070                         encoder->pre_pll_enable(encoder);
6071
6072         if (!is_dsi) {
6073                 if (IS_CHERRYVIEW(dev))
6074                         chv_enable_pll(intel_crtc, intel_crtc->config);
6075                 else
6076                         vlv_enable_pll(intel_crtc, intel_crtc->config);
6077         }
6078
6079         for_each_encoder_on_crtc(dev, crtc, encoder)
6080                 if (encoder->pre_enable)
6081                         encoder->pre_enable(encoder);
6082
6083         i9xx_pfit_enable(intel_crtc);
6084
6085         intel_crtc_load_lut(crtc);
6086
6087         intel_update_watermarks(crtc);
6088         intel_enable_pipe(intel_crtc);
6089
6090         assert_vblank_disabled(crtc);
6091         drm_crtc_vblank_on(crtc);
6092
6093         for_each_encoder_on_crtc(dev, crtc, encoder)
6094                 encoder->enable(encoder);
6095 }
6096
6097 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
6098 {
6099         struct drm_device *dev = crtc->base.dev;
6100         struct drm_i915_private *dev_priv = dev->dev_private;
6101
6102         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
6103         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
6104 }
6105
6106 static void i9xx_crtc_enable(struct drm_crtc *crtc)
6107 {
6108         struct drm_device *dev = crtc->dev;
6109         struct drm_i915_private *dev_priv = to_i915(dev);
6110         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6111         struct intel_encoder *encoder;
6112         int pipe = intel_crtc->pipe;
6113
6114         if (WARN_ON(intel_crtc->active))
6115                 return;
6116
6117         i9xx_set_pll_dividers(intel_crtc);
6118
6119         if (intel_crtc->config->has_dp_encoder)
6120                 intel_dp_set_m_n(intel_crtc, M1_N1);
6121
6122         intel_set_pipe_timings(intel_crtc);
6123
6124         i9xx_set_pipeconf(intel_crtc);
6125
6126         intel_crtc->active = true;
6127
6128         if (!IS_GEN2(dev))
6129                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6130
6131         for_each_encoder_on_crtc(dev, crtc, encoder)
6132                 if (encoder->pre_enable)
6133                         encoder->pre_enable(encoder);
6134
6135         i9xx_enable_pll(intel_crtc);
6136
6137         i9xx_pfit_enable(intel_crtc);
6138
6139         intel_crtc_load_lut(crtc);
6140
6141         intel_update_watermarks(crtc);
6142         intel_enable_pipe(intel_crtc);
6143
6144         assert_vblank_disabled(crtc);
6145         drm_crtc_vblank_on(crtc);
6146
6147         for_each_encoder_on_crtc(dev, crtc, encoder)
6148                 encoder->enable(encoder);
6149 }
6150
6151 static void i9xx_pfit_disable(struct intel_crtc *crtc)
6152 {
6153         struct drm_device *dev = crtc->base.dev;
6154         struct drm_i915_private *dev_priv = dev->dev_private;
6155
6156         if (!crtc->config->gmch_pfit.control)
6157                 return;
6158
6159         assert_pipe_disabled(dev_priv, crtc->pipe);
6160
6161         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
6162                          I915_READ(PFIT_CONTROL));
6163         I915_WRITE(PFIT_CONTROL, 0);
6164 }
6165
6166 static void i9xx_crtc_disable(struct drm_crtc *crtc)
6167 {
6168         struct drm_device *dev = crtc->dev;
6169         struct drm_i915_private *dev_priv = dev->dev_private;
6170         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6171         struct intel_encoder *encoder;
6172         int pipe = intel_crtc->pipe;
6173
6174         if (WARN_ON(!intel_crtc->active))
6175                 return;
6176
6177         /*
6178          * On gen2 planes are double buffered but the pipe isn't, so we must
6179          * wait for planes to fully turn off before disabling the pipe.
6180          * We also need to wait on all gmch platforms because of the
6181          * self-refresh mode constraint explained above.
6182          */
6183         intel_wait_for_vblank(dev, pipe);
6184
6185         for_each_encoder_on_crtc(dev, crtc, encoder)
6186                 encoder->disable(encoder);
6187
6188         drm_crtc_vblank_off(crtc);
6189         assert_vblank_disabled(crtc);
6190
6191         intel_disable_pipe(intel_crtc);
6192
6193         i9xx_pfit_disable(intel_crtc);
6194
6195         for_each_encoder_on_crtc(dev, crtc, encoder)
6196                 if (encoder->post_disable)
6197                         encoder->post_disable(encoder);
6198
6199         if (!intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_DSI)) {
6200                 if (IS_CHERRYVIEW(dev))
6201                         chv_disable_pll(dev_priv, pipe);
6202                 else if (IS_VALLEYVIEW(dev))
6203                         vlv_disable_pll(dev_priv, pipe);
6204                 else
6205                         i9xx_disable_pll(intel_crtc);
6206         }
6207
6208         if (!IS_GEN2(dev))
6209                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6210
6211         intel_crtc->active = false;
6212         intel_update_watermarks(crtc);
6213
6214         mutex_lock(&dev->struct_mutex);
6215         intel_fbc_update(dev);
6216         mutex_unlock(&dev->struct_mutex);
6217 }
6218
6219 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc)
6220 {
6221         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6222         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6223         enum intel_display_power_domain domain;
6224         unsigned long domains;
6225
6226         if (!intel_crtc->active)
6227                 return;
6228
6229         intel_crtc_disable_planes(crtc);
6230         dev_priv->display.crtc_disable(crtc);
6231
6232         domains = intel_crtc->enabled_power_domains;
6233         for_each_power_domain(domain, domains)
6234                 intel_display_power_put(dev_priv, domain);
6235         intel_crtc->enabled_power_domains = 0;
6236 }
6237
6238 /*
6239  * turn all crtc's off, but do not adjust state
6240  * This has to be paired with a call to intel_modeset_setup_hw_state.
6241  */
6242 void intel_display_suspend(struct drm_device *dev)
6243 {
6244         struct drm_crtc *crtc;
6245
6246         for_each_crtc(dev, crtc)
6247                 intel_crtc_disable_noatomic(crtc);
6248 }
6249
6250 /* Master function to enable/disable CRTC and corresponding power wells */
6251 int intel_crtc_control(struct drm_crtc *crtc, bool enable)
6252 {
6253         struct drm_device *dev = crtc->dev;
6254         struct drm_mode_config *config = &dev->mode_config;
6255         struct drm_modeset_acquire_ctx *ctx = config->acquire_ctx;
6256         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6257         struct intel_crtc_state *pipe_config;
6258         struct drm_atomic_state *state;
6259         int ret;
6260
6261         if (enable == intel_crtc->active)
6262                 return 0;
6263
6264         if (enable && !crtc->state->enable)
6265                 return 0;
6266
6267         /* this function should be called with drm_modeset_lock_all for now */
6268         if (WARN_ON(!ctx))
6269                 return -EIO;
6270         lockdep_assert_held(&ctx->ww_ctx);
6271
6272         state = drm_atomic_state_alloc(dev);
6273         if (WARN_ON(!state))
6274                 return -ENOMEM;
6275
6276         state->acquire_ctx = ctx;
6277         state->allow_modeset = true;
6278
6279         pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
6280         if (IS_ERR(pipe_config)) {
6281                 ret = PTR_ERR(pipe_config);
6282                 goto err;
6283         }
6284         pipe_config->base.active = enable;
6285
6286         ret = intel_set_mode(state);
6287         if (!ret)
6288                 return ret;
6289
6290 err:
6291         DRM_ERROR("Updating crtc active failed with %i\n", ret);
6292         drm_atomic_state_free(state);
6293         return ret;
6294 }
6295
6296 /**
6297  * Sets the power management mode of the pipe and plane.
6298  */
6299 void intel_crtc_update_dpms(struct drm_crtc *crtc)
6300 {
6301         struct drm_device *dev = crtc->dev;
6302         struct intel_encoder *intel_encoder;
6303         bool enable = false;
6304
6305         for_each_encoder_on_crtc(dev, crtc, intel_encoder)
6306                 enable |= intel_encoder->connectors_active;
6307
6308         intel_crtc_control(crtc, enable);
6309 }
6310
6311 void intel_encoder_destroy(struct drm_encoder *encoder)
6312 {
6313         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6314
6315         drm_encoder_cleanup(encoder);
6316         kfree(intel_encoder);
6317 }
6318
6319 /* Simple dpms helper for encoders with just one connector, no cloning and only
6320  * one kind of off state. It clamps all !ON modes to fully OFF and changes the
6321  * state of the entire output pipe. */
6322 static void intel_encoder_dpms(struct intel_encoder *encoder, int mode)
6323 {
6324         if (mode == DRM_MODE_DPMS_ON) {
6325                 encoder->connectors_active = true;
6326
6327                 intel_crtc_update_dpms(encoder->base.crtc);
6328         } else {
6329                 encoder->connectors_active = false;
6330
6331                 intel_crtc_update_dpms(encoder->base.crtc);
6332         }
6333 }
6334
6335 /* Cross check the actual hw state with our own modeset state tracking (and it's
6336  * internal consistency). */
6337 static void intel_connector_check_state(struct intel_connector *connector)
6338 {
6339         if (connector->get_hw_state(connector)) {
6340                 struct intel_encoder *encoder = connector->encoder;
6341                 struct drm_crtc *crtc;
6342                 bool encoder_enabled;
6343                 enum pipe pipe;
6344
6345                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6346                               connector->base.base.id,
6347                               connector->base.name);
6348
6349                 /* there is no real hw state for MST connectors */
6350                 if (connector->mst_port)
6351                         return;
6352
6353                 I915_STATE_WARN(connector->base.dpms == DRM_MODE_DPMS_OFF,
6354                      "wrong connector dpms state\n");
6355                 I915_STATE_WARN(connector->base.encoder != &encoder->base,
6356                      "active connector not linked to encoder\n");
6357
6358                 if (encoder) {
6359                         I915_STATE_WARN(!encoder->connectors_active,
6360                              "encoder->connectors_active not set\n");
6361
6362                         encoder_enabled = encoder->get_hw_state(encoder, &pipe);
6363                         I915_STATE_WARN(!encoder_enabled, "encoder not enabled\n");
6364                         if (I915_STATE_WARN_ON(!encoder->base.crtc))
6365                                 return;
6366
6367                         crtc = encoder->base.crtc;
6368
6369                         I915_STATE_WARN(!crtc->state->enable,
6370                                         "crtc not enabled\n");
6371                         I915_STATE_WARN(!to_intel_crtc(crtc)->active, "crtc not active\n");
6372                         I915_STATE_WARN(pipe != to_intel_crtc(crtc)->pipe,
6373                              "encoder active on the wrong pipe\n");
6374                 }
6375         }
6376 }
6377
6378 int intel_connector_init(struct intel_connector *connector)
6379 {
6380         struct drm_connector_state *connector_state;
6381
6382         connector_state = kzalloc(sizeof *connector_state, GFP_KERNEL);
6383         if (!connector_state)
6384                 return -ENOMEM;
6385
6386         connector->base.state = connector_state;
6387         return 0;
6388 }
6389
6390 struct intel_connector *intel_connector_alloc(void)
6391 {
6392         struct intel_connector *connector;
6393
6394         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6395         if (!connector)
6396                 return NULL;
6397
6398         if (intel_connector_init(connector) < 0) {
6399                 kfree(connector);
6400                 return NULL;
6401         }
6402
6403         return connector;
6404 }
6405
6406 /* Even simpler default implementation, if there's really no special case to
6407  * consider. */
6408 void intel_connector_dpms(struct drm_connector *connector, int mode)
6409 {
6410         /* All the simple cases only support two dpms states. */
6411         if (mode != DRM_MODE_DPMS_ON)
6412                 mode = DRM_MODE_DPMS_OFF;
6413
6414         if (mode == connector->dpms)
6415                 return;
6416
6417         connector->dpms = mode;
6418
6419         /* Only need to change hw state when actually enabled */
6420         if (connector->encoder)
6421                 intel_encoder_dpms(to_intel_encoder(connector->encoder), mode);
6422
6423         intel_modeset_check_state(connector->dev);
6424 }
6425
6426 /* Simple connector->get_hw_state implementation for encoders that support only
6427  * one connector and no cloning and hence the encoder state determines the state
6428  * of the connector. */
6429 bool intel_connector_get_hw_state(struct intel_connector *connector)
6430 {
6431         enum pipe pipe = 0;
6432         struct intel_encoder *encoder = connector->encoder;
6433
6434         return encoder->get_hw_state(encoder, &pipe);
6435 }
6436
6437 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6438 {
6439         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6440                 return crtc_state->fdi_lanes;
6441
6442         return 0;
6443 }
6444
6445 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6446                                      struct intel_crtc_state *pipe_config)
6447 {
6448         struct drm_atomic_state *state = pipe_config->base.state;
6449         struct intel_crtc *other_crtc;
6450         struct intel_crtc_state *other_crtc_state;
6451
6452         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6453                       pipe_name(pipe), pipe_config->fdi_lanes);
6454         if (pipe_config->fdi_lanes > 4) {
6455                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6456                               pipe_name(pipe), pipe_config->fdi_lanes);
6457                 return -EINVAL;
6458         }
6459
6460         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
6461                 if (pipe_config->fdi_lanes > 2) {
6462                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6463                                       pipe_config->fdi_lanes);
6464                         return -EINVAL;
6465                 } else {
6466                         return 0;
6467                 }
6468         }
6469
6470         if (INTEL_INFO(dev)->num_pipes == 2)
6471                 return 0;
6472
6473         /* Ivybridge 3 pipe is really complicated */
6474         switch (pipe) {
6475         case PIPE_A:
6476                 return 0;
6477         case PIPE_B:
6478                 if (pipe_config->fdi_lanes <= 2)
6479                         return 0;
6480
6481                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_C));
6482                 other_crtc_state =
6483                         intel_atomic_get_crtc_state(state, other_crtc);
6484                 if (IS_ERR(other_crtc_state))
6485                         return PTR_ERR(other_crtc_state);
6486
6487                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6488                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6489                                       pipe_name(pipe), pipe_config->fdi_lanes);
6490                         return -EINVAL;
6491                 }
6492                 return 0;
6493         case PIPE_C:
6494                 if (pipe_config->fdi_lanes > 2) {
6495                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6496                                       pipe_name(pipe), pipe_config->fdi_lanes);
6497                         return -EINVAL;
6498                 }
6499
6500                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_B));
6501                 other_crtc_state =
6502                         intel_atomic_get_crtc_state(state, other_crtc);
6503                 if (IS_ERR(other_crtc_state))
6504                         return PTR_ERR(other_crtc_state);
6505
6506                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6507                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6508                         return -EINVAL;
6509                 }
6510                 return 0;
6511         default:
6512                 BUG();
6513         }
6514 }
6515
6516 #define RETRY 1
6517 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6518                                        struct intel_crtc_state *pipe_config)
6519 {
6520         struct drm_device *dev = intel_crtc->base.dev;
6521         struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6522         int lane, link_bw, fdi_dotclock, ret;
6523         bool needs_recompute = false;
6524
6525 retry:
6526         /* FDI is a binary signal running at ~2.7GHz, encoding
6527          * each output octet as 10 bits. The actual frequency
6528          * is stored as a divider into a 100MHz clock, and the
6529          * mode pixel clock is stored in units of 1KHz.
6530          * Hence the bw of each lane in terms of the mode signal
6531          * is:
6532          */
6533         link_bw = intel_fdi_link_freq(dev) * MHz(100)/KHz(1)/10;
6534
6535         fdi_dotclock = adjusted_mode->crtc_clock;
6536
6537         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6538                                            pipe_config->pipe_bpp);
6539
6540         pipe_config->fdi_lanes = lane;
6541
6542         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6543                                link_bw, &pipe_config->fdi_m_n);
6544
6545         ret = ironlake_check_fdi_lanes(intel_crtc->base.dev,
6546                                        intel_crtc->pipe, pipe_config);
6547         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6548                 pipe_config->pipe_bpp -= 2*3;
6549                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6550                               pipe_config->pipe_bpp);
6551                 needs_recompute = true;
6552                 pipe_config->bw_constrained = true;
6553
6554                 goto retry;
6555         }
6556
6557         if (needs_recompute)
6558                 return RETRY;
6559
6560         return ret;
6561 }
6562
6563 static bool pipe_config_supports_ips(struct drm_i915_private *dev_priv,
6564                                      struct intel_crtc_state *pipe_config)
6565 {
6566         if (pipe_config->pipe_bpp > 24)
6567                 return false;
6568
6569         /* HSW can handle pixel rate up to cdclk? */
6570         if (IS_HASWELL(dev_priv->dev))
6571                 return true;
6572
6573         /*
6574          * We compare against max which means we must take
6575          * the increased cdclk requirement into account when
6576          * calculating the new cdclk.
6577          *
6578          * Should measure whether using a lower cdclk w/o IPS
6579          */
6580         return ilk_pipe_pixel_rate(pipe_config) <=
6581                 dev_priv->max_cdclk_freq * 95 / 100;
6582 }
6583
6584 static void hsw_compute_ips_config(struct intel_crtc *crtc,
6585                                    struct intel_crtc_state *pipe_config)
6586 {
6587         struct drm_device *dev = crtc->base.dev;
6588         struct drm_i915_private *dev_priv = dev->dev_private;
6589
6590         pipe_config->ips_enabled = i915.enable_ips &&
6591                 hsw_crtc_supports_ips(crtc) &&
6592                 pipe_config_supports_ips(dev_priv, pipe_config);
6593 }
6594
6595 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6596                                      struct intel_crtc_state *pipe_config)
6597 {
6598         struct drm_device *dev = crtc->base.dev;
6599         struct drm_i915_private *dev_priv = dev->dev_private;
6600         struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6601
6602         /* FIXME should check pixel clock limits on all platforms */
6603         if (INTEL_INFO(dev)->gen < 4) {
6604                 int clock_limit = dev_priv->max_cdclk_freq;
6605
6606                 /*
6607                  * Enable pixel doubling when the dot clock
6608                  * is > 90% of the (display) core speed.
6609                  *
6610                  * GDG double wide on either pipe,
6611                  * otherwise pipe A only.
6612                  */
6613                 if ((crtc->pipe == PIPE_A || IS_I915G(dev)) &&
6614                     adjusted_mode->crtc_clock > clock_limit * 9 / 10) {
6615                         clock_limit *= 2;
6616                         pipe_config->double_wide = true;
6617                 }
6618
6619                 if (adjusted_mode->crtc_clock > clock_limit * 9 / 10)
6620                         return -EINVAL;
6621         }
6622
6623         /*
6624          * Pipe horizontal size must be even in:
6625          * - DVO ganged mode
6626          * - LVDS dual channel mode
6627          * - Double wide pipe
6628          */
6629         if ((intel_pipe_will_have_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6630              intel_is_dual_link_lvds(dev)) || pipe_config->double_wide)
6631                 pipe_config->pipe_src_w &= ~1;
6632
6633         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6634          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6635          */
6636         if ((INTEL_INFO(dev)->gen > 4 || IS_G4X(dev)) &&
6637                 adjusted_mode->hsync_start == adjusted_mode->hdisplay)
6638                 return -EINVAL;
6639
6640         if (HAS_IPS(dev))
6641                 hsw_compute_ips_config(crtc, pipe_config);
6642
6643         if (pipe_config->has_pch_encoder)
6644                 return ironlake_fdi_compute_config(crtc, pipe_config);
6645
6646         return 0;
6647 }
6648
6649 static int skylake_get_display_clock_speed(struct drm_device *dev)
6650 {
6651         struct drm_i915_private *dev_priv = to_i915(dev);
6652         uint32_t lcpll1 = I915_READ(LCPLL1_CTL);
6653         uint32_t cdctl = I915_READ(CDCLK_CTL);
6654         uint32_t linkrate;
6655
6656         if (!(lcpll1 & LCPLL_PLL_ENABLE))
6657                 return 24000; /* 24MHz is the cd freq with NSSC ref */
6658
6659         if ((cdctl & CDCLK_FREQ_SEL_MASK) == CDCLK_FREQ_540)
6660                 return 540000;
6661
6662         linkrate = (I915_READ(DPLL_CTRL1) &
6663                     DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0)) >> 1;
6664
6665         if (linkrate == DPLL_CTRL1_LINK_RATE_2160 ||
6666             linkrate == DPLL_CTRL1_LINK_RATE_1080) {
6667                 /* vco 8640 */
6668                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6669                 case CDCLK_FREQ_450_432:
6670                         return 432000;
6671                 case CDCLK_FREQ_337_308:
6672                         return 308570;
6673                 case CDCLK_FREQ_675_617:
6674                         return 617140;
6675                 default:
6676                         WARN(1, "Unknown cd freq selection\n");
6677                 }
6678         } else {
6679                 /* vco 8100 */
6680                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6681                 case CDCLK_FREQ_450_432:
6682                         return 450000;
6683                 case CDCLK_FREQ_337_308:
6684                         return 337500;
6685                 case CDCLK_FREQ_675_617:
6686                         return 675000;
6687                 default:
6688                         WARN(1, "Unknown cd freq selection\n");
6689                 }
6690         }
6691
6692         /* error case, do as if DPLL0 isn't enabled */
6693         return 24000;
6694 }
6695
6696 static int broadwell_get_display_clock_speed(struct drm_device *dev)
6697 {
6698         struct drm_i915_private *dev_priv = dev->dev_private;
6699         uint32_t lcpll = I915_READ(LCPLL_CTL);
6700         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6701
6702         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6703                 return 800000;
6704         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6705                 return 450000;
6706         else if (freq == LCPLL_CLK_FREQ_450)
6707                 return 450000;
6708         else if (freq == LCPLL_CLK_FREQ_54O_BDW)
6709                 return 540000;
6710         else if (freq == LCPLL_CLK_FREQ_337_5_BDW)
6711                 return 337500;
6712         else
6713                 return 675000;
6714 }
6715
6716 static int haswell_get_display_clock_speed(struct drm_device *dev)
6717 {
6718         struct drm_i915_private *dev_priv = dev->dev_private;
6719         uint32_t lcpll = I915_READ(LCPLL_CTL);
6720         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6721
6722         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6723                 return 800000;
6724         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6725                 return 450000;
6726         else if (freq == LCPLL_CLK_FREQ_450)
6727                 return 450000;
6728         else if (IS_HSW_ULT(dev))
6729                 return 337500;
6730         else
6731                 return 540000;
6732 }
6733
6734 static int valleyview_get_display_clock_speed(struct drm_device *dev)
6735 {
6736         struct drm_i915_private *dev_priv = dev->dev_private;
6737         u32 val;
6738         int divider;
6739
6740         if (dev_priv->hpll_freq == 0)
6741                 dev_priv->hpll_freq = valleyview_get_vco(dev_priv);
6742
6743         mutex_lock(&dev_priv->sb_lock);
6744         val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
6745         mutex_unlock(&dev_priv->sb_lock);
6746
6747         divider = val & DISPLAY_FREQUENCY_VALUES;
6748
6749         WARN((val & DISPLAY_FREQUENCY_STATUS) !=
6750              (divider << DISPLAY_FREQUENCY_STATUS_SHIFT),
6751              "cdclk change in progress\n");
6752
6753         return DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, divider + 1);
6754 }
6755
6756 static int ilk_get_display_clock_speed(struct drm_device *dev)
6757 {
6758         return 450000;
6759 }
6760
6761 static int i945_get_display_clock_speed(struct drm_device *dev)
6762 {
6763         return 400000;
6764 }
6765
6766 static int i915_get_display_clock_speed(struct drm_device *dev)
6767 {
6768         return 333333;
6769 }
6770
6771 static int i9xx_misc_get_display_clock_speed(struct drm_device *dev)
6772 {
6773         return 200000;
6774 }
6775
6776 static int pnv_get_display_clock_speed(struct drm_device *dev)
6777 {
6778         u16 gcfgc = 0;
6779
6780         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6781
6782         switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6783         case GC_DISPLAY_CLOCK_267_MHZ_PNV:
6784                 return 266667;
6785         case GC_DISPLAY_CLOCK_333_MHZ_PNV:
6786                 return 333333;
6787         case GC_DISPLAY_CLOCK_444_MHZ_PNV:
6788                 return 444444;
6789         case GC_DISPLAY_CLOCK_200_MHZ_PNV:
6790                 return 200000;
6791         default:
6792                 DRM_ERROR("Unknown pnv display core clock 0x%04x\n", gcfgc);
6793         case GC_DISPLAY_CLOCK_133_MHZ_PNV:
6794                 return 133333;
6795         case GC_DISPLAY_CLOCK_167_MHZ_PNV:
6796                 return 166667;
6797         }
6798 }
6799
6800 static int i915gm_get_display_clock_speed(struct drm_device *dev)
6801 {
6802         u16 gcfgc = 0;
6803
6804         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6805
6806         if (gcfgc & GC_LOW_FREQUENCY_ENABLE)
6807                 return 133333;
6808         else {
6809                 switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6810                 case GC_DISPLAY_CLOCK_333_MHZ:
6811                         return 333333;
6812                 default:
6813                 case GC_DISPLAY_CLOCK_190_200_MHZ:
6814                         return 190000;
6815                 }
6816         }
6817 }
6818
6819 static int i865_get_display_clock_speed(struct drm_device *dev)
6820 {
6821         return 266667;
6822 }
6823
6824 static int i85x_get_display_clock_speed(struct drm_device *dev)
6825 {
6826         u16 hpllcc = 0;
6827
6828         /*
6829          * 852GM/852GMV only supports 133 MHz and the HPLLCC
6830          * encoding is different :(
6831          * FIXME is this the right way to detect 852GM/852GMV?
6832          */
6833         if (dev->pdev->revision == 0x1)
6834                 return 133333;
6835
6836         pci_bus_read_config_word(dev->pdev->bus,
6837                                  PCI_DEVFN(0, 3), HPLLCC, &hpllcc);
6838
6839         /* Assume that the hardware is in the high speed state.  This
6840          * should be the default.
6841          */
6842         switch (hpllcc & GC_CLOCK_CONTROL_MASK) {
6843         case GC_CLOCK_133_200:
6844         case GC_CLOCK_133_200_2:
6845         case GC_CLOCK_100_200:
6846                 return 200000;
6847         case GC_CLOCK_166_250:
6848                 return 250000;
6849         case GC_CLOCK_100_133:
6850                 return 133333;
6851         case GC_CLOCK_133_266:
6852         case GC_CLOCK_133_266_2:
6853         case GC_CLOCK_166_266:
6854                 return 266667;
6855         }
6856
6857         /* Shouldn't happen */
6858         return 0;
6859 }
6860
6861 static int i830_get_display_clock_speed(struct drm_device *dev)
6862 {
6863         return 133333;
6864 }
6865
6866 static unsigned int intel_hpll_vco(struct drm_device *dev)
6867 {
6868         struct drm_i915_private *dev_priv = dev->dev_private;
6869         static const unsigned int blb_vco[8] = {
6870                 [0] = 3200000,
6871                 [1] = 4000000,
6872                 [2] = 5333333,
6873                 [3] = 4800000,
6874                 [4] = 6400000,
6875         };
6876         static const unsigned int pnv_vco[8] = {
6877                 [0] = 3200000,
6878                 [1] = 4000000,
6879                 [2] = 5333333,
6880                 [3] = 4800000,
6881                 [4] = 2666667,
6882         };
6883         static const unsigned int cl_vco[8] = {
6884                 [0] = 3200000,
6885                 [1] = 4000000,
6886                 [2] = 5333333,
6887                 [3] = 6400000,
6888                 [4] = 3333333,
6889                 [5] = 3566667,
6890                 [6] = 4266667,
6891         };
6892         static const unsigned int elk_vco[8] = {
6893                 [0] = 3200000,
6894                 [1] = 4000000,
6895                 [2] = 5333333,
6896                 [3] = 4800000,
6897         };
6898         static const unsigned int ctg_vco[8] = {
6899                 [0] = 3200000,
6900                 [1] = 4000000,
6901                 [2] = 5333333,
6902                 [3] = 6400000,
6903                 [4] = 2666667,
6904                 [5] = 4266667,
6905         };
6906         const unsigned int *vco_table;
6907         unsigned int vco;
6908         uint8_t tmp = 0;
6909
6910         /* FIXME other chipsets? */
6911         if (IS_GM45(dev))
6912                 vco_table = ctg_vco;
6913         else if (IS_G4X(dev))
6914                 vco_table = elk_vco;
6915         else if (IS_CRESTLINE(dev))
6916                 vco_table = cl_vco;
6917         else if (IS_PINEVIEW(dev))
6918                 vco_table = pnv_vco;
6919         else if (IS_G33(dev))
6920                 vco_table = blb_vco;
6921         else
6922                 return 0;
6923
6924         tmp = I915_READ(IS_MOBILE(dev) ? HPLLVCO_MOBILE : HPLLVCO);
6925
6926         vco = vco_table[tmp & 0x7];
6927         if (vco == 0)
6928                 DRM_ERROR("Bad HPLL VCO (HPLLVCO=0x%02x)\n", tmp);
6929         else
6930                 DRM_DEBUG_KMS("HPLL VCO %u kHz\n", vco);
6931
6932         return vco;
6933 }
6934
6935 static int gm45_get_display_clock_speed(struct drm_device *dev)
6936 {
6937         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
6938         uint16_t tmp = 0;
6939
6940         pci_read_config_word(dev->pdev, GCFGC, &tmp);
6941
6942         cdclk_sel = (tmp >> 12) & 0x1;
6943
6944         switch (vco) {
6945         case 2666667:
6946         case 4000000:
6947         case 5333333:
6948                 return cdclk_sel ? 333333 : 222222;
6949         case 3200000:
6950                 return cdclk_sel ? 320000 : 228571;
6951         default:
6952                 DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u, CFGC=0x%04x\n", vco, tmp);
6953                 return 222222;
6954         }
6955 }
6956
6957 static int i965gm_get_display_clock_speed(struct drm_device *dev)
6958 {
6959         static const uint8_t div_3200[] = { 16, 10,  8 };
6960         static const uint8_t div_4000[] = { 20, 12, 10 };
6961         static const uint8_t div_5333[] = { 24, 16, 14 };
6962         const uint8_t *div_table;
6963         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
6964         uint16_t tmp = 0;
6965
6966         pci_read_config_word(dev->pdev, GCFGC, &tmp);
6967
6968         cdclk_sel = ((tmp >> 8) & 0x1f) - 1;
6969
6970         if (cdclk_sel >= ARRAY_SIZE(div_3200))
6971                 goto fail;
6972
6973         switch (vco) {
6974         case 3200000:
6975                 div_table = div_3200;
6976                 break;
6977         case 4000000:
6978                 div_table = div_4000;
6979                 break;
6980         case 5333333:
6981                 div_table = div_5333;
6982                 break;
6983         default:
6984                 goto fail;
6985         }
6986
6987         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
6988
6989 fail:
6990         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%04x\n", vco, tmp);
6991         return 200000;
6992 }
6993
6994 static int g33_get_display_clock_speed(struct drm_device *dev)
6995 {
6996         static const uint8_t div_3200[] = { 12, 10,  8,  7, 5, 16 };
6997         static const uint8_t div_4000[] = { 14, 12, 10,  8, 6, 20 };
6998         static const uint8_t div_4800[] = { 20, 14, 12, 10, 8, 24 };
6999         static const uint8_t div_5333[] = { 20, 16, 12, 12, 8, 28 };
7000         const uint8_t *div_table;
7001         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
7002         uint16_t tmp = 0;
7003
7004         pci_read_config_word(dev->pdev, GCFGC, &tmp);
7005
7006         cdclk_sel = (tmp >> 4) & 0x7;
7007
7008         if (cdclk_sel >= ARRAY_SIZE(div_3200))
7009                 goto fail;
7010
7011         switch (vco) {
7012         case 3200000:
7013                 div_table = div_3200;
7014                 break;
7015         case 4000000:
7016                 div_table = div_4000;
7017                 break;
7018         case 4800000:
7019                 div_table = div_4800;
7020                 break;
7021         case 5333333:
7022                 div_table = div_5333;
7023                 break;
7024         default:
7025                 goto fail;
7026         }
7027
7028         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
7029
7030 fail:
7031         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%08x\n", vco, tmp);
7032         return 190476;
7033 }
7034
7035 static void
7036 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
7037 {
7038         while (*num > DATA_LINK_M_N_MASK ||
7039                *den > DATA_LINK_M_N_MASK) {
7040                 *num >>= 1;
7041                 *den >>= 1;
7042         }
7043 }
7044
7045 static void compute_m_n(unsigned int m, unsigned int n,
7046                         uint32_t *ret_m, uint32_t *ret_n)
7047 {
7048         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
7049         *ret_m = div_u64((uint64_t) m * *ret_n, n);
7050         intel_reduce_m_n_ratio(ret_m, ret_n);
7051 }
7052
7053 void
7054 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
7055                        int pixel_clock, int link_clock,
7056                        struct intel_link_m_n *m_n)
7057 {
7058         m_n->tu = 64;
7059
7060         compute_m_n(bits_per_pixel * pixel_clock,
7061                     link_clock * nlanes * 8,
7062                     &m_n->gmch_m, &m_n->gmch_n);
7063
7064         compute_m_n(pixel_clock, link_clock,
7065                     &m_n->link_m, &m_n->link_n);
7066 }
7067
7068 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
7069 {
7070         if (i915.panel_use_ssc >= 0)
7071                 return i915.panel_use_ssc != 0;
7072         return dev_priv->vbt.lvds_use_ssc
7073                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
7074 }
7075
7076 static int i9xx_get_refclk(const struct intel_crtc_state *crtc_state,
7077                            int num_connectors)
7078 {
7079         struct drm_device *dev = crtc_state->base.crtc->dev;
7080         struct drm_i915_private *dev_priv = dev->dev_private;
7081         int refclk;
7082
7083         WARN_ON(!crtc_state->base.state);
7084
7085         if (IS_VALLEYVIEW(dev) || IS_BROXTON(dev)) {
7086                 refclk = 100000;
7087         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7088             intel_panel_use_ssc(dev_priv) && num_connectors < 2) {
7089                 refclk = dev_priv->vbt.lvds_ssc_freq;
7090                 DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7091         } else if (!IS_GEN2(dev)) {
7092                 refclk = 96000;
7093         } else {
7094                 refclk = 48000;
7095         }
7096
7097         return refclk;
7098 }
7099
7100 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
7101 {
7102         return (1 << dpll->n) << 16 | dpll->m2;
7103 }
7104
7105 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
7106 {
7107         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
7108 }
7109
7110 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
7111                                      struct intel_crtc_state *crtc_state,
7112                                      intel_clock_t *reduced_clock)
7113 {
7114         struct drm_device *dev = crtc->base.dev;
7115         u32 fp, fp2 = 0;
7116
7117         if (IS_PINEVIEW(dev)) {
7118                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
7119                 if (reduced_clock)
7120                         fp2 = pnv_dpll_compute_fp(reduced_clock);
7121         } else {
7122                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
7123                 if (reduced_clock)
7124                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
7125         }
7126
7127         crtc_state->dpll_hw_state.fp0 = fp;
7128
7129         crtc->lowfreq_avail = false;
7130         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7131             reduced_clock) {
7132                 crtc_state->dpll_hw_state.fp1 = fp2;
7133                 crtc->lowfreq_avail = true;
7134         } else {
7135                 crtc_state->dpll_hw_state.fp1 = fp;
7136         }
7137 }
7138
7139 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
7140                 pipe)
7141 {
7142         u32 reg_val;
7143
7144         /*
7145          * PLLB opamp always calibrates to max value of 0x3f, force enable it
7146          * and set it to a reasonable value instead.
7147          */
7148         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7149         reg_val &= 0xffffff00;
7150         reg_val |= 0x00000030;
7151         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7152
7153         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7154         reg_val &= 0x8cffffff;
7155         reg_val = 0x8c000000;
7156         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7157
7158         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7159         reg_val &= 0xffffff00;
7160         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7161
7162         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7163         reg_val &= 0x00ffffff;
7164         reg_val |= 0xb0000000;
7165         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7166 }
7167
7168 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
7169                                          struct intel_link_m_n *m_n)
7170 {
7171         struct drm_device *dev = crtc->base.dev;
7172         struct drm_i915_private *dev_priv = dev->dev_private;
7173         int pipe = crtc->pipe;
7174
7175         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7176         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
7177         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
7178         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
7179 }
7180
7181 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
7182                                          struct intel_link_m_n *m_n,
7183                                          struct intel_link_m_n *m2_n2)
7184 {
7185         struct drm_device *dev = crtc->base.dev;
7186         struct drm_i915_private *dev_priv = dev->dev_private;
7187         int pipe = crtc->pipe;
7188         enum transcoder transcoder = crtc->config->cpu_transcoder;
7189
7190         if (INTEL_INFO(dev)->gen >= 5) {
7191                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
7192                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
7193                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
7194                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
7195                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
7196                  * for gen < 8) and if DRRS is supported (to make sure the
7197                  * registers are not unnecessarily accessed).
7198                  */
7199                 if (m2_n2 && (IS_CHERRYVIEW(dev) || INTEL_INFO(dev)->gen < 8) &&
7200                         crtc->config->has_drrs) {
7201                         I915_WRITE(PIPE_DATA_M2(transcoder),
7202                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
7203                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
7204                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
7205                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
7206                 }
7207         } else {
7208                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7209                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
7210                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
7211                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
7212         }
7213 }
7214
7215 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
7216 {
7217         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
7218
7219         if (m_n == M1_N1) {
7220                 dp_m_n = &crtc->config->dp_m_n;
7221                 dp_m2_n2 = &crtc->config->dp_m2_n2;
7222         } else if (m_n == M2_N2) {
7223
7224                 /*
7225                  * M2_N2 registers are not supported. Hence m2_n2 divider value
7226                  * needs to be programmed into M1_N1.
7227                  */
7228                 dp_m_n = &crtc->config->dp_m2_n2;
7229         } else {
7230                 DRM_ERROR("Unsupported divider value\n");
7231                 return;
7232         }
7233
7234         if (crtc->config->has_pch_encoder)
7235                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
7236         else
7237                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
7238 }
7239
7240 static void vlv_update_pll(struct intel_crtc *crtc,
7241                            struct intel_crtc_state *pipe_config)
7242 {
7243         u32 dpll, dpll_md;
7244
7245         /*
7246          * Enable DPIO clock input. We should never disable the reference
7247          * clock for pipe B, since VGA hotplug / manual detection depends
7248          * on it.
7249          */
7250         dpll = DPLL_EXT_BUFFER_ENABLE_VLV | DPLL_REFA_CLK_ENABLE_VLV |
7251                 DPLL_VGA_MODE_DIS | DPLL_INTEGRATED_CLOCK_VLV;
7252         /* We should never disable this, set it here for state tracking */
7253         if (crtc->pipe == PIPE_B)
7254                 dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7255         dpll |= DPLL_VCO_ENABLE;
7256         pipe_config->dpll_hw_state.dpll = dpll;
7257
7258         dpll_md = (pipe_config->pixel_multiplier - 1)
7259                 << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7260         pipe_config->dpll_hw_state.dpll_md = dpll_md;
7261 }
7262
7263 static void vlv_prepare_pll(struct intel_crtc *crtc,
7264                             const struct intel_crtc_state *pipe_config)
7265 {
7266         struct drm_device *dev = crtc->base.dev;
7267         struct drm_i915_private *dev_priv = dev->dev_private;
7268         int pipe = crtc->pipe;
7269         u32 mdiv;
7270         u32 bestn, bestm1, bestm2, bestp1, bestp2;
7271         u32 coreclk, reg_val;
7272
7273         mutex_lock(&dev_priv->sb_lock);
7274
7275         bestn = pipe_config->dpll.n;
7276         bestm1 = pipe_config->dpll.m1;
7277         bestm2 = pipe_config->dpll.m2;
7278         bestp1 = pipe_config->dpll.p1;
7279         bestp2 = pipe_config->dpll.p2;
7280
7281         /* See eDP HDMI DPIO driver vbios notes doc */
7282
7283         /* PLL B needs special handling */
7284         if (pipe == PIPE_B)
7285                 vlv_pllb_recal_opamp(dev_priv, pipe);
7286
7287         /* Set up Tx target for periodic Rcomp update */
7288         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
7289
7290         /* Disable target IRef on PLL */
7291         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
7292         reg_val &= 0x00ffffff;
7293         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
7294
7295         /* Disable fast lock */
7296         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
7297
7298         /* Set idtafcrecal before PLL is enabled */
7299         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
7300         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
7301         mdiv |= ((bestn << DPIO_N_SHIFT));
7302         mdiv |= (1 << DPIO_K_SHIFT);
7303
7304         /*
7305          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
7306          * but we don't support that).
7307          * Note: don't use the DAC post divider as it seems unstable.
7308          */
7309         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
7310         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7311
7312         mdiv |= DPIO_ENABLE_CALIBRATION;
7313         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7314
7315         /* Set HBR and RBR LPF coefficients */
7316         if (pipe_config->port_clock == 162000 ||
7317             intel_pipe_has_type(crtc, INTEL_OUTPUT_ANALOG) ||
7318             intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI))
7319                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7320                                  0x009f0003);
7321         else
7322                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7323                                  0x00d0000f);
7324
7325         if (pipe_config->has_dp_encoder) {
7326                 /* Use SSC source */
7327                 if (pipe == PIPE_A)
7328                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7329                                          0x0df40000);
7330                 else
7331                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7332                                          0x0df70000);
7333         } else { /* HDMI or VGA */
7334                 /* Use bend source */
7335                 if (pipe == PIPE_A)
7336                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7337                                          0x0df70000);
7338                 else
7339                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7340                                          0x0df40000);
7341         }
7342
7343         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
7344         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
7345         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DISPLAYPORT) ||
7346             intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP))
7347                 coreclk |= 0x01000000;
7348         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
7349
7350         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
7351         mutex_unlock(&dev_priv->sb_lock);
7352 }
7353
7354 static void chv_update_pll(struct intel_crtc *crtc,
7355                            struct intel_crtc_state *pipe_config)
7356 {
7357         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLOCK_CHV |
7358                 DPLL_REFA_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS |
7359                 DPLL_VCO_ENABLE;
7360         if (crtc->pipe != PIPE_A)
7361                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7362
7363         pipe_config->dpll_hw_state.dpll_md =
7364                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7365 }
7366
7367 static void chv_prepare_pll(struct intel_crtc *crtc,
7368                             const struct intel_crtc_state *pipe_config)
7369 {
7370         struct drm_device *dev = crtc->base.dev;
7371         struct drm_i915_private *dev_priv = dev->dev_private;
7372         int pipe = crtc->pipe;
7373         int dpll_reg = DPLL(crtc->pipe);
7374         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7375         u32 loopfilter, tribuf_calcntr;
7376         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
7377         u32 dpio_val;
7378         int vco;
7379
7380         bestn = pipe_config->dpll.n;
7381         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
7382         bestm1 = pipe_config->dpll.m1;
7383         bestm2 = pipe_config->dpll.m2 >> 22;
7384         bestp1 = pipe_config->dpll.p1;
7385         bestp2 = pipe_config->dpll.p2;
7386         vco = pipe_config->dpll.vco;
7387         dpio_val = 0;
7388         loopfilter = 0;
7389
7390         /*
7391          * Enable Refclk and SSC
7392          */
7393         I915_WRITE(dpll_reg,
7394                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
7395
7396         mutex_lock(&dev_priv->sb_lock);
7397
7398         /* p1 and p2 divider */
7399         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
7400                         5 << DPIO_CHV_S1_DIV_SHIFT |
7401                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
7402                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
7403                         1 << DPIO_CHV_K_DIV_SHIFT);
7404
7405         /* Feedback post-divider - m2 */
7406         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
7407
7408         /* Feedback refclk divider - n and m1 */
7409         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
7410                         DPIO_CHV_M1_DIV_BY_2 |
7411                         1 << DPIO_CHV_N_DIV_SHIFT);
7412
7413         /* M2 fraction division */
7414         if (bestm2_frac)
7415                 vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
7416
7417         /* M2 fraction division enable */
7418         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7419         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
7420         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
7421         if (bestm2_frac)
7422                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
7423         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
7424
7425         /* Program digital lock detect threshold */
7426         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
7427         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
7428                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
7429         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
7430         if (!bestm2_frac)
7431                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
7432         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
7433
7434         /* Loop filter */
7435         if (vco == 5400000) {
7436                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
7437                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
7438                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
7439                 tribuf_calcntr = 0x9;
7440         } else if (vco <= 6200000) {
7441                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
7442                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
7443                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7444                 tribuf_calcntr = 0x9;
7445         } else if (vco <= 6480000) {
7446                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7447                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7448                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7449                 tribuf_calcntr = 0x8;
7450         } else {
7451                 /* Not supported. Apply the same limits as in the max case */
7452                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7453                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7454                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7455                 tribuf_calcntr = 0;
7456         }
7457         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
7458
7459         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
7460         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
7461         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
7462         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
7463
7464         /* AFC Recal */
7465         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
7466                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
7467                         DPIO_AFC_RECAL);
7468
7469         mutex_unlock(&dev_priv->sb_lock);
7470 }
7471
7472 /**
7473  * vlv_force_pll_on - forcibly enable just the PLL
7474  * @dev_priv: i915 private structure
7475  * @pipe: pipe PLL to enable
7476  * @dpll: PLL configuration
7477  *
7478  * Enable the PLL for @pipe using the supplied @dpll config. To be used
7479  * in cases where we need the PLL enabled even when @pipe is not going to
7480  * be enabled.
7481  */
7482 void vlv_force_pll_on(struct drm_device *dev, enum pipe pipe,
7483                       const struct dpll *dpll)
7484 {
7485         struct intel_crtc *crtc =
7486                 to_intel_crtc(intel_get_crtc_for_pipe(dev, pipe));
7487         struct intel_crtc_state pipe_config = {
7488                 .base.crtc = &crtc->base,
7489                 .pixel_multiplier = 1,
7490                 .dpll = *dpll,
7491         };
7492
7493         if (IS_CHERRYVIEW(dev)) {
7494                 chv_update_pll(crtc, &pipe_config);
7495                 chv_prepare_pll(crtc, &pipe_config);
7496                 chv_enable_pll(crtc, &pipe_config);
7497         } else {
7498                 vlv_update_pll(crtc, &pipe_config);
7499                 vlv_prepare_pll(crtc, &pipe_config);
7500                 vlv_enable_pll(crtc, &pipe_config);
7501         }
7502 }
7503
7504 /**
7505  * vlv_force_pll_off - forcibly disable just the PLL
7506  * @dev_priv: i915 private structure
7507  * @pipe: pipe PLL to disable
7508  *
7509  * Disable the PLL for @pipe. To be used in cases where we need
7510  * the PLL enabled even when @pipe is not going to be enabled.
7511  */
7512 void vlv_force_pll_off(struct drm_device *dev, enum pipe pipe)
7513 {
7514         if (IS_CHERRYVIEW(dev))
7515                 chv_disable_pll(to_i915(dev), pipe);
7516         else
7517                 vlv_disable_pll(to_i915(dev), pipe);
7518 }
7519
7520 static void i9xx_update_pll(struct intel_crtc *crtc,
7521                             struct intel_crtc_state *crtc_state,
7522                             intel_clock_t *reduced_clock,
7523                             int num_connectors)
7524 {
7525         struct drm_device *dev = crtc->base.dev;
7526         struct drm_i915_private *dev_priv = dev->dev_private;
7527         u32 dpll;
7528         bool is_sdvo;
7529         struct dpll *clock = &crtc_state->dpll;
7530
7531         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7532
7533         is_sdvo = intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7534                 intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_HDMI);
7535
7536         dpll = DPLL_VGA_MODE_DIS;
7537
7538         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
7539                 dpll |= DPLLB_MODE_LVDS;
7540         else
7541                 dpll |= DPLLB_MODE_DAC_SERIAL;
7542
7543         if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
7544                 dpll |= (crtc_state->pixel_multiplier - 1)
7545                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7546         }
7547
7548         if (is_sdvo)
7549                 dpll |= DPLL_SDVO_HIGH_SPEED;
7550
7551         if (crtc_state->has_dp_encoder)
7552                 dpll |= DPLL_SDVO_HIGH_SPEED;
7553
7554         /* compute bitmask from p1 value */
7555         if (IS_PINEVIEW(dev))
7556                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7557         else {
7558                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7559                 if (IS_G4X(dev) && reduced_clock)
7560                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7561         }
7562         switch (clock->p2) {
7563         case 5:
7564                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7565                 break;
7566         case 7:
7567                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7568                 break;
7569         case 10:
7570                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7571                 break;
7572         case 14:
7573                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7574                 break;
7575         }
7576         if (INTEL_INFO(dev)->gen >= 4)
7577                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7578
7579         if (crtc_state->sdvo_tv_clock)
7580                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7581         else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7582                  intel_panel_use_ssc(dev_priv) && num_connectors < 2)
7583                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7584         else
7585                 dpll |= PLL_REF_INPUT_DREFCLK;
7586
7587         dpll |= DPLL_VCO_ENABLE;
7588         crtc_state->dpll_hw_state.dpll = dpll;
7589
7590         if (INTEL_INFO(dev)->gen >= 4) {
7591                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7592                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7593                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7594         }
7595 }
7596
7597 static void i8xx_update_pll(struct intel_crtc *crtc,
7598                             struct intel_crtc_state *crtc_state,
7599                             intel_clock_t *reduced_clock,
7600                             int num_connectors)
7601 {
7602         struct drm_device *dev = crtc->base.dev;
7603         struct drm_i915_private *dev_priv = dev->dev_private;
7604         u32 dpll;
7605         struct dpll *clock = &crtc_state->dpll;
7606
7607         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7608
7609         dpll = DPLL_VGA_MODE_DIS;
7610
7611         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7612                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7613         } else {
7614                 if (clock->p1 == 2)
7615                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7616                 else
7617                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7618                 if (clock->p2 == 4)
7619                         dpll |= PLL_P2_DIVIDE_BY_4;
7620         }
7621
7622         if (!IS_I830(dev) && intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_DVO))
7623                 dpll |= DPLL_DVO_2X_MODE;
7624
7625         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7626                  intel_panel_use_ssc(dev_priv) && num_connectors < 2)
7627                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7628         else
7629                 dpll |= PLL_REF_INPUT_DREFCLK;
7630
7631         dpll |= DPLL_VCO_ENABLE;
7632         crtc_state->dpll_hw_state.dpll = dpll;
7633 }
7634
7635 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
7636 {
7637         struct drm_device *dev = intel_crtc->base.dev;
7638         struct drm_i915_private *dev_priv = dev->dev_private;
7639         enum pipe pipe = intel_crtc->pipe;
7640         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
7641         struct drm_display_mode *adjusted_mode =
7642                 &intel_crtc->config->base.adjusted_mode;
7643         uint32_t crtc_vtotal, crtc_vblank_end;
7644         int vsyncshift = 0;
7645
7646         /* We need to be careful not to changed the adjusted mode, for otherwise
7647          * the hw state checker will get angry at the mismatch. */
7648         crtc_vtotal = adjusted_mode->crtc_vtotal;
7649         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7650
7651         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7652                 /* the chip adds 2 halflines automatically */
7653                 crtc_vtotal -= 1;
7654                 crtc_vblank_end -= 1;
7655
7656                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
7657                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7658                 else
7659                         vsyncshift = adjusted_mode->crtc_hsync_start -
7660                                 adjusted_mode->crtc_htotal / 2;
7661                 if (vsyncshift < 0)
7662                         vsyncshift += adjusted_mode->crtc_htotal;
7663         }
7664
7665         if (INTEL_INFO(dev)->gen > 3)
7666                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7667
7668         I915_WRITE(HTOTAL(cpu_transcoder),
7669                    (adjusted_mode->crtc_hdisplay - 1) |
7670                    ((adjusted_mode->crtc_htotal - 1) << 16));
7671         I915_WRITE(HBLANK(cpu_transcoder),
7672                    (adjusted_mode->crtc_hblank_start - 1) |
7673                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7674         I915_WRITE(HSYNC(cpu_transcoder),
7675                    (adjusted_mode->crtc_hsync_start - 1) |
7676                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7677
7678         I915_WRITE(VTOTAL(cpu_transcoder),
7679                    (adjusted_mode->crtc_vdisplay - 1) |
7680                    ((crtc_vtotal - 1) << 16));
7681         I915_WRITE(VBLANK(cpu_transcoder),
7682                    (adjusted_mode->crtc_vblank_start - 1) |
7683                    ((crtc_vblank_end - 1) << 16));
7684         I915_WRITE(VSYNC(cpu_transcoder),
7685                    (adjusted_mode->crtc_vsync_start - 1) |
7686                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7687
7688         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7689          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7690          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7691          * bits. */
7692         if (IS_HASWELL(dev) && cpu_transcoder == TRANSCODER_EDP &&
7693             (pipe == PIPE_B || pipe == PIPE_C))
7694                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7695
7696         /* pipesrc controls the size that is scaled from, which should
7697          * always be the user's requested size.
7698          */
7699         I915_WRITE(PIPESRC(pipe),
7700                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
7701                    (intel_crtc->config->pipe_src_h - 1));
7702 }
7703
7704 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7705                                    struct intel_crtc_state *pipe_config)
7706 {
7707         struct drm_device *dev = crtc->base.dev;
7708         struct drm_i915_private *dev_priv = dev->dev_private;
7709         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7710         uint32_t tmp;
7711
7712         tmp = I915_READ(HTOTAL(cpu_transcoder));
7713         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7714         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7715         tmp = I915_READ(HBLANK(cpu_transcoder));
7716         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7717         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7718         tmp = I915_READ(HSYNC(cpu_transcoder));
7719         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7720         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7721
7722         tmp = I915_READ(VTOTAL(cpu_transcoder));
7723         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7724         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7725         tmp = I915_READ(VBLANK(cpu_transcoder));
7726         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7727         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7728         tmp = I915_READ(VSYNC(cpu_transcoder));
7729         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7730         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7731
7732         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7733                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7734                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7735                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7736         }
7737
7738         tmp = I915_READ(PIPESRC(crtc->pipe));
7739         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7740         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7741
7742         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7743         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7744 }
7745
7746 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7747                                  struct intel_crtc_state *pipe_config)
7748 {
7749         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7750         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7751         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7752         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7753
7754         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7755         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7756         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7757         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7758
7759         mode->flags = pipe_config->base.adjusted_mode.flags;
7760
7761         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7762         mode->flags |= pipe_config->base.adjusted_mode.flags;
7763 }
7764
7765 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
7766 {
7767         struct drm_device *dev = intel_crtc->base.dev;
7768         struct drm_i915_private *dev_priv = dev->dev_private;
7769         uint32_t pipeconf;
7770
7771         pipeconf = 0;
7772
7773         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
7774             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
7775                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
7776
7777         if (intel_crtc->config->double_wide)
7778                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7779
7780         /* only g4x and later have fancy bpc/dither controls */
7781         if (IS_G4X(dev) || IS_VALLEYVIEW(dev)) {
7782                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7783                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
7784                         pipeconf |= PIPECONF_DITHER_EN |
7785                                     PIPECONF_DITHER_TYPE_SP;
7786
7787                 switch (intel_crtc->config->pipe_bpp) {
7788                 case 18:
7789                         pipeconf |= PIPECONF_6BPC;
7790                         break;
7791                 case 24:
7792                         pipeconf |= PIPECONF_8BPC;
7793                         break;
7794                 case 30:
7795                         pipeconf |= PIPECONF_10BPC;
7796                         break;
7797                 default:
7798                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7799                         BUG();
7800                 }
7801         }
7802
7803         if (HAS_PIPE_CXSR(dev)) {
7804                 if (intel_crtc->lowfreq_avail) {
7805                         DRM_DEBUG_KMS("enabling CxSR downclocking\n");
7806                         pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
7807                 } else {
7808                         DRM_DEBUG_KMS("disabling CxSR downclocking\n");
7809                 }
7810         }
7811
7812         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7813                 if (INTEL_INFO(dev)->gen < 4 ||
7814                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
7815                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7816                 else
7817                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7818         } else
7819                 pipeconf |= PIPECONF_PROGRESSIVE;
7820
7821         if (IS_VALLEYVIEW(dev) && intel_crtc->config->limited_color_range)
7822                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7823
7824         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
7825         POSTING_READ(PIPECONF(intel_crtc->pipe));
7826 }
7827
7828 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7829                                    struct intel_crtc_state *crtc_state)
7830 {
7831         struct drm_device *dev = crtc->base.dev;
7832         struct drm_i915_private *dev_priv = dev->dev_private;
7833         int refclk, num_connectors = 0;
7834         intel_clock_t clock, reduced_clock;
7835         bool ok, has_reduced_clock = false;
7836         bool is_lvds = false, is_dsi = false;
7837         struct intel_encoder *encoder;
7838         const intel_limit_t *limit;
7839         struct drm_atomic_state *state = crtc_state->base.state;
7840         struct drm_connector *connector;
7841         struct drm_connector_state *connector_state;
7842         int i;
7843
7844         memset(&crtc_state->dpll_hw_state, 0,
7845                sizeof(crtc_state->dpll_hw_state));
7846
7847         for_each_connector_in_state(state, connector, connector_state, i) {
7848                 if (connector_state->crtc != &crtc->base)
7849                         continue;
7850
7851                 encoder = to_intel_encoder(connector_state->best_encoder);
7852
7853                 switch (encoder->type) {
7854                 case INTEL_OUTPUT_LVDS:
7855                         is_lvds = true;
7856                         break;
7857                 case INTEL_OUTPUT_DSI:
7858                         is_dsi = true;
7859                         break;
7860                 default:
7861                         break;
7862                 }
7863
7864                 num_connectors++;
7865         }
7866
7867         if (is_dsi)
7868                 return 0;
7869
7870         if (!crtc_state->clock_set) {
7871                 refclk = i9xx_get_refclk(crtc_state, num_connectors);
7872
7873                 /*
7874                  * Returns a set of divisors for the desired target clock with
7875                  * the given refclk, or FALSE.  The returned values represent
7876                  * the clock equation: reflck * (5 * (m1 + 2) + (m2 + 2)) / (n +
7877                  * 2) / p1 / p2.
7878                  */
7879                 limit = intel_limit(crtc_state, refclk);
7880                 ok = dev_priv->display.find_dpll(limit, crtc_state,
7881                                                  crtc_state->port_clock,
7882                                                  refclk, NULL, &clock);
7883                 if (!ok) {
7884                         DRM_ERROR("Couldn't find PLL settings for mode!\n");
7885                         return -EINVAL;
7886                 }
7887
7888                 if (is_lvds && dev_priv->lvds_downclock_avail) {
7889                         /*
7890                          * Ensure we match the reduced clock's P to the target
7891                          * clock.  If the clocks don't match, we can't switch
7892                          * the display clock by using the FP0/FP1. In such case
7893                          * we will disable the LVDS downclock feature.
7894                          */
7895                         has_reduced_clock =
7896                                 dev_priv->display.find_dpll(limit, crtc_state,
7897                                                             dev_priv->lvds_downclock,
7898                                                             refclk, &clock,
7899                                                             &reduced_clock);
7900                 }
7901                 /* Compat-code for transition, will disappear. */
7902                 crtc_state->dpll.n = clock.n;
7903                 crtc_state->dpll.m1 = clock.m1;
7904                 crtc_state->dpll.m2 = clock.m2;
7905                 crtc_state->dpll.p1 = clock.p1;
7906                 crtc_state->dpll.p2 = clock.p2;
7907         }
7908
7909         if (IS_GEN2(dev)) {
7910                 i8xx_update_pll(crtc, crtc_state,
7911                                 has_reduced_clock ? &reduced_clock : NULL,
7912                                 num_connectors);
7913         } else if (IS_CHERRYVIEW(dev)) {
7914                 chv_update_pll(crtc, crtc_state);
7915         } else if (IS_VALLEYVIEW(dev)) {
7916                 vlv_update_pll(crtc, crtc_state);
7917         } else {
7918                 i9xx_update_pll(crtc, crtc_state,
7919                                 has_reduced_clock ? &reduced_clock : NULL,
7920                                 num_connectors);
7921         }
7922
7923         return 0;
7924 }
7925
7926 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
7927                                  struct intel_crtc_state *pipe_config)
7928 {
7929         struct drm_device *dev = crtc->base.dev;
7930         struct drm_i915_private *dev_priv = dev->dev_private;
7931         uint32_t tmp;
7932
7933         if (INTEL_INFO(dev)->gen <= 3 && (IS_I830(dev) || !IS_MOBILE(dev)))
7934                 return;
7935
7936         tmp = I915_READ(PFIT_CONTROL);
7937         if (!(tmp & PFIT_ENABLE))
7938                 return;
7939
7940         /* Check whether the pfit is attached to our pipe. */
7941         if (INTEL_INFO(dev)->gen < 4) {
7942                 if (crtc->pipe != PIPE_B)
7943                         return;
7944         } else {
7945                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
7946                         return;
7947         }
7948
7949         pipe_config->gmch_pfit.control = tmp;
7950         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
7951         if (INTEL_INFO(dev)->gen < 5)
7952                 pipe_config->gmch_pfit.lvds_border_bits =
7953                         I915_READ(LVDS) & LVDS_BORDER_ENABLE;
7954 }
7955
7956 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
7957                                struct intel_crtc_state *pipe_config)
7958 {
7959         struct drm_device *dev = crtc->base.dev;
7960         struct drm_i915_private *dev_priv = dev->dev_private;
7961         int pipe = pipe_config->cpu_transcoder;
7962         intel_clock_t clock;
7963         u32 mdiv;
7964         int refclk = 100000;
7965
7966         /* In case of MIPI DPLL will not even be used */
7967         if (!(pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE))
7968                 return;
7969
7970         mutex_lock(&dev_priv->sb_lock);
7971         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
7972         mutex_unlock(&dev_priv->sb_lock);
7973
7974         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
7975         clock.m2 = mdiv & DPIO_M2DIV_MASK;
7976         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
7977         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
7978         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
7979
7980         vlv_clock(refclk, &clock);
7981
7982         /* clock.dot is the fast clock */
7983         pipe_config->port_clock = clock.dot / 5;
7984 }
7985
7986 static void
7987 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
7988                               struct intel_initial_plane_config *plane_config)
7989 {
7990         struct drm_device *dev = crtc->base.dev;
7991         struct drm_i915_private *dev_priv = dev->dev_private;
7992         u32 val, base, offset;
7993         int pipe = crtc->pipe, plane = crtc->plane;
7994         int fourcc, pixel_format;
7995         unsigned int aligned_height;
7996         struct drm_framebuffer *fb;
7997         struct intel_framebuffer *intel_fb;
7998
7999         val = I915_READ(DSPCNTR(plane));
8000         if (!(val & DISPLAY_PLANE_ENABLE))
8001                 return;
8002
8003         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8004         if (!intel_fb) {
8005                 DRM_DEBUG_KMS("failed to alloc fb\n");
8006                 return;
8007         }
8008
8009         fb = &intel_fb->base;
8010
8011         if (INTEL_INFO(dev)->gen >= 4) {
8012                 if (val & DISPPLANE_TILED) {
8013                         plane_config->tiling = I915_TILING_X;
8014                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
8015                 }
8016         }
8017
8018         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
8019         fourcc = i9xx_format_to_fourcc(pixel_format);
8020         fb->pixel_format = fourcc;
8021         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
8022
8023         if (INTEL_INFO(dev)->gen >= 4) {
8024                 if (plane_config->tiling)
8025                         offset = I915_READ(DSPTILEOFF(plane));
8026                 else
8027                         offset = I915_READ(DSPLINOFF(plane));
8028                 base = I915_READ(DSPSURF(plane)) & 0xfffff000;
8029         } else {
8030                 base = I915_READ(DSPADDR(plane));
8031         }
8032         plane_config->base = base;
8033
8034         val = I915_READ(PIPESRC(pipe));
8035         fb->width = ((val >> 16) & 0xfff) + 1;
8036         fb->height = ((val >> 0) & 0xfff) + 1;
8037
8038         val = I915_READ(DSPSTRIDE(pipe));
8039         fb->pitches[0] = val & 0xffffffc0;
8040
8041         aligned_height = intel_fb_align_height(dev, fb->height,
8042                                                fb->pixel_format,
8043                                                fb->modifier[0]);
8044
8045         plane_config->size = fb->pitches[0] * aligned_height;
8046
8047         DRM_DEBUG_KMS("pipe/plane %c/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8048                       pipe_name(pipe), plane, fb->width, fb->height,
8049                       fb->bits_per_pixel, base, fb->pitches[0],
8050                       plane_config->size);
8051
8052         plane_config->fb = intel_fb;
8053 }
8054
8055 static void chv_crtc_clock_get(struct intel_crtc *crtc,
8056                                struct intel_crtc_state *pipe_config)
8057 {
8058         struct drm_device *dev = crtc->base.dev;
8059         struct drm_i915_private *dev_priv = dev->dev_private;
8060         int pipe = pipe_config->cpu_transcoder;
8061         enum dpio_channel port = vlv_pipe_to_channel(pipe);
8062         intel_clock_t clock;
8063         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2;
8064         int refclk = 100000;
8065
8066         mutex_lock(&dev_priv->sb_lock);
8067         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
8068         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
8069         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
8070         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
8071         mutex_unlock(&dev_priv->sb_lock);
8072
8073         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
8074         clock.m2 = ((pll_dw0 & 0xff) << 22) | (pll_dw2 & 0x3fffff);
8075         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
8076         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
8077         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
8078
8079         chv_clock(refclk, &clock);
8080
8081         /* clock.dot is the fast clock */
8082         pipe_config->port_clock = clock.dot / 5;
8083 }
8084
8085 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
8086                                  struct intel_crtc_state *pipe_config)
8087 {
8088         struct drm_device *dev = crtc->base.dev;
8089         struct drm_i915_private *dev_priv = dev->dev_private;
8090         uint32_t tmp;
8091
8092         if (!intel_display_power_is_enabled(dev_priv,
8093                                             POWER_DOMAIN_PIPE(crtc->pipe)))
8094                 return false;
8095
8096         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8097         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
8098
8099         tmp = I915_READ(PIPECONF(crtc->pipe));
8100         if (!(tmp & PIPECONF_ENABLE))
8101                 return false;
8102
8103         if (IS_G4X(dev) || IS_VALLEYVIEW(dev)) {
8104                 switch (tmp & PIPECONF_BPC_MASK) {
8105                 case PIPECONF_6BPC:
8106                         pipe_config->pipe_bpp = 18;
8107                         break;
8108                 case PIPECONF_8BPC:
8109                         pipe_config->pipe_bpp = 24;
8110                         break;
8111                 case PIPECONF_10BPC:
8112                         pipe_config->pipe_bpp = 30;
8113                         break;
8114                 default:
8115                         break;
8116                 }
8117         }
8118
8119         if (IS_VALLEYVIEW(dev) && (tmp & PIPECONF_COLOR_RANGE_SELECT))
8120                 pipe_config->limited_color_range = true;
8121
8122         if (INTEL_INFO(dev)->gen < 4)
8123                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
8124
8125         intel_get_pipe_timings(crtc, pipe_config);
8126
8127         i9xx_get_pfit_config(crtc, pipe_config);
8128
8129         if (INTEL_INFO(dev)->gen >= 4) {
8130                 tmp = I915_READ(DPLL_MD(crtc->pipe));
8131                 pipe_config->pixel_multiplier =
8132                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
8133                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
8134                 pipe_config->dpll_hw_state.dpll_md = tmp;
8135         } else if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
8136                 tmp = I915_READ(DPLL(crtc->pipe));
8137                 pipe_config->pixel_multiplier =
8138                         ((tmp & SDVO_MULTIPLIER_MASK)
8139                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
8140         } else {
8141                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
8142                  * port and will be fixed up in the encoder->get_config
8143                  * function. */
8144                 pipe_config->pixel_multiplier = 1;
8145         }
8146         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
8147         if (!IS_VALLEYVIEW(dev)) {
8148                 /*
8149                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
8150                  * on 830. Filter it out here so that we don't
8151                  * report errors due to that.
8152                  */
8153                 if (IS_I830(dev))
8154                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
8155
8156                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
8157                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
8158         } else {
8159                 /* Mask out read-only status bits. */
8160                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
8161                                                      DPLL_PORTC_READY_MASK |
8162                                                      DPLL_PORTB_READY_MASK);
8163         }
8164
8165         if (IS_CHERRYVIEW(dev))
8166                 chv_crtc_clock_get(crtc, pipe_config);
8167         else if (IS_VALLEYVIEW(dev))
8168                 vlv_crtc_clock_get(crtc, pipe_config);
8169         else
8170                 i9xx_crtc_clock_get(crtc, pipe_config);
8171
8172         return true;
8173 }
8174
8175 static void ironlake_init_pch_refclk(struct drm_device *dev)
8176 {
8177         struct drm_i915_private *dev_priv = dev->dev_private;
8178         struct intel_encoder *encoder;
8179         u32 val, final;
8180         bool has_lvds = false;
8181         bool has_cpu_edp = false;
8182         bool has_panel = false;
8183         bool has_ck505 = false;
8184         bool can_ssc = false;
8185
8186         /* We need to take the global config into account */
8187         for_each_intel_encoder(dev, encoder) {
8188                 switch (encoder->type) {
8189                 case INTEL_OUTPUT_LVDS:
8190                         has_panel = true;
8191                         has_lvds = true;
8192                         break;
8193                 case INTEL_OUTPUT_EDP:
8194                         has_panel = true;
8195                         if (enc_to_dig_port(&encoder->base)->port == PORT_A)
8196                                 has_cpu_edp = true;
8197                         break;
8198                 default:
8199                         break;
8200                 }
8201         }
8202
8203         if (HAS_PCH_IBX(dev)) {
8204                 has_ck505 = dev_priv->vbt.display_clock_mode;
8205                 can_ssc = has_ck505;
8206         } else {
8207                 has_ck505 = false;
8208                 can_ssc = true;
8209         }
8210
8211         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d\n",
8212                       has_panel, has_lvds, has_ck505);
8213
8214         /* Ironlake: try to setup display ref clock before DPLL
8215          * enabling. This is only under driver's control after
8216          * PCH B stepping, previous chipset stepping should be
8217          * ignoring this setting.
8218          */
8219         val = I915_READ(PCH_DREF_CONTROL);
8220
8221         /* As we must carefully and slowly disable/enable each source in turn,
8222          * compute the final state we want first and check if we need to
8223          * make any changes at all.
8224          */
8225         final = val;
8226         final &= ~DREF_NONSPREAD_SOURCE_MASK;
8227         if (has_ck505)
8228                 final |= DREF_NONSPREAD_CK505_ENABLE;
8229         else
8230                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
8231
8232         final &= ~DREF_SSC_SOURCE_MASK;
8233         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8234         final &= ~DREF_SSC1_ENABLE;
8235
8236         if (has_panel) {
8237                 final |= DREF_SSC_SOURCE_ENABLE;
8238
8239                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
8240                         final |= DREF_SSC1_ENABLE;
8241
8242                 if (has_cpu_edp) {
8243                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
8244                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8245                         else
8246                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8247                 } else
8248                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8249         } else {
8250                 final |= DREF_SSC_SOURCE_DISABLE;
8251                 final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8252         }
8253
8254         if (final == val)
8255                 return;
8256
8257         /* Always enable nonspread source */
8258         val &= ~DREF_NONSPREAD_SOURCE_MASK;
8259
8260         if (has_ck505)
8261                 val |= DREF_NONSPREAD_CK505_ENABLE;
8262         else
8263                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
8264
8265         if (has_panel) {
8266                 val &= ~DREF_SSC_SOURCE_MASK;
8267                 val |= DREF_SSC_SOURCE_ENABLE;
8268
8269                 /* SSC must be turned on before enabling the CPU output  */
8270                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8271                         DRM_DEBUG_KMS("Using SSC on panel\n");
8272                         val |= DREF_SSC1_ENABLE;
8273                 } else
8274                         val &= ~DREF_SSC1_ENABLE;
8275
8276                 /* Get SSC going before enabling the outputs */
8277                 I915_WRITE(PCH_DREF_CONTROL, val);
8278                 POSTING_READ(PCH_DREF_CONTROL);
8279                 udelay(200);
8280
8281                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8282
8283                 /* Enable CPU source on CPU attached eDP */
8284                 if (has_cpu_edp) {
8285                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8286                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
8287                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8288                         } else
8289                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8290                 } else
8291                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8292
8293                 I915_WRITE(PCH_DREF_CONTROL, val);
8294                 POSTING_READ(PCH_DREF_CONTROL);
8295                 udelay(200);
8296         } else {
8297                 DRM_DEBUG_KMS("Disabling SSC entirely\n");
8298
8299                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8300
8301                 /* Turn off CPU output */
8302                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8303
8304                 I915_WRITE(PCH_DREF_CONTROL, val);
8305                 POSTING_READ(PCH_DREF_CONTROL);
8306                 udelay(200);
8307
8308                 /* Turn off the SSC source */
8309                 val &= ~DREF_SSC_SOURCE_MASK;
8310                 val |= DREF_SSC_SOURCE_DISABLE;
8311
8312                 /* Turn off SSC1 */
8313                 val &= ~DREF_SSC1_ENABLE;
8314
8315                 I915_WRITE(PCH_DREF_CONTROL, val);
8316                 POSTING_READ(PCH_DREF_CONTROL);
8317                 udelay(200);
8318         }
8319
8320         BUG_ON(val != final);
8321 }
8322
8323 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
8324 {
8325         uint32_t tmp;
8326
8327         tmp = I915_READ(SOUTH_CHICKEN2);
8328         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
8329         I915_WRITE(SOUTH_CHICKEN2, tmp);
8330
8331         if (wait_for_atomic_us(I915_READ(SOUTH_CHICKEN2) &
8332                                FDI_MPHY_IOSFSB_RESET_STATUS, 100))
8333                 DRM_ERROR("FDI mPHY reset assert timeout\n");
8334
8335         tmp = I915_READ(SOUTH_CHICKEN2);
8336         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
8337         I915_WRITE(SOUTH_CHICKEN2, tmp);
8338
8339         if (wait_for_atomic_us((I915_READ(SOUTH_CHICKEN2) &
8340                                 FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
8341                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
8342 }
8343
8344 /* WaMPhyProgramming:hsw */
8345 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
8346 {
8347         uint32_t tmp;
8348
8349         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
8350         tmp &= ~(0xFF << 24);
8351         tmp |= (0x12 << 24);
8352         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
8353
8354         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
8355         tmp |= (1 << 11);
8356         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
8357
8358         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
8359         tmp |= (1 << 11);
8360         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
8361
8362         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
8363         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8364         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
8365
8366         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
8367         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8368         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
8369
8370         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
8371         tmp &= ~(7 << 13);
8372         tmp |= (5 << 13);
8373         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
8374
8375         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
8376         tmp &= ~(7 << 13);
8377         tmp |= (5 << 13);
8378         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
8379
8380         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
8381         tmp &= ~0xFF;
8382         tmp |= 0x1C;
8383         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
8384
8385         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
8386         tmp &= ~0xFF;
8387         tmp |= 0x1C;
8388         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
8389
8390         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
8391         tmp &= ~(0xFF << 16);
8392         tmp |= (0x1C << 16);
8393         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
8394
8395         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
8396         tmp &= ~(0xFF << 16);
8397         tmp |= (0x1C << 16);
8398         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
8399
8400         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8401         tmp |= (1 << 27);
8402         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8403
8404         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8405         tmp |= (1 << 27);
8406         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8407
8408         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8409         tmp &= ~(0xF << 28);
8410         tmp |= (4 << 28);
8411         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8412
8413         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
8414         tmp &= ~(0xF << 28);
8415         tmp |= (4 << 28);
8416         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
8417 }
8418
8419 /* Implements 3 different sequences from BSpec chapter "Display iCLK
8420  * Programming" based on the parameters passed:
8421  * - Sequence to enable CLKOUT_DP
8422  * - Sequence to enable CLKOUT_DP without spread
8423  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
8424  */
8425 static void lpt_enable_clkout_dp(struct drm_device *dev, bool with_spread,
8426                                  bool with_fdi)
8427 {
8428         struct drm_i915_private *dev_priv = dev->dev_private;
8429         uint32_t reg, tmp;
8430
8431         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
8432                 with_spread = true;
8433         if (WARN(dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE &&
8434                  with_fdi, "LP PCH doesn't have FDI\n"))
8435                 with_fdi = false;
8436
8437         mutex_lock(&dev_priv->sb_lock);
8438
8439         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8440         tmp &= ~SBI_SSCCTL_DISABLE;
8441         tmp |= SBI_SSCCTL_PATHALT;
8442         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8443
8444         udelay(24);
8445
8446         if (with_spread) {
8447                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8448                 tmp &= ~SBI_SSCCTL_PATHALT;
8449                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8450
8451                 if (with_fdi) {
8452                         lpt_reset_fdi_mphy(dev_priv);
8453                         lpt_program_fdi_mphy(dev_priv);
8454                 }
8455         }
8456
8457         reg = (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) ?
8458                SBI_GEN0 : SBI_DBUFF0;
8459         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8460         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8461         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8462
8463         mutex_unlock(&dev_priv->sb_lock);
8464 }
8465
8466 /* Sequence to disable CLKOUT_DP */
8467 static void lpt_disable_clkout_dp(struct drm_device *dev)
8468 {
8469         struct drm_i915_private *dev_priv = dev->dev_private;
8470         uint32_t reg, tmp;
8471
8472         mutex_lock(&dev_priv->sb_lock);
8473
8474         reg = (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) ?
8475                SBI_GEN0 : SBI_DBUFF0;
8476         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8477         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8478         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8479
8480         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8481         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8482                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8483                         tmp |= SBI_SSCCTL_PATHALT;
8484                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8485                         udelay(32);
8486                 }
8487                 tmp |= SBI_SSCCTL_DISABLE;
8488                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8489         }
8490
8491         mutex_unlock(&dev_priv->sb_lock);
8492 }
8493
8494 static void lpt_init_pch_refclk(struct drm_device *dev)
8495 {
8496         struct intel_encoder *encoder;
8497         bool has_vga = false;
8498
8499         for_each_intel_encoder(dev, encoder) {
8500                 switch (encoder->type) {
8501                 case INTEL_OUTPUT_ANALOG:
8502                         has_vga = true;
8503                         break;
8504                 default:
8505                         break;
8506                 }
8507         }
8508
8509         if (has_vga)
8510                 lpt_enable_clkout_dp(dev, true, true);
8511         else
8512                 lpt_disable_clkout_dp(dev);
8513 }
8514
8515 /*
8516  * Initialize reference clocks when the driver loads
8517  */
8518 void intel_init_pch_refclk(struct drm_device *dev)
8519 {
8520         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
8521                 ironlake_init_pch_refclk(dev);
8522         else if (HAS_PCH_LPT(dev))
8523                 lpt_init_pch_refclk(dev);
8524 }
8525
8526 static int ironlake_get_refclk(struct intel_crtc_state *crtc_state)
8527 {
8528         struct drm_device *dev = crtc_state->base.crtc->dev;
8529         struct drm_i915_private *dev_priv = dev->dev_private;
8530         struct drm_atomic_state *state = crtc_state->base.state;
8531         struct drm_connector *connector;
8532         struct drm_connector_state *connector_state;
8533         struct intel_encoder *encoder;
8534         int num_connectors = 0, i;
8535         bool is_lvds = false;
8536
8537         for_each_connector_in_state(state, connector, connector_state, i) {
8538                 if (connector_state->crtc != crtc_state->base.crtc)
8539                         continue;
8540
8541                 encoder = to_intel_encoder(connector_state->best_encoder);
8542
8543                 switch (encoder->type) {
8544                 case INTEL_OUTPUT_LVDS:
8545                         is_lvds = true;
8546                         break;
8547                 default:
8548                         break;
8549                 }
8550                 num_connectors++;
8551         }
8552
8553         if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2) {
8554                 DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8555                               dev_priv->vbt.lvds_ssc_freq);
8556                 return dev_priv->vbt.lvds_ssc_freq;
8557         }
8558
8559         return 120000;
8560 }
8561
8562 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
8563 {
8564         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
8565         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8566         int pipe = intel_crtc->pipe;
8567         uint32_t val;
8568
8569         val = 0;
8570
8571         switch (intel_crtc->config->pipe_bpp) {
8572         case 18:
8573                 val |= PIPECONF_6BPC;
8574                 break;
8575         case 24:
8576                 val |= PIPECONF_8BPC;
8577                 break;
8578         case 30:
8579                 val |= PIPECONF_10BPC;
8580                 break;
8581         case 36:
8582                 val |= PIPECONF_12BPC;
8583                 break;
8584         default:
8585                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8586                 BUG();
8587         }
8588
8589         if (intel_crtc->config->dither)
8590                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8591
8592         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8593                 val |= PIPECONF_INTERLACED_ILK;
8594         else
8595                 val |= PIPECONF_PROGRESSIVE;
8596
8597         if (intel_crtc->config->limited_color_range)
8598                 val |= PIPECONF_COLOR_RANGE_SELECT;
8599
8600         I915_WRITE(PIPECONF(pipe), val);
8601         POSTING_READ(PIPECONF(pipe));
8602 }
8603
8604 /*
8605  * Set up the pipe CSC unit.
8606  *
8607  * Currently only full range RGB to limited range RGB conversion
8608  * is supported, but eventually this should handle various
8609  * RGB<->YCbCr scenarios as well.
8610  */
8611 static void intel_set_pipe_csc(struct drm_crtc *crtc)
8612 {
8613         struct drm_device *dev = crtc->dev;
8614         struct drm_i915_private *dev_priv = dev->dev_private;
8615         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8616         int pipe = intel_crtc->pipe;
8617         uint16_t coeff = 0x7800; /* 1.0 */
8618
8619         /*
8620          * TODO: Check what kind of values actually come out of the pipe
8621          * with these coeff/postoff values and adjust to get the best
8622          * accuracy. Perhaps we even need to take the bpc value into
8623          * consideration.
8624          */
8625
8626         if (intel_crtc->config->limited_color_range)
8627                 coeff = ((235 - 16) * (1 << 12) / 255) & 0xff8; /* 0.xxx... */
8628
8629         /*
8630          * GY/GU and RY/RU should be the other way around according
8631          * to BSpec, but reality doesn't agree. Just set them up in
8632          * a way that results in the correct picture.
8633          */
8634         I915_WRITE(PIPE_CSC_COEFF_RY_GY(pipe), coeff << 16);
8635         I915_WRITE(PIPE_CSC_COEFF_BY(pipe), 0);
8636
8637         I915_WRITE(PIPE_CSC_COEFF_RU_GU(pipe), coeff);
8638         I915_WRITE(PIPE_CSC_COEFF_BU(pipe), 0);
8639
8640         I915_WRITE(PIPE_CSC_COEFF_RV_GV(pipe), 0);
8641         I915_WRITE(PIPE_CSC_COEFF_BV(pipe), coeff << 16);
8642
8643         I915_WRITE(PIPE_CSC_PREOFF_HI(pipe), 0);
8644         I915_WRITE(PIPE_CSC_PREOFF_ME(pipe), 0);
8645         I915_WRITE(PIPE_CSC_PREOFF_LO(pipe), 0);
8646
8647         if (INTEL_INFO(dev)->gen > 6) {
8648                 uint16_t postoff = 0;
8649
8650                 if (intel_crtc->config->limited_color_range)
8651                         postoff = (16 * (1 << 12) / 255) & 0x1fff;
8652
8653                 I915_WRITE(PIPE_CSC_POSTOFF_HI(pipe), postoff);
8654                 I915_WRITE(PIPE_CSC_POSTOFF_ME(pipe), postoff);
8655                 I915_WRITE(PIPE_CSC_POSTOFF_LO(pipe), postoff);
8656
8657                 I915_WRITE(PIPE_CSC_MODE(pipe), 0);
8658         } else {
8659                 uint32_t mode = CSC_MODE_YUV_TO_RGB;
8660
8661                 if (intel_crtc->config->limited_color_range)
8662                         mode |= CSC_BLACK_SCREEN_OFFSET;
8663
8664                 I915_WRITE(PIPE_CSC_MODE(pipe), mode);
8665         }
8666 }
8667
8668 static void haswell_set_pipeconf(struct drm_crtc *crtc)
8669 {
8670         struct drm_device *dev = crtc->dev;
8671         struct drm_i915_private *dev_priv = dev->dev_private;
8672         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8673         enum pipe pipe = intel_crtc->pipe;
8674         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8675         uint32_t val;
8676
8677         val = 0;
8678
8679         if (IS_HASWELL(dev) && intel_crtc->config->dither)
8680                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8681
8682         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8683                 val |= PIPECONF_INTERLACED_ILK;
8684         else
8685                 val |= PIPECONF_PROGRESSIVE;
8686
8687         I915_WRITE(PIPECONF(cpu_transcoder), val);
8688         POSTING_READ(PIPECONF(cpu_transcoder));
8689
8690         I915_WRITE(GAMMA_MODE(intel_crtc->pipe), GAMMA_MODE_MODE_8BIT);
8691         POSTING_READ(GAMMA_MODE(intel_crtc->pipe));
8692
8693         if (IS_BROADWELL(dev) || INTEL_INFO(dev)->gen >= 9) {
8694                 val = 0;
8695
8696                 switch (intel_crtc->config->pipe_bpp) {
8697                 case 18:
8698                         val |= PIPEMISC_DITHER_6_BPC;
8699                         break;
8700                 case 24:
8701                         val |= PIPEMISC_DITHER_8_BPC;
8702                         break;
8703                 case 30:
8704                         val |= PIPEMISC_DITHER_10_BPC;
8705                         break;
8706                 case 36:
8707                         val |= PIPEMISC_DITHER_12_BPC;
8708                         break;
8709                 default:
8710                         /* Case prevented by pipe_config_set_bpp. */
8711                         BUG();
8712                 }
8713
8714                 if (intel_crtc->config->dither)
8715                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8716
8717                 I915_WRITE(PIPEMISC(pipe), val);
8718         }
8719 }
8720
8721 static bool ironlake_compute_clocks(struct drm_crtc *crtc,
8722                                     struct intel_crtc_state *crtc_state,
8723                                     intel_clock_t *clock,
8724                                     bool *has_reduced_clock,
8725                                     intel_clock_t *reduced_clock)
8726 {
8727         struct drm_device *dev = crtc->dev;
8728         struct drm_i915_private *dev_priv = dev->dev_private;
8729         int refclk;
8730         const intel_limit_t *limit;
8731         bool ret, is_lvds = false;
8732
8733         is_lvds = intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS);
8734
8735         refclk = ironlake_get_refclk(crtc_state);
8736
8737         /*
8738          * Returns a set of divisors for the desired target clock with the given
8739          * refclk, or FALSE.  The returned values represent the clock equation:
8740          * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
8741          */
8742         limit = intel_limit(crtc_state, refclk);
8743         ret = dev_priv->display.find_dpll(limit, crtc_state,
8744                                           crtc_state->port_clock,
8745                                           refclk, NULL, clock);
8746         if (!ret)
8747                 return false;
8748
8749         if (is_lvds && dev_priv->lvds_downclock_avail) {
8750                 /*
8751                  * Ensure we match the reduced clock's P to the target clock.
8752                  * If the clocks don't match, we can't switch the display clock
8753                  * by using the FP0/FP1. In such case we will disable the LVDS
8754                  * downclock feature.
8755                 */
8756                 *has_reduced_clock =
8757                         dev_priv->display.find_dpll(limit, crtc_state,
8758                                                     dev_priv->lvds_downclock,
8759                                                     refclk, clock,
8760                                                     reduced_clock);
8761         }
8762
8763         return true;
8764 }
8765
8766 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8767 {
8768         /*
8769          * Account for spread spectrum to avoid
8770          * oversubscribing the link. Max center spread
8771          * is 2.5%; use 5% for safety's sake.
8772          */
8773         u32 bps = target_clock * bpp * 21 / 20;
8774         return DIV_ROUND_UP(bps, link_bw * 8);
8775 }
8776
8777 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8778 {
8779         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8780 }
8781
8782 static uint32_t ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8783                                       struct intel_crtc_state *crtc_state,
8784                                       u32 *fp,
8785                                       intel_clock_t *reduced_clock, u32 *fp2)
8786 {
8787         struct drm_crtc *crtc = &intel_crtc->base;
8788         struct drm_device *dev = crtc->dev;
8789         struct drm_i915_private *dev_priv = dev->dev_private;
8790         struct drm_atomic_state *state = crtc_state->base.state;
8791         struct drm_connector *connector;
8792         struct drm_connector_state *connector_state;
8793         struct intel_encoder *encoder;
8794         uint32_t dpll;
8795         int factor, num_connectors = 0, i;
8796         bool is_lvds = false, is_sdvo = false;
8797
8798         for_each_connector_in_state(state, connector, connector_state, i) {
8799                 if (connector_state->crtc != crtc_state->base.crtc)
8800                         continue;
8801
8802                 encoder = to_intel_encoder(connector_state->best_encoder);
8803
8804                 switch (encoder->type) {
8805                 case INTEL_OUTPUT_LVDS:
8806                         is_lvds = true;
8807                         break;
8808                 case INTEL_OUTPUT_SDVO:
8809                 case INTEL_OUTPUT_HDMI:
8810                         is_sdvo = true;
8811                         break;
8812                 default:
8813                         break;
8814                 }
8815
8816                 num_connectors++;
8817         }
8818
8819         /* Enable autotuning of the PLL clock (if permissible) */
8820         factor = 21;
8821         if (is_lvds) {
8822                 if ((intel_panel_use_ssc(dev_priv) &&
8823                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8824                     (HAS_PCH_IBX(dev) && intel_is_dual_link_lvds(dev)))
8825                         factor = 25;
8826         } else if (crtc_state->sdvo_tv_clock)
8827                 factor = 20;
8828
8829         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8830                 *fp |= FP_CB_TUNE;
8831
8832         if (fp2 && (reduced_clock->m < factor * reduced_clock->n))
8833                 *fp2 |= FP_CB_TUNE;
8834
8835         dpll = 0;
8836
8837         if (is_lvds)
8838                 dpll |= DPLLB_MODE_LVDS;
8839         else
8840                 dpll |= DPLLB_MODE_DAC_SERIAL;
8841
8842         dpll |= (crtc_state->pixel_multiplier - 1)
8843                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8844
8845         if (is_sdvo)
8846                 dpll |= DPLL_SDVO_HIGH_SPEED;
8847         if (crtc_state->has_dp_encoder)
8848                 dpll |= DPLL_SDVO_HIGH_SPEED;
8849
8850         /* compute bitmask from p1 value */
8851         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8852         /* also FPA1 */
8853         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8854
8855         switch (crtc_state->dpll.p2) {
8856         case 5:
8857                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8858                 break;
8859         case 7:
8860                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8861                 break;
8862         case 10:
8863                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8864                 break;
8865         case 14:
8866                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8867                 break;
8868         }
8869
8870         if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2)
8871                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8872         else
8873                 dpll |= PLL_REF_INPUT_DREFCLK;
8874
8875         return dpll | DPLL_VCO_ENABLE;
8876 }
8877
8878 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
8879                                        struct intel_crtc_state *crtc_state)
8880 {
8881         struct drm_device *dev = crtc->base.dev;
8882         intel_clock_t clock, reduced_clock;
8883         u32 dpll = 0, fp = 0, fp2 = 0;
8884         bool ok, has_reduced_clock = false;
8885         bool is_lvds = false;
8886         struct intel_shared_dpll *pll;
8887
8888         memset(&crtc_state->dpll_hw_state, 0,
8889                sizeof(crtc_state->dpll_hw_state));
8890
8891         is_lvds = intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS);
8892
8893         WARN(!(HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev)),
8894              "Unexpected PCH type %d\n", INTEL_PCH_TYPE(dev));
8895
8896         ok = ironlake_compute_clocks(&crtc->base, crtc_state, &clock,
8897                                      &has_reduced_clock, &reduced_clock);
8898         if (!ok && !crtc_state->clock_set) {
8899                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8900                 return -EINVAL;
8901         }
8902         /* Compat-code for transition, will disappear. */
8903         if (!crtc_state->clock_set) {
8904                 crtc_state->dpll.n = clock.n;
8905                 crtc_state->dpll.m1 = clock.m1;
8906                 crtc_state->dpll.m2 = clock.m2;
8907                 crtc_state->dpll.p1 = clock.p1;
8908                 crtc_state->dpll.p2 = clock.p2;
8909         }
8910
8911         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
8912         if (crtc_state->has_pch_encoder) {
8913                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8914                 if (has_reduced_clock)
8915                         fp2 = i9xx_dpll_compute_fp(&reduced_clock);
8916
8917                 dpll = ironlake_compute_dpll(crtc, crtc_state,
8918                                              &fp, &reduced_clock,
8919                                              has_reduced_clock ? &fp2 : NULL);
8920
8921                 crtc_state->dpll_hw_state.dpll = dpll;
8922                 crtc_state->dpll_hw_state.fp0 = fp;
8923                 if (has_reduced_clock)
8924                         crtc_state->dpll_hw_state.fp1 = fp2;
8925                 else
8926                         crtc_state->dpll_hw_state.fp1 = fp;
8927
8928                 pll = intel_get_shared_dpll(crtc, crtc_state);
8929                 if (pll == NULL) {
8930                         DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
8931                                          pipe_name(crtc->pipe));
8932                         return -EINVAL;
8933                 }
8934         }
8935
8936         if (is_lvds && has_reduced_clock)
8937                 crtc->lowfreq_avail = true;
8938         else
8939                 crtc->lowfreq_avail = false;
8940
8941         return 0;
8942 }
8943
8944 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
8945                                          struct intel_link_m_n *m_n)
8946 {
8947         struct drm_device *dev = crtc->base.dev;
8948         struct drm_i915_private *dev_priv = dev->dev_private;
8949         enum pipe pipe = crtc->pipe;
8950
8951         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
8952         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
8953         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
8954                 & ~TU_SIZE_MASK;
8955         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
8956         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
8957                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8958 }
8959
8960 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
8961                                          enum transcoder transcoder,
8962                                          struct intel_link_m_n *m_n,
8963                                          struct intel_link_m_n *m2_n2)
8964 {
8965         struct drm_device *dev = crtc->base.dev;
8966         struct drm_i915_private *dev_priv = dev->dev_private;
8967         enum pipe pipe = crtc->pipe;
8968
8969         if (INTEL_INFO(dev)->gen >= 5) {
8970                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
8971                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
8972                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
8973                         & ~TU_SIZE_MASK;
8974                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
8975                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
8976                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8977                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
8978                  * gen < 8) and if DRRS is supported (to make sure the
8979                  * registers are not unnecessarily read).
8980                  */
8981                 if (m2_n2 && INTEL_INFO(dev)->gen < 8 &&
8982                         crtc->config->has_drrs) {
8983                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
8984                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
8985                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
8986                                         & ~TU_SIZE_MASK;
8987                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
8988                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
8989                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8990                 }
8991         } else {
8992                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
8993                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
8994                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
8995                         & ~TU_SIZE_MASK;
8996                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
8997                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
8998                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8999         }
9000 }
9001
9002 void intel_dp_get_m_n(struct intel_crtc *crtc,
9003                       struct intel_crtc_state *pipe_config)
9004 {
9005         if (pipe_config->has_pch_encoder)
9006                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
9007         else
9008                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9009                                              &pipe_config->dp_m_n,
9010                                              &pipe_config->dp_m2_n2);
9011 }
9012
9013 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
9014                                         struct intel_crtc_state *pipe_config)
9015 {
9016         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9017                                      &pipe_config->fdi_m_n, NULL);
9018 }
9019
9020 static void skylake_get_pfit_config(struct intel_crtc *crtc,
9021                                     struct intel_crtc_state *pipe_config)
9022 {
9023         struct drm_device *dev = crtc->base.dev;
9024         struct drm_i915_private *dev_priv = dev->dev_private;
9025         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
9026         uint32_t ps_ctrl = 0;
9027         int id = -1;
9028         int i;
9029
9030         /* find scaler attached to this pipe */
9031         for (i = 0; i < crtc->num_scalers; i++) {
9032                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
9033                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
9034                         id = i;
9035                         pipe_config->pch_pfit.enabled = true;
9036                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
9037                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
9038                         break;
9039                 }
9040         }
9041
9042         scaler_state->scaler_id = id;
9043         if (id >= 0) {
9044                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
9045         } else {
9046                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
9047         }
9048 }
9049
9050 static void
9051 skylake_get_initial_plane_config(struct intel_crtc *crtc,
9052                                  struct intel_initial_plane_config *plane_config)
9053 {
9054         struct drm_device *dev = crtc->base.dev;
9055         struct drm_i915_private *dev_priv = dev->dev_private;
9056         u32 val, base, offset, stride_mult, tiling;
9057         int pipe = crtc->pipe;
9058         int fourcc, pixel_format;
9059         unsigned int aligned_height;
9060         struct drm_framebuffer *fb;
9061         struct intel_framebuffer *intel_fb;
9062
9063         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9064         if (!intel_fb) {
9065                 DRM_DEBUG_KMS("failed to alloc fb\n");
9066                 return;
9067         }
9068
9069         fb = &intel_fb->base;
9070
9071         val = I915_READ(PLANE_CTL(pipe, 0));
9072         if (!(val & PLANE_CTL_ENABLE))
9073                 goto error;
9074
9075         pixel_format = val & PLANE_CTL_FORMAT_MASK;
9076         fourcc = skl_format_to_fourcc(pixel_format,
9077                                       val & PLANE_CTL_ORDER_RGBX,
9078                                       val & PLANE_CTL_ALPHA_MASK);
9079         fb->pixel_format = fourcc;
9080         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9081
9082         tiling = val & PLANE_CTL_TILED_MASK;
9083         switch (tiling) {
9084         case PLANE_CTL_TILED_LINEAR:
9085                 fb->modifier[0] = DRM_FORMAT_MOD_NONE;
9086                 break;
9087         case PLANE_CTL_TILED_X:
9088                 plane_config->tiling = I915_TILING_X;
9089                 fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9090                 break;
9091         case PLANE_CTL_TILED_Y:
9092                 fb->modifier[0] = I915_FORMAT_MOD_Y_TILED;
9093                 break;
9094         case PLANE_CTL_TILED_YF:
9095                 fb->modifier[0] = I915_FORMAT_MOD_Yf_TILED;
9096                 break;
9097         default:
9098                 MISSING_CASE(tiling);
9099                 goto error;
9100         }
9101
9102         base = I915_READ(PLANE_SURF(pipe, 0)) & 0xfffff000;
9103         plane_config->base = base;
9104
9105         offset = I915_READ(PLANE_OFFSET(pipe, 0));
9106
9107         val = I915_READ(PLANE_SIZE(pipe, 0));
9108         fb->height = ((val >> 16) & 0xfff) + 1;
9109         fb->width = ((val >> 0) & 0x1fff) + 1;
9110
9111         val = I915_READ(PLANE_STRIDE(pipe, 0));
9112         stride_mult = intel_fb_stride_alignment(dev, fb->modifier[0],
9113                                                 fb->pixel_format);
9114         fb->pitches[0] = (val & 0x3ff) * stride_mult;
9115
9116         aligned_height = intel_fb_align_height(dev, fb->height,
9117                                                fb->pixel_format,
9118                                                fb->modifier[0]);
9119
9120         plane_config->size = fb->pitches[0] * aligned_height;
9121
9122         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9123                       pipe_name(pipe), fb->width, fb->height,
9124                       fb->bits_per_pixel, base, fb->pitches[0],
9125                       plane_config->size);
9126
9127         plane_config->fb = intel_fb;
9128         return;
9129
9130 error:
9131         kfree(fb);
9132 }
9133
9134 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
9135                                      struct intel_crtc_state *pipe_config)
9136 {
9137         struct drm_device *dev = crtc->base.dev;
9138         struct drm_i915_private *dev_priv = dev->dev_private;
9139         uint32_t tmp;
9140
9141         tmp = I915_READ(PF_CTL(crtc->pipe));
9142
9143         if (tmp & PF_ENABLE) {
9144                 pipe_config->pch_pfit.enabled = true;
9145                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
9146                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
9147
9148                 /* We currently do not free assignements of panel fitters on
9149                  * ivb/hsw (since we don't use the higher upscaling modes which
9150                  * differentiates them) so just WARN about this case for now. */
9151                 if (IS_GEN7(dev)) {
9152                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
9153                                 PF_PIPE_SEL_IVB(crtc->pipe));
9154                 }
9155         }
9156 }
9157
9158 static void
9159 ironlake_get_initial_plane_config(struct intel_crtc *crtc,
9160                                   struct intel_initial_plane_config *plane_config)
9161 {
9162         struct drm_device *dev = crtc->base.dev;
9163         struct drm_i915_private *dev_priv = dev->dev_private;
9164         u32 val, base, offset;
9165         int pipe = crtc->pipe;
9166         int fourcc, pixel_format;
9167         unsigned int aligned_height;
9168         struct drm_framebuffer *fb;
9169         struct intel_framebuffer *intel_fb;
9170
9171         val = I915_READ(DSPCNTR(pipe));
9172         if (!(val & DISPLAY_PLANE_ENABLE))
9173                 return;
9174
9175         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9176         if (!intel_fb) {
9177                 DRM_DEBUG_KMS("failed to alloc fb\n");
9178                 return;
9179         }
9180
9181         fb = &intel_fb->base;
9182
9183         if (INTEL_INFO(dev)->gen >= 4) {
9184                 if (val & DISPPLANE_TILED) {
9185                         plane_config->tiling = I915_TILING_X;
9186                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9187                 }
9188         }
9189
9190         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
9191         fourcc = i9xx_format_to_fourcc(pixel_format);
9192         fb->pixel_format = fourcc;
9193         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9194
9195         base = I915_READ(DSPSURF(pipe)) & 0xfffff000;
9196         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
9197                 offset = I915_READ(DSPOFFSET(pipe));
9198         } else {
9199                 if (plane_config->tiling)
9200                         offset = I915_READ(DSPTILEOFF(pipe));
9201                 else
9202                         offset = I915_READ(DSPLINOFF(pipe));
9203         }
9204         plane_config->base = base;
9205
9206         val = I915_READ(PIPESRC(pipe));
9207         fb->width = ((val >> 16) & 0xfff) + 1;
9208         fb->height = ((val >> 0) & 0xfff) + 1;
9209
9210         val = I915_READ(DSPSTRIDE(pipe));
9211         fb->pitches[0] = val & 0xffffffc0;
9212
9213         aligned_height = intel_fb_align_height(dev, fb->height,
9214                                                fb->pixel_format,
9215                                                fb->modifier[0]);
9216
9217         plane_config->size = fb->pitches[0] * aligned_height;
9218
9219         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9220                       pipe_name(pipe), fb->width, fb->height,
9221                       fb->bits_per_pixel, base, fb->pitches[0],
9222                       plane_config->size);
9223
9224         plane_config->fb = intel_fb;
9225 }
9226
9227 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
9228                                      struct intel_crtc_state *pipe_config)
9229 {
9230         struct drm_device *dev = crtc->base.dev;
9231         struct drm_i915_private *dev_priv = dev->dev_private;
9232         uint32_t tmp;
9233
9234         if (!intel_display_power_is_enabled(dev_priv,
9235                                             POWER_DOMAIN_PIPE(crtc->pipe)))
9236                 return false;
9237
9238         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9239         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
9240
9241         tmp = I915_READ(PIPECONF(crtc->pipe));
9242         if (!(tmp & PIPECONF_ENABLE))
9243                 return false;
9244
9245         switch (tmp & PIPECONF_BPC_MASK) {
9246         case PIPECONF_6BPC:
9247                 pipe_config->pipe_bpp = 18;
9248                 break;
9249         case PIPECONF_8BPC:
9250                 pipe_config->pipe_bpp = 24;
9251                 break;
9252         case PIPECONF_10BPC:
9253                 pipe_config->pipe_bpp = 30;
9254                 break;
9255         case PIPECONF_12BPC:
9256                 pipe_config->pipe_bpp = 36;
9257                 break;
9258         default:
9259                 break;
9260         }
9261
9262         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
9263                 pipe_config->limited_color_range = true;
9264
9265         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
9266                 struct intel_shared_dpll *pll;
9267
9268                 pipe_config->has_pch_encoder = true;
9269
9270                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
9271                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9272                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9273
9274                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9275
9276                 if (HAS_PCH_IBX(dev_priv->dev)) {
9277                         pipe_config->shared_dpll =
9278                                 (enum intel_dpll_id) crtc->pipe;
9279                 } else {
9280                         tmp = I915_READ(PCH_DPLL_SEL);
9281                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
9282                                 pipe_config->shared_dpll = DPLL_ID_PCH_PLL_B;
9283                         else
9284                                 pipe_config->shared_dpll = DPLL_ID_PCH_PLL_A;
9285                 }
9286
9287                 pll = &dev_priv->shared_dplls[pipe_config->shared_dpll];
9288
9289                 WARN_ON(!pll->get_hw_state(dev_priv, pll,
9290                                            &pipe_config->dpll_hw_state));
9291
9292                 tmp = pipe_config->dpll_hw_state.dpll;
9293                 pipe_config->pixel_multiplier =
9294                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
9295                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
9296
9297                 ironlake_pch_clock_get(crtc, pipe_config);
9298         } else {
9299                 pipe_config->pixel_multiplier = 1;
9300         }
9301
9302         intel_get_pipe_timings(crtc, pipe_config);
9303
9304         ironlake_get_pfit_config(crtc, pipe_config);
9305
9306         return true;
9307 }
9308
9309 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
9310 {
9311         struct drm_device *dev = dev_priv->dev;
9312         struct intel_crtc *crtc;
9313
9314         for_each_intel_crtc(dev, crtc)
9315                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
9316                      pipe_name(crtc->pipe));
9317
9318         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_DRIVER), "Power well on\n");
9319         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
9320         I915_STATE_WARN(I915_READ(WRPLL_CTL1) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
9321         I915_STATE_WARN(I915_READ(WRPLL_CTL2) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
9322         I915_STATE_WARN(I915_READ(PCH_PP_STATUS) & PP_ON, "Panel power on\n");
9323         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
9324              "CPU PWM1 enabled\n");
9325         if (IS_HASWELL(dev))
9326                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
9327                      "CPU PWM2 enabled\n");
9328         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
9329              "PCH PWM1 enabled\n");
9330         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
9331              "Utility pin enabled\n");
9332         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
9333
9334         /*
9335          * In theory we can still leave IRQs enabled, as long as only the HPD
9336          * interrupts remain enabled. We used to check for that, but since it's
9337          * gen-specific and since we only disable LCPLL after we fully disable
9338          * the interrupts, the check below should be enough.
9339          */
9340         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
9341 }
9342
9343 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
9344 {
9345         struct drm_device *dev = dev_priv->dev;
9346
9347         if (IS_HASWELL(dev))
9348                 return I915_READ(D_COMP_HSW);
9349         else
9350                 return I915_READ(D_COMP_BDW);
9351 }
9352
9353 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
9354 {
9355         struct drm_device *dev = dev_priv->dev;
9356
9357         if (IS_HASWELL(dev)) {
9358                 mutex_lock(&dev_priv->rps.hw_lock);
9359                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
9360                                             val))
9361                         DRM_ERROR("Failed to write to D_COMP\n");
9362                 mutex_unlock(&dev_priv->rps.hw_lock);
9363         } else {
9364                 I915_WRITE(D_COMP_BDW, val);
9365                 POSTING_READ(D_COMP_BDW);
9366         }
9367 }
9368
9369 /*
9370  * This function implements pieces of two sequences from BSpec:
9371  * - Sequence for display software to disable LCPLL
9372  * - Sequence for display software to allow package C8+
9373  * The steps implemented here are just the steps that actually touch the LCPLL
9374  * register. Callers should take care of disabling all the display engine
9375  * functions, doing the mode unset, fixing interrupts, etc.
9376  */
9377 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
9378                               bool switch_to_fclk, bool allow_power_down)
9379 {
9380         uint32_t val;
9381
9382         assert_can_disable_lcpll(dev_priv);
9383
9384         val = I915_READ(LCPLL_CTL);
9385
9386         if (switch_to_fclk) {
9387                 val |= LCPLL_CD_SOURCE_FCLK;
9388                 I915_WRITE(LCPLL_CTL, val);
9389
9390                 if (wait_for_atomic_us(I915_READ(LCPLL_CTL) &
9391                                        LCPLL_CD_SOURCE_FCLK_DONE, 1))
9392                         DRM_ERROR("Switching to FCLK failed\n");
9393
9394                 val = I915_READ(LCPLL_CTL);
9395         }
9396
9397         val |= LCPLL_PLL_DISABLE;
9398         I915_WRITE(LCPLL_CTL, val);
9399         POSTING_READ(LCPLL_CTL);
9400
9401         if (wait_for((I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK) == 0, 1))
9402                 DRM_ERROR("LCPLL still locked\n");
9403
9404         val = hsw_read_dcomp(dev_priv);
9405         val |= D_COMP_COMP_DISABLE;
9406         hsw_write_dcomp(dev_priv, val);
9407         ndelay(100);
9408
9409         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
9410                      1))
9411                 DRM_ERROR("D_COMP RCOMP still in progress\n");
9412
9413         if (allow_power_down) {
9414                 val = I915_READ(LCPLL_CTL);
9415                 val |= LCPLL_POWER_DOWN_ALLOW;
9416                 I915_WRITE(LCPLL_CTL, val);
9417                 POSTING_READ(LCPLL_CTL);
9418         }
9419 }
9420
9421 /*
9422  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
9423  * source.
9424  */
9425 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
9426 {
9427         uint32_t val;
9428
9429         val = I915_READ(LCPLL_CTL);
9430
9431         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
9432                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
9433                 return;
9434
9435         /*
9436          * Make sure we're not on PC8 state before disabling PC8, otherwise
9437          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
9438          */
9439         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
9440
9441         if (val & LCPLL_POWER_DOWN_ALLOW) {
9442                 val &= ~LCPLL_POWER_DOWN_ALLOW;
9443                 I915_WRITE(LCPLL_CTL, val);
9444                 POSTING_READ(LCPLL_CTL);
9445         }
9446
9447         val = hsw_read_dcomp(dev_priv);
9448         val |= D_COMP_COMP_FORCE;
9449         val &= ~D_COMP_COMP_DISABLE;
9450         hsw_write_dcomp(dev_priv, val);
9451
9452         val = I915_READ(LCPLL_CTL);
9453         val &= ~LCPLL_PLL_DISABLE;
9454         I915_WRITE(LCPLL_CTL, val);
9455
9456         if (wait_for(I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK, 5))
9457                 DRM_ERROR("LCPLL not locked yet\n");
9458
9459         if (val & LCPLL_CD_SOURCE_FCLK) {
9460                 val = I915_READ(LCPLL_CTL);
9461                 val &= ~LCPLL_CD_SOURCE_FCLK;
9462                 I915_WRITE(LCPLL_CTL, val);
9463
9464                 if (wait_for_atomic_us((I915_READ(LCPLL_CTL) &
9465                                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9466                         DRM_ERROR("Switching back to LCPLL failed\n");
9467         }
9468
9469         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
9470         intel_update_cdclk(dev_priv->dev);
9471 }
9472
9473 /*
9474  * Package states C8 and deeper are really deep PC states that can only be
9475  * reached when all the devices on the system allow it, so even if the graphics
9476  * device allows PC8+, it doesn't mean the system will actually get to these
9477  * states. Our driver only allows PC8+ when going into runtime PM.
9478  *
9479  * The requirements for PC8+ are that all the outputs are disabled, the power
9480  * well is disabled and most interrupts are disabled, and these are also
9481  * requirements for runtime PM. When these conditions are met, we manually do
9482  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
9483  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
9484  * hang the machine.
9485  *
9486  * When we really reach PC8 or deeper states (not just when we allow it) we lose
9487  * the state of some registers, so when we come back from PC8+ we need to
9488  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
9489  * need to take care of the registers kept by RC6. Notice that this happens even
9490  * if we don't put the device in PCI D3 state (which is what currently happens
9491  * because of the runtime PM support).
9492  *
9493  * For more, read "Display Sequences for Package C8" on the hardware
9494  * documentation.
9495  */
9496 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
9497 {
9498         struct drm_device *dev = dev_priv->dev;
9499         uint32_t val;
9500
9501         DRM_DEBUG_KMS("Enabling package C8+\n");
9502
9503         if (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) {
9504                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9505                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
9506                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9507         }
9508
9509         lpt_disable_clkout_dp(dev);
9510         hsw_disable_lcpll(dev_priv, true, true);
9511 }
9512
9513 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
9514 {
9515         struct drm_device *dev = dev_priv->dev;
9516         uint32_t val;
9517
9518         DRM_DEBUG_KMS("Disabling package C8+\n");
9519
9520         hsw_restore_lcpll(dev_priv);
9521         lpt_init_pch_refclk(dev);
9522
9523         if (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) {
9524                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9525                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
9526                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9527         }
9528
9529         intel_prepare_ddi(dev);
9530 }
9531
9532 static void broxton_modeset_global_resources(struct drm_atomic_state *old_state)
9533 {
9534         struct drm_device *dev = old_state->dev;
9535         struct drm_i915_private *dev_priv = dev->dev_private;
9536         int max_pixclk = intel_mode_max_pixclk(dev, NULL);
9537         int req_cdclk;
9538
9539         /* see the comment in valleyview_modeset_global_resources */
9540         if (WARN_ON(max_pixclk < 0))
9541                 return;
9542
9543         req_cdclk = broxton_calc_cdclk(dev_priv, max_pixclk);
9544
9545         if (req_cdclk != dev_priv->cdclk_freq)
9546                 broxton_set_cdclk(dev, req_cdclk);
9547 }
9548
9549 /* compute the max rate for new configuration */
9550 static int ilk_max_pixel_rate(struct drm_i915_private *dev_priv)
9551 {
9552         struct drm_device *dev = dev_priv->dev;
9553         struct intel_crtc *intel_crtc;
9554         struct drm_crtc *crtc;
9555         int max_pixel_rate = 0;
9556         int pixel_rate;
9557
9558         for_each_crtc(dev, crtc) {
9559                 if (!crtc->state->enable)
9560                         continue;
9561
9562                 intel_crtc = to_intel_crtc(crtc);
9563                 pixel_rate = ilk_pipe_pixel_rate(intel_crtc->config);
9564
9565                 /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
9566                 if (IS_BROADWELL(dev) && intel_crtc->config->ips_enabled)
9567                         pixel_rate = DIV_ROUND_UP(pixel_rate * 100, 95);
9568
9569                 max_pixel_rate = max(max_pixel_rate, pixel_rate);
9570         }
9571
9572         return max_pixel_rate;
9573 }
9574
9575 static void broadwell_set_cdclk(struct drm_device *dev, int cdclk)
9576 {
9577         struct drm_i915_private *dev_priv = dev->dev_private;
9578         uint32_t val, data;
9579         int ret;
9580
9581         if (WARN((I915_READ(LCPLL_CTL) &
9582                   (LCPLL_PLL_DISABLE | LCPLL_PLL_LOCK |
9583                    LCPLL_CD_CLOCK_DISABLE | LCPLL_ROOT_CD_CLOCK_DISABLE |
9584                    LCPLL_CD2X_CLOCK_DISABLE | LCPLL_POWER_DOWN_ALLOW |
9585                    LCPLL_CD_SOURCE_FCLK)) != LCPLL_PLL_LOCK,
9586                  "trying to change cdclk frequency with cdclk not enabled\n"))
9587                 return;
9588
9589         mutex_lock(&dev_priv->rps.hw_lock);
9590         ret = sandybridge_pcode_write(dev_priv,
9591                                       BDW_PCODE_DISPLAY_FREQ_CHANGE_REQ, 0x0);
9592         mutex_unlock(&dev_priv->rps.hw_lock);
9593         if (ret) {
9594                 DRM_ERROR("failed to inform pcode about cdclk change\n");
9595                 return;
9596         }
9597
9598         val = I915_READ(LCPLL_CTL);
9599         val |= LCPLL_CD_SOURCE_FCLK;
9600         I915_WRITE(LCPLL_CTL, val);
9601
9602         if (wait_for_atomic_us(I915_READ(LCPLL_CTL) &
9603                                LCPLL_CD_SOURCE_FCLK_DONE, 1))
9604                 DRM_ERROR("Switching to FCLK failed\n");
9605
9606         val = I915_READ(LCPLL_CTL);
9607         val &= ~LCPLL_CLK_FREQ_MASK;
9608
9609         switch (cdclk) {
9610         case 450000:
9611                 val |= LCPLL_CLK_FREQ_450;
9612                 data = 0;
9613                 break;
9614         case 540000:
9615                 val |= LCPLL_CLK_FREQ_54O_BDW;
9616                 data = 1;
9617                 break;
9618         case 337500:
9619                 val |= LCPLL_CLK_FREQ_337_5_BDW;
9620                 data = 2;
9621                 break;
9622         case 675000:
9623                 val |= LCPLL_CLK_FREQ_675_BDW;
9624                 data = 3;
9625                 break;
9626         default:
9627                 WARN(1, "invalid cdclk frequency\n");
9628                 return;
9629         }
9630
9631         I915_WRITE(LCPLL_CTL, val);
9632
9633         val = I915_READ(LCPLL_CTL);
9634         val &= ~LCPLL_CD_SOURCE_FCLK;
9635         I915_WRITE(LCPLL_CTL, val);
9636
9637         if (wait_for_atomic_us((I915_READ(LCPLL_CTL) &
9638                                 LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9639                 DRM_ERROR("Switching back to LCPLL failed\n");
9640
9641         mutex_lock(&dev_priv->rps.hw_lock);
9642         sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ, data);
9643         mutex_unlock(&dev_priv->rps.hw_lock);
9644
9645         intel_update_cdclk(dev);
9646
9647         WARN(cdclk != dev_priv->cdclk_freq,
9648              "cdclk requested %d kHz but got %d kHz\n",
9649              cdclk, dev_priv->cdclk_freq);
9650 }
9651
9652 static int broadwell_calc_cdclk(struct drm_i915_private *dev_priv,
9653                               int max_pixel_rate)
9654 {
9655         int cdclk;
9656
9657         /*
9658          * FIXME should also account for plane ratio
9659          * once 64bpp pixel formats are supported.
9660          */
9661         if (max_pixel_rate > 540000)
9662                 cdclk = 675000;
9663         else if (max_pixel_rate > 450000)
9664                 cdclk = 540000;
9665         else if (max_pixel_rate > 337500)
9666                 cdclk = 450000;
9667         else
9668                 cdclk = 337500;
9669
9670         /*
9671          * FIXME move the cdclk caclulation to
9672          * compute_config() so we can fail gracegully.
9673          */
9674         if (cdclk > dev_priv->max_cdclk_freq) {
9675                 DRM_ERROR("requested cdclk (%d kHz) exceeds max (%d kHz)\n",
9676                           cdclk, dev_priv->max_cdclk_freq);
9677                 cdclk = dev_priv->max_cdclk_freq;
9678         }
9679
9680         return cdclk;
9681 }
9682
9683 static int broadwell_modeset_global_pipes(struct drm_atomic_state *state)
9684 {
9685         struct drm_i915_private *dev_priv = to_i915(state->dev);
9686         struct drm_crtc *crtc;
9687         struct drm_crtc_state *crtc_state;
9688         int max_pixclk = ilk_max_pixel_rate(dev_priv);
9689         int cdclk, i;
9690
9691         cdclk = broadwell_calc_cdclk(dev_priv, max_pixclk);
9692
9693         if (cdclk == dev_priv->cdclk_freq)
9694                 return 0;
9695
9696         /* add all active pipes to the state */
9697         for_each_crtc(state->dev, crtc) {
9698                 if (!crtc->state->enable)
9699                         continue;
9700
9701                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
9702                 if (IS_ERR(crtc_state))
9703                         return PTR_ERR(crtc_state);
9704         }
9705
9706         /* disable/enable all currently active pipes while we change cdclk */
9707         for_each_crtc_in_state(state, crtc, crtc_state, i)
9708                 if (crtc_state->enable)
9709                         crtc_state->mode_changed = true;
9710
9711         return 0;
9712 }
9713
9714 static void broadwell_modeset_global_resources(struct drm_atomic_state *state)
9715 {
9716         struct drm_device *dev = state->dev;
9717         struct drm_i915_private *dev_priv = dev->dev_private;
9718         int max_pixel_rate = ilk_max_pixel_rate(dev_priv);
9719         int req_cdclk = broadwell_calc_cdclk(dev_priv, max_pixel_rate);
9720
9721         if (req_cdclk != dev_priv->cdclk_freq)
9722                 broadwell_set_cdclk(dev, req_cdclk);
9723 }
9724
9725 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9726                                       struct intel_crtc_state *crtc_state)
9727 {
9728         if (!intel_ddi_pll_select(crtc, crtc_state))
9729                 return -EINVAL;
9730
9731         crtc->lowfreq_avail = false;
9732
9733         return 0;
9734 }
9735
9736 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9737                                 enum port port,
9738                                 struct intel_crtc_state *pipe_config)
9739 {
9740         switch (port) {
9741         case PORT_A:
9742                 pipe_config->ddi_pll_sel = SKL_DPLL0;
9743                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL1;
9744                 break;
9745         case PORT_B:
9746                 pipe_config->ddi_pll_sel = SKL_DPLL1;
9747                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL2;
9748                 break;
9749         case PORT_C:
9750                 pipe_config->ddi_pll_sel = SKL_DPLL2;
9751                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL3;
9752                 break;
9753         default:
9754                 DRM_ERROR("Incorrect port type\n");
9755         }
9756 }
9757
9758 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9759                                 enum port port,
9760                                 struct intel_crtc_state *pipe_config)
9761 {
9762         u32 temp, dpll_ctl1;
9763
9764         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9765         pipe_config->ddi_pll_sel = temp >> (port * 3 + 1);
9766
9767         switch (pipe_config->ddi_pll_sel) {
9768         case SKL_DPLL0:
9769                 /*
9770                  * On SKL the eDP DPLL (DPLL0 as we don't use SSC) is not part
9771                  * of the shared DPLL framework and thus needs to be read out
9772                  * separately
9773                  */
9774                 dpll_ctl1 = I915_READ(DPLL_CTRL1);
9775                 pipe_config->dpll_hw_state.ctrl1 = dpll_ctl1 & 0x3f;
9776                 break;
9777         case SKL_DPLL1:
9778                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL1;
9779                 break;
9780         case SKL_DPLL2:
9781                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL2;
9782                 break;
9783         case SKL_DPLL3:
9784                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL3;
9785                 break;
9786         }
9787 }
9788
9789 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9790                                 enum port port,
9791                                 struct intel_crtc_state *pipe_config)
9792 {
9793         pipe_config->ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9794
9795         switch (pipe_config->ddi_pll_sel) {
9796         case PORT_CLK_SEL_WRPLL1:
9797                 pipe_config->shared_dpll = DPLL_ID_WRPLL1;
9798                 break;
9799         case PORT_CLK_SEL_WRPLL2:
9800                 pipe_config->shared_dpll = DPLL_ID_WRPLL2;
9801                 break;
9802         }
9803 }
9804
9805 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9806                                        struct intel_crtc_state *pipe_config)
9807 {
9808         struct drm_device *dev = crtc->base.dev;
9809         struct drm_i915_private *dev_priv = dev->dev_private;
9810         struct intel_shared_dpll *pll;
9811         enum port port;
9812         uint32_t tmp;
9813
9814         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9815
9816         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9817
9818         if (IS_SKYLAKE(dev))
9819                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
9820         else if (IS_BROXTON(dev))
9821                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
9822         else
9823                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
9824
9825         if (pipe_config->shared_dpll >= 0) {
9826                 pll = &dev_priv->shared_dplls[pipe_config->shared_dpll];
9827
9828                 WARN_ON(!pll->get_hw_state(dev_priv, pll,
9829                                            &pipe_config->dpll_hw_state));
9830         }
9831
9832         /*
9833          * Haswell has only FDI/PCH transcoder A. It is which is connected to
9834          * DDI E. So just check whether this pipe is wired to DDI E and whether
9835          * the PCH transcoder is on.
9836          */
9837         if (INTEL_INFO(dev)->gen < 9 &&
9838             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
9839                 pipe_config->has_pch_encoder = true;
9840
9841                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
9842                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9843                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9844
9845                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9846         }
9847 }
9848
9849 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
9850                                     struct intel_crtc_state *pipe_config)
9851 {
9852         struct drm_device *dev = crtc->base.dev;
9853         struct drm_i915_private *dev_priv = dev->dev_private;
9854         enum intel_display_power_domain pfit_domain;
9855         uint32_t tmp;
9856
9857         if (!intel_display_power_is_enabled(dev_priv,
9858                                          POWER_DOMAIN_PIPE(crtc->pipe)))
9859                 return false;
9860
9861         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9862         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
9863
9864         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
9865         if (tmp & TRANS_DDI_FUNC_ENABLE) {
9866                 enum pipe trans_edp_pipe;
9867                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9868                 default:
9869                         WARN(1, "unknown pipe linked to edp transcoder\n");
9870                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9871                 case TRANS_DDI_EDP_INPUT_A_ON:
9872                         trans_edp_pipe = PIPE_A;
9873                         break;
9874                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
9875                         trans_edp_pipe = PIPE_B;
9876                         break;
9877                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
9878                         trans_edp_pipe = PIPE_C;
9879                         break;
9880                 }
9881
9882                 if (trans_edp_pipe == crtc->pipe)
9883                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
9884         }
9885
9886         if (!intel_display_power_is_enabled(dev_priv,
9887                         POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder)))
9888                 return false;
9889
9890         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
9891         if (!(tmp & PIPECONF_ENABLE))
9892                 return false;
9893
9894         haswell_get_ddi_port_state(crtc, pipe_config);
9895
9896         intel_get_pipe_timings(crtc, pipe_config);
9897
9898         if (INTEL_INFO(dev)->gen >= 9) {
9899                 skl_init_scalers(dev, crtc, pipe_config);
9900         }
9901
9902         pfit_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
9903
9904         if (INTEL_INFO(dev)->gen >= 9) {
9905                 pipe_config->scaler_state.scaler_id = -1;
9906                 pipe_config->scaler_state.scaler_users &= ~(1 << SKL_CRTC_INDEX);
9907         }
9908
9909         if (intel_display_power_is_enabled(dev_priv, pfit_domain)) {
9910                 if (INTEL_INFO(dev)->gen == 9)
9911                         skylake_get_pfit_config(crtc, pipe_config);
9912                 else if (INTEL_INFO(dev)->gen < 9)
9913                         ironlake_get_pfit_config(crtc, pipe_config);
9914                 else
9915                         MISSING_CASE(INTEL_INFO(dev)->gen);
9916         }
9917
9918         if (IS_HASWELL(dev))
9919                 pipe_config->ips_enabled = hsw_crtc_supports_ips(crtc) &&
9920                         (I915_READ(IPS_CTL) & IPS_ENABLE);
9921
9922         if (pipe_config->cpu_transcoder != TRANSCODER_EDP) {
9923                 pipe_config->pixel_multiplier =
9924                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
9925         } else {
9926                 pipe_config->pixel_multiplier = 1;
9927         }
9928
9929         return true;
9930 }
9931
9932 static void i845_update_cursor(struct drm_crtc *crtc, u32 base)
9933 {
9934         struct drm_device *dev = crtc->dev;
9935         struct drm_i915_private *dev_priv = dev->dev_private;
9936         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9937         uint32_t cntl = 0, size = 0;
9938
9939         if (base) {
9940                 unsigned int width = intel_crtc->base.cursor->state->crtc_w;
9941                 unsigned int height = intel_crtc->base.cursor->state->crtc_h;
9942                 unsigned int stride = roundup_pow_of_two(width) * 4;
9943
9944                 switch (stride) {
9945                 default:
9946                         WARN_ONCE(1, "Invalid cursor width/stride, width=%u, stride=%u\n",
9947                                   width, stride);
9948                         stride = 256;
9949                         /* fallthrough */
9950                 case 256:
9951                 case 512:
9952                 case 1024:
9953                 case 2048:
9954                         break;
9955                 }
9956
9957                 cntl |= CURSOR_ENABLE |
9958                         CURSOR_GAMMA_ENABLE |
9959                         CURSOR_FORMAT_ARGB |
9960                         CURSOR_STRIDE(stride);
9961
9962                 size = (height << 12) | width;
9963         }
9964
9965         if (intel_crtc->cursor_cntl != 0 &&
9966             (intel_crtc->cursor_base != base ||
9967              intel_crtc->cursor_size != size ||
9968              intel_crtc->cursor_cntl != cntl)) {
9969                 /* On these chipsets we can only modify the base/size/stride
9970                  * whilst the cursor is disabled.
9971                  */
9972                 I915_WRITE(_CURACNTR, 0);
9973                 POSTING_READ(_CURACNTR);
9974                 intel_crtc->cursor_cntl = 0;
9975         }
9976
9977         if (intel_crtc->cursor_base != base) {
9978                 I915_WRITE(_CURABASE, base);
9979                 intel_crtc->cursor_base = base;
9980         }
9981
9982         if (intel_crtc->cursor_size != size) {
9983                 I915_WRITE(CURSIZE, size);
9984                 intel_crtc->cursor_size = size;
9985         }
9986
9987         if (intel_crtc->cursor_cntl != cntl) {
9988                 I915_WRITE(_CURACNTR, cntl);
9989                 POSTING_READ(_CURACNTR);
9990                 intel_crtc->cursor_cntl = cntl;
9991         }
9992 }
9993
9994 static void i9xx_update_cursor(struct drm_crtc *crtc, u32 base)
9995 {
9996         struct drm_device *dev = crtc->dev;
9997         struct drm_i915_private *dev_priv = dev->dev_private;
9998         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9999         int pipe = intel_crtc->pipe;
10000         uint32_t cntl;
10001
10002         cntl = 0;
10003         if (base) {
10004                 cntl = MCURSOR_GAMMA_ENABLE;
10005                 switch (intel_crtc->base.cursor->state->crtc_w) {
10006                         case 64:
10007                                 cntl |= CURSOR_MODE_64_ARGB_AX;
10008                                 break;
10009                         case 128:
10010                                 cntl |= CURSOR_MODE_128_ARGB_AX;
10011                                 break;
10012                         case 256:
10013                                 cntl |= CURSOR_MODE_256_ARGB_AX;
10014                                 break;
10015                         default:
10016                                 MISSING_CASE(intel_crtc->base.cursor->state->crtc_w);
10017                                 return;
10018                 }
10019                 cntl |= pipe << 28; /* Connect to correct pipe */
10020
10021                 if (IS_HASWELL(dev) || IS_BROADWELL(dev))
10022                         cntl |= CURSOR_PIPE_CSC_ENABLE;
10023         }
10024
10025         if (crtc->cursor->state->rotation == BIT(DRM_ROTATE_180))
10026                 cntl |= CURSOR_ROTATE_180;
10027
10028         if (intel_crtc->cursor_cntl != cntl) {
10029                 I915_WRITE(CURCNTR(pipe), cntl);
10030                 POSTING_READ(CURCNTR(pipe));
10031                 intel_crtc->cursor_cntl = cntl;
10032         }
10033
10034         /* and commit changes on next vblank */
10035         I915_WRITE(CURBASE(pipe), base);
10036         POSTING_READ(CURBASE(pipe));
10037
10038         intel_crtc->cursor_base = base;
10039 }
10040
10041 /* If no-part of the cursor is visible on the framebuffer, then the GPU may hang... */
10042 static void intel_crtc_update_cursor(struct drm_crtc *crtc,
10043                                      bool on)
10044 {
10045         struct drm_device *dev = crtc->dev;
10046         struct drm_i915_private *dev_priv = dev->dev_private;
10047         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10048         int pipe = intel_crtc->pipe;
10049         int x = crtc->cursor_x;
10050         int y = crtc->cursor_y;
10051         u32 base = 0, pos = 0;
10052
10053         if (on)
10054                 base = intel_crtc->cursor_addr;
10055
10056         if (x >= intel_crtc->config->pipe_src_w)
10057                 base = 0;
10058
10059         if (y >= intel_crtc->config->pipe_src_h)
10060                 base = 0;
10061
10062         if (x < 0) {
10063                 if (x + intel_crtc->base.cursor->state->crtc_w <= 0)
10064                         base = 0;
10065
10066                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
10067                 x = -x;
10068         }
10069         pos |= x << CURSOR_X_SHIFT;
10070
10071         if (y < 0) {
10072                 if (y + intel_crtc->base.cursor->state->crtc_h <= 0)
10073                         base = 0;
10074
10075                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
10076                 y = -y;
10077         }
10078         pos |= y << CURSOR_Y_SHIFT;
10079
10080         if (base == 0 && intel_crtc->cursor_base == 0)
10081                 return;
10082
10083         I915_WRITE(CURPOS(pipe), pos);
10084
10085         /* ILK+ do this automagically */
10086         if (HAS_GMCH_DISPLAY(dev) &&
10087             crtc->cursor->state->rotation == BIT(DRM_ROTATE_180)) {
10088                 base += (intel_crtc->base.cursor->state->crtc_h *
10089                         intel_crtc->base.cursor->state->crtc_w - 1) * 4;
10090         }
10091
10092         if (IS_845G(dev) || IS_I865G(dev))
10093                 i845_update_cursor(crtc, base);
10094         else
10095                 i9xx_update_cursor(crtc, base);
10096 }
10097
10098 static bool cursor_size_ok(struct drm_device *dev,
10099                            uint32_t width, uint32_t height)
10100 {
10101         if (width == 0 || height == 0)
10102                 return false;
10103
10104         /*
10105          * 845g/865g are special in that they are only limited by
10106          * the width of their cursors, the height is arbitrary up to
10107          * the precision of the register. Everything else requires
10108          * square cursors, limited to a few power-of-two sizes.
10109          */
10110         if (IS_845G(dev) || IS_I865G(dev)) {
10111                 if ((width & 63) != 0)
10112                         return false;
10113
10114                 if (width > (IS_845G(dev) ? 64 : 512))
10115                         return false;
10116
10117                 if (height > 1023)
10118                         return false;
10119         } else {
10120                 switch (width | height) {
10121                 case 256:
10122                 case 128:
10123                         if (IS_GEN2(dev))
10124                                 return false;
10125                 case 64:
10126                         break;
10127                 default:
10128                         return false;
10129                 }
10130         }
10131
10132         return true;
10133 }
10134
10135 static void intel_crtc_gamma_set(struct drm_crtc *crtc, u16 *red, u16 *green,
10136                                  u16 *blue, uint32_t start, uint32_t size)
10137 {
10138         int end = (start + size > 256) ? 256 : start + size, i;
10139         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10140
10141         for (i = start; i < end; i++) {
10142                 intel_crtc->lut_r[i] = red[i] >> 8;
10143                 intel_crtc->lut_g[i] = green[i] >> 8;
10144                 intel_crtc->lut_b[i] = blue[i] >> 8;
10145         }
10146
10147         intel_crtc_load_lut(crtc);
10148 }
10149
10150 /* VESA 640x480x72Hz mode to set on the pipe */
10151 static struct drm_display_mode load_detect_mode = {
10152         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10153                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10154 };
10155
10156 struct drm_framebuffer *
10157 __intel_framebuffer_create(struct drm_device *dev,
10158                            struct drm_mode_fb_cmd2 *mode_cmd,
10159                            struct drm_i915_gem_object *obj)
10160 {
10161         struct intel_framebuffer *intel_fb;
10162         int ret;
10163
10164         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10165         if (!intel_fb) {
10166                 drm_gem_object_unreference(&obj->base);
10167                 return ERR_PTR(-ENOMEM);
10168         }
10169
10170         ret = intel_framebuffer_init(dev, intel_fb, mode_cmd, obj);
10171         if (ret)
10172                 goto err;
10173
10174         return &intel_fb->base;
10175 err:
10176         drm_gem_object_unreference(&obj->base);
10177         kfree(intel_fb);
10178
10179         return ERR_PTR(ret);
10180 }
10181
10182 static struct drm_framebuffer *
10183 intel_framebuffer_create(struct drm_device *dev,
10184                          struct drm_mode_fb_cmd2 *mode_cmd,
10185                          struct drm_i915_gem_object *obj)
10186 {
10187         struct drm_framebuffer *fb;
10188         int ret;
10189
10190         ret = i915_mutex_lock_interruptible(dev);
10191         if (ret)
10192                 return ERR_PTR(ret);
10193         fb = __intel_framebuffer_create(dev, mode_cmd, obj);
10194         mutex_unlock(&dev->struct_mutex);
10195
10196         return fb;
10197 }
10198
10199 static u32
10200 intel_framebuffer_pitch_for_width(int width, int bpp)
10201 {
10202         u32 pitch = DIV_ROUND_UP(width * bpp, 8);
10203         return ALIGN(pitch, 64);
10204 }
10205
10206 static u32
10207 intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
10208 {
10209         u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
10210         return PAGE_ALIGN(pitch * mode->vdisplay);
10211 }
10212
10213 static struct drm_framebuffer *
10214 intel_framebuffer_create_for_mode(struct drm_device *dev,
10215                                   struct drm_display_mode *mode,
10216                                   int depth, int bpp)
10217 {
10218         struct drm_i915_gem_object *obj;
10219         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
10220
10221         obj = i915_gem_alloc_object(dev,
10222                                     intel_framebuffer_size_for_mode(mode, bpp));
10223         if (obj == NULL)
10224                 return ERR_PTR(-ENOMEM);
10225
10226         mode_cmd.width = mode->hdisplay;
10227         mode_cmd.height = mode->vdisplay;
10228         mode_cmd.pitches[0] = intel_framebuffer_pitch_for_width(mode_cmd.width,
10229                                                                 bpp);
10230         mode_cmd.pixel_format = drm_mode_legacy_fb_format(bpp, depth);
10231
10232         return intel_framebuffer_create(dev, &mode_cmd, obj);
10233 }
10234
10235 static struct drm_framebuffer *
10236 mode_fits_in_fbdev(struct drm_device *dev,
10237                    struct drm_display_mode *mode)
10238 {
10239 #ifdef CONFIG_DRM_I915_FBDEV
10240         struct drm_i915_private *dev_priv = dev->dev_private;
10241         struct drm_i915_gem_object *obj;
10242         struct drm_framebuffer *fb;
10243
10244         if (!dev_priv->fbdev)
10245                 return NULL;
10246
10247         if (!dev_priv->fbdev->fb)
10248                 return NULL;
10249
10250         obj = dev_priv->fbdev->fb->obj;
10251         BUG_ON(!obj);
10252
10253         fb = &dev_priv->fbdev->fb->base;
10254         if (fb->pitches[0] < intel_framebuffer_pitch_for_width(mode->hdisplay,
10255                                                                fb->bits_per_pixel))
10256                 return NULL;
10257
10258         if (obj->base.size < mode->vdisplay * fb->pitches[0])
10259                 return NULL;
10260
10261         return fb;
10262 #else
10263         return NULL;
10264 #endif
10265 }
10266
10267 static int intel_modeset_setup_plane_state(struct drm_atomic_state *state,
10268                                            struct drm_crtc *crtc,
10269                                            struct drm_display_mode *mode,
10270                                            struct drm_framebuffer *fb,
10271                                            int x, int y)
10272 {
10273         struct drm_plane_state *plane_state;
10274         int hdisplay, vdisplay;
10275         int ret;
10276
10277         plane_state = drm_atomic_get_plane_state(state, crtc->primary);
10278         if (IS_ERR(plane_state))
10279                 return PTR_ERR(plane_state);
10280
10281         if (mode)
10282                 drm_crtc_get_hv_timing(mode, &hdisplay, &vdisplay);
10283         else
10284                 hdisplay = vdisplay = 0;
10285
10286         ret = drm_atomic_set_crtc_for_plane(plane_state, fb ? crtc : NULL);
10287         if (ret)
10288                 return ret;
10289         drm_atomic_set_fb_for_plane(plane_state, fb);
10290         plane_state->crtc_x = 0;
10291         plane_state->crtc_y = 0;
10292         plane_state->crtc_w = hdisplay;
10293         plane_state->crtc_h = vdisplay;
10294         plane_state->src_x = x << 16;
10295         plane_state->src_y = y << 16;
10296         plane_state->src_w = hdisplay << 16;
10297         plane_state->src_h = vdisplay << 16;
10298
10299         return 0;
10300 }
10301
10302 bool intel_get_load_detect_pipe(struct drm_connector *connector,
10303                                 struct drm_display_mode *mode,
10304                                 struct intel_load_detect_pipe *old,
10305                                 struct drm_modeset_acquire_ctx *ctx)
10306 {
10307         struct intel_crtc *intel_crtc;
10308         struct intel_encoder *intel_encoder =
10309                 intel_attached_encoder(connector);
10310         struct drm_crtc *possible_crtc;
10311         struct drm_encoder *encoder = &intel_encoder->base;
10312         struct drm_crtc *crtc = NULL;
10313         struct drm_device *dev = encoder->dev;
10314         struct drm_framebuffer *fb;
10315         struct drm_mode_config *config = &dev->mode_config;
10316         struct drm_atomic_state *state = NULL;
10317         struct drm_connector_state *connector_state;
10318         struct intel_crtc_state *crtc_state;
10319         int ret, i = -1;
10320
10321         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10322                       connector->base.id, connector->name,
10323                       encoder->base.id, encoder->name);
10324
10325 retry:
10326         ret = drm_modeset_lock(&config->connection_mutex, ctx);
10327         if (ret)
10328                 goto fail_unlock;
10329
10330         /*
10331          * Algorithm gets a little messy:
10332          *
10333          *   - if the connector already has an assigned crtc, use it (but make
10334          *     sure it's on first)
10335          *
10336          *   - try to find the first unused crtc that can drive this connector,
10337          *     and use that if we find one
10338          */
10339
10340         /* See if we already have a CRTC for this connector */
10341         if (encoder->crtc) {
10342                 crtc = encoder->crtc;
10343
10344                 ret = drm_modeset_lock(&crtc->mutex, ctx);
10345                 if (ret)
10346                         goto fail_unlock;
10347                 ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
10348                 if (ret)
10349                         goto fail_unlock;
10350
10351                 old->dpms_mode = connector->dpms;
10352                 old->load_detect_temp = false;
10353
10354                 /* Make sure the crtc and connector are running */
10355                 if (connector->dpms != DRM_MODE_DPMS_ON)
10356                         connector->funcs->dpms(connector, DRM_MODE_DPMS_ON);
10357
10358                 return true;
10359         }
10360
10361         /* Find an unused one (if possible) */
10362         for_each_crtc(dev, possible_crtc) {
10363                 i++;
10364                 if (!(encoder->possible_crtcs & (1 << i)))
10365                         continue;
10366                 if (possible_crtc->state->enable)
10367                         continue;
10368                 /* This can occur when applying the pipe A quirk on resume. */
10369                 if (to_intel_crtc(possible_crtc)->new_enabled)
10370                         continue;
10371
10372                 crtc = possible_crtc;
10373                 break;
10374         }
10375
10376         /*
10377          * If we didn't find an unused CRTC, don't use any.
10378          */
10379         if (!crtc) {
10380                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
10381                 goto fail_unlock;
10382         }
10383
10384         ret = drm_modeset_lock(&crtc->mutex, ctx);
10385         if (ret)
10386                 goto fail_unlock;
10387         ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
10388         if (ret)
10389                 goto fail_unlock;
10390         intel_encoder->new_crtc = to_intel_crtc(crtc);
10391         to_intel_connector(connector)->new_encoder = intel_encoder;
10392
10393         intel_crtc = to_intel_crtc(crtc);
10394         intel_crtc->new_enabled = true;
10395         old->dpms_mode = connector->dpms;
10396         old->load_detect_temp = true;
10397         old->release_fb = NULL;
10398
10399         state = drm_atomic_state_alloc(dev);
10400         if (!state)
10401                 return false;
10402
10403         state->acquire_ctx = ctx;
10404
10405         connector_state = drm_atomic_get_connector_state(state, connector);
10406         if (IS_ERR(connector_state)) {
10407                 ret = PTR_ERR(connector_state);
10408                 goto fail;
10409         }
10410
10411         connector_state->crtc = crtc;
10412         connector_state->best_encoder = &intel_encoder->base;
10413
10414         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10415         if (IS_ERR(crtc_state)) {
10416                 ret = PTR_ERR(crtc_state);
10417                 goto fail;
10418         }
10419
10420         crtc_state->base.active = crtc_state->base.enable = true;
10421
10422         if (!mode)
10423                 mode = &load_detect_mode;
10424
10425         /* We need a framebuffer large enough to accommodate all accesses
10426          * that the plane may generate whilst we perform load detection.
10427          * We can not rely on the fbcon either being present (we get called
10428          * during its initialisation to detect all boot displays, or it may
10429          * not even exist) or that it is large enough to satisfy the
10430          * requested mode.
10431          */
10432         fb = mode_fits_in_fbdev(dev, mode);
10433         if (fb == NULL) {
10434                 DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
10435                 fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
10436                 old->release_fb = fb;
10437         } else
10438                 DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
10439         if (IS_ERR(fb)) {
10440                 DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
10441                 goto fail;
10442         }
10443
10444         ret = intel_modeset_setup_plane_state(state, crtc, mode, fb, 0, 0);
10445         if (ret)
10446                 goto fail;
10447
10448         drm_mode_copy(&crtc_state->base.mode, mode);
10449
10450         if (intel_set_mode(state)) {
10451                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
10452                 if (old->release_fb)
10453                         old->release_fb->funcs->destroy(old->release_fb);
10454                 goto fail;
10455         }
10456         crtc->primary->crtc = crtc;
10457
10458         /* let the connector get through one full cycle before testing */
10459         intel_wait_for_vblank(dev, intel_crtc->pipe);
10460         return true;
10461
10462  fail:
10463         intel_crtc->new_enabled = crtc->state->enable;
10464 fail_unlock:
10465         drm_atomic_state_free(state);
10466         state = NULL;
10467
10468         if (ret == -EDEADLK) {
10469                 drm_modeset_backoff(ctx);
10470                 goto retry;
10471         }
10472
10473         return false;
10474 }
10475
10476 void intel_release_load_detect_pipe(struct drm_connector *connector,
10477                                     struct intel_load_detect_pipe *old,
10478                                     struct drm_modeset_acquire_ctx *ctx)
10479 {
10480         struct drm_device *dev = connector->dev;
10481         struct intel_encoder *intel_encoder =
10482                 intel_attached_encoder(connector);
10483         struct drm_encoder *encoder = &intel_encoder->base;
10484         struct drm_crtc *crtc = encoder->crtc;
10485         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10486         struct drm_atomic_state *state;
10487         struct drm_connector_state *connector_state;
10488         struct intel_crtc_state *crtc_state;
10489         int ret;
10490
10491         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10492                       connector->base.id, connector->name,
10493                       encoder->base.id, encoder->name);
10494
10495         if (old->load_detect_temp) {
10496                 state = drm_atomic_state_alloc(dev);
10497                 if (!state)
10498                         goto fail;
10499
10500                 state->acquire_ctx = ctx;
10501
10502                 connector_state = drm_atomic_get_connector_state(state, connector);
10503                 if (IS_ERR(connector_state))
10504                         goto fail;
10505
10506                 crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10507                 if (IS_ERR(crtc_state))
10508                         goto fail;
10509
10510                 to_intel_connector(connector)->new_encoder = NULL;
10511                 intel_encoder->new_crtc = NULL;
10512                 intel_crtc->new_enabled = false;
10513
10514                 connector_state->best_encoder = NULL;
10515                 connector_state->crtc = NULL;
10516
10517                 crtc_state->base.enable = crtc_state->base.active = false;
10518
10519                 ret = intel_modeset_setup_plane_state(state, crtc, NULL, NULL,
10520                                                       0, 0);
10521                 if (ret)
10522                         goto fail;
10523
10524                 ret = intel_set_mode(state);
10525                 if (ret)
10526                         goto fail;
10527
10528                 if (old->release_fb) {
10529                         drm_framebuffer_unregister_private(old->release_fb);
10530                         drm_framebuffer_unreference(old->release_fb);
10531                 }
10532
10533                 return;
10534         }
10535
10536         /* Switch crtc and encoder back off if necessary */
10537         if (old->dpms_mode != DRM_MODE_DPMS_ON)
10538                 connector->funcs->dpms(connector, old->dpms_mode);
10539
10540         return;
10541 fail:
10542         DRM_DEBUG_KMS("Couldn't release load detect pipe.\n");
10543         drm_atomic_state_free(state);
10544 }
10545
10546 static int i9xx_pll_refclk(struct drm_device *dev,
10547                            const struct intel_crtc_state *pipe_config)
10548 {
10549         struct drm_i915_private *dev_priv = dev->dev_private;
10550         u32 dpll = pipe_config->dpll_hw_state.dpll;
10551
10552         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10553                 return dev_priv->vbt.lvds_ssc_freq;
10554         else if (HAS_PCH_SPLIT(dev))
10555                 return 120000;
10556         else if (!IS_GEN2(dev))
10557                 return 96000;
10558         else
10559                 return 48000;
10560 }
10561
10562 /* Returns the clock of the currently programmed mode of the given pipe. */
10563 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
10564                                 struct intel_crtc_state *pipe_config)
10565 {
10566         struct drm_device *dev = crtc->base.dev;
10567         struct drm_i915_private *dev_priv = dev->dev_private;
10568         int pipe = pipe_config->cpu_transcoder;
10569         u32 dpll = pipe_config->dpll_hw_state.dpll;
10570         u32 fp;
10571         intel_clock_t clock;
10572         int refclk = i9xx_pll_refclk(dev, pipe_config);
10573
10574         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10575                 fp = pipe_config->dpll_hw_state.fp0;
10576         else
10577                 fp = pipe_config->dpll_hw_state.fp1;
10578
10579         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10580         if (IS_PINEVIEW(dev)) {
10581                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10582                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10583         } else {
10584                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10585                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10586         }
10587
10588         if (!IS_GEN2(dev)) {
10589                 if (IS_PINEVIEW(dev))
10590                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10591                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10592                 else
10593                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10594                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10595
10596                 switch (dpll & DPLL_MODE_MASK) {
10597                 case DPLLB_MODE_DAC_SERIAL:
10598                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10599                                 5 : 10;
10600                         break;
10601                 case DPLLB_MODE_LVDS:
10602                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10603                                 7 : 14;
10604                         break;
10605                 default:
10606                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10607                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10608                         return;
10609                 }
10610
10611                 if (IS_PINEVIEW(dev))
10612                         pineview_clock(refclk, &clock);
10613                 else
10614                         i9xx_clock(refclk, &clock);
10615         } else {
10616                 u32 lvds = IS_I830(dev) ? 0 : I915_READ(LVDS);
10617                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10618
10619                 if (is_lvds) {
10620                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10621                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10622
10623                         if (lvds & LVDS_CLKB_POWER_UP)
10624                                 clock.p2 = 7;
10625                         else
10626                                 clock.p2 = 14;
10627                 } else {
10628                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10629                                 clock.p1 = 2;
10630                         else {
10631                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10632                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10633                         }
10634                         if (dpll & PLL_P2_DIVIDE_BY_4)
10635                                 clock.p2 = 4;
10636                         else
10637                                 clock.p2 = 2;
10638                 }
10639
10640                 i9xx_clock(refclk, &clock);
10641         }
10642
10643         /*
10644          * This value includes pixel_multiplier. We will use
10645          * port_clock to compute adjusted_mode.crtc_clock in the
10646          * encoder's get_config() function.
10647          */
10648         pipe_config->port_clock = clock.dot;
10649 }
10650
10651 int intel_dotclock_calculate(int link_freq,
10652                              const struct intel_link_m_n *m_n)
10653 {
10654         /*
10655          * The calculation for the data clock is:
10656          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10657          * But we want to avoid losing precison if possible, so:
10658          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10659          *
10660          * and the link clock is simpler:
10661          * link_clock = (m * link_clock) / n
10662          */
10663
10664         if (!m_n->link_n)
10665                 return 0;
10666
10667         return div_u64((u64)m_n->link_m * link_freq, m_n->link_n);
10668 }
10669
10670 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10671                                    struct intel_crtc_state *pipe_config)
10672 {
10673         struct drm_device *dev = crtc->base.dev;
10674
10675         /* read out port_clock from the DPLL */
10676         i9xx_crtc_clock_get(crtc, pipe_config);
10677
10678         /*
10679          * This value does not include pixel_multiplier.
10680          * We will check that port_clock and adjusted_mode.crtc_clock
10681          * agree once we know their relationship in the encoder's
10682          * get_config() function.
10683          */
10684         pipe_config->base.adjusted_mode.crtc_clock =
10685                 intel_dotclock_calculate(intel_fdi_link_freq(dev) * 10000,
10686                                          &pipe_config->fdi_m_n);
10687 }
10688
10689 /** Returns the currently programmed mode of the given pipe. */
10690 struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
10691                                              struct drm_crtc *crtc)
10692 {
10693         struct drm_i915_private *dev_priv = dev->dev_private;
10694         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10695         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
10696         struct drm_display_mode *mode;
10697         struct intel_crtc_state pipe_config;
10698         int htot = I915_READ(HTOTAL(cpu_transcoder));
10699         int hsync = I915_READ(HSYNC(cpu_transcoder));
10700         int vtot = I915_READ(VTOTAL(cpu_transcoder));
10701         int vsync = I915_READ(VSYNC(cpu_transcoder));
10702         enum pipe pipe = intel_crtc->pipe;
10703
10704         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10705         if (!mode)
10706                 return NULL;
10707
10708         /*
10709          * Construct a pipe_config sufficient for getting the clock info
10710          * back out of crtc_clock_get.
10711          *
10712          * Note, if LVDS ever uses a non-1 pixel multiplier, we'll need
10713          * to use a real value here instead.
10714          */
10715         pipe_config.cpu_transcoder = (enum transcoder) pipe;
10716         pipe_config.pixel_multiplier = 1;
10717         pipe_config.dpll_hw_state.dpll = I915_READ(DPLL(pipe));
10718         pipe_config.dpll_hw_state.fp0 = I915_READ(FP0(pipe));
10719         pipe_config.dpll_hw_state.fp1 = I915_READ(FP1(pipe));
10720         i9xx_crtc_clock_get(intel_crtc, &pipe_config);
10721
10722         mode->clock = pipe_config.port_clock / pipe_config.pixel_multiplier;
10723         mode->hdisplay = (htot & 0xffff) + 1;
10724         mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
10725         mode->hsync_start = (hsync & 0xffff) + 1;
10726         mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
10727         mode->vdisplay = (vtot & 0xffff) + 1;
10728         mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
10729         mode->vsync_start = (vsync & 0xffff) + 1;
10730         mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
10731
10732         drm_mode_set_name(mode);
10733
10734         return mode;
10735 }
10736
10737 static void intel_decrease_pllclock(struct drm_crtc *crtc)
10738 {
10739         struct drm_device *dev = crtc->dev;
10740         struct drm_i915_private *dev_priv = dev->dev_private;
10741         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10742
10743         if (!HAS_GMCH_DISPLAY(dev))
10744                 return;
10745
10746         if (!dev_priv->lvds_downclock_avail)
10747                 return;
10748
10749         /*
10750          * Since this is called by a timer, we should never get here in
10751          * the manual case.
10752          */
10753         if (!HAS_PIPE_CXSR(dev) && intel_crtc->lowfreq_avail) {
10754                 int pipe = intel_crtc->pipe;
10755                 int dpll_reg = DPLL(pipe);
10756                 int dpll;
10757
10758                 DRM_DEBUG_DRIVER("downclocking LVDS\n");
10759
10760                 assert_panel_unlocked(dev_priv, pipe);
10761
10762                 dpll = I915_READ(dpll_reg);
10763                 dpll |= DISPLAY_RATE_SELECT_FPA1;
10764                 I915_WRITE(dpll_reg, dpll);
10765                 intel_wait_for_vblank(dev, pipe);
10766                 dpll = I915_READ(dpll_reg);
10767                 if (!(dpll & DISPLAY_RATE_SELECT_FPA1))
10768                         DRM_DEBUG_DRIVER("failed to downclock LVDS!\n");
10769         }
10770
10771 }
10772
10773 void intel_mark_busy(struct drm_device *dev)
10774 {
10775         struct drm_i915_private *dev_priv = dev->dev_private;
10776
10777         if (dev_priv->mm.busy)
10778                 return;
10779
10780         intel_runtime_pm_get(dev_priv);
10781         i915_update_gfx_val(dev_priv);
10782         if (INTEL_INFO(dev)->gen >= 6)
10783                 gen6_rps_busy(dev_priv);
10784         dev_priv->mm.busy = true;
10785 }
10786
10787 void intel_mark_idle(struct drm_device *dev)
10788 {
10789         struct drm_i915_private *dev_priv = dev->dev_private;
10790         struct drm_crtc *crtc;
10791
10792         if (!dev_priv->mm.busy)
10793                 return;
10794
10795         dev_priv->mm.busy = false;
10796
10797         for_each_crtc(dev, crtc) {
10798                 if (!crtc->primary->fb)
10799                         continue;
10800
10801                 intel_decrease_pllclock(crtc);
10802         }
10803
10804         if (INTEL_INFO(dev)->gen >= 6)
10805                 gen6_rps_idle(dev->dev_private);
10806
10807         intel_runtime_pm_put(dev_priv);
10808 }
10809
10810 static void intel_crtc_destroy(struct drm_crtc *crtc)
10811 {
10812         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10813         struct drm_device *dev = crtc->dev;
10814         struct intel_unpin_work *work;
10815
10816         spin_lock_irq(&dev->event_lock);
10817         work = intel_crtc->unpin_work;
10818         intel_crtc->unpin_work = NULL;
10819         spin_unlock_irq(&dev->event_lock);
10820
10821         if (work) {
10822                 cancel_work_sync(&work->work);
10823                 kfree(work);
10824         }
10825
10826         drm_crtc_cleanup(crtc);
10827
10828         kfree(intel_crtc);
10829 }
10830
10831 static void intel_unpin_work_fn(struct work_struct *__work)
10832 {
10833         struct intel_unpin_work *work =
10834                 container_of(__work, struct intel_unpin_work, work);
10835         struct drm_device *dev = work->crtc->dev;
10836         enum pipe pipe = to_intel_crtc(work->crtc)->pipe;
10837
10838         mutex_lock(&dev->struct_mutex);
10839         intel_unpin_fb_obj(work->old_fb, work->crtc->primary->state);
10840         drm_gem_object_unreference(&work->pending_flip_obj->base);
10841
10842         intel_fbc_update(dev);
10843
10844         if (work->flip_queued_req)
10845                 i915_gem_request_assign(&work->flip_queued_req, NULL);
10846         mutex_unlock(&dev->struct_mutex);
10847
10848         intel_frontbuffer_flip_complete(dev, INTEL_FRONTBUFFER_PRIMARY(pipe));
10849         drm_framebuffer_unreference(work->old_fb);
10850
10851         BUG_ON(atomic_read(&to_intel_crtc(work->crtc)->unpin_work_count) == 0);
10852         atomic_dec(&to_intel_crtc(work->crtc)->unpin_work_count);
10853
10854         kfree(work);
10855 }
10856
10857 static void do_intel_finish_page_flip(struct drm_device *dev,
10858                                       struct drm_crtc *crtc)
10859 {
10860         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10861         struct intel_unpin_work *work;
10862         unsigned long flags;
10863
10864         /* Ignore early vblank irqs */
10865         if (intel_crtc == NULL)
10866                 return;
10867
10868         /*
10869          * This is called both by irq handlers and the reset code (to complete
10870          * lost pageflips) so needs the full irqsave spinlocks.
10871          */
10872         spin_lock_irqsave(&dev->event_lock, flags);
10873         work = intel_crtc->unpin_work;
10874
10875         /* Ensure we don't miss a work->pending update ... */
10876         smp_rmb();
10877
10878         if (work == NULL || atomic_read(&work->pending) < INTEL_FLIP_COMPLETE) {
10879                 spin_unlock_irqrestore(&dev->event_lock, flags);
10880                 return;
10881         }
10882
10883         page_flip_completed(intel_crtc);
10884
10885         spin_unlock_irqrestore(&dev->event_lock, flags);
10886 }
10887
10888 void intel_finish_page_flip(struct drm_device *dev, int pipe)
10889 {
10890         struct drm_i915_private *dev_priv = dev->dev_private;
10891         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
10892
10893         do_intel_finish_page_flip(dev, crtc);
10894 }
10895
10896 void intel_finish_page_flip_plane(struct drm_device *dev, int plane)
10897 {
10898         struct drm_i915_private *dev_priv = dev->dev_private;
10899         struct drm_crtc *crtc = dev_priv->plane_to_crtc_mapping[plane];
10900
10901         do_intel_finish_page_flip(dev, crtc);
10902 }
10903
10904 /* Is 'a' after or equal to 'b'? */
10905 static bool g4x_flip_count_after_eq(u32 a, u32 b)
10906 {
10907         return !((a - b) & 0x80000000);
10908 }
10909
10910 static bool page_flip_finished(struct intel_crtc *crtc)
10911 {
10912         struct drm_device *dev = crtc->base.dev;
10913         struct drm_i915_private *dev_priv = dev->dev_private;
10914
10915         if (i915_reset_in_progress(&dev_priv->gpu_error) ||
10916             crtc->reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
10917                 return true;
10918
10919         /*
10920          * The relevant registers doen't exist on pre-ctg.
10921          * As the flip done interrupt doesn't trigger for mmio
10922          * flips on gmch platforms, a flip count check isn't
10923          * really needed there. But since ctg has the registers,
10924          * include it in the check anyway.
10925          */
10926         if (INTEL_INFO(dev)->gen < 5 && !IS_G4X(dev))
10927                 return true;
10928
10929         /*
10930          * A DSPSURFLIVE check isn't enough in case the mmio and CS flips
10931          * used the same base address. In that case the mmio flip might
10932          * have completed, but the CS hasn't even executed the flip yet.
10933          *
10934          * A flip count check isn't enough as the CS might have updated
10935          * the base address just after start of vblank, but before we
10936          * managed to process the interrupt. This means we'd complete the
10937          * CS flip too soon.
10938          *
10939          * Combining both checks should get us a good enough result. It may
10940          * still happen that the CS flip has been executed, but has not
10941          * yet actually completed. But in case the base address is the same
10942          * anyway, we don't really care.
10943          */
10944         return (I915_READ(DSPSURFLIVE(crtc->plane)) & ~0xfff) ==
10945                 crtc->unpin_work->gtt_offset &&
10946                 g4x_flip_count_after_eq(I915_READ(PIPE_FLIPCOUNT_GM45(crtc->pipe)),
10947                                     crtc->unpin_work->flip_count);
10948 }
10949
10950 void intel_prepare_page_flip(struct drm_device *dev, int plane)
10951 {
10952         struct drm_i915_private *dev_priv = dev->dev_private;
10953         struct intel_crtc *intel_crtc =
10954                 to_intel_crtc(dev_priv->plane_to_crtc_mapping[plane]);
10955         unsigned long flags;
10956
10957
10958         /*
10959          * This is called both by irq handlers and the reset code (to complete
10960          * lost pageflips) so needs the full irqsave spinlocks.
10961          *
10962          * NB: An MMIO update of the plane base pointer will also
10963          * generate a page-flip completion irq, i.e. every modeset
10964          * is also accompanied by a spurious intel_prepare_page_flip().
10965          */
10966         spin_lock_irqsave(&dev->event_lock, flags);
10967         if (intel_crtc->unpin_work && page_flip_finished(intel_crtc))
10968                 atomic_inc_not_zero(&intel_crtc->unpin_work->pending);
10969         spin_unlock_irqrestore(&dev->event_lock, flags);
10970 }
10971
10972 static inline void intel_mark_page_flip_active(struct intel_crtc *intel_crtc)
10973 {
10974         /* Ensure that the work item is consistent when activating it ... */
10975         smp_wmb();
10976         atomic_set(&intel_crtc->unpin_work->pending, INTEL_FLIP_PENDING);
10977         /* and that it is marked active as soon as the irq could fire. */
10978         smp_wmb();
10979 }
10980
10981 static int intel_gen2_queue_flip(struct drm_device *dev,
10982                                  struct drm_crtc *crtc,
10983                                  struct drm_framebuffer *fb,
10984                                  struct drm_i915_gem_object *obj,
10985                                  struct intel_engine_cs *ring,
10986                                  uint32_t flags)
10987 {
10988         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10989         u32 flip_mask;
10990         int ret;
10991
10992         ret = intel_ring_begin(ring, 6);
10993         if (ret)
10994                 return ret;
10995
10996         /* Can't queue multiple flips, so wait for the previous
10997          * one to finish before executing the next.
10998          */
10999         if (intel_crtc->plane)
11000                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
11001         else
11002                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
11003         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
11004         intel_ring_emit(ring, MI_NOOP);
11005         intel_ring_emit(ring, MI_DISPLAY_FLIP |
11006                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11007         intel_ring_emit(ring, fb->pitches[0]);
11008         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
11009         intel_ring_emit(ring, 0); /* aux display base address, unused */
11010
11011         intel_mark_page_flip_active(intel_crtc);
11012         __intel_ring_advance(ring);
11013         return 0;
11014 }
11015
11016 static int intel_gen3_queue_flip(struct drm_device *dev,
11017                                  struct drm_crtc *crtc,
11018                                  struct drm_framebuffer *fb,
11019                                  struct drm_i915_gem_object *obj,
11020                                  struct intel_engine_cs *ring,
11021                                  uint32_t flags)
11022 {
11023         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11024         u32 flip_mask;
11025         int ret;
11026
11027         ret = intel_ring_begin(ring, 6);
11028         if (ret)
11029                 return ret;
11030
11031         if (intel_crtc->plane)
11032                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
11033         else
11034                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
11035         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
11036         intel_ring_emit(ring, MI_NOOP);
11037         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 |
11038                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11039         intel_ring_emit(ring, fb->pitches[0]);
11040         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
11041         intel_ring_emit(ring, MI_NOOP);
11042
11043         intel_mark_page_flip_active(intel_crtc);
11044         __intel_ring_advance(ring);
11045         return 0;
11046 }
11047
11048 static int intel_gen4_queue_flip(struct drm_device *dev,
11049                                  struct drm_crtc *crtc,
11050                                  struct drm_framebuffer *fb,
11051                                  struct drm_i915_gem_object *obj,
11052                                  struct intel_engine_cs *ring,
11053                                  uint32_t flags)
11054 {
11055         struct drm_i915_private *dev_priv = dev->dev_private;
11056         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11057         uint32_t pf, pipesrc;
11058         int ret;
11059
11060         ret = intel_ring_begin(ring, 4);
11061         if (ret)
11062                 return ret;
11063
11064         /* i965+ uses the linear or tiled offsets from the
11065          * Display Registers (which do not change across a page-flip)
11066          * so we need only reprogram the base address.
11067          */
11068         intel_ring_emit(ring, MI_DISPLAY_FLIP |
11069                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11070         intel_ring_emit(ring, fb->pitches[0]);
11071         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset |
11072                         obj->tiling_mode);
11073
11074         /* XXX Enabling the panel-fitter across page-flip is so far
11075          * untested on non-native modes, so ignore it for now.
11076          * pf = I915_READ(pipe == 0 ? PFA_CTL_1 : PFB_CTL_1) & PF_ENABLE;
11077          */
11078         pf = 0;
11079         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
11080         intel_ring_emit(ring, pf | pipesrc);
11081
11082         intel_mark_page_flip_active(intel_crtc);
11083         __intel_ring_advance(ring);
11084         return 0;
11085 }
11086
11087 static int intel_gen6_queue_flip(struct drm_device *dev,
11088                                  struct drm_crtc *crtc,
11089                                  struct drm_framebuffer *fb,
11090                                  struct drm_i915_gem_object *obj,
11091                                  struct intel_engine_cs *ring,
11092                                  uint32_t flags)
11093 {
11094         struct drm_i915_private *dev_priv = dev->dev_private;
11095         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11096         uint32_t pf, pipesrc;
11097         int ret;
11098
11099         ret = intel_ring_begin(ring, 4);
11100         if (ret)
11101                 return ret;
11102
11103         intel_ring_emit(ring, MI_DISPLAY_FLIP |
11104                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11105         intel_ring_emit(ring, fb->pitches[0] | obj->tiling_mode);
11106         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
11107
11108         /* Contrary to the suggestions in the documentation,
11109          * "Enable Panel Fitter" does not seem to be required when page
11110          * flipping with a non-native mode, and worse causes a normal
11111          * modeset to fail.
11112          * pf = I915_READ(PF_CTL(intel_crtc->pipe)) & PF_ENABLE;
11113          */
11114         pf = 0;
11115         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
11116         intel_ring_emit(ring, pf | pipesrc);
11117
11118         intel_mark_page_flip_active(intel_crtc);
11119         __intel_ring_advance(ring);
11120         return 0;
11121 }
11122
11123 static int intel_gen7_queue_flip(struct drm_device *dev,
11124                                  struct drm_crtc *crtc,
11125                                  struct drm_framebuffer *fb,
11126                                  struct drm_i915_gem_object *obj,
11127                                  struct intel_engine_cs *ring,
11128                                  uint32_t flags)
11129 {
11130         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11131         uint32_t plane_bit = 0;
11132         int len, ret;
11133
11134         switch (intel_crtc->plane) {
11135         case PLANE_A:
11136                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_A;
11137                 break;
11138         case PLANE_B:
11139                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_B;
11140                 break;
11141         case PLANE_C:
11142                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_C;
11143                 break;
11144         default:
11145                 WARN_ONCE(1, "unknown plane in flip command\n");
11146                 return -ENODEV;
11147         }
11148
11149         len = 4;
11150         if (ring->id == RCS) {
11151                 len += 6;
11152                 /*
11153                  * On Gen 8, SRM is now taking an extra dword to accommodate
11154                  * 48bits addresses, and we need a NOOP for the batch size to
11155                  * stay even.
11156                  */
11157                 if (IS_GEN8(dev))
11158                         len += 2;
11159         }
11160
11161         /*
11162          * BSpec MI_DISPLAY_FLIP for IVB:
11163          * "The full packet must be contained within the same cache line."
11164          *
11165          * Currently the LRI+SRM+MI_DISPLAY_FLIP all fit within the same
11166          * cacheline, if we ever start emitting more commands before
11167          * the MI_DISPLAY_FLIP we may need to first emit everything else,
11168          * then do the cacheline alignment, and finally emit the
11169          * MI_DISPLAY_FLIP.
11170          */
11171         ret = intel_ring_cacheline_align(ring);
11172         if (ret)
11173                 return ret;
11174
11175         ret = intel_ring_begin(ring, len);
11176         if (ret)
11177                 return ret;
11178
11179         /* Unmask the flip-done completion message. Note that the bspec says that
11180          * we should do this for both the BCS and RCS, and that we must not unmask
11181          * more than one flip event at any time (or ensure that one flip message
11182          * can be sent by waiting for flip-done prior to queueing new flips).
11183          * Experimentation says that BCS works despite DERRMR masking all
11184          * flip-done completion events and that unmasking all planes at once
11185          * for the RCS also doesn't appear to drop events. Setting the DERRMR
11186          * to zero does lead to lockups within MI_DISPLAY_FLIP.
11187          */
11188         if (ring->id == RCS) {
11189                 intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
11190                 intel_ring_emit(ring, DERRMR);
11191                 intel_ring_emit(ring, ~(DERRMR_PIPEA_PRI_FLIP_DONE |
11192                                         DERRMR_PIPEB_PRI_FLIP_DONE |
11193                                         DERRMR_PIPEC_PRI_FLIP_DONE));
11194                 if (IS_GEN8(dev))
11195                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM_GEN8(1) |
11196                                               MI_SRM_LRM_GLOBAL_GTT);
11197                 else
11198                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM(1) |
11199                                               MI_SRM_LRM_GLOBAL_GTT);
11200                 intel_ring_emit(ring, DERRMR);
11201                 intel_ring_emit(ring, ring->scratch.gtt_offset + 256);
11202                 if (IS_GEN8(dev)) {
11203                         intel_ring_emit(ring, 0);
11204                         intel_ring_emit(ring, MI_NOOP);
11205                 }
11206         }
11207
11208         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 | plane_bit);
11209         intel_ring_emit(ring, (fb->pitches[0] | obj->tiling_mode));
11210         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
11211         intel_ring_emit(ring, (MI_NOOP));
11212
11213         intel_mark_page_flip_active(intel_crtc);
11214         __intel_ring_advance(ring);
11215         return 0;
11216 }
11217
11218 static bool use_mmio_flip(struct intel_engine_cs *ring,
11219                           struct drm_i915_gem_object *obj)
11220 {
11221         /*
11222          * This is not being used for older platforms, because
11223          * non-availability of flip done interrupt forces us to use
11224          * CS flips. Older platforms derive flip done using some clever
11225          * tricks involving the flip_pending status bits and vblank irqs.
11226          * So using MMIO flips there would disrupt this mechanism.
11227          */
11228
11229         if (ring == NULL)
11230                 return true;
11231
11232         if (INTEL_INFO(ring->dev)->gen < 5)
11233                 return false;
11234
11235         if (i915.use_mmio_flip < 0)
11236                 return false;
11237         else if (i915.use_mmio_flip > 0)
11238                 return true;
11239         else if (i915.enable_execlists)
11240                 return true;
11241         else
11242                 return ring != i915_gem_request_get_ring(obj->last_write_req);
11243 }
11244
11245 static void skl_do_mmio_flip(struct intel_crtc *intel_crtc)
11246 {
11247         struct drm_device *dev = intel_crtc->base.dev;
11248         struct drm_i915_private *dev_priv = dev->dev_private;
11249         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
11250         const enum pipe pipe = intel_crtc->pipe;
11251         u32 ctl, stride;
11252
11253         ctl = I915_READ(PLANE_CTL(pipe, 0));
11254         ctl &= ~PLANE_CTL_TILED_MASK;
11255         switch (fb->modifier[0]) {
11256         case DRM_FORMAT_MOD_NONE:
11257                 break;
11258         case I915_FORMAT_MOD_X_TILED:
11259                 ctl |= PLANE_CTL_TILED_X;
11260                 break;
11261         case I915_FORMAT_MOD_Y_TILED:
11262                 ctl |= PLANE_CTL_TILED_Y;
11263                 break;
11264         case I915_FORMAT_MOD_Yf_TILED:
11265                 ctl |= PLANE_CTL_TILED_YF;
11266                 break;
11267         default:
11268                 MISSING_CASE(fb->modifier[0]);
11269         }
11270
11271         /*
11272          * The stride is either expressed as a multiple of 64 bytes chunks for
11273          * linear buffers or in number of tiles for tiled buffers.
11274          */
11275         stride = fb->pitches[0] /
11276                  intel_fb_stride_alignment(dev, fb->modifier[0],
11277                                            fb->pixel_format);
11278
11279         /*
11280          * Both PLANE_CTL and PLANE_STRIDE are not updated on vblank but on
11281          * PLANE_SURF updates, the update is then guaranteed to be atomic.
11282          */
11283         I915_WRITE(PLANE_CTL(pipe, 0), ctl);
11284         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
11285
11286         I915_WRITE(PLANE_SURF(pipe, 0), intel_crtc->unpin_work->gtt_offset);
11287         POSTING_READ(PLANE_SURF(pipe, 0));
11288 }
11289
11290 static void ilk_do_mmio_flip(struct intel_crtc *intel_crtc)
11291 {
11292         struct drm_device *dev = intel_crtc->base.dev;
11293         struct drm_i915_private *dev_priv = dev->dev_private;
11294         struct intel_framebuffer *intel_fb =
11295                 to_intel_framebuffer(intel_crtc->base.primary->fb);
11296         struct drm_i915_gem_object *obj = intel_fb->obj;
11297         u32 dspcntr;
11298         u32 reg;
11299
11300         reg = DSPCNTR(intel_crtc->plane);
11301         dspcntr = I915_READ(reg);
11302
11303         if (obj->tiling_mode != I915_TILING_NONE)
11304                 dspcntr |= DISPPLANE_TILED;
11305         else
11306                 dspcntr &= ~DISPPLANE_TILED;
11307
11308         I915_WRITE(reg, dspcntr);
11309
11310         I915_WRITE(DSPSURF(intel_crtc->plane),
11311                    intel_crtc->unpin_work->gtt_offset);
11312         POSTING_READ(DSPSURF(intel_crtc->plane));
11313
11314 }
11315
11316 /*
11317  * XXX: This is the temporary way to update the plane registers until we get
11318  * around to using the usual plane update functions for MMIO flips
11319  */
11320 static void intel_do_mmio_flip(struct intel_crtc *intel_crtc)
11321 {
11322         struct drm_device *dev = intel_crtc->base.dev;
11323         bool atomic_update;
11324         u32 start_vbl_count;
11325
11326         intel_mark_page_flip_active(intel_crtc);
11327
11328         atomic_update = intel_pipe_update_start(intel_crtc, &start_vbl_count);
11329
11330         if (INTEL_INFO(dev)->gen >= 9)
11331                 skl_do_mmio_flip(intel_crtc);
11332         else
11333                 /* use_mmio_flip() retricts MMIO flips to ilk+ */
11334                 ilk_do_mmio_flip(intel_crtc);
11335
11336         if (atomic_update)
11337                 intel_pipe_update_end(intel_crtc, start_vbl_count);
11338 }
11339
11340 static void intel_mmio_flip_work_func(struct work_struct *work)
11341 {
11342         struct intel_mmio_flip *mmio_flip =
11343                 container_of(work, struct intel_mmio_flip, work);
11344
11345         if (mmio_flip->req)
11346                 WARN_ON(__i915_wait_request(mmio_flip->req,
11347                                             mmio_flip->crtc->reset_counter,
11348                                             false, NULL,
11349                                             &mmio_flip->i915->rps.mmioflips));
11350
11351         intel_do_mmio_flip(mmio_flip->crtc);
11352
11353         i915_gem_request_unreference__unlocked(mmio_flip->req);
11354         kfree(mmio_flip);
11355 }
11356
11357 static int intel_queue_mmio_flip(struct drm_device *dev,
11358                                  struct drm_crtc *crtc,
11359                                  struct drm_framebuffer *fb,
11360                                  struct drm_i915_gem_object *obj,
11361                                  struct intel_engine_cs *ring,
11362                                  uint32_t flags)
11363 {
11364         struct intel_mmio_flip *mmio_flip;
11365
11366         mmio_flip = kmalloc(sizeof(*mmio_flip), GFP_KERNEL);
11367         if (mmio_flip == NULL)
11368                 return -ENOMEM;
11369
11370         mmio_flip->i915 = to_i915(dev);
11371         mmio_flip->req = i915_gem_request_reference(obj->last_write_req);
11372         mmio_flip->crtc = to_intel_crtc(crtc);
11373
11374         INIT_WORK(&mmio_flip->work, intel_mmio_flip_work_func);
11375         schedule_work(&mmio_flip->work);
11376
11377         return 0;
11378 }
11379
11380 static int intel_default_queue_flip(struct drm_device *dev,
11381                                     struct drm_crtc *crtc,
11382                                     struct drm_framebuffer *fb,
11383                                     struct drm_i915_gem_object *obj,
11384                                     struct intel_engine_cs *ring,
11385                                     uint32_t flags)
11386 {
11387         return -ENODEV;
11388 }
11389
11390 static bool __intel_pageflip_stall_check(struct drm_device *dev,
11391                                          struct drm_crtc *crtc)
11392 {
11393         struct drm_i915_private *dev_priv = dev->dev_private;
11394         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11395         struct intel_unpin_work *work = intel_crtc->unpin_work;
11396         u32 addr;
11397
11398         if (atomic_read(&work->pending) >= INTEL_FLIP_COMPLETE)
11399                 return true;
11400
11401         if (!work->enable_stall_check)
11402                 return false;
11403
11404         if (work->flip_ready_vblank == 0) {
11405                 if (work->flip_queued_req &&
11406                     !i915_gem_request_completed(work->flip_queued_req, true))
11407                         return false;
11408
11409                 work->flip_ready_vblank = drm_crtc_vblank_count(crtc);
11410         }
11411
11412         if (drm_crtc_vblank_count(crtc) - work->flip_ready_vblank < 3)
11413                 return false;
11414
11415         /* Potential stall - if we see that the flip has happened,
11416          * assume a missed interrupt. */
11417         if (INTEL_INFO(dev)->gen >= 4)
11418                 addr = I915_HI_DISPBASE(I915_READ(DSPSURF(intel_crtc->plane)));
11419         else
11420                 addr = I915_READ(DSPADDR(intel_crtc->plane));
11421
11422         /* There is a potential issue here with a false positive after a flip
11423          * to the same address. We could address this by checking for a
11424          * non-incrementing frame counter.
11425          */
11426         return addr == work->gtt_offset;
11427 }
11428
11429 void intel_check_page_flip(struct drm_device *dev, int pipe)
11430 {
11431         struct drm_i915_private *dev_priv = dev->dev_private;
11432         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11433         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11434         struct intel_unpin_work *work;
11435
11436         WARN_ON(!in_interrupt());
11437
11438         if (crtc == NULL)
11439                 return;
11440
11441         spin_lock(&dev->event_lock);
11442         work = intel_crtc->unpin_work;
11443         if (work != NULL && __intel_pageflip_stall_check(dev, crtc)) {
11444                 WARN_ONCE(1, "Kicking stuck page flip: queued at %d, now %d\n",
11445                          work->flip_queued_vblank, drm_vblank_count(dev, pipe));
11446                 page_flip_completed(intel_crtc);
11447                 work = NULL;
11448         }
11449         if (work != NULL &&
11450             drm_vblank_count(dev, pipe) - work->flip_queued_vblank > 1)
11451                 intel_queue_rps_boost_for_request(dev, work->flip_queued_req);
11452         spin_unlock(&dev->event_lock);
11453 }
11454
11455 static int intel_crtc_page_flip(struct drm_crtc *crtc,
11456                                 struct drm_framebuffer *fb,
11457                                 struct drm_pending_vblank_event *event,
11458                                 uint32_t page_flip_flags)
11459 {
11460         struct drm_device *dev = crtc->dev;
11461         struct drm_i915_private *dev_priv = dev->dev_private;
11462         struct drm_framebuffer *old_fb = crtc->primary->fb;
11463         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
11464         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11465         struct drm_plane *primary = crtc->primary;
11466         enum pipe pipe = intel_crtc->pipe;
11467         struct intel_unpin_work *work;
11468         struct intel_engine_cs *ring;
11469         bool mmio_flip;
11470         int ret;
11471
11472         /*
11473          * drm_mode_page_flip_ioctl() should already catch this, but double
11474          * check to be safe.  In the future we may enable pageflipping from
11475          * a disabled primary plane.
11476          */
11477         if (WARN_ON(intel_fb_obj(old_fb) == NULL))
11478                 return -EBUSY;
11479
11480         /* Can't change pixel format via MI display flips. */
11481         if (fb->pixel_format != crtc->primary->fb->pixel_format)
11482                 return -EINVAL;
11483
11484         /*
11485          * TILEOFF/LINOFF registers can't be changed via MI display flips.
11486          * Note that pitch changes could also affect these register.
11487          */
11488         if (INTEL_INFO(dev)->gen > 3 &&
11489             (fb->offsets[0] != crtc->primary->fb->offsets[0] ||
11490              fb->pitches[0] != crtc->primary->fb->pitches[0]))
11491                 return -EINVAL;
11492
11493         if (i915_terminally_wedged(&dev_priv->gpu_error))
11494                 goto out_hang;
11495
11496         work = kzalloc(sizeof(*work), GFP_KERNEL);
11497         if (work == NULL)
11498                 return -ENOMEM;
11499
11500         work->event = event;
11501         work->crtc = crtc;
11502         work->old_fb = old_fb;
11503         INIT_WORK(&work->work, intel_unpin_work_fn);
11504
11505         ret = drm_crtc_vblank_get(crtc);
11506         if (ret)
11507                 goto free_work;
11508
11509         /* We borrow the event spin lock for protecting unpin_work */
11510         spin_lock_irq(&dev->event_lock);
11511         if (intel_crtc->unpin_work) {
11512                 /* Before declaring the flip queue wedged, check if
11513                  * the hardware completed the operation behind our backs.
11514                  */
11515                 if (__intel_pageflip_stall_check(dev, crtc)) {
11516                         DRM_DEBUG_DRIVER("flip queue: previous flip completed, continuing\n");
11517                         page_flip_completed(intel_crtc);
11518                 } else {
11519                         DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
11520                         spin_unlock_irq(&dev->event_lock);
11521
11522                         drm_crtc_vblank_put(crtc);
11523                         kfree(work);
11524                         return -EBUSY;
11525                 }
11526         }
11527         intel_crtc->unpin_work = work;
11528         spin_unlock_irq(&dev->event_lock);
11529
11530         if (atomic_read(&intel_crtc->unpin_work_count) >= 2)
11531                 flush_workqueue(dev_priv->wq);
11532
11533         /* Reference the objects for the scheduled work. */
11534         drm_framebuffer_reference(work->old_fb);
11535         drm_gem_object_reference(&obj->base);
11536
11537         crtc->primary->fb = fb;
11538         update_state_fb(crtc->primary);
11539
11540         work->pending_flip_obj = obj;
11541
11542         ret = i915_mutex_lock_interruptible(dev);
11543         if (ret)
11544                 goto cleanup;
11545
11546         atomic_inc(&intel_crtc->unpin_work_count);
11547         intel_crtc->reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
11548
11549         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
11550                 work->flip_count = I915_READ(PIPE_FLIPCOUNT_GM45(pipe)) + 1;
11551
11552         if (IS_VALLEYVIEW(dev)) {
11553                 ring = &dev_priv->ring[BCS];
11554                 if (obj->tiling_mode != intel_fb_obj(work->old_fb)->tiling_mode)
11555                         /* vlv: DISPLAY_FLIP fails to change tiling */
11556                         ring = NULL;
11557         } else if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev)) {
11558                 ring = &dev_priv->ring[BCS];
11559         } else if (INTEL_INFO(dev)->gen >= 7) {
11560                 ring = i915_gem_request_get_ring(obj->last_write_req);
11561                 if (ring == NULL || ring->id != RCS)
11562                         ring = &dev_priv->ring[BCS];
11563         } else {
11564                 ring = &dev_priv->ring[RCS];
11565         }
11566
11567         mmio_flip = use_mmio_flip(ring, obj);
11568
11569         /* When using CS flips, we want to emit semaphores between rings.
11570          * However, when using mmio flips we will create a task to do the
11571          * synchronisation, so all we want here is to pin the framebuffer
11572          * into the display plane and skip any waits.
11573          */
11574         ret = intel_pin_and_fence_fb_obj(crtc->primary, fb,
11575                                          crtc->primary->state,
11576                                          mmio_flip ? i915_gem_request_get_ring(obj->last_write_req) : ring);
11577         if (ret)
11578                 goto cleanup_pending;
11579
11580         work->gtt_offset = intel_plane_obj_offset(to_intel_plane(primary), obj)
11581                                                   + intel_crtc->dspaddr_offset;
11582
11583         if (mmio_flip) {
11584                 ret = intel_queue_mmio_flip(dev, crtc, fb, obj, ring,
11585                                             page_flip_flags);
11586                 if (ret)
11587                         goto cleanup_unpin;
11588
11589                 i915_gem_request_assign(&work->flip_queued_req,
11590                                         obj->last_write_req);
11591         } else {
11592                 if (obj->last_write_req) {
11593                         ret = i915_gem_check_olr(obj->last_write_req);
11594                         if (ret)
11595                                 goto cleanup_unpin;
11596                 }
11597
11598                 ret = dev_priv->display.queue_flip(dev, crtc, fb, obj, ring,
11599                                                    page_flip_flags);
11600                 if (ret)
11601                         goto cleanup_unpin;
11602
11603                 i915_gem_request_assign(&work->flip_queued_req,
11604                                         intel_ring_get_request(ring));
11605         }
11606
11607         work->flip_queued_vblank = drm_crtc_vblank_count(crtc);
11608         work->enable_stall_check = true;
11609
11610         i915_gem_track_fb(intel_fb_obj(work->old_fb), obj,
11611                           INTEL_FRONTBUFFER_PRIMARY(pipe));
11612
11613         intel_fbc_disable(dev);
11614         intel_frontbuffer_flip_prepare(dev, INTEL_FRONTBUFFER_PRIMARY(pipe));
11615         mutex_unlock(&dev->struct_mutex);
11616
11617         trace_i915_flip_request(intel_crtc->plane, obj);
11618
11619         return 0;
11620
11621 cleanup_unpin:
11622         intel_unpin_fb_obj(fb, crtc->primary->state);
11623 cleanup_pending:
11624         atomic_dec(&intel_crtc->unpin_work_count);
11625         mutex_unlock(&dev->struct_mutex);
11626 cleanup:
11627         crtc->primary->fb = old_fb;
11628         update_state_fb(crtc->primary);
11629
11630         drm_gem_object_unreference_unlocked(&obj->base);
11631         drm_framebuffer_unreference(work->old_fb);
11632
11633         spin_lock_irq(&dev->event_lock);
11634         intel_crtc->unpin_work = NULL;
11635         spin_unlock_irq(&dev->event_lock);
11636
11637         drm_crtc_vblank_put(crtc);
11638 free_work:
11639         kfree(work);
11640
11641         if (ret == -EIO) {
11642                 struct drm_atomic_state *state;
11643                 struct drm_plane_state *plane_state;
11644
11645 out_hang:
11646                 state = drm_atomic_state_alloc(dev);
11647                 if (!state)
11648                         return -ENOMEM;
11649                 state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
11650
11651 retry:
11652                 plane_state = drm_atomic_get_plane_state(state, primary);
11653                 ret = PTR_ERR_OR_ZERO(plane_state);
11654                 if (!ret) {
11655                         drm_atomic_set_fb_for_plane(plane_state, fb);
11656
11657                         ret = drm_atomic_set_crtc_for_plane(plane_state, crtc);
11658                         if (!ret)
11659                                 ret = drm_atomic_commit(state);
11660                 }
11661
11662                 if (ret == -EDEADLK) {
11663                         drm_modeset_backoff(state->acquire_ctx);
11664                         drm_atomic_state_clear(state);
11665                         goto retry;
11666                 }
11667
11668                 if (ret)
11669                         drm_atomic_state_free(state);
11670
11671                 if (ret == 0 && event) {
11672                         spin_lock_irq(&dev->event_lock);
11673                         drm_send_vblank_event(dev, pipe, event);
11674                         spin_unlock_irq(&dev->event_lock);
11675                 }
11676         }
11677         return ret;
11678 }
11679
11680
11681 /**
11682  * intel_wm_need_update - Check whether watermarks need updating
11683  * @plane: drm plane
11684  * @state: new plane state
11685  *
11686  * Check current plane state versus the new one to determine whether
11687  * watermarks need to be recalculated.
11688  *
11689  * Returns true or false.
11690  */
11691 static bool intel_wm_need_update(struct drm_plane *plane,
11692                                  struct drm_plane_state *state)
11693 {
11694         /* Update watermarks on tiling changes. */
11695         if (!plane->state->fb || !state->fb ||
11696             plane->state->fb->modifier[0] != state->fb->modifier[0] ||
11697             plane->state->rotation != state->rotation)
11698                 return true;
11699
11700         if (plane->state->crtc_w != state->crtc_w)
11701                 return true;
11702
11703         return false;
11704 }
11705
11706 int intel_plane_atomic_calc_changes(struct drm_crtc_state *crtc_state,
11707                                     struct drm_plane_state *plane_state)
11708 {
11709         struct drm_crtc *crtc = crtc_state->crtc;
11710         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11711         struct drm_plane *plane = plane_state->plane;
11712         struct drm_device *dev = crtc->dev;
11713         struct drm_i915_private *dev_priv = dev->dev_private;
11714         struct intel_plane_state *old_plane_state =
11715                 to_intel_plane_state(plane->state);
11716         int idx = intel_crtc->base.base.id, ret;
11717         int i = drm_plane_index(plane);
11718         bool mode_changed = needs_modeset(crtc_state);
11719         bool was_crtc_enabled = crtc->state->active;
11720         bool is_crtc_enabled = crtc_state->active;
11721
11722         bool turn_off, turn_on, visible, was_visible;
11723         struct drm_framebuffer *fb = plane_state->fb;
11724
11725         if (crtc_state && INTEL_INFO(dev)->gen >= 9 &&
11726             plane->type != DRM_PLANE_TYPE_CURSOR) {
11727                 ret = skl_update_scaler_plane(
11728                         to_intel_crtc_state(crtc_state),
11729                         to_intel_plane_state(plane_state));
11730                 if (ret)
11731                         return ret;
11732         }
11733
11734         /*
11735          * Disabling a plane is always okay; we just need to update
11736          * fb tracking in a special way since cleanup_fb() won't
11737          * get called by the plane helpers.
11738          */
11739         if (old_plane_state->base.fb && !fb)
11740                 intel_crtc->atomic.disabled_planes |= 1 << i;
11741
11742         /* don't run rest during modeset yet */
11743         if (!intel_crtc->active || mode_changed)
11744                 return 0;
11745
11746         was_visible = old_plane_state->visible;
11747         visible = to_intel_plane_state(plane_state)->visible;
11748
11749         if (!was_crtc_enabled && WARN_ON(was_visible))
11750                 was_visible = false;
11751
11752         if (!is_crtc_enabled && WARN_ON(visible))
11753                 visible = false;
11754
11755         if (!was_visible && !visible)
11756                 return 0;
11757
11758         turn_off = was_visible && (!visible || mode_changed);
11759         turn_on = visible && (!was_visible || mode_changed);
11760
11761         DRM_DEBUG_ATOMIC("[CRTC:%i] has [PLANE:%i] with fb %i\n", idx,
11762                          plane->base.id, fb ? fb->base.id : -1);
11763
11764         DRM_DEBUG_ATOMIC("[PLANE:%i] visible %i -> %i, off %i, on %i, ms %i\n",
11765                          plane->base.id, was_visible, visible,
11766                          turn_off, turn_on, mode_changed);
11767
11768         if (intel_wm_need_update(plane, plane_state))
11769                 intel_crtc->atomic.update_wm = true;
11770
11771         switch (plane->type) {
11772         case DRM_PLANE_TYPE_PRIMARY:
11773                 if (visible)
11774                         intel_crtc->atomic.fb_bits |=
11775                             INTEL_FRONTBUFFER_PRIMARY(intel_crtc->pipe);
11776
11777                 intel_crtc->atomic.wait_for_flips = true;
11778                 intel_crtc->atomic.pre_disable_primary = turn_off;
11779                 intel_crtc->atomic.post_enable_primary = turn_on;
11780
11781                 if (turn_off)
11782                         intel_crtc->atomic.disable_fbc = true;
11783
11784                 /*
11785                  * FBC does not work on some platforms for rotated
11786                  * planes, so disable it when rotation is not 0 and
11787                  * update it when rotation is set back to 0.
11788                  *
11789                  * FIXME: This is redundant with the fbc update done in
11790                  * the primary plane enable function except that that
11791                  * one is done too late. We eventually need to unify
11792                  * this.
11793                  */
11794
11795                 if (visible &&
11796                     INTEL_INFO(dev)->gen <= 4 && !IS_G4X(dev) &&
11797                     dev_priv->fbc.crtc == intel_crtc &&
11798                     plane_state->rotation != BIT(DRM_ROTATE_0))
11799                         intel_crtc->atomic.disable_fbc = true;
11800
11801                 /*
11802                  * BDW signals flip done immediately if the plane
11803                  * is disabled, even if the plane enable is already
11804                  * armed to occur at the next vblank :(
11805                  */
11806                 if (turn_on && IS_BROADWELL(dev))
11807                         intel_crtc->atomic.wait_vblank = true;
11808
11809                 intel_crtc->atomic.update_fbc |= visible || mode_changed;
11810                 break;
11811         case DRM_PLANE_TYPE_CURSOR:
11812                 if (visible)
11813                         intel_crtc->atomic.fb_bits |=
11814                             INTEL_FRONTBUFFER_CURSOR(intel_crtc->pipe);
11815                 break;
11816         case DRM_PLANE_TYPE_OVERLAY:
11817                 /*
11818                  * 'prepare' is never called when plane is being disabled, so
11819                  * we need to handle frontbuffer tracking as a special case
11820                  */
11821                 if (visible)
11822                         intel_crtc->atomic.fb_bits |=
11823                             INTEL_FRONTBUFFER_SPRITE(intel_crtc->pipe);
11824
11825                 if (turn_off && is_crtc_enabled) {
11826                         intel_crtc->atomic.wait_vblank = true;
11827                         intel_crtc->atomic.update_sprite_watermarks |=
11828                                 1 << i;
11829                 }
11830                 break;
11831         }
11832         return 0;
11833 }
11834
11835 static bool encoders_cloneable(const struct intel_encoder *a,
11836                                const struct intel_encoder *b)
11837 {
11838         /* masks could be asymmetric, so check both ways */
11839         return a == b || (a->cloneable & (1 << b->type) &&
11840                           b->cloneable & (1 << a->type));
11841 }
11842
11843 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
11844                                          struct intel_crtc *crtc,
11845                                          struct intel_encoder *encoder)
11846 {
11847         struct intel_encoder *source_encoder;
11848         struct drm_connector *connector;
11849         struct drm_connector_state *connector_state;
11850         int i;
11851
11852         for_each_connector_in_state(state, connector, connector_state, i) {
11853                 if (connector_state->crtc != &crtc->base)
11854                         continue;
11855
11856                 source_encoder =
11857                         to_intel_encoder(connector_state->best_encoder);
11858                 if (!encoders_cloneable(encoder, source_encoder))
11859                         return false;
11860         }
11861
11862         return true;
11863 }
11864
11865 static bool check_encoder_cloning(struct drm_atomic_state *state,
11866                                   struct intel_crtc *crtc)
11867 {
11868         struct intel_encoder *encoder;
11869         struct drm_connector *connector;
11870         struct drm_connector_state *connector_state;
11871         int i;
11872
11873         for_each_connector_in_state(state, connector, connector_state, i) {
11874                 if (connector_state->crtc != &crtc->base)
11875                         continue;
11876
11877                 encoder = to_intel_encoder(connector_state->best_encoder);
11878                 if (!check_single_encoder_cloning(state, crtc, encoder))
11879                         return false;
11880         }
11881
11882         return true;
11883 }
11884
11885 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
11886                                    struct drm_crtc_state *crtc_state)
11887 {
11888         struct drm_device *dev = crtc->dev;
11889         struct drm_i915_private *dev_priv = dev->dev_private;
11890         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11891         struct intel_crtc_state *pipe_config =
11892                 to_intel_crtc_state(crtc_state);
11893         struct drm_atomic_state *state = crtc_state->state;
11894         int ret, idx = crtc->base.id;
11895         bool mode_changed = needs_modeset(crtc_state);
11896
11897         if (mode_changed && !check_encoder_cloning(state, intel_crtc)) {
11898                 DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
11899                 return -EINVAL;
11900         }
11901
11902         I915_STATE_WARN(crtc->state->active != intel_crtc->active,
11903                 "[CRTC:%i] mismatch between state->active(%i) and crtc->active(%i)\n",
11904                 idx, crtc->state->active, intel_crtc->active);
11905
11906         if (mode_changed && crtc_state->enable &&
11907             dev_priv->display.crtc_compute_clock &&
11908             !WARN_ON(pipe_config->shared_dpll != DPLL_ID_PRIVATE)) {
11909                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
11910                                                            pipe_config);
11911                 if (ret)
11912                         return ret;
11913         }
11914
11915         return intel_atomic_setup_scalers(dev, intel_crtc, pipe_config);
11916 }
11917
11918 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
11919         .mode_set_base_atomic = intel_pipe_set_base_atomic,
11920         .load_lut = intel_crtc_load_lut,
11921         .atomic_begin = intel_begin_crtc_commit,
11922         .atomic_flush = intel_finish_crtc_commit,
11923         .atomic_check = intel_crtc_atomic_check,
11924 };
11925
11926 /**
11927  * intel_modeset_update_staged_output_state
11928  *
11929  * Updates the staged output configuration state, e.g. after we've read out the
11930  * current hw state.
11931  */
11932 static void intel_modeset_update_staged_output_state(struct drm_device *dev)
11933 {
11934         struct intel_crtc *crtc;
11935         struct intel_encoder *encoder;
11936         struct intel_connector *connector;
11937
11938         for_each_intel_connector(dev, connector) {
11939                 connector->new_encoder =
11940                         to_intel_encoder(connector->base.encoder);
11941         }
11942
11943         for_each_intel_encoder(dev, encoder) {
11944                 encoder->new_crtc =
11945                         to_intel_crtc(encoder->base.crtc);
11946         }
11947
11948         for_each_intel_crtc(dev, crtc) {
11949                 crtc->new_enabled = crtc->base.state->enable;
11950         }
11951 }
11952
11953 /* Transitional helper to copy current connector/encoder state to
11954  * connector->state. This is needed so that code that is partially
11955  * converted to atomic does the right thing.
11956  */
11957 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
11958 {
11959         struct intel_connector *connector;
11960
11961         for_each_intel_connector(dev, connector) {
11962                 if (connector->base.encoder) {
11963                         connector->base.state->best_encoder =
11964                                 connector->base.encoder;
11965                         connector->base.state->crtc =
11966                                 connector->base.encoder->crtc;
11967                 } else {
11968                         connector->base.state->best_encoder = NULL;
11969                         connector->base.state->crtc = NULL;
11970                 }
11971         }
11972 }
11973
11974 static void
11975 connected_sink_compute_bpp(struct intel_connector *connector,
11976                            struct intel_crtc_state *pipe_config)
11977 {
11978         int bpp = pipe_config->pipe_bpp;
11979
11980         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
11981                 connector->base.base.id,
11982                 connector->base.name);
11983
11984         /* Don't use an invalid EDID bpc value */
11985         if (connector->base.display_info.bpc &&
11986             connector->base.display_info.bpc * 3 < bpp) {
11987                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
11988                               bpp, connector->base.display_info.bpc*3);
11989                 pipe_config->pipe_bpp = connector->base.display_info.bpc*3;
11990         }
11991
11992         /* Clamp bpp to 8 on screens without EDID 1.4 */
11993         if (connector->base.display_info.bpc == 0 && bpp > 24) {
11994                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
11995                               bpp);
11996                 pipe_config->pipe_bpp = 24;
11997         }
11998 }
11999
12000 static int
12001 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
12002                           struct intel_crtc_state *pipe_config)
12003 {
12004         struct drm_device *dev = crtc->base.dev;
12005         struct drm_atomic_state *state;
12006         struct drm_connector *connector;
12007         struct drm_connector_state *connector_state;
12008         int bpp, i;
12009
12010         if ((IS_G4X(dev) || IS_VALLEYVIEW(dev)))
12011                 bpp = 10*3;
12012         else if (INTEL_INFO(dev)->gen >= 5)
12013                 bpp = 12*3;
12014         else
12015                 bpp = 8*3;
12016
12017
12018         pipe_config->pipe_bpp = bpp;
12019
12020         state = pipe_config->base.state;
12021
12022         /* Clamp display bpp to EDID value */
12023         for_each_connector_in_state(state, connector, connector_state, i) {
12024                 if (connector_state->crtc != &crtc->base)
12025                         continue;
12026
12027                 connected_sink_compute_bpp(to_intel_connector(connector),
12028                                            pipe_config);
12029         }
12030
12031         return bpp;
12032 }
12033
12034 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
12035 {
12036         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
12037                         "type: 0x%x flags: 0x%x\n",
12038                 mode->crtc_clock,
12039                 mode->crtc_hdisplay, mode->crtc_hsync_start,
12040                 mode->crtc_hsync_end, mode->crtc_htotal,
12041                 mode->crtc_vdisplay, mode->crtc_vsync_start,
12042                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
12043 }
12044
12045 static void intel_dump_pipe_config(struct intel_crtc *crtc,
12046                                    struct intel_crtc_state *pipe_config,
12047                                    const char *context)
12048 {
12049         struct drm_device *dev = crtc->base.dev;
12050         struct drm_plane *plane;
12051         struct intel_plane *intel_plane;
12052         struct intel_plane_state *state;
12053         struct drm_framebuffer *fb;
12054
12055         DRM_DEBUG_KMS("[CRTC:%d]%s config %p for pipe %c\n", crtc->base.base.id,
12056                       context, pipe_config, pipe_name(crtc->pipe));
12057
12058         DRM_DEBUG_KMS("cpu_transcoder: %c\n", transcoder_name(pipe_config->cpu_transcoder));
12059         DRM_DEBUG_KMS("pipe bpp: %i, dithering: %i\n",
12060                       pipe_config->pipe_bpp, pipe_config->dither);
12061         DRM_DEBUG_KMS("fdi/pch: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
12062                       pipe_config->has_pch_encoder,
12063                       pipe_config->fdi_lanes,
12064                       pipe_config->fdi_m_n.gmch_m, pipe_config->fdi_m_n.gmch_n,
12065                       pipe_config->fdi_m_n.link_m, pipe_config->fdi_m_n.link_n,
12066                       pipe_config->fdi_m_n.tu);
12067         DRM_DEBUG_KMS("dp: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
12068                       pipe_config->has_dp_encoder,
12069                       pipe_config->dp_m_n.gmch_m, pipe_config->dp_m_n.gmch_n,
12070                       pipe_config->dp_m_n.link_m, pipe_config->dp_m_n.link_n,
12071                       pipe_config->dp_m_n.tu);
12072
12073         DRM_DEBUG_KMS("dp: %i, gmch_m2: %u, gmch_n2: %u, link_m2: %u, link_n2: %u, tu2: %u\n",
12074                       pipe_config->has_dp_encoder,
12075                       pipe_config->dp_m2_n2.gmch_m,
12076                       pipe_config->dp_m2_n2.gmch_n,
12077                       pipe_config->dp_m2_n2.link_m,
12078                       pipe_config->dp_m2_n2.link_n,
12079                       pipe_config->dp_m2_n2.tu);
12080
12081         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
12082                       pipe_config->has_audio,
12083                       pipe_config->has_infoframe);
12084
12085         DRM_DEBUG_KMS("requested mode:\n");
12086         drm_mode_debug_printmodeline(&pipe_config->base.mode);
12087         DRM_DEBUG_KMS("adjusted mode:\n");
12088         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
12089         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
12090         DRM_DEBUG_KMS("port clock: %d\n", pipe_config->port_clock);
12091         DRM_DEBUG_KMS("pipe src size: %dx%d\n",
12092                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
12093         DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
12094                       crtc->num_scalers,
12095                       pipe_config->scaler_state.scaler_users,
12096                       pipe_config->scaler_state.scaler_id);
12097         DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
12098                       pipe_config->gmch_pfit.control,
12099                       pipe_config->gmch_pfit.pgm_ratios,
12100                       pipe_config->gmch_pfit.lvds_border_bits);
12101         DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
12102                       pipe_config->pch_pfit.pos,
12103                       pipe_config->pch_pfit.size,
12104                       pipe_config->pch_pfit.enabled ? "enabled" : "disabled");
12105         DRM_DEBUG_KMS("ips: %i\n", pipe_config->ips_enabled);
12106         DRM_DEBUG_KMS("double wide: %i\n", pipe_config->double_wide);
12107
12108         if (IS_BROXTON(dev)) {
12109                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: ebb0: 0x%x, "
12110                               "pll0: 0x%x, pll1: 0x%x, pll2: 0x%x, pll3: 0x%x, "
12111                               "pll6: 0x%x, pll8: 0x%x, pcsdw12: 0x%x\n",
12112                               pipe_config->ddi_pll_sel,
12113                               pipe_config->dpll_hw_state.ebb0,
12114                               pipe_config->dpll_hw_state.pll0,
12115                               pipe_config->dpll_hw_state.pll1,
12116                               pipe_config->dpll_hw_state.pll2,
12117                               pipe_config->dpll_hw_state.pll3,
12118                               pipe_config->dpll_hw_state.pll6,
12119                               pipe_config->dpll_hw_state.pll8,
12120                               pipe_config->dpll_hw_state.pcsdw12);
12121         } else if (IS_SKYLAKE(dev)) {
12122                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: "
12123                               "ctrl1: 0x%x, cfgcr1: 0x%x, cfgcr2: 0x%x\n",
12124                               pipe_config->ddi_pll_sel,
12125                               pipe_config->dpll_hw_state.ctrl1,
12126                               pipe_config->dpll_hw_state.cfgcr1,
12127                               pipe_config->dpll_hw_state.cfgcr2);
12128         } else if (HAS_DDI(dev)) {
12129                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: wrpll: 0x%x\n",
12130                               pipe_config->ddi_pll_sel,
12131                               pipe_config->dpll_hw_state.wrpll);
12132         } else {
12133                 DRM_DEBUG_KMS("dpll_hw_state: dpll: 0x%x, dpll_md: 0x%x, "
12134                               "fp0: 0x%x, fp1: 0x%x\n",
12135                               pipe_config->dpll_hw_state.dpll,
12136                               pipe_config->dpll_hw_state.dpll_md,
12137                               pipe_config->dpll_hw_state.fp0,
12138                               pipe_config->dpll_hw_state.fp1);
12139         }
12140
12141         DRM_DEBUG_KMS("planes on this crtc\n");
12142         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
12143                 intel_plane = to_intel_plane(plane);
12144                 if (intel_plane->pipe != crtc->pipe)
12145                         continue;
12146
12147                 state = to_intel_plane_state(plane->state);
12148                 fb = state->base.fb;
12149                 if (!fb) {
12150                         DRM_DEBUG_KMS("%s PLANE:%d plane: %u.%u idx: %d "
12151                                 "disabled, scaler_id = %d\n",
12152                                 plane->type == DRM_PLANE_TYPE_CURSOR ? "CURSOR" : "STANDARD",
12153                                 plane->base.id, intel_plane->pipe,
12154                                 (crtc->base.primary == plane) ? 0 : intel_plane->plane + 1,
12155                                 drm_plane_index(plane), state->scaler_id);
12156                         continue;
12157                 }
12158
12159                 DRM_DEBUG_KMS("%s PLANE:%d plane: %u.%u idx: %d enabled",
12160                         plane->type == DRM_PLANE_TYPE_CURSOR ? "CURSOR" : "STANDARD",
12161                         plane->base.id, intel_plane->pipe,
12162                         crtc->base.primary == plane ? 0 : intel_plane->plane + 1,
12163                         drm_plane_index(plane));
12164                 DRM_DEBUG_KMS("\tFB:%d, fb = %ux%u format = 0x%x",
12165                         fb->base.id, fb->width, fb->height, fb->pixel_format);
12166                 DRM_DEBUG_KMS("\tscaler:%d src (%u, %u) %ux%u dst (%u, %u) %ux%u\n",
12167                         state->scaler_id,
12168                         state->src.x1 >> 16, state->src.y1 >> 16,
12169                         drm_rect_width(&state->src) >> 16,
12170                         drm_rect_height(&state->src) >> 16,
12171                         state->dst.x1, state->dst.y1,
12172                         drm_rect_width(&state->dst), drm_rect_height(&state->dst));
12173         }
12174 }
12175
12176 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
12177 {
12178         struct drm_device *dev = state->dev;
12179         struct intel_encoder *encoder;
12180         struct drm_connector *connector;
12181         struct drm_connector_state *connector_state;
12182         unsigned int used_ports = 0;
12183         int i;
12184
12185         /*
12186          * Walk the connector list instead of the encoder
12187          * list to detect the problem on ddi platforms
12188          * where there's just one encoder per digital port.
12189          */
12190         for_each_connector_in_state(state, connector, connector_state, i) {
12191                 if (!connector_state->best_encoder)
12192                         continue;
12193
12194                 encoder = to_intel_encoder(connector_state->best_encoder);
12195
12196                 WARN_ON(!connector_state->crtc);
12197
12198                 switch (encoder->type) {
12199                         unsigned int port_mask;
12200                 case INTEL_OUTPUT_UNKNOWN:
12201                         if (WARN_ON(!HAS_DDI(dev)))
12202                                 break;
12203                 case INTEL_OUTPUT_DISPLAYPORT:
12204                 case INTEL_OUTPUT_HDMI:
12205                 case INTEL_OUTPUT_EDP:
12206                         port_mask = 1 << enc_to_dig_port(&encoder->base)->port;
12207
12208                         /* the same port mustn't appear more than once */
12209                         if (used_ports & port_mask)
12210                                 return false;
12211
12212                         used_ports |= port_mask;
12213                 default:
12214                         break;
12215                 }
12216         }
12217
12218         return true;
12219 }
12220
12221 static void
12222 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
12223 {
12224         struct drm_crtc_state tmp_state;
12225         struct intel_crtc_scaler_state scaler_state;
12226         struct intel_dpll_hw_state dpll_hw_state;
12227         enum intel_dpll_id shared_dpll;
12228         uint32_t ddi_pll_sel;
12229
12230         /* FIXME: before the switch to atomic started, a new pipe_config was
12231          * kzalloc'd. Code that depends on any field being zero should be
12232          * fixed, so that the crtc_state can be safely duplicated. For now,
12233          * only fields that are know to not cause problems are preserved. */
12234
12235         tmp_state = crtc_state->base;
12236         scaler_state = crtc_state->scaler_state;
12237         shared_dpll = crtc_state->shared_dpll;
12238         dpll_hw_state = crtc_state->dpll_hw_state;
12239         ddi_pll_sel = crtc_state->ddi_pll_sel;
12240
12241         memset(crtc_state, 0, sizeof *crtc_state);
12242
12243         crtc_state->base = tmp_state;
12244         crtc_state->scaler_state = scaler_state;
12245         crtc_state->shared_dpll = shared_dpll;
12246         crtc_state->dpll_hw_state = dpll_hw_state;
12247         crtc_state->ddi_pll_sel = ddi_pll_sel;
12248 }
12249
12250 static int
12251 intel_modeset_pipe_config(struct drm_crtc *crtc,
12252                           struct intel_crtc_state *pipe_config)
12253 {
12254         struct drm_atomic_state *state = pipe_config->base.state;
12255         struct intel_encoder *encoder;
12256         struct drm_connector *connector;
12257         struct drm_connector_state *connector_state;
12258         int base_bpp, ret = -EINVAL;
12259         int i;
12260         bool retry = true;
12261
12262         clear_intel_crtc_state(pipe_config);
12263
12264         pipe_config->cpu_transcoder =
12265                 (enum transcoder) to_intel_crtc(crtc)->pipe;
12266
12267         /*
12268          * Sanitize sync polarity flags based on requested ones. If neither
12269          * positive or negative polarity is requested, treat this as meaning
12270          * negative polarity.
12271          */
12272         if (!(pipe_config->base.adjusted_mode.flags &
12273               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
12274                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
12275
12276         if (!(pipe_config->base.adjusted_mode.flags &
12277               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
12278                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
12279
12280         /* Compute a starting value for pipe_config->pipe_bpp taking the source
12281          * plane pixel format and any sink constraints into account. Returns the
12282          * source plane bpp so that dithering can be selected on mismatches
12283          * after encoders and crtc also have had their say. */
12284         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
12285                                              pipe_config);
12286         if (base_bpp < 0)
12287                 goto fail;
12288
12289         /*
12290          * Determine the real pipe dimensions. Note that stereo modes can
12291          * increase the actual pipe size due to the frame doubling and
12292          * insertion of additional space for blanks between the frame. This
12293          * is stored in the crtc timings. We use the requested mode to do this
12294          * computation to clearly distinguish it from the adjusted mode, which
12295          * can be changed by the connectors in the below retry loop.
12296          */
12297         drm_crtc_get_hv_timing(&pipe_config->base.mode,
12298                                &pipe_config->pipe_src_w,
12299                                &pipe_config->pipe_src_h);
12300
12301 encoder_retry:
12302         /* Ensure the port clock defaults are reset when retrying. */
12303         pipe_config->port_clock = 0;
12304         pipe_config->pixel_multiplier = 1;
12305
12306         /* Fill in default crtc timings, allow encoders to overwrite them. */
12307         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
12308                               CRTC_STEREO_DOUBLE);
12309
12310         /* Pass our mode to the connectors and the CRTC to give them a chance to
12311          * adjust it according to limitations or connector properties, and also
12312          * a chance to reject the mode entirely.
12313          */
12314         for_each_connector_in_state(state, connector, connector_state, i) {
12315                 if (connector_state->crtc != crtc)
12316                         continue;
12317
12318                 encoder = to_intel_encoder(connector_state->best_encoder);
12319
12320                 if (!(encoder->compute_config(encoder, pipe_config))) {
12321                         DRM_DEBUG_KMS("Encoder config failure\n");
12322                         goto fail;
12323                 }
12324         }
12325
12326         /* Set default port clock if not overwritten by the encoder. Needs to be
12327          * done afterwards in case the encoder adjusts the mode. */
12328         if (!pipe_config->port_clock)
12329                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
12330                         * pipe_config->pixel_multiplier;
12331
12332         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
12333         if (ret < 0) {
12334                 DRM_DEBUG_KMS("CRTC fixup failed\n");
12335                 goto fail;
12336         }
12337
12338         if (ret == RETRY) {
12339                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
12340                         ret = -EINVAL;
12341                         goto fail;
12342                 }
12343
12344                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
12345                 retry = false;
12346                 goto encoder_retry;
12347         }
12348
12349         pipe_config->dither = pipe_config->pipe_bpp != base_bpp;
12350         DRM_DEBUG_KMS("plane bpp: %i, pipe bpp: %i, dithering: %i\n",
12351                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
12352
12353         /* Check if we need to force a modeset */
12354         if (pipe_config->has_audio !=
12355             to_intel_crtc_state(crtc->state)->has_audio) {
12356                 pipe_config->base.mode_changed = true;
12357                 ret = drm_atomic_add_affected_planes(state, crtc);
12358         }
12359
12360         /*
12361          * Note we have an issue here with infoframes: current code
12362          * only updates them on the full mode set path per hw
12363          * requirements.  So here we should be checking for any
12364          * required changes and forcing a mode set.
12365          */
12366 fail:
12367         return ret;
12368 }
12369
12370 static bool intel_crtc_in_use(struct drm_crtc *crtc)
12371 {
12372         struct drm_encoder *encoder;
12373         struct drm_device *dev = crtc->dev;
12374
12375         list_for_each_entry(encoder, &dev->mode_config.encoder_list, head)
12376                 if (encoder->crtc == crtc)
12377                         return true;
12378
12379         return false;
12380 }
12381
12382 static void
12383 intel_modeset_update_state(struct drm_atomic_state *state)
12384 {
12385         struct drm_device *dev = state->dev;
12386         struct intel_encoder *intel_encoder;
12387         struct drm_crtc *crtc;
12388         struct drm_crtc_state *crtc_state;
12389         struct drm_connector *connector;
12390
12391         intel_shared_dpll_commit(state);
12392
12393         for_each_intel_encoder(dev, intel_encoder) {
12394                 if (!intel_encoder->base.crtc)
12395                         continue;
12396
12397                 crtc = intel_encoder->base.crtc;
12398                 crtc_state = drm_atomic_get_existing_crtc_state(state, crtc);
12399                 if (!crtc_state || !needs_modeset(crtc->state))
12400                         continue;
12401
12402                 intel_encoder->connectors_active = false;
12403         }
12404
12405         drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
12406         intel_modeset_update_staged_output_state(state->dev);
12407
12408         /* Double check state. */
12409         for_each_crtc(dev, crtc) {
12410                 WARN_ON(crtc->state->enable != intel_crtc_in_use(crtc));
12411
12412                 to_intel_crtc(crtc)->config = to_intel_crtc_state(crtc->state);
12413
12414                 /* Update hwmode for vblank functions */
12415                 if (crtc->state->active)
12416                         crtc->hwmode = crtc->state->adjusted_mode;
12417                 else
12418                         crtc->hwmode.crtc_clock = 0;
12419         }
12420
12421         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
12422                 if (!connector->encoder || !connector->encoder->crtc)
12423                         continue;
12424
12425                 crtc = connector->encoder->crtc;
12426                 crtc_state = drm_atomic_get_existing_crtc_state(state, crtc);
12427                 if (!crtc_state || !needs_modeset(crtc->state))
12428                         continue;
12429
12430                 if (crtc->state->active) {
12431                         struct drm_property *dpms_property =
12432                                 dev->mode_config.dpms_property;
12433
12434                         connector->dpms = DRM_MODE_DPMS_ON;
12435                         drm_object_property_set_value(&connector->base, dpms_property, DRM_MODE_DPMS_ON);
12436
12437                         intel_encoder = to_intel_encoder(connector->encoder);
12438                         intel_encoder->connectors_active = true;
12439                 } else
12440                         connector->dpms = DRM_MODE_DPMS_OFF;
12441         }
12442 }
12443
12444 static bool intel_fuzzy_clock_check(int clock1, int clock2)
12445 {
12446         int diff;
12447
12448         if (clock1 == clock2)
12449                 return true;
12450
12451         if (!clock1 || !clock2)
12452                 return false;
12453
12454         diff = abs(clock1 - clock2);
12455
12456         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
12457                 return true;
12458
12459         return false;
12460 }
12461
12462 #define for_each_intel_crtc_masked(dev, mask, intel_crtc) \
12463         list_for_each_entry((intel_crtc), \
12464                             &(dev)->mode_config.crtc_list, \
12465                             base.head) \
12466                 if (mask & (1 <<(intel_crtc)->pipe))
12467
12468 static bool
12469 intel_pipe_config_compare(struct drm_device *dev,
12470                           struct intel_crtc_state *current_config,
12471                           struct intel_crtc_state *pipe_config)
12472 {
12473 #define PIPE_CONF_CHECK_X(name) \
12474         if (current_config->name != pipe_config->name) { \
12475                 DRM_ERROR("mismatch in " #name " " \
12476                           "(expected 0x%08x, found 0x%08x)\n", \
12477                           current_config->name, \
12478                           pipe_config->name); \
12479                 return false; \
12480         }
12481
12482 #define PIPE_CONF_CHECK_I(name) \
12483         if (current_config->name != pipe_config->name) { \
12484                 DRM_ERROR("mismatch in " #name " " \
12485                           "(expected %i, found %i)\n", \
12486                           current_config->name, \
12487                           pipe_config->name); \
12488                 return false; \
12489         }
12490
12491 /* This is required for BDW+ where there is only one set of registers for
12492  * switching between high and low RR.
12493  * This macro can be used whenever a comparison has to be made between one
12494  * hw state and multiple sw state variables.
12495  */
12496 #define PIPE_CONF_CHECK_I_ALT(name, alt_name) \
12497         if ((current_config->name != pipe_config->name) && \
12498                 (current_config->alt_name != pipe_config->name)) { \
12499                         DRM_ERROR("mismatch in " #name " " \
12500                                   "(expected %i or %i, found %i)\n", \
12501                                   current_config->name, \
12502                                   current_config->alt_name, \
12503                                   pipe_config->name); \
12504                         return false; \
12505         }
12506
12507 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
12508         if ((current_config->name ^ pipe_config->name) & (mask)) { \
12509                 DRM_ERROR("mismatch in " #name "(" #mask ") "      \
12510                           "(expected %i, found %i)\n", \
12511                           current_config->name & (mask), \
12512                           pipe_config->name & (mask)); \
12513                 return false; \
12514         }
12515
12516 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
12517         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
12518                 DRM_ERROR("mismatch in " #name " " \
12519                           "(expected %i, found %i)\n", \
12520                           current_config->name, \
12521                           pipe_config->name); \
12522                 return false; \
12523         }
12524
12525 #define PIPE_CONF_QUIRK(quirk)  \
12526         ((current_config->quirks | pipe_config->quirks) & (quirk))
12527
12528         PIPE_CONF_CHECK_I(cpu_transcoder);
12529
12530         PIPE_CONF_CHECK_I(has_pch_encoder);
12531         PIPE_CONF_CHECK_I(fdi_lanes);
12532         PIPE_CONF_CHECK_I(fdi_m_n.gmch_m);
12533         PIPE_CONF_CHECK_I(fdi_m_n.gmch_n);
12534         PIPE_CONF_CHECK_I(fdi_m_n.link_m);
12535         PIPE_CONF_CHECK_I(fdi_m_n.link_n);
12536         PIPE_CONF_CHECK_I(fdi_m_n.tu);
12537
12538         PIPE_CONF_CHECK_I(has_dp_encoder);
12539
12540         if (INTEL_INFO(dev)->gen < 8) {
12541                 PIPE_CONF_CHECK_I(dp_m_n.gmch_m);
12542                 PIPE_CONF_CHECK_I(dp_m_n.gmch_n);
12543                 PIPE_CONF_CHECK_I(dp_m_n.link_m);
12544                 PIPE_CONF_CHECK_I(dp_m_n.link_n);
12545                 PIPE_CONF_CHECK_I(dp_m_n.tu);
12546
12547                 if (current_config->has_drrs) {
12548                         PIPE_CONF_CHECK_I(dp_m2_n2.gmch_m);
12549                         PIPE_CONF_CHECK_I(dp_m2_n2.gmch_n);
12550                         PIPE_CONF_CHECK_I(dp_m2_n2.link_m);
12551                         PIPE_CONF_CHECK_I(dp_m2_n2.link_n);
12552                         PIPE_CONF_CHECK_I(dp_m2_n2.tu);
12553                 }
12554         } else {
12555                 PIPE_CONF_CHECK_I_ALT(dp_m_n.gmch_m, dp_m2_n2.gmch_m);
12556                 PIPE_CONF_CHECK_I_ALT(dp_m_n.gmch_n, dp_m2_n2.gmch_n);
12557                 PIPE_CONF_CHECK_I_ALT(dp_m_n.link_m, dp_m2_n2.link_m);
12558                 PIPE_CONF_CHECK_I_ALT(dp_m_n.link_n, dp_m2_n2.link_n);
12559                 PIPE_CONF_CHECK_I_ALT(dp_m_n.tu, dp_m2_n2.tu);
12560         }
12561
12562         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
12563         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
12564         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
12565         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
12566         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
12567         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
12568
12569         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
12570         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
12571         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
12572         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
12573         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
12574         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
12575
12576         PIPE_CONF_CHECK_I(pixel_multiplier);
12577         PIPE_CONF_CHECK_I(has_hdmi_sink);
12578         if ((INTEL_INFO(dev)->gen < 8 && !IS_HASWELL(dev)) ||
12579             IS_VALLEYVIEW(dev))
12580                 PIPE_CONF_CHECK_I(limited_color_range);
12581         PIPE_CONF_CHECK_I(has_infoframe);
12582
12583         PIPE_CONF_CHECK_I(has_audio);
12584
12585         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12586                               DRM_MODE_FLAG_INTERLACE);
12587
12588         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
12589                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12590                                       DRM_MODE_FLAG_PHSYNC);
12591                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12592                                       DRM_MODE_FLAG_NHSYNC);
12593                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12594                                       DRM_MODE_FLAG_PVSYNC);
12595                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12596                                       DRM_MODE_FLAG_NVSYNC);
12597         }
12598
12599         PIPE_CONF_CHECK_I(pipe_src_w);
12600         PIPE_CONF_CHECK_I(pipe_src_h);
12601
12602         /*
12603          * FIXME: BIOS likes to set up a cloned config with lvds+external
12604          * screen. Since we don't yet re-compute the pipe config when moving
12605          * just the lvds port away to another pipe the sw tracking won't match.
12606          *
12607          * Proper atomic modesets with recomputed global state will fix this.
12608          * Until then just don't check gmch state for inherited modes.
12609          */
12610         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_INHERITED_MODE)) {
12611                 PIPE_CONF_CHECK_I(gmch_pfit.control);
12612                 /* pfit ratios are autocomputed by the hw on gen4+ */
12613                 if (INTEL_INFO(dev)->gen < 4)
12614                         PIPE_CONF_CHECK_I(gmch_pfit.pgm_ratios);
12615                 PIPE_CONF_CHECK_I(gmch_pfit.lvds_border_bits);
12616         }
12617
12618         PIPE_CONF_CHECK_I(pch_pfit.enabled);
12619         if (current_config->pch_pfit.enabled) {
12620                 PIPE_CONF_CHECK_I(pch_pfit.pos);
12621                 PIPE_CONF_CHECK_I(pch_pfit.size);
12622         }
12623
12624         PIPE_CONF_CHECK_I(scaler_state.scaler_id);
12625
12626         /* BDW+ don't expose a synchronous way to read the state */
12627         if (IS_HASWELL(dev))
12628                 PIPE_CONF_CHECK_I(ips_enabled);
12629
12630         PIPE_CONF_CHECK_I(double_wide);
12631
12632         PIPE_CONF_CHECK_X(ddi_pll_sel);
12633
12634         PIPE_CONF_CHECK_I(shared_dpll);
12635         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
12636         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
12637         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
12638         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
12639         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
12640         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
12641         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
12642         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
12643
12644         if (IS_G4X(dev) || INTEL_INFO(dev)->gen >= 5)
12645                 PIPE_CONF_CHECK_I(pipe_bpp);
12646
12647         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
12648         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
12649
12650 #undef PIPE_CONF_CHECK_X
12651 #undef PIPE_CONF_CHECK_I
12652 #undef PIPE_CONF_CHECK_I_ALT
12653 #undef PIPE_CONF_CHECK_FLAGS
12654 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
12655 #undef PIPE_CONF_QUIRK
12656
12657         return true;
12658 }
12659
12660 static void check_wm_state(struct drm_device *dev)
12661 {
12662         struct drm_i915_private *dev_priv = dev->dev_private;
12663         struct skl_ddb_allocation hw_ddb, *sw_ddb;
12664         struct intel_crtc *intel_crtc;
12665         int plane;
12666
12667         if (INTEL_INFO(dev)->gen < 9)
12668                 return;
12669
12670         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
12671         sw_ddb = &dev_priv->wm.skl_hw.ddb;
12672
12673         for_each_intel_crtc(dev, intel_crtc) {
12674                 struct skl_ddb_entry *hw_entry, *sw_entry;
12675                 const enum pipe pipe = intel_crtc->pipe;
12676
12677                 if (!intel_crtc->active)
12678                         continue;
12679
12680                 /* planes */
12681                 for_each_plane(dev_priv, pipe, plane) {
12682                         hw_entry = &hw_ddb.plane[pipe][plane];
12683                         sw_entry = &sw_ddb->plane[pipe][plane];
12684
12685                         if (skl_ddb_entry_equal(hw_entry, sw_entry))
12686                                 continue;
12687
12688                         DRM_ERROR("mismatch in DDB state pipe %c plane %d "
12689                                   "(expected (%u,%u), found (%u,%u))\n",
12690                                   pipe_name(pipe), plane + 1,
12691                                   sw_entry->start, sw_entry->end,
12692                                   hw_entry->start, hw_entry->end);
12693                 }
12694
12695                 /* cursor */
12696                 hw_entry = &hw_ddb.cursor[pipe];
12697                 sw_entry = &sw_ddb->cursor[pipe];
12698
12699                 if (skl_ddb_entry_equal(hw_entry, sw_entry))
12700                         continue;
12701
12702                 DRM_ERROR("mismatch in DDB state pipe %c cursor "
12703                           "(expected (%u,%u), found (%u,%u))\n",
12704                           pipe_name(pipe),
12705                           sw_entry->start, sw_entry->end,
12706                           hw_entry->start, hw_entry->end);
12707         }
12708 }
12709
12710 static void
12711 check_connector_state(struct drm_device *dev)
12712 {
12713         struct intel_connector *connector;
12714
12715         for_each_intel_connector(dev, connector) {
12716                 /* This also checks the encoder/connector hw state with the
12717                  * ->get_hw_state callbacks. */
12718                 intel_connector_check_state(connector);
12719
12720                 I915_STATE_WARN(&connector->new_encoder->base != connector->base.encoder,
12721                      "connector's staged encoder doesn't match current encoder\n");
12722         }
12723 }
12724
12725 static void
12726 check_encoder_state(struct drm_device *dev)
12727 {
12728         struct intel_encoder *encoder;
12729         struct intel_connector *connector;
12730
12731         for_each_intel_encoder(dev, encoder) {
12732                 bool enabled = false;
12733                 bool active = false;
12734                 enum pipe pipe, tracked_pipe;
12735
12736                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
12737                               encoder->base.base.id,
12738                               encoder->base.name);
12739
12740                 I915_STATE_WARN(&encoder->new_crtc->base != encoder->base.crtc,
12741                      "encoder's stage crtc doesn't match current crtc\n");
12742                 I915_STATE_WARN(encoder->connectors_active && !encoder->base.crtc,
12743                      "encoder's active_connectors set, but no crtc\n");
12744
12745                 for_each_intel_connector(dev, connector) {
12746                         if (connector->base.encoder != &encoder->base)
12747                                 continue;
12748                         enabled = true;
12749                         if (connector->base.dpms != DRM_MODE_DPMS_OFF)
12750                                 active = true;
12751                 }
12752                 /*
12753                  * for MST connectors if we unplug the connector is gone
12754                  * away but the encoder is still connected to a crtc
12755                  * until a modeset happens in response to the hotplug.
12756                  */
12757                 if (!enabled && encoder->base.encoder_type == DRM_MODE_ENCODER_DPMST)
12758                         continue;
12759
12760                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
12761                      "encoder's enabled state mismatch "
12762                      "(expected %i, found %i)\n",
12763                      !!encoder->base.crtc, enabled);
12764                 I915_STATE_WARN(active && !encoder->base.crtc,
12765                      "active encoder with no crtc\n");
12766
12767                 I915_STATE_WARN(encoder->connectors_active != active,
12768                      "encoder's computed active state doesn't match tracked active state "
12769                      "(expected %i, found %i)\n", active, encoder->connectors_active);
12770
12771                 active = encoder->get_hw_state(encoder, &pipe);
12772                 I915_STATE_WARN(active != encoder->connectors_active,
12773                      "encoder's hw state doesn't match sw tracking "
12774                      "(expected %i, found %i)\n",
12775                      encoder->connectors_active, active);
12776
12777                 if (!encoder->base.crtc)
12778                         continue;
12779
12780                 tracked_pipe = to_intel_crtc(encoder->base.crtc)->pipe;
12781                 I915_STATE_WARN(active && pipe != tracked_pipe,
12782                      "active encoder's pipe doesn't match"
12783                      "(expected %i, found %i)\n",
12784                      tracked_pipe, pipe);
12785
12786         }
12787 }
12788
12789 static void
12790 check_crtc_state(struct drm_device *dev)
12791 {
12792         struct drm_i915_private *dev_priv = dev->dev_private;
12793         struct intel_crtc *crtc;
12794         struct intel_encoder *encoder;
12795         struct intel_crtc_state pipe_config;
12796
12797         for_each_intel_crtc(dev, crtc) {
12798                 bool enabled = false;
12799                 bool active = false;
12800
12801                 memset(&pipe_config, 0, sizeof(pipe_config));
12802
12803                 DRM_DEBUG_KMS("[CRTC:%d]\n",
12804                               crtc->base.base.id);
12805
12806                 I915_STATE_WARN(crtc->active && !crtc->base.state->enable,
12807                      "active crtc, but not enabled in sw tracking\n");
12808
12809                 for_each_intel_encoder(dev, encoder) {
12810                         if (encoder->base.crtc != &crtc->base)
12811                                 continue;
12812                         enabled = true;
12813                         if (encoder->connectors_active)
12814                                 active = true;
12815                 }
12816
12817                 I915_STATE_WARN(active != crtc->active,
12818                      "crtc's computed active state doesn't match tracked active state "
12819                      "(expected %i, found %i)\n", active, crtc->active);
12820                 I915_STATE_WARN(enabled != crtc->base.state->enable,
12821                      "crtc's computed enabled state doesn't match tracked enabled state "
12822                      "(expected %i, found %i)\n", enabled,
12823                                 crtc->base.state->enable);
12824
12825                 active = dev_priv->display.get_pipe_config(crtc,
12826                                                            &pipe_config);
12827
12828                 /* hw state is inconsistent with the pipe quirk */
12829                 if ((crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
12830                     (crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
12831                         active = crtc->active;
12832
12833                 for_each_intel_encoder(dev, encoder) {
12834                         enum pipe pipe;
12835                         if (encoder->base.crtc != &crtc->base)
12836                                 continue;
12837                         if (encoder->get_hw_state(encoder, &pipe))
12838                                 encoder->get_config(encoder, &pipe_config);
12839                 }
12840
12841                 I915_STATE_WARN(crtc->active != active,
12842                      "crtc active state doesn't match with hw state "
12843                      "(expected %i, found %i)\n", crtc->active, active);
12844
12845                 I915_STATE_WARN(crtc->active != crtc->base.state->active,
12846                      "transitional active state does not match atomic hw state "
12847                      "(expected %i, found %i)\n", crtc->base.state->active, crtc->active);
12848
12849                 if (active &&
12850                     !intel_pipe_config_compare(dev, crtc->config, &pipe_config)) {
12851                         I915_STATE_WARN(1, "pipe state doesn't match!\n");
12852                         intel_dump_pipe_config(crtc, &pipe_config,
12853                                                "[hw state]");
12854                         intel_dump_pipe_config(crtc, crtc->config,
12855                                                "[sw state]");
12856                 }
12857         }
12858 }
12859
12860 static void
12861 check_shared_dpll_state(struct drm_device *dev)
12862 {
12863         struct drm_i915_private *dev_priv = dev->dev_private;
12864         struct intel_crtc *crtc;
12865         struct intel_dpll_hw_state dpll_hw_state;
12866         int i;
12867
12868         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
12869                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
12870                 int enabled_crtcs = 0, active_crtcs = 0;
12871                 bool active;
12872
12873                 memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
12874
12875                 DRM_DEBUG_KMS("%s\n", pll->name);
12876
12877                 active = pll->get_hw_state(dev_priv, pll, &dpll_hw_state);
12878
12879                 I915_STATE_WARN(pll->active > hweight32(pll->config.crtc_mask),
12880                      "more active pll users than references: %i vs %i\n",
12881                      pll->active, hweight32(pll->config.crtc_mask));
12882                 I915_STATE_WARN(pll->active && !pll->on,
12883                      "pll in active use but not on in sw tracking\n");
12884                 I915_STATE_WARN(pll->on && !pll->active,
12885                      "pll in on but not on in use in sw tracking\n");
12886                 I915_STATE_WARN(pll->on != active,
12887                      "pll on state mismatch (expected %i, found %i)\n",
12888                      pll->on, active);
12889
12890                 for_each_intel_crtc(dev, crtc) {
12891                         if (crtc->base.state->enable && intel_crtc_to_shared_dpll(crtc) == pll)
12892                                 enabled_crtcs++;
12893                         if (crtc->active && intel_crtc_to_shared_dpll(crtc) == pll)
12894                                 active_crtcs++;
12895                 }
12896                 I915_STATE_WARN(pll->active != active_crtcs,
12897                      "pll active crtcs mismatch (expected %i, found %i)\n",
12898                      pll->active, active_crtcs);
12899                 I915_STATE_WARN(hweight32(pll->config.crtc_mask) != enabled_crtcs,
12900                      "pll enabled crtcs mismatch (expected %i, found %i)\n",
12901                      hweight32(pll->config.crtc_mask), enabled_crtcs);
12902
12903                 I915_STATE_WARN(pll->on && memcmp(&pll->config.hw_state, &dpll_hw_state,
12904                                        sizeof(dpll_hw_state)),
12905                      "pll hw state mismatch\n");
12906         }
12907 }
12908
12909 void
12910 intel_modeset_check_state(struct drm_device *dev)
12911 {
12912         check_wm_state(dev);
12913         check_connector_state(dev);
12914         check_encoder_state(dev);
12915         check_crtc_state(dev);
12916         check_shared_dpll_state(dev);
12917 }
12918
12919 void ironlake_check_encoder_dotclock(const struct intel_crtc_state *pipe_config,
12920                                      int dotclock)
12921 {
12922         /*
12923          * FDI already provided one idea for the dotclock.
12924          * Yell if the encoder disagrees.
12925          */
12926         WARN(!intel_fuzzy_clock_check(pipe_config->base.adjusted_mode.crtc_clock, dotclock),
12927              "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
12928              pipe_config->base.adjusted_mode.crtc_clock, dotclock);
12929 }
12930
12931 static void update_scanline_offset(struct intel_crtc *crtc)
12932 {
12933         struct drm_device *dev = crtc->base.dev;
12934
12935         /*
12936          * The scanline counter increments at the leading edge of hsync.
12937          *
12938          * On most platforms it starts counting from vtotal-1 on the
12939          * first active line. That means the scanline counter value is
12940          * always one less than what we would expect. Ie. just after
12941          * start of vblank, which also occurs at start of hsync (on the
12942          * last active line), the scanline counter will read vblank_start-1.
12943          *
12944          * On gen2 the scanline counter starts counting from 1 instead
12945          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
12946          * to keep the value positive), instead of adding one.
12947          *
12948          * On HSW+ the behaviour of the scanline counter depends on the output
12949          * type. For DP ports it behaves like most other platforms, but on HDMI
12950          * there's an extra 1 line difference. So we need to add two instead of
12951          * one to the value.
12952          */
12953         if (IS_GEN2(dev)) {
12954                 const struct drm_display_mode *mode = &crtc->config->base.adjusted_mode;
12955                 int vtotal;
12956
12957                 vtotal = mode->crtc_vtotal;
12958                 if (mode->flags & DRM_MODE_FLAG_INTERLACE)
12959                         vtotal /= 2;
12960
12961                 crtc->scanline_offset = vtotal - 1;
12962         } else if (HAS_DDI(dev) &&
12963                    intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI)) {
12964                 crtc->scanline_offset = 2;
12965         } else
12966                 crtc->scanline_offset = 1;
12967 }
12968
12969 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
12970 {
12971         struct drm_device *dev = state->dev;
12972         struct drm_i915_private *dev_priv = to_i915(dev);
12973         struct intel_shared_dpll_config *shared_dpll = NULL;
12974         struct intel_crtc *intel_crtc;
12975         struct intel_crtc_state *intel_crtc_state;
12976         struct drm_crtc *crtc;
12977         struct drm_crtc_state *crtc_state;
12978         int i;
12979
12980         if (!dev_priv->display.crtc_compute_clock)
12981                 return;
12982
12983         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12984                 int dpll;
12985
12986                 intel_crtc = to_intel_crtc(crtc);
12987                 intel_crtc_state = to_intel_crtc_state(crtc_state);
12988                 dpll = intel_crtc_state->shared_dpll;
12989
12990                 if (!needs_modeset(crtc_state) || dpll == DPLL_ID_PRIVATE)
12991                         continue;
12992
12993                 intel_crtc_state->shared_dpll = DPLL_ID_PRIVATE;
12994
12995                 if (!shared_dpll)
12996                         shared_dpll = intel_atomic_get_shared_dpll_state(state);
12997
12998                 shared_dpll[dpll].crtc_mask &= ~(1 << intel_crtc->pipe);
12999         }
13000 }
13001
13002 /*
13003  * This implements the workaround described in the "notes" section of the mode
13004  * set sequence documentation. When going from no pipes or single pipe to
13005  * multiple pipes, and planes are enabled after the pipe, we need to wait at
13006  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
13007  */
13008 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
13009 {
13010         struct drm_crtc_state *crtc_state;
13011         struct intel_crtc *intel_crtc;
13012         struct drm_crtc *crtc;
13013         struct intel_crtc_state *first_crtc_state = NULL;
13014         struct intel_crtc_state *other_crtc_state = NULL;
13015         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
13016         int i;
13017
13018         /* look at all crtc's that are going to be enabled in during modeset */
13019         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13020                 intel_crtc = to_intel_crtc(crtc);
13021
13022                 if (!crtc_state->active || !needs_modeset(crtc_state))
13023                         continue;
13024
13025                 if (first_crtc_state) {
13026                         other_crtc_state = to_intel_crtc_state(crtc_state);
13027                         break;
13028                 } else {
13029                         first_crtc_state = to_intel_crtc_state(crtc_state);
13030                         first_pipe = intel_crtc->pipe;
13031                 }
13032         }
13033
13034         /* No workaround needed? */
13035         if (!first_crtc_state)
13036                 return 0;
13037
13038         /* w/a possibly needed, check how many crtc's are already enabled. */
13039         for_each_intel_crtc(state->dev, intel_crtc) {
13040                 struct intel_crtc_state *pipe_config;
13041
13042                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
13043                 if (IS_ERR(pipe_config))
13044                         return PTR_ERR(pipe_config);
13045
13046                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
13047
13048                 if (!pipe_config->base.active ||
13049                     needs_modeset(&pipe_config->base))
13050                         continue;
13051
13052                 /* 2 or more enabled crtcs means no need for w/a */
13053                 if (enabled_pipe != INVALID_PIPE)
13054                         return 0;
13055
13056                 enabled_pipe = intel_crtc->pipe;
13057         }
13058
13059         if (enabled_pipe != INVALID_PIPE)
13060                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
13061         else if (other_crtc_state)
13062                 other_crtc_state->hsw_workaround_pipe = first_pipe;
13063
13064         return 0;
13065 }
13066
13067 /* Code that should eventually be part of atomic_check() */
13068 static int intel_modeset_checks(struct drm_atomic_state *state)
13069 {
13070         struct drm_device *dev = state->dev;
13071         int ret;
13072
13073         if (!check_digital_port_conflicts(state)) {
13074                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
13075                 return -EINVAL;
13076         }
13077
13078         /*
13079          * See if the config requires any additional preparation, e.g.
13080          * to adjust global state with pipes off.  We need to do this
13081          * here so we can get the modeset_pipe updated config for the new
13082          * mode set on this crtc.  For other crtcs we need to use the
13083          * adjusted_mode bits in the crtc directly.
13084          */
13085         if (IS_VALLEYVIEW(dev) || IS_BROXTON(dev) || IS_BROADWELL(dev)) {
13086                 if (IS_VALLEYVIEW(dev) || IS_BROXTON(dev))
13087                         ret = valleyview_modeset_global_pipes(state);
13088                 else
13089                         ret = broadwell_modeset_global_pipes(state);
13090
13091                 if (ret)
13092                         return ret;
13093         }
13094
13095         intel_modeset_clear_plls(state);
13096
13097         if (IS_HASWELL(dev))
13098                 return haswell_mode_set_planes_workaround(state);
13099
13100         return 0;
13101 }
13102
13103 static int
13104 intel_modeset_compute_config(struct drm_atomic_state *state)
13105 {
13106         struct drm_crtc *crtc;
13107         struct drm_crtc_state *crtc_state;
13108         int ret, i;
13109
13110         ret = drm_atomic_helper_check_modeset(state->dev, state);
13111         if (ret)
13112                 return ret;
13113
13114         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13115                 if (!crtc_state->enable &&
13116                     WARN_ON(crtc_state->active))
13117                         crtc_state->active = false;
13118
13119                 if (!crtc_state->enable)
13120                         continue;
13121
13122                 if (!needs_modeset(crtc_state)) {
13123                         ret = drm_atomic_add_affected_connectors(state, crtc);
13124                         if (ret)
13125                                 return ret;
13126                 }
13127
13128                 ret = intel_modeset_pipe_config(crtc,
13129                                         to_intel_crtc_state(crtc_state));
13130                 if (ret)
13131                         return ret;
13132
13133                 intel_dump_pipe_config(to_intel_crtc(crtc),
13134                                        to_intel_crtc_state(crtc_state),
13135                                        "[modeset]");
13136         }
13137
13138         ret = intel_modeset_checks(state);
13139         if (ret)
13140                 return ret;
13141
13142         return drm_atomic_helper_check_planes(state->dev, state);
13143 }
13144
13145 static int __intel_set_mode(struct drm_atomic_state *state)
13146 {
13147         struct drm_device *dev = state->dev;
13148         struct drm_i915_private *dev_priv = dev->dev_private;
13149         struct drm_crtc *crtc;
13150         struct drm_crtc_state *crtc_state;
13151         int ret = 0;
13152         int i;
13153
13154         ret = drm_atomic_helper_prepare_planes(dev, state);
13155         if (ret)
13156                 return ret;
13157
13158         drm_atomic_helper_swap_state(dev, state);
13159
13160         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13161                 if (!needs_modeset(crtc->state) || !crtc_state->active)
13162                         continue;
13163
13164                 intel_crtc_disable_planes(crtc);
13165                 dev_priv->display.crtc_disable(crtc);
13166         }
13167
13168         /* Only after disabling all output pipelines that will be changed can we
13169          * update the the output configuration. */
13170         intel_modeset_update_state(state);
13171
13172         /* The state has been swaped above, so state actually contains the
13173          * old state now. */
13174
13175         modeset_update_crtc_power_domains(state);
13176
13177         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
13178         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13179                 drm_atomic_helper_commit_planes_on_crtc(crtc_state);
13180
13181                 if (!needs_modeset(crtc->state) || !crtc->state->active)
13182                         continue;
13183
13184                 update_scanline_offset(to_intel_crtc(crtc));
13185
13186                 dev_priv->display.crtc_enable(crtc);
13187                 intel_crtc_enable_planes(crtc);
13188         }
13189
13190         /* FIXME: add subpixel order */
13191
13192         drm_atomic_helper_cleanup_planes(dev, state);
13193
13194         drm_atomic_state_free(state);
13195
13196         return 0;
13197 }
13198
13199 static int intel_set_mode_checked(struct drm_atomic_state *state)
13200 {
13201         struct drm_device *dev = state->dev;
13202         int ret;
13203
13204         ret = __intel_set_mode(state);
13205         if (ret == 0)
13206                 intel_modeset_check_state(dev);
13207
13208         return ret;
13209 }
13210
13211 static int intel_set_mode(struct drm_atomic_state *state)
13212 {
13213         int ret;
13214
13215         ret = intel_modeset_compute_config(state);
13216         if (ret)
13217                 return ret;
13218
13219         return intel_set_mode_checked(state);
13220 }
13221
13222 void intel_crtc_restore_mode(struct drm_crtc *crtc)
13223 {
13224         struct drm_device *dev = crtc->dev;
13225         struct drm_atomic_state *state;
13226         struct intel_crtc *intel_crtc;
13227         struct intel_encoder *encoder;
13228         struct intel_connector *connector;
13229         struct drm_connector_state *connector_state;
13230         struct intel_crtc_state *crtc_state;
13231         int ret;
13232
13233         state = drm_atomic_state_alloc(dev);
13234         if (!state) {
13235                 DRM_DEBUG_KMS("[CRTC:%d] mode restore failed, out of memory",
13236                               crtc->base.id);
13237                 return;
13238         }
13239
13240         state->acquire_ctx = dev->mode_config.acquire_ctx;
13241
13242         /* The force restore path in the HW readout code relies on the staged
13243          * config still keeping the user requested config while the actual
13244          * state has been overwritten by the configuration read from HW. We
13245          * need to copy the staged config to the atomic state, otherwise the
13246          * mode set will just reapply the state the HW is already in. */
13247         for_each_intel_encoder(dev, encoder) {
13248                 if (&encoder->new_crtc->base != crtc)
13249                         continue;
13250
13251                 for_each_intel_connector(dev, connector) {
13252                         if (connector->new_encoder != encoder)
13253                                 continue;
13254
13255                         connector_state = drm_atomic_get_connector_state(state, &connector->base);
13256                         if (IS_ERR(connector_state)) {
13257                                 DRM_DEBUG_KMS("Failed to add [CONNECTOR:%d:%s] to state: %ld\n",
13258                                               connector->base.base.id,
13259                                               connector->base.name,
13260                                               PTR_ERR(connector_state));
13261                                 continue;
13262                         }
13263
13264                         connector_state->crtc = crtc;
13265                         connector_state->best_encoder = &encoder->base;
13266                 }
13267         }
13268
13269         for_each_intel_crtc(dev, intel_crtc) {
13270                 if (intel_crtc->new_enabled == intel_crtc->base.enabled)
13271                         continue;
13272
13273                 crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
13274                 if (IS_ERR(crtc_state)) {
13275                         DRM_DEBUG_KMS("Failed to add [CRTC:%d] to state: %ld\n",
13276                                       intel_crtc->base.base.id,
13277                                       PTR_ERR(crtc_state));
13278                         continue;
13279                 }
13280
13281                 crtc_state->base.active = crtc_state->base.enable =
13282                         intel_crtc->new_enabled;
13283
13284                 if (&intel_crtc->base == crtc)
13285                         drm_mode_copy(&crtc_state->base.mode, &crtc->mode);
13286         }
13287
13288         intel_modeset_setup_plane_state(state, crtc, &crtc->mode,
13289                                         crtc->primary->fb, crtc->x, crtc->y);
13290
13291         ret = intel_set_mode(state);
13292         if (ret)
13293                 drm_atomic_state_free(state);
13294 }
13295
13296 #undef for_each_intel_crtc_masked
13297
13298 static bool intel_connector_in_mode_set(struct intel_connector *connector,
13299                                         struct drm_mode_set *set)
13300 {
13301         int ro;
13302
13303         for (ro = 0; ro < set->num_connectors; ro++)
13304                 if (set->connectors[ro] == &connector->base)
13305                         return true;
13306
13307         return false;
13308 }
13309
13310 static int
13311 intel_modeset_stage_output_state(struct drm_device *dev,
13312                                  struct drm_mode_set *set,
13313                                  struct drm_atomic_state *state)
13314 {
13315         struct intel_connector *connector;
13316         struct drm_connector *drm_connector;
13317         struct drm_connector_state *connector_state;
13318         struct drm_crtc *crtc;
13319         struct drm_crtc_state *crtc_state;
13320         int i, ret;
13321
13322         /* The upper layers ensure that we either disable a crtc or have a list
13323          * of connectors. For paranoia, double-check this. */
13324         WARN_ON(!set->fb && (set->num_connectors != 0));
13325         WARN_ON(set->fb && (set->num_connectors == 0));
13326
13327         for_each_intel_connector(dev, connector) {
13328                 bool in_mode_set = intel_connector_in_mode_set(connector, set);
13329
13330                 if (!in_mode_set && connector->base.state->crtc != set->crtc)
13331                         continue;
13332
13333                 connector_state =
13334                         drm_atomic_get_connector_state(state, &connector->base);
13335                 if (IS_ERR(connector_state))
13336                         return PTR_ERR(connector_state);
13337
13338                 if (in_mode_set) {
13339                         int pipe = to_intel_crtc(set->crtc)->pipe;
13340                         connector_state->best_encoder =
13341                                 &intel_find_encoder(connector, pipe)->base;
13342                 }
13343
13344                 if (connector->base.state->crtc != set->crtc)
13345                         continue;
13346
13347                 /* If we disable the crtc, disable all its connectors. Also, if
13348                  * the connector is on the changing crtc but not on the new
13349                  * connector list, disable it. */
13350                 if (!set->fb || !in_mode_set) {
13351                         connector_state->best_encoder = NULL;
13352
13353                         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] to [NOCRTC]\n",
13354                                 connector->base.base.id,
13355                                 connector->base.name);
13356                 }
13357         }
13358         /* connector->new_encoder is now updated for all connectors. */
13359
13360         for_each_connector_in_state(state, drm_connector, connector_state, i) {
13361                 connector = to_intel_connector(drm_connector);
13362
13363                 if (!connector_state->best_encoder) {
13364                         ret = drm_atomic_set_crtc_for_connector(connector_state,
13365                                                                 NULL);
13366                         if (ret)
13367                                 return ret;
13368
13369                         continue;
13370                 }
13371
13372                 if (intel_connector_in_mode_set(connector, set)) {
13373                         struct drm_crtc *crtc = connector->base.state->crtc;
13374
13375                         /* If this connector was in a previous crtc, add it
13376                          * to the state. We might need to disable it. */
13377                         if (crtc) {
13378                                 crtc_state =
13379                                         drm_atomic_get_crtc_state(state, crtc);
13380                                 if (IS_ERR(crtc_state))
13381                                         return PTR_ERR(crtc_state);
13382                         }
13383
13384                         ret = drm_atomic_set_crtc_for_connector(connector_state,
13385                                                                 set->crtc);
13386                         if (ret)
13387                                 return ret;
13388                 }
13389
13390                 /* Make sure the new CRTC will work with the encoder */
13391                 if (!drm_encoder_crtc_ok(connector_state->best_encoder,
13392                                          connector_state->crtc)) {
13393                         return -EINVAL;
13394                 }
13395
13396                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] to [CRTC:%d]\n",
13397                         connector->base.base.id,
13398                         connector->base.name,
13399                         connector_state->crtc->base.id);
13400
13401                 if (connector_state->best_encoder != &connector->encoder->base)
13402                         connector->encoder =
13403                                 to_intel_encoder(connector_state->best_encoder);
13404         }
13405
13406         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13407                 bool has_connectors;
13408
13409                 ret = drm_atomic_add_affected_connectors(state, crtc);
13410                 if (ret)
13411                         return ret;
13412
13413                 has_connectors = !!drm_atomic_connectors_for_crtc(state, crtc);
13414                 if (has_connectors != crtc_state->enable)
13415                         crtc_state->enable =
13416                         crtc_state->active = has_connectors;
13417         }
13418
13419         ret = intel_modeset_setup_plane_state(state, set->crtc, set->mode,
13420                                               set->fb, set->x, set->y);
13421         if (ret)
13422                 return ret;
13423
13424         crtc_state = drm_atomic_get_crtc_state(state, set->crtc);
13425         if (IS_ERR(crtc_state))
13426                 return PTR_ERR(crtc_state);
13427
13428         ret = drm_atomic_set_mode_for_crtc(crtc_state, set->mode);
13429         if (ret)
13430                 return ret;
13431
13432         if (set->num_connectors)
13433                 crtc_state->active = true;
13434
13435         return 0;
13436 }
13437
13438 static int intel_crtc_set_config(struct drm_mode_set *set)
13439 {
13440         struct drm_device *dev;
13441         struct drm_atomic_state *state = NULL;
13442         int ret;
13443
13444         BUG_ON(!set);
13445         BUG_ON(!set->crtc);
13446         BUG_ON(!set->crtc->helper_private);
13447
13448         /* Enforce sane interface api - has been abused by the fb helper. */
13449         BUG_ON(!set->mode && set->fb);
13450         BUG_ON(set->fb && set->num_connectors == 0);
13451
13452         if (set->fb) {
13453                 DRM_DEBUG_KMS("[CRTC:%d] [FB:%d] #connectors=%d (x y) (%i %i)\n",
13454                                 set->crtc->base.id, set->fb->base.id,
13455                                 (int)set->num_connectors, set->x, set->y);
13456         } else {
13457                 DRM_DEBUG_KMS("[CRTC:%d] [NOFB]\n", set->crtc->base.id);
13458         }
13459
13460         dev = set->crtc->dev;
13461
13462         state = drm_atomic_state_alloc(dev);
13463         if (!state)
13464                 return -ENOMEM;
13465
13466         state->acquire_ctx = dev->mode_config.acquire_ctx;
13467
13468         ret = intel_modeset_stage_output_state(dev, set, state);
13469         if (ret)
13470                 goto out;
13471
13472         ret = intel_modeset_compute_config(state);
13473         if (ret)
13474                 goto out;
13475
13476         intel_update_pipe_size(to_intel_crtc(set->crtc));
13477
13478         ret = intel_set_mode_checked(state);
13479         if (ret) {
13480                 DRM_DEBUG_KMS("failed to set mode on [CRTC:%d], err = %d\n",
13481                               set->crtc->base.id, ret);
13482         }
13483
13484 out:
13485         if (ret)
13486                 drm_atomic_state_free(state);
13487         return ret;
13488 }
13489
13490 static const struct drm_crtc_funcs intel_crtc_funcs = {
13491         .gamma_set = intel_crtc_gamma_set,
13492         .set_config = intel_crtc_set_config,
13493         .destroy = intel_crtc_destroy,
13494         .page_flip = intel_crtc_page_flip,
13495         .atomic_duplicate_state = intel_crtc_duplicate_state,
13496         .atomic_destroy_state = intel_crtc_destroy_state,
13497 };
13498
13499 static bool ibx_pch_dpll_get_hw_state(struct drm_i915_private *dev_priv,
13500                                       struct intel_shared_dpll *pll,
13501                                       struct intel_dpll_hw_state *hw_state)
13502 {
13503         uint32_t val;
13504
13505         if (!intel_display_power_is_enabled(dev_priv, POWER_DOMAIN_PLLS))
13506                 return false;
13507
13508         val = I915_READ(PCH_DPLL(pll->id));
13509         hw_state->dpll = val;
13510         hw_state->fp0 = I915_READ(PCH_FP0(pll->id));
13511         hw_state->fp1 = I915_READ(PCH_FP1(pll->id));
13512
13513         return val & DPLL_VCO_ENABLE;
13514 }
13515
13516 static void ibx_pch_dpll_mode_set(struct drm_i915_private *dev_priv,
13517                                   struct intel_shared_dpll *pll)
13518 {
13519         I915_WRITE(PCH_FP0(pll->id), pll->config.hw_state.fp0);
13520         I915_WRITE(PCH_FP1(pll->id), pll->config.hw_state.fp1);
13521 }
13522
13523 static void ibx_pch_dpll_enable(struct drm_i915_private *dev_priv,
13524                                 struct intel_shared_dpll *pll)
13525 {
13526         /* PCH refclock must be enabled first */
13527         ibx_assert_pch_refclk_enabled(dev_priv);
13528
13529         I915_WRITE(PCH_DPLL(pll->id), pll->config.hw_state.dpll);
13530
13531         /* Wait for the clocks to stabilize. */
13532         POSTING_READ(PCH_DPLL(pll->id));
13533         udelay(150);
13534
13535         /* The pixel multiplier can only be updated once the
13536          * DPLL is enabled and the clocks are stable.
13537          *
13538          * So write it again.
13539          */
13540         I915_WRITE(PCH_DPLL(pll->id), pll->config.hw_state.dpll);
13541         POSTING_READ(PCH_DPLL(pll->id));
13542         udelay(200);
13543 }
13544
13545 static void ibx_pch_dpll_disable(struct drm_i915_private *dev_priv,
13546                                  struct intel_shared_dpll *pll)
13547 {
13548         struct drm_device *dev = dev_priv->dev;
13549         struct intel_crtc *crtc;
13550
13551         /* Make sure no transcoder isn't still depending on us. */
13552         for_each_intel_crtc(dev, crtc) {
13553                 if (intel_crtc_to_shared_dpll(crtc) == pll)
13554                         assert_pch_transcoder_disabled(dev_priv, crtc->pipe);
13555         }
13556
13557         I915_WRITE(PCH_DPLL(pll->id), 0);
13558         POSTING_READ(PCH_DPLL(pll->id));
13559         udelay(200);
13560 }
13561
13562 static char *ibx_pch_dpll_names[] = {
13563         "PCH DPLL A",
13564         "PCH DPLL B",
13565 };
13566
13567 static void ibx_pch_dpll_init(struct drm_device *dev)
13568 {
13569         struct drm_i915_private *dev_priv = dev->dev_private;
13570         int i;
13571
13572         dev_priv->num_shared_dpll = 2;
13573
13574         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
13575                 dev_priv->shared_dplls[i].id = i;
13576                 dev_priv->shared_dplls[i].name = ibx_pch_dpll_names[i];
13577                 dev_priv->shared_dplls[i].mode_set = ibx_pch_dpll_mode_set;
13578                 dev_priv->shared_dplls[i].enable = ibx_pch_dpll_enable;
13579                 dev_priv->shared_dplls[i].disable = ibx_pch_dpll_disable;
13580                 dev_priv->shared_dplls[i].get_hw_state =
13581                         ibx_pch_dpll_get_hw_state;
13582         }
13583 }
13584
13585 static void intel_shared_dpll_init(struct drm_device *dev)
13586 {
13587         struct drm_i915_private *dev_priv = dev->dev_private;
13588
13589         intel_update_cdclk(dev);
13590
13591         if (HAS_DDI(dev))
13592                 intel_ddi_pll_init(dev);
13593         else if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
13594                 ibx_pch_dpll_init(dev);
13595         else
13596                 dev_priv->num_shared_dpll = 0;
13597
13598         BUG_ON(dev_priv->num_shared_dpll > I915_NUM_PLLS);
13599 }
13600
13601 /**
13602  * intel_prepare_plane_fb - Prepare fb for usage on plane
13603  * @plane: drm plane to prepare for
13604  * @fb: framebuffer to prepare for presentation
13605  *
13606  * Prepares a framebuffer for usage on a display plane.  Generally this
13607  * involves pinning the underlying object and updating the frontbuffer tracking
13608  * bits.  Some older platforms need special physical address handling for
13609  * cursor planes.
13610  *
13611  * Returns 0 on success, negative error code on failure.
13612  */
13613 int
13614 intel_prepare_plane_fb(struct drm_plane *plane,
13615                        struct drm_framebuffer *fb,
13616                        const struct drm_plane_state *new_state)
13617 {
13618         struct drm_device *dev = plane->dev;
13619         struct intel_plane *intel_plane = to_intel_plane(plane);
13620         enum pipe pipe = intel_plane->pipe;
13621         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13622         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->fb);
13623         unsigned frontbuffer_bits = 0;
13624         int ret = 0;
13625
13626         if (!obj)
13627                 return 0;
13628
13629         switch (plane->type) {
13630         case DRM_PLANE_TYPE_PRIMARY:
13631                 frontbuffer_bits = INTEL_FRONTBUFFER_PRIMARY(pipe);
13632                 break;
13633         case DRM_PLANE_TYPE_CURSOR:
13634                 frontbuffer_bits = INTEL_FRONTBUFFER_CURSOR(pipe);
13635                 break;
13636         case DRM_PLANE_TYPE_OVERLAY:
13637                 frontbuffer_bits = INTEL_FRONTBUFFER_SPRITE(pipe);
13638                 break;
13639         }
13640
13641         mutex_lock(&dev->struct_mutex);
13642
13643         if (plane->type == DRM_PLANE_TYPE_CURSOR &&
13644             INTEL_INFO(dev)->cursor_needs_physical) {
13645                 int align = IS_I830(dev) ? 16 * 1024 : 256;
13646                 ret = i915_gem_object_attach_phys(obj, align);
13647                 if (ret)
13648                         DRM_DEBUG_KMS("failed to attach phys object\n");
13649         } else {
13650                 ret = intel_pin_and_fence_fb_obj(plane, fb, new_state, NULL);
13651         }
13652
13653         if (ret == 0)
13654                 i915_gem_track_fb(old_obj, obj, frontbuffer_bits);
13655
13656         mutex_unlock(&dev->struct_mutex);
13657
13658         return ret;
13659 }
13660
13661 /**
13662  * intel_cleanup_plane_fb - Cleans up an fb after plane use
13663  * @plane: drm plane to clean up for
13664  * @fb: old framebuffer that was on plane
13665  *
13666  * Cleans up a framebuffer that has just been removed from a plane.
13667  */
13668 void
13669 intel_cleanup_plane_fb(struct drm_plane *plane,
13670                        struct drm_framebuffer *fb,
13671                        const struct drm_plane_state *old_state)
13672 {
13673         struct drm_device *dev = plane->dev;
13674         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13675
13676         if (WARN_ON(!obj))
13677                 return;
13678
13679         if (plane->type != DRM_PLANE_TYPE_CURSOR ||
13680             !INTEL_INFO(dev)->cursor_needs_physical) {
13681                 mutex_lock(&dev->struct_mutex);
13682                 intel_unpin_fb_obj(fb, old_state);
13683                 mutex_unlock(&dev->struct_mutex);
13684         }
13685 }
13686
13687 int
13688 skl_max_scale(struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state)
13689 {
13690         int max_scale;
13691         struct drm_device *dev;
13692         struct drm_i915_private *dev_priv;
13693         int crtc_clock, cdclk;
13694
13695         if (!intel_crtc || !crtc_state)
13696                 return DRM_PLANE_HELPER_NO_SCALING;
13697
13698         dev = intel_crtc->base.dev;
13699         dev_priv = dev->dev_private;
13700         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
13701         cdclk = dev_priv->display.get_display_clock_speed(dev);
13702
13703         if (!crtc_clock || !cdclk)
13704                 return DRM_PLANE_HELPER_NO_SCALING;
13705
13706         /*
13707          * skl max scale is lower of:
13708          *    close to 3 but not 3, -1 is for that purpose
13709          *            or
13710          *    cdclk/crtc_clock
13711          */
13712         max_scale = min((1 << 16) * 3 - 1, (1 << 8) * ((cdclk << 8) / crtc_clock));
13713
13714         return max_scale;
13715 }
13716
13717 static int
13718 intel_check_primary_plane(struct drm_plane *plane,
13719                           struct intel_crtc_state *crtc_state,
13720                           struct intel_plane_state *state)
13721 {
13722         struct drm_crtc *crtc = state->base.crtc;
13723         struct drm_framebuffer *fb = state->base.fb;
13724         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
13725         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
13726         bool can_position = false;
13727
13728         /* use scaler when colorkey is not required */
13729         if (INTEL_INFO(plane->dev)->gen >= 9 &&
13730             to_intel_plane(plane)->ckey.flags == I915_SET_COLORKEY_NONE) {
13731                 min_scale = 1;
13732                 max_scale = skl_max_scale(to_intel_crtc(crtc), crtc_state);
13733                 can_position = true;
13734         }
13735
13736         return drm_plane_helper_check_update(plane, crtc, fb, &state->src,
13737                                              &state->dst, &state->clip,
13738                                              min_scale, max_scale,
13739                                              can_position, true,
13740                                              &state->visible);
13741 }
13742
13743 static void
13744 intel_commit_primary_plane(struct drm_plane *plane,
13745                            struct intel_plane_state *state)
13746 {
13747         struct drm_crtc *crtc = state->base.crtc;
13748         struct drm_framebuffer *fb = state->base.fb;
13749         struct drm_device *dev = plane->dev;
13750         struct drm_i915_private *dev_priv = dev->dev_private;
13751         struct intel_crtc *intel_crtc;
13752         struct drm_rect *src = &state->src;
13753
13754         crtc = crtc ? crtc : plane->crtc;
13755         intel_crtc = to_intel_crtc(crtc);
13756
13757         plane->fb = fb;
13758         crtc->x = src->x1 >> 16;
13759         crtc->y = src->y1 >> 16;
13760
13761         if (!intel_crtc->active)
13762                 return;
13763
13764         if (state->visible)
13765                 /* FIXME: kill this fastboot hack */
13766                 intel_update_pipe_size(intel_crtc);
13767
13768         dev_priv->display.update_primary_plane(crtc, fb, crtc->x, crtc->y);
13769 }
13770
13771 static void
13772 intel_disable_primary_plane(struct drm_plane *plane,
13773                             struct drm_crtc *crtc,
13774                             bool force)
13775 {
13776         struct drm_device *dev = plane->dev;
13777         struct drm_i915_private *dev_priv = dev->dev_private;
13778
13779         dev_priv->display.update_primary_plane(crtc, NULL, 0, 0);
13780 }
13781
13782 static void intel_begin_crtc_commit(struct drm_crtc *crtc)
13783 {
13784         struct drm_device *dev = crtc->dev;
13785         struct drm_i915_private *dev_priv = dev->dev_private;
13786         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13787         struct drm_crtc_state *crtc_state = intel_crtc->base.state;
13788         struct intel_plane *intel_plane;
13789         struct drm_plane *p;
13790         unsigned fb_bits = 0;
13791
13792         /* Track fb's for any planes being disabled */
13793         list_for_each_entry(p, &dev->mode_config.plane_list, head) {
13794                 intel_plane = to_intel_plane(p);
13795
13796                 if (intel_crtc->atomic.disabled_planes &
13797                     (1 << drm_plane_index(p))) {
13798                         switch (p->type) {
13799                         case DRM_PLANE_TYPE_PRIMARY:
13800                                 fb_bits = INTEL_FRONTBUFFER_PRIMARY(intel_plane->pipe);
13801                                 break;
13802                         case DRM_PLANE_TYPE_CURSOR:
13803                                 fb_bits = INTEL_FRONTBUFFER_CURSOR(intel_plane->pipe);
13804                                 break;
13805                         case DRM_PLANE_TYPE_OVERLAY:
13806                                 fb_bits = INTEL_FRONTBUFFER_SPRITE(intel_plane->pipe);
13807                                 break;
13808                         }
13809
13810                         mutex_lock(&dev->struct_mutex);
13811                         i915_gem_track_fb(intel_fb_obj(p->fb), NULL, fb_bits);
13812                         mutex_unlock(&dev->struct_mutex);
13813                 }
13814         }
13815
13816         if (intel_crtc->atomic.wait_for_flips)
13817                 intel_crtc_wait_for_pending_flips(crtc);
13818
13819         if (intel_crtc->atomic.disable_fbc)
13820                 intel_fbc_disable(dev);
13821
13822         if (intel_crtc->atomic.pre_disable_primary)
13823                 intel_pre_disable_primary(crtc);
13824
13825         if (intel_crtc->atomic.update_wm)
13826                 intel_update_watermarks(crtc);
13827
13828         intel_runtime_pm_get(dev_priv);
13829
13830         /* Perform vblank evasion around commit operation */
13831         if (crtc_state->active && !needs_modeset(crtc_state))
13832                 intel_crtc->atomic.evade =
13833                         intel_pipe_update_start(intel_crtc,
13834                                                 &intel_crtc->atomic.start_vbl_count);
13835 }
13836
13837 static void intel_finish_crtc_commit(struct drm_crtc *crtc)
13838 {
13839         struct drm_device *dev = crtc->dev;
13840         struct drm_i915_private *dev_priv = dev->dev_private;
13841         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13842         struct drm_plane *p;
13843
13844         if (intel_crtc->atomic.evade)
13845                 intel_pipe_update_end(intel_crtc,
13846                                       intel_crtc->atomic.start_vbl_count);
13847
13848         intel_runtime_pm_put(dev_priv);
13849
13850         if (intel_crtc->atomic.wait_vblank && intel_crtc->active)
13851                 intel_wait_for_vblank(dev, intel_crtc->pipe);
13852
13853         intel_frontbuffer_flip(dev, intel_crtc->atomic.fb_bits);
13854
13855         if (intel_crtc->atomic.update_fbc) {
13856                 mutex_lock(&dev->struct_mutex);
13857                 intel_fbc_update(dev);
13858                 mutex_unlock(&dev->struct_mutex);
13859         }
13860
13861         if (intel_crtc->atomic.post_enable_primary)
13862                 intel_post_enable_primary(crtc);
13863
13864         drm_for_each_legacy_plane(p, &dev->mode_config.plane_list)
13865                 if (intel_crtc->atomic.update_sprite_watermarks & drm_plane_index(p))
13866                         intel_update_sprite_watermarks(p, crtc, 0, 0, 0,
13867                                                        false, false);
13868
13869         memset(&intel_crtc->atomic, 0, sizeof(intel_crtc->atomic));
13870 }
13871
13872 /**
13873  * intel_plane_destroy - destroy a plane
13874  * @plane: plane to destroy
13875  *
13876  * Common destruction function for all types of planes (primary, cursor,
13877  * sprite).
13878  */
13879 void intel_plane_destroy(struct drm_plane *plane)
13880 {
13881         struct intel_plane *intel_plane = to_intel_plane(plane);
13882         drm_plane_cleanup(plane);
13883         kfree(intel_plane);
13884 }
13885
13886 const struct drm_plane_funcs intel_plane_funcs = {
13887         .update_plane = drm_atomic_helper_update_plane,
13888         .disable_plane = drm_atomic_helper_disable_plane,
13889         .destroy = intel_plane_destroy,
13890         .set_property = drm_atomic_helper_plane_set_property,
13891         .atomic_get_property = intel_plane_atomic_get_property,
13892         .atomic_set_property = intel_plane_atomic_set_property,
13893         .atomic_duplicate_state = intel_plane_duplicate_state,
13894         .atomic_destroy_state = intel_plane_destroy_state,
13895
13896 };
13897
13898 static struct drm_plane *intel_primary_plane_create(struct drm_device *dev,
13899                                                     int pipe)
13900 {
13901         struct intel_plane *primary;
13902         struct intel_plane_state *state;
13903         const uint32_t *intel_primary_formats;
13904         int num_formats;
13905
13906         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
13907         if (primary == NULL)
13908                 return NULL;
13909
13910         state = intel_create_plane_state(&primary->base);
13911         if (!state) {
13912                 kfree(primary);
13913                 return NULL;
13914         }
13915         primary->base.state = &state->base;
13916
13917         primary->can_scale = false;
13918         primary->max_downscale = 1;
13919         if (INTEL_INFO(dev)->gen >= 9) {
13920                 primary->can_scale = true;
13921                 state->scaler_id = -1;
13922         }
13923         primary->pipe = pipe;
13924         primary->plane = pipe;
13925         primary->check_plane = intel_check_primary_plane;
13926         primary->commit_plane = intel_commit_primary_plane;
13927         primary->disable_plane = intel_disable_primary_plane;
13928         primary->ckey.flags = I915_SET_COLORKEY_NONE;
13929         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4)
13930                 primary->plane = !pipe;
13931
13932         if (INTEL_INFO(dev)->gen >= 9) {
13933                 intel_primary_formats = skl_primary_formats;
13934                 num_formats = ARRAY_SIZE(skl_primary_formats);
13935         } else if (INTEL_INFO(dev)->gen >= 4) {
13936                 intel_primary_formats = i965_primary_formats;
13937                 num_formats = ARRAY_SIZE(i965_primary_formats);
13938         } else {
13939                 intel_primary_formats = i8xx_primary_formats;
13940                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
13941         }
13942
13943         drm_universal_plane_init(dev, &primary->base, 0,
13944                                  &intel_plane_funcs,
13945                                  intel_primary_formats, num_formats,
13946                                  DRM_PLANE_TYPE_PRIMARY);
13947
13948         if (INTEL_INFO(dev)->gen >= 4)
13949                 intel_create_rotation_property(dev, primary);
13950
13951         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
13952
13953         return &primary->base;
13954 }
13955
13956 void intel_create_rotation_property(struct drm_device *dev, struct intel_plane *plane)
13957 {
13958         if (!dev->mode_config.rotation_property) {
13959                 unsigned long flags = BIT(DRM_ROTATE_0) |
13960                         BIT(DRM_ROTATE_180);
13961
13962                 if (INTEL_INFO(dev)->gen >= 9)
13963                         flags |= BIT(DRM_ROTATE_90) | BIT(DRM_ROTATE_270);
13964
13965                 dev->mode_config.rotation_property =
13966                         drm_mode_create_rotation_property(dev, flags);
13967         }
13968         if (dev->mode_config.rotation_property)
13969                 drm_object_attach_property(&plane->base.base,
13970                                 dev->mode_config.rotation_property,
13971                                 plane->base.state->rotation);
13972 }
13973
13974 static int
13975 intel_check_cursor_plane(struct drm_plane *plane,
13976                          struct intel_crtc_state *crtc_state,
13977                          struct intel_plane_state *state)
13978 {
13979         struct drm_crtc *crtc = crtc_state->base.crtc;
13980         struct drm_framebuffer *fb = state->base.fb;
13981         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13982         unsigned stride;
13983         int ret;
13984
13985         ret = drm_plane_helper_check_update(plane, crtc, fb, &state->src,
13986                                             &state->dst, &state->clip,
13987                                             DRM_PLANE_HELPER_NO_SCALING,
13988                                             DRM_PLANE_HELPER_NO_SCALING,
13989                                             true, true, &state->visible);
13990         if (ret)
13991                 return ret;
13992
13993         /* if we want to turn off the cursor ignore width and height */
13994         if (!obj)
13995                 return 0;
13996
13997         /* Check for which cursor types we support */
13998         if (!cursor_size_ok(plane->dev, state->base.crtc_w, state->base.crtc_h)) {
13999                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
14000                           state->base.crtc_w, state->base.crtc_h);
14001                 return -EINVAL;
14002         }
14003
14004         stride = roundup_pow_of_two(state->base.crtc_w) * 4;
14005         if (obj->base.size < stride * state->base.crtc_h) {
14006                 DRM_DEBUG_KMS("buffer is too small\n");
14007                 return -ENOMEM;
14008         }
14009
14010         if (fb->modifier[0] != DRM_FORMAT_MOD_NONE) {
14011                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
14012                 return -EINVAL;
14013         }
14014
14015         return 0;
14016 }
14017
14018 static void
14019 intel_disable_cursor_plane(struct drm_plane *plane,
14020                            struct drm_crtc *crtc,
14021                            bool force)
14022 {
14023         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14024
14025         if (!force) {
14026                 plane->fb = NULL;
14027                 intel_crtc->cursor_bo = NULL;
14028                 intel_crtc->cursor_addr = 0;
14029         }
14030
14031         intel_crtc_update_cursor(crtc, false);
14032 }
14033
14034 static void
14035 intel_commit_cursor_plane(struct drm_plane *plane,
14036                           struct intel_plane_state *state)
14037 {
14038         struct drm_crtc *crtc = state->base.crtc;
14039         struct drm_device *dev = plane->dev;
14040         struct intel_crtc *intel_crtc;
14041         struct drm_i915_gem_object *obj = intel_fb_obj(state->base.fb);
14042         uint32_t addr;
14043
14044         crtc = crtc ? crtc : plane->crtc;
14045         intel_crtc = to_intel_crtc(crtc);
14046
14047         plane->fb = state->base.fb;
14048         crtc->cursor_x = state->base.crtc_x;
14049         crtc->cursor_y = state->base.crtc_y;
14050
14051         if (intel_crtc->cursor_bo == obj)
14052                 goto update;
14053
14054         if (!obj)
14055                 addr = 0;
14056         else if (!INTEL_INFO(dev)->cursor_needs_physical)
14057                 addr = i915_gem_obj_ggtt_offset(obj);
14058         else
14059                 addr = obj->phys_handle->busaddr;
14060
14061         intel_crtc->cursor_addr = addr;
14062         intel_crtc->cursor_bo = obj;
14063
14064 update:
14065         if (intel_crtc->active)
14066                 intel_crtc_update_cursor(crtc, state->visible);
14067 }
14068
14069 static struct drm_plane *intel_cursor_plane_create(struct drm_device *dev,
14070                                                    int pipe)
14071 {
14072         struct intel_plane *cursor;
14073         struct intel_plane_state *state;
14074
14075         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
14076         if (cursor == NULL)
14077                 return NULL;
14078
14079         state = intel_create_plane_state(&cursor->base);
14080         if (!state) {
14081                 kfree(cursor);
14082                 return NULL;
14083         }
14084         cursor->base.state = &state->base;
14085
14086         cursor->can_scale = false;
14087         cursor->max_downscale = 1;
14088         cursor->pipe = pipe;
14089         cursor->plane = pipe;
14090         cursor->check_plane = intel_check_cursor_plane;
14091         cursor->commit_plane = intel_commit_cursor_plane;
14092         cursor->disable_plane = intel_disable_cursor_plane;
14093
14094         drm_universal_plane_init(dev, &cursor->base, 0,
14095                                  &intel_plane_funcs,
14096                                  intel_cursor_formats,
14097                                  ARRAY_SIZE(intel_cursor_formats),
14098                                  DRM_PLANE_TYPE_CURSOR);
14099
14100         if (INTEL_INFO(dev)->gen >= 4) {
14101                 if (!dev->mode_config.rotation_property)
14102                         dev->mode_config.rotation_property =
14103                                 drm_mode_create_rotation_property(dev,
14104                                                         BIT(DRM_ROTATE_0) |
14105                                                         BIT(DRM_ROTATE_180));
14106                 if (dev->mode_config.rotation_property)
14107                         drm_object_attach_property(&cursor->base.base,
14108                                 dev->mode_config.rotation_property,
14109                                 state->base.rotation);
14110         }
14111
14112         if (INTEL_INFO(dev)->gen >=9)
14113                 state->scaler_id = -1;
14114
14115         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
14116
14117         return &cursor->base;
14118 }
14119
14120 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
14121         struct intel_crtc_state *crtc_state)
14122 {
14123         int i;
14124         struct intel_scaler *intel_scaler;
14125         struct intel_crtc_scaler_state *scaler_state = &crtc_state->scaler_state;
14126
14127         for (i = 0; i < intel_crtc->num_scalers; i++) {
14128                 intel_scaler = &scaler_state->scalers[i];
14129                 intel_scaler->in_use = 0;
14130                 intel_scaler->mode = PS_SCALER_MODE_DYN;
14131         }
14132
14133         scaler_state->scaler_id = -1;
14134 }
14135
14136 static void intel_crtc_init(struct drm_device *dev, int pipe)
14137 {
14138         struct drm_i915_private *dev_priv = dev->dev_private;
14139         struct intel_crtc *intel_crtc;
14140         struct intel_crtc_state *crtc_state = NULL;
14141         struct drm_plane *primary = NULL;
14142         struct drm_plane *cursor = NULL;
14143         int i, ret;
14144
14145         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
14146         if (intel_crtc == NULL)
14147                 return;
14148
14149         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
14150         if (!crtc_state)
14151                 goto fail;
14152         intel_crtc->config = crtc_state;
14153         intel_crtc->base.state = &crtc_state->base;
14154         crtc_state->base.crtc = &intel_crtc->base;
14155
14156         /* initialize shared scalers */
14157         if (INTEL_INFO(dev)->gen >= 9) {
14158                 if (pipe == PIPE_C)
14159                         intel_crtc->num_scalers = 1;
14160                 else
14161                         intel_crtc->num_scalers = SKL_NUM_SCALERS;
14162
14163                 skl_init_scalers(dev, intel_crtc, crtc_state);
14164         }
14165
14166         primary = intel_primary_plane_create(dev, pipe);
14167         if (!primary)
14168                 goto fail;
14169
14170         cursor = intel_cursor_plane_create(dev, pipe);
14171         if (!cursor)
14172                 goto fail;
14173
14174         ret = drm_crtc_init_with_planes(dev, &intel_crtc->base, primary,
14175                                         cursor, &intel_crtc_funcs);
14176         if (ret)
14177                 goto fail;
14178
14179         drm_mode_crtc_set_gamma_size(&intel_crtc->base, 256);
14180         for (i = 0; i < 256; i++) {
14181                 intel_crtc->lut_r[i] = i;
14182                 intel_crtc->lut_g[i] = i;
14183                 intel_crtc->lut_b[i] = i;
14184         }
14185
14186         /*
14187          * On gen2/3 only plane A can do fbc, but the panel fitter and lvds port
14188          * is hooked to pipe B. Hence we want plane A feeding pipe B.
14189          */
14190         intel_crtc->pipe = pipe;
14191         intel_crtc->plane = pipe;
14192         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4) {
14193                 DRM_DEBUG_KMS("swapping pipes & planes for FBC\n");
14194                 intel_crtc->plane = !pipe;
14195         }
14196
14197         intel_crtc->cursor_base = ~0;
14198         intel_crtc->cursor_cntl = ~0;
14199         intel_crtc->cursor_size = ~0;
14200
14201         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
14202                dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
14203         dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = &intel_crtc->base;
14204         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = &intel_crtc->base;
14205
14206         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
14207
14208         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
14209         return;
14210
14211 fail:
14212         if (primary)
14213                 drm_plane_cleanup(primary);
14214         if (cursor)
14215                 drm_plane_cleanup(cursor);
14216         kfree(crtc_state);
14217         kfree(intel_crtc);
14218 }
14219
14220 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
14221 {
14222         struct drm_encoder *encoder = connector->base.encoder;
14223         struct drm_device *dev = connector->base.dev;
14224
14225         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
14226
14227         if (!encoder || WARN_ON(!encoder->crtc))
14228                 return INVALID_PIPE;
14229
14230         return to_intel_crtc(encoder->crtc)->pipe;
14231 }
14232
14233 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
14234                                 struct drm_file *file)
14235 {
14236         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
14237         struct drm_crtc *drmmode_crtc;
14238         struct intel_crtc *crtc;
14239
14240         drmmode_crtc = drm_crtc_find(dev, pipe_from_crtc_id->crtc_id);
14241
14242         if (!drmmode_crtc) {
14243                 DRM_ERROR("no such CRTC id\n");
14244                 return -ENOENT;
14245         }
14246
14247         crtc = to_intel_crtc(drmmode_crtc);
14248         pipe_from_crtc_id->pipe = crtc->pipe;
14249
14250         return 0;
14251 }
14252
14253 static int intel_encoder_clones(struct intel_encoder *encoder)
14254 {
14255         struct drm_device *dev = encoder->base.dev;
14256         struct intel_encoder *source_encoder;
14257         int index_mask = 0;
14258         int entry = 0;
14259
14260         for_each_intel_encoder(dev, source_encoder) {
14261                 if (encoders_cloneable(encoder, source_encoder))
14262                         index_mask |= (1 << entry);
14263
14264                 entry++;
14265         }
14266
14267         return index_mask;
14268 }
14269
14270 static bool has_edp_a(struct drm_device *dev)
14271 {
14272         struct drm_i915_private *dev_priv = dev->dev_private;
14273
14274         if (!IS_MOBILE(dev))
14275                 return false;
14276
14277         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
14278                 return false;
14279
14280         if (IS_GEN5(dev) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
14281                 return false;
14282
14283         return true;
14284 }
14285
14286 static bool intel_crt_present(struct drm_device *dev)
14287 {
14288         struct drm_i915_private *dev_priv = dev->dev_private;
14289
14290         if (INTEL_INFO(dev)->gen >= 9)
14291                 return false;
14292
14293         if (IS_HSW_ULT(dev) || IS_BDW_ULT(dev))
14294                 return false;
14295
14296         if (IS_CHERRYVIEW(dev))
14297                 return false;
14298
14299         if (IS_VALLEYVIEW(dev) && !dev_priv->vbt.int_crt_support)
14300                 return false;
14301
14302         return true;
14303 }
14304
14305 static void intel_setup_outputs(struct drm_device *dev)
14306 {
14307         struct drm_i915_private *dev_priv = dev->dev_private;
14308         struct intel_encoder *encoder;
14309         bool dpd_is_edp = false;
14310
14311         intel_lvds_init(dev);
14312
14313         if (intel_crt_present(dev))
14314                 intel_crt_init(dev);
14315
14316         if (IS_BROXTON(dev)) {
14317                 /*
14318                  * FIXME: Broxton doesn't support port detection via the
14319                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
14320                  * detect the ports.
14321                  */
14322                 intel_ddi_init(dev, PORT_A);
14323                 intel_ddi_init(dev, PORT_B);
14324                 intel_ddi_init(dev, PORT_C);
14325         } else if (HAS_DDI(dev)) {
14326                 int found;
14327
14328                 /*
14329                  * Haswell uses DDI functions to detect digital outputs.
14330                  * On SKL pre-D0 the strap isn't connected, so we assume
14331                  * it's there.
14332                  */
14333                 found = I915_READ(DDI_BUF_CTL_A) & DDI_INIT_DISPLAY_DETECTED;
14334                 /* WaIgnoreDDIAStrap: skl */
14335                 if (found ||
14336                     (IS_SKYLAKE(dev) && INTEL_REVID(dev) < SKL_REVID_D0))
14337                         intel_ddi_init(dev, PORT_A);
14338
14339                 /* DDI B, C and D detection is indicated by the SFUSE_STRAP
14340                  * register */
14341                 found = I915_READ(SFUSE_STRAP);
14342
14343                 if (found & SFUSE_STRAP_DDIB_DETECTED)
14344                         intel_ddi_init(dev, PORT_B);
14345                 if (found & SFUSE_STRAP_DDIC_DETECTED)
14346                         intel_ddi_init(dev, PORT_C);
14347                 if (found & SFUSE_STRAP_DDID_DETECTED)
14348                         intel_ddi_init(dev, PORT_D);
14349         } else if (HAS_PCH_SPLIT(dev)) {
14350                 int found;
14351                 dpd_is_edp = intel_dp_is_edp(dev, PORT_D);
14352
14353                 if (has_edp_a(dev))
14354                         intel_dp_init(dev, DP_A, PORT_A);
14355
14356                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
14357                         /* PCH SDVOB multiplex with HDMIB */
14358                         found = intel_sdvo_init(dev, PCH_SDVOB, true);
14359                         if (!found)
14360                                 intel_hdmi_init(dev, PCH_HDMIB, PORT_B);
14361                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
14362                                 intel_dp_init(dev, PCH_DP_B, PORT_B);
14363                 }
14364
14365                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
14366                         intel_hdmi_init(dev, PCH_HDMIC, PORT_C);
14367
14368                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
14369                         intel_hdmi_init(dev, PCH_HDMID, PORT_D);
14370
14371                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
14372                         intel_dp_init(dev, PCH_DP_C, PORT_C);
14373
14374                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
14375                         intel_dp_init(dev, PCH_DP_D, PORT_D);
14376         } else if (IS_VALLEYVIEW(dev)) {
14377                 /*
14378                  * The DP_DETECTED bit is the latched state of the DDC
14379                  * SDA pin at boot. However since eDP doesn't require DDC
14380                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
14381                  * eDP ports may have been muxed to an alternate function.
14382                  * Thus we can't rely on the DP_DETECTED bit alone to detect
14383                  * eDP ports. Consult the VBT as well as DP_DETECTED to
14384                  * detect eDP ports.
14385                  */
14386                 if (I915_READ(VLV_DISPLAY_BASE + GEN4_HDMIB) & SDVO_DETECTED &&
14387                     !intel_dp_is_edp(dev, PORT_B))
14388                         intel_hdmi_init(dev, VLV_DISPLAY_BASE + GEN4_HDMIB,
14389                                         PORT_B);
14390                 if (I915_READ(VLV_DISPLAY_BASE + DP_B) & DP_DETECTED ||
14391                     intel_dp_is_edp(dev, PORT_B))
14392                         intel_dp_init(dev, VLV_DISPLAY_BASE + DP_B, PORT_B);
14393
14394                 if (I915_READ(VLV_DISPLAY_BASE + GEN4_HDMIC) & SDVO_DETECTED &&
14395                     !intel_dp_is_edp(dev, PORT_C))
14396                         intel_hdmi_init(dev, VLV_DISPLAY_BASE + GEN4_HDMIC,
14397                                         PORT_C);
14398                 if (I915_READ(VLV_DISPLAY_BASE + DP_C) & DP_DETECTED ||
14399                     intel_dp_is_edp(dev, PORT_C))
14400                         intel_dp_init(dev, VLV_DISPLAY_BASE + DP_C, PORT_C);
14401
14402                 if (IS_CHERRYVIEW(dev)) {
14403                         if (I915_READ(VLV_DISPLAY_BASE + CHV_HDMID) & SDVO_DETECTED)
14404                                 intel_hdmi_init(dev, VLV_DISPLAY_BASE + CHV_HDMID,
14405                                                 PORT_D);
14406                         /* eDP not supported on port D, so don't check VBT */
14407                         if (I915_READ(VLV_DISPLAY_BASE + DP_D) & DP_DETECTED)
14408                                 intel_dp_init(dev, VLV_DISPLAY_BASE + DP_D, PORT_D);
14409                 }
14410
14411                 intel_dsi_init(dev);
14412         } else if (SUPPORTS_DIGITAL_OUTPUTS(dev)) {
14413                 bool found = false;
14414
14415                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14416                         DRM_DEBUG_KMS("probing SDVOB\n");
14417                         found = intel_sdvo_init(dev, GEN3_SDVOB, true);
14418                         if (!found && SUPPORTS_INTEGRATED_HDMI(dev)) {
14419                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
14420                                 intel_hdmi_init(dev, GEN4_HDMIB, PORT_B);
14421                         }
14422
14423                         if (!found && SUPPORTS_INTEGRATED_DP(dev))
14424                                 intel_dp_init(dev, DP_B, PORT_B);
14425                 }
14426
14427                 /* Before G4X SDVOC doesn't have its own detect register */
14428
14429                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14430                         DRM_DEBUG_KMS("probing SDVOC\n");
14431                         found = intel_sdvo_init(dev, GEN3_SDVOC, false);
14432                 }
14433
14434                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
14435
14436                         if (SUPPORTS_INTEGRATED_HDMI(dev)) {
14437                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
14438                                 intel_hdmi_init(dev, GEN4_HDMIC, PORT_C);
14439                         }
14440                         if (SUPPORTS_INTEGRATED_DP(dev))
14441                                 intel_dp_init(dev, DP_C, PORT_C);
14442                 }
14443
14444                 if (SUPPORTS_INTEGRATED_DP(dev) &&
14445                     (I915_READ(DP_D) & DP_DETECTED))
14446                         intel_dp_init(dev, DP_D, PORT_D);
14447         } else if (IS_GEN2(dev))
14448                 intel_dvo_init(dev);
14449
14450         if (SUPPORTS_TV(dev))
14451                 intel_tv_init(dev);
14452
14453         intel_psr_init(dev);
14454
14455         for_each_intel_encoder(dev, encoder) {
14456                 encoder->base.possible_crtcs = encoder->crtc_mask;
14457                 encoder->base.possible_clones =
14458                         intel_encoder_clones(encoder);
14459         }
14460
14461         intel_init_pch_refclk(dev);
14462
14463         drm_helper_move_panel_connectors_to_head(dev);
14464 }
14465
14466 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
14467 {
14468         struct drm_device *dev = fb->dev;
14469         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14470
14471         drm_framebuffer_cleanup(fb);
14472         mutex_lock(&dev->struct_mutex);
14473         WARN_ON(!intel_fb->obj->framebuffer_references--);
14474         drm_gem_object_unreference(&intel_fb->obj->base);
14475         mutex_unlock(&dev->struct_mutex);
14476         kfree(intel_fb);
14477 }
14478
14479 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
14480                                                 struct drm_file *file,
14481                                                 unsigned int *handle)
14482 {
14483         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14484         struct drm_i915_gem_object *obj = intel_fb->obj;
14485
14486         return drm_gem_handle_create(file, &obj->base, handle);
14487 }
14488
14489 static const struct drm_framebuffer_funcs intel_fb_funcs = {
14490         .destroy = intel_user_framebuffer_destroy,
14491         .create_handle = intel_user_framebuffer_create_handle,
14492 };
14493
14494 static
14495 u32 intel_fb_pitch_limit(struct drm_device *dev, uint64_t fb_modifier,
14496                          uint32_t pixel_format)
14497 {
14498         u32 gen = INTEL_INFO(dev)->gen;
14499
14500         if (gen >= 9) {
14501                 /* "The stride in bytes must not exceed the of the size of 8K
14502                  *  pixels and 32K bytes."
14503                  */
14504                  return min(8192*drm_format_plane_cpp(pixel_format, 0), 32768);
14505         } else if (gen >= 5 && !IS_VALLEYVIEW(dev)) {
14506                 return 32*1024;
14507         } else if (gen >= 4) {
14508                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14509                         return 16*1024;
14510                 else
14511                         return 32*1024;
14512         } else if (gen >= 3) {
14513                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14514                         return 8*1024;
14515                 else
14516                         return 16*1024;
14517         } else {
14518                 /* XXX DSPC is limited to 4k tiled */
14519                 return 8*1024;
14520         }
14521 }
14522
14523 static int intel_framebuffer_init(struct drm_device *dev,
14524                                   struct intel_framebuffer *intel_fb,
14525                                   struct drm_mode_fb_cmd2 *mode_cmd,
14526                                   struct drm_i915_gem_object *obj)
14527 {
14528         unsigned int aligned_height;
14529         int ret;
14530         u32 pitch_limit, stride_alignment;
14531
14532         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
14533
14534         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
14535                 /* Enforce that fb modifier and tiling mode match, but only for
14536                  * X-tiled. This is needed for FBC. */
14537                 if (!!(obj->tiling_mode == I915_TILING_X) !=
14538                     !!(mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED)) {
14539                         DRM_DEBUG("tiling_mode doesn't match fb modifier\n");
14540                         return -EINVAL;
14541                 }
14542         } else {
14543                 if (obj->tiling_mode == I915_TILING_X)
14544                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
14545                 else if (obj->tiling_mode == I915_TILING_Y) {
14546                         DRM_DEBUG("No Y tiling for legacy addfb\n");
14547                         return -EINVAL;
14548                 }
14549         }
14550
14551         /* Passed in modifier sanity checking. */
14552         switch (mode_cmd->modifier[0]) {
14553         case I915_FORMAT_MOD_Y_TILED:
14554         case I915_FORMAT_MOD_Yf_TILED:
14555                 if (INTEL_INFO(dev)->gen < 9) {
14556                         DRM_DEBUG("Unsupported tiling 0x%llx!\n",
14557                                   mode_cmd->modifier[0]);
14558                         return -EINVAL;
14559                 }
14560         case DRM_FORMAT_MOD_NONE:
14561         case I915_FORMAT_MOD_X_TILED:
14562                 break;
14563         default:
14564                 DRM_DEBUG("Unsupported fb modifier 0x%llx!\n",
14565                           mode_cmd->modifier[0]);
14566                 return -EINVAL;
14567         }
14568
14569         stride_alignment = intel_fb_stride_alignment(dev, mode_cmd->modifier[0],
14570                                                      mode_cmd->pixel_format);
14571         if (mode_cmd->pitches[0] & (stride_alignment - 1)) {
14572                 DRM_DEBUG("pitch (%d) must be at least %u byte aligned\n",
14573                           mode_cmd->pitches[0], stride_alignment);
14574                 return -EINVAL;
14575         }
14576
14577         pitch_limit = intel_fb_pitch_limit(dev, mode_cmd->modifier[0],
14578                                            mode_cmd->pixel_format);
14579         if (mode_cmd->pitches[0] > pitch_limit) {
14580                 DRM_DEBUG("%s pitch (%u) must be at less than %d\n",
14581                           mode_cmd->modifier[0] != DRM_FORMAT_MOD_NONE ?
14582                           "tiled" : "linear",
14583                           mode_cmd->pitches[0], pitch_limit);
14584                 return -EINVAL;
14585         }
14586
14587         if (mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED &&
14588             mode_cmd->pitches[0] != obj->stride) {
14589                 DRM_DEBUG("pitch (%d) must match tiling stride (%d)\n",
14590                           mode_cmd->pitches[0], obj->stride);
14591                 return -EINVAL;
14592         }
14593
14594         /* Reject formats not supported by any plane early. */
14595         switch (mode_cmd->pixel_format) {
14596         case DRM_FORMAT_C8:
14597         case DRM_FORMAT_RGB565:
14598         case DRM_FORMAT_XRGB8888:
14599         case DRM_FORMAT_ARGB8888:
14600                 break;
14601         case DRM_FORMAT_XRGB1555:
14602                 if (INTEL_INFO(dev)->gen > 3) {
14603                         DRM_DEBUG("unsupported pixel format: %s\n",
14604                                   drm_get_format_name(mode_cmd->pixel_format));
14605                         return -EINVAL;
14606                 }
14607                 break;
14608         case DRM_FORMAT_ABGR8888:
14609                 if (!IS_VALLEYVIEW(dev) && INTEL_INFO(dev)->gen < 9) {
14610                         DRM_DEBUG("unsupported pixel format: %s\n",
14611                                   drm_get_format_name(mode_cmd->pixel_format));
14612                         return -EINVAL;
14613                 }
14614                 break;
14615         case DRM_FORMAT_XBGR8888:
14616         case DRM_FORMAT_XRGB2101010:
14617         case DRM_FORMAT_XBGR2101010:
14618                 if (INTEL_INFO(dev)->gen < 4) {
14619                         DRM_DEBUG("unsupported pixel format: %s\n",
14620                                   drm_get_format_name(mode_cmd->pixel_format));
14621                         return -EINVAL;
14622                 }
14623                 break;
14624         case DRM_FORMAT_ABGR2101010:
14625                 if (!IS_VALLEYVIEW(dev)) {
14626                         DRM_DEBUG("unsupported pixel format: %s\n",
14627                                   drm_get_format_name(mode_cmd->pixel_format));
14628                         return -EINVAL;
14629                 }
14630                 break;
14631         case DRM_FORMAT_YUYV:
14632         case DRM_FORMAT_UYVY:
14633         case DRM_FORMAT_YVYU:
14634         case DRM_FORMAT_VYUY:
14635                 if (INTEL_INFO(dev)->gen < 5) {
14636                         DRM_DEBUG("unsupported pixel format: %s\n",
14637                                   drm_get_format_name(mode_cmd->pixel_format));
14638                         return -EINVAL;
14639                 }
14640                 break;
14641         default:
14642                 DRM_DEBUG("unsupported pixel format: %s\n",
14643                           drm_get_format_name(mode_cmd->pixel_format));
14644                 return -EINVAL;
14645         }
14646
14647         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14648         if (mode_cmd->offsets[0] != 0)
14649                 return -EINVAL;
14650
14651         aligned_height = intel_fb_align_height(dev, mode_cmd->height,
14652                                                mode_cmd->pixel_format,
14653                                                mode_cmd->modifier[0]);
14654         /* FIXME drm helper for size checks (especially planar formats)? */
14655         if (obj->base.size < aligned_height * mode_cmd->pitches[0])
14656                 return -EINVAL;
14657
14658         drm_helper_mode_fill_fb_struct(&intel_fb->base, mode_cmd);
14659         intel_fb->obj = obj;
14660         intel_fb->obj->framebuffer_references++;
14661
14662         ret = drm_framebuffer_init(dev, &intel_fb->base, &intel_fb_funcs);
14663         if (ret) {
14664                 DRM_ERROR("framebuffer init failed %d\n", ret);
14665                 return ret;
14666         }
14667
14668         return 0;
14669 }
14670
14671 static struct drm_framebuffer *
14672 intel_user_framebuffer_create(struct drm_device *dev,
14673                               struct drm_file *filp,
14674                               struct drm_mode_fb_cmd2 *mode_cmd)
14675 {
14676         struct drm_i915_gem_object *obj;
14677
14678         obj = to_intel_bo(drm_gem_object_lookup(dev, filp,
14679                                                 mode_cmd->handles[0]));
14680         if (&obj->base == NULL)
14681                 return ERR_PTR(-ENOENT);
14682
14683         return intel_framebuffer_create(dev, mode_cmd, obj);
14684 }
14685
14686 #ifndef CONFIG_DRM_I915_FBDEV
14687 static inline void intel_fbdev_output_poll_changed(struct drm_device *dev)
14688 {
14689 }
14690 #endif
14691
14692 static const struct drm_mode_config_funcs intel_mode_funcs = {
14693         .fb_create = intel_user_framebuffer_create,
14694         .output_poll_changed = intel_fbdev_output_poll_changed,
14695         .atomic_check = intel_atomic_check,
14696         .atomic_commit = intel_atomic_commit,
14697         .atomic_state_alloc = intel_atomic_state_alloc,
14698         .atomic_state_clear = intel_atomic_state_clear,
14699 };
14700
14701 /* Set up chip specific display functions */
14702 static void intel_init_display(struct drm_device *dev)
14703 {
14704         struct drm_i915_private *dev_priv = dev->dev_private;
14705
14706         if (HAS_PCH_SPLIT(dev) || IS_G4X(dev))
14707                 dev_priv->display.find_dpll = g4x_find_best_dpll;
14708         else if (IS_CHERRYVIEW(dev))
14709                 dev_priv->display.find_dpll = chv_find_best_dpll;
14710         else if (IS_VALLEYVIEW(dev))
14711                 dev_priv->display.find_dpll = vlv_find_best_dpll;
14712         else if (IS_PINEVIEW(dev))
14713                 dev_priv->display.find_dpll = pnv_find_best_dpll;
14714         else
14715                 dev_priv->display.find_dpll = i9xx_find_best_dpll;
14716
14717         if (INTEL_INFO(dev)->gen >= 9) {
14718                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14719                 dev_priv->display.get_initial_plane_config =
14720                         skylake_get_initial_plane_config;
14721                 dev_priv->display.crtc_compute_clock =
14722                         haswell_crtc_compute_clock;
14723                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14724                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14725                 dev_priv->display.update_primary_plane =
14726                         skylake_update_primary_plane;
14727         } else if (HAS_DDI(dev)) {
14728                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14729                 dev_priv->display.get_initial_plane_config =
14730                         ironlake_get_initial_plane_config;
14731                 dev_priv->display.crtc_compute_clock =
14732                         haswell_crtc_compute_clock;
14733                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14734                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14735                 dev_priv->display.update_primary_plane =
14736                         ironlake_update_primary_plane;
14737         } else if (HAS_PCH_SPLIT(dev)) {
14738                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
14739                 dev_priv->display.get_initial_plane_config =
14740                         ironlake_get_initial_plane_config;
14741                 dev_priv->display.crtc_compute_clock =
14742                         ironlake_crtc_compute_clock;
14743                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
14744                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
14745                 dev_priv->display.update_primary_plane =
14746                         ironlake_update_primary_plane;
14747         } else if (IS_VALLEYVIEW(dev)) {
14748                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14749                 dev_priv->display.get_initial_plane_config =
14750                         i9xx_get_initial_plane_config;
14751                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14752                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14753                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14754                 dev_priv->display.update_primary_plane =
14755                         i9xx_update_primary_plane;
14756         } else {
14757                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14758                 dev_priv->display.get_initial_plane_config =
14759                         i9xx_get_initial_plane_config;
14760                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14761                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14762                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14763                 dev_priv->display.update_primary_plane =
14764                         i9xx_update_primary_plane;
14765         }
14766
14767         /* Returns the core display clock speed */
14768         if (IS_SKYLAKE(dev))
14769                 dev_priv->display.get_display_clock_speed =
14770                         skylake_get_display_clock_speed;
14771         else if (IS_BROADWELL(dev))
14772                 dev_priv->display.get_display_clock_speed =
14773                         broadwell_get_display_clock_speed;
14774         else if (IS_HASWELL(dev))
14775                 dev_priv->display.get_display_clock_speed =
14776                         haswell_get_display_clock_speed;
14777         else if (IS_VALLEYVIEW(dev))
14778                 dev_priv->display.get_display_clock_speed =
14779                         valleyview_get_display_clock_speed;
14780         else if (IS_GEN5(dev))
14781                 dev_priv->display.get_display_clock_speed =
14782                         ilk_get_display_clock_speed;
14783         else if (IS_I945G(dev) || IS_BROADWATER(dev) ||
14784                  IS_GEN6(dev) || IS_IVYBRIDGE(dev))
14785                 dev_priv->display.get_display_clock_speed =
14786                         i945_get_display_clock_speed;
14787         else if (IS_GM45(dev))
14788                 dev_priv->display.get_display_clock_speed =
14789                         gm45_get_display_clock_speed;
14790         else if (IS_CRESTLINE(dev))
14791                 dev_priv->display.get_display_clock_speed =
14792                         i965gm_get_display_clock_speed;
14793         else if (IS_PINEVIEW(dev))
14794                 dev_priv->display.get_display_clock_speed =
14795                         pnv_get_display_clock_speed;
14796         else if (IS_G33(dev) || IS_G4X(dev))
14797                 dev_priv->display.get_display_clock_speed =
14798                         g33_get_display_clock_speed;
14799         else if (IS_I915G(dev))
14800                 dev_priv->display.get_display_clock_speed =
14801                         i915_get_display_clock_speed;
14802         else if (IS_I945GM(dev) || IS_845G(dev))
14803                 dev_priv->display.get_display_clock_speed =
14804                         i9xx_misc_get_display_clock_speed;
14805         else if (IS_PINEVIEW(dev))
14806                 dev_priv->display.get_display_clock_speed =
14807                         pnv_get_display_clock_speed;
14808         else if (IS_I915GM(dev))
14809                 dev_priv->display.get_display_clock_speed =
14810                         i915gm_get_display_clock_speed;
14811         else if (IS_I865G(dev))
14812                 dev_priv->display.get_display_clock_speed =
14813                         i865_get_display_clock_speed;
14814         else if (IS_I85X(dev))
14815                 dev_priv->display.get_display_clock_speed =
14816                         i85x_get_display_clock_speed;
14817         else { /* 830 */
14818                 WARN(!IS_I830(dev), "Unknown platform. Assuming 133 MHz CDCLK\n");
14819                 dev_priv->display.get_display_clock_speed =
14820                         i830_get_display_clock_speed;
14821         }
14822
14823         if (IS_GEN5(dev)) {
14824                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
14825         } else if (IS_GEN6(dev)) {
14826                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
14827         } else if (IS_IVYBRIDGE(dev)) {
14828                 /* FIXME: detect B0+ stepping and use auto training */
14829                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
14830         } else if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
14831                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
14832                 if (IS_BROADWELL(dev))
14833                         dev_priv->display.modeset_global_resources =
14834                                 broadwell_modeset_global_resources;
14835         } else if (IS_VALLEYVIEW(dev)) {
14836                 dev_priv->display.modeset_global_resources =
14837                         valleyview_modeset_global_resources;
14838         } else if (IS_BROXTON(dev)) {
14839                 dev_priv->display.modeset_global_resources =
14840                         broxton_modeset_global_resources;
14841         }
14842
14843         switch (INTEL_INFO(dev)->gen) {
14844         case 2:
14845                 dev_priv->display.queue_flip = intel_gen2_queue_flip;
14846                 break;
14847
14848         case 3:
14849                 dev_priv->display.queue_flip = intel_gen3_queue_flip;
14850                 break;
14851
14852         case 4:
14853         case 5:
14854                 dev_priv->display.queue_flip = intel_gen4_queue_flip;
14855                 break;
14856
14857         case 6:
14858                 dev_priv->display.queue_flip = intel_gen6_queue_flip;
14859                 break;
14860         case 7:
14861         case 8: /* FIXME(BDW): Check that the gen8 RCS flip works. */
14862                 dev_priv->display.queue_flip = intel_gen7_queue_flip;
14863                 break;
14864         case 9:
14865                 /* Drop through - unsupported since execlist only. */
14866         default:
14867                 /* Default just returns -ENODEV to indicate unsupported */
14868                 dev_priv->display.queue_flip = intel_default_queue_flip;
14869         }
14870
14871         intel_panel_init_backlight_funcs(dev);
14872
14873         mutex_init(&dev_priv->pps_mutex);
14874 }
14875
14876 /*
14877  * Some BIOSes insist on assuming the GPU's pipe A is enabled at suspend,
14878  * resume, or other times.  This quirk makes sure that's the case for
14879  * affected systems.
14880  */
14881 static void quirk_pipea_force(struct drm_device *dev)
14882 {
14883         struct drm_i915_private *dev_priv = dev->dev_private;
14884
14885         dev_priv->quirks |= QUIRK_PIPEA_FORCE;
14886         DRM_INFO("applying pipe a force quirk\n");
14887 }
14888
14889 static void quirk_pipeb_force(struct drm_device *dev)
14890 {
14891         struct drm_i915_private *dev_priv = dev->dev_private;
14892
14893         dev_priv->quirks |= QUIRK_PIPEB_FORCE;
14894         DRM_INFO("applying pipe b force quirk\n");
14895 }
14896
14897 /*
14898  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
14899  */
14900 static void quirk_ssc_force_disable(struct drm_device *dev)
14901 {
14902         struct drm_i915_private *dev_priv = dev->dev_private;
14903         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
14904         DRM_INFO("applying lvds SSC disable quirk\n");
14905 }
14906
14907 /*
14908  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
14909  * brightness value
14910  */
14911 static void quirk_invert_brightness(struct drm_device *dev)
14912 {
14913         struct drm_i915_private *dev_priv = dev->dev_private;
14914         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
14915         DRM_INFO("applying inverted panel brightness quirk\n");
14916 }
14917
14918 /* Some VBT's incorrectly indicate no backlight is present */
14919 static void quirk_backlight_present(struct drm_device *dev)
14920 {
14921         struct drm_i915_private *dev_priv = dev->dev_private;
14922         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
14923         DRM_INFO("applying backlight present quirk\n");
14924 }
14925
14926 struct intel_quirk {
14927         int device;
14928         int subsystem_vendor;
14929         int subsystem_device;
14930         void (*hook)(struct drm_device *dev);
14931 };
14932
14933 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
14934 struct intel_dmi_quirk {
14935         void (*hook)(struct drm_device *dev);
14936         const struct dmi_system_id (*dmi_id_list)[];
14937 };
14938
14939 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
14940 {
14941         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
14942         return 1;
14943 }
14944
14945 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
14946         {
14947                 .dmi_id_list = &(const struct dmi_system_id[]) {
14948                         {
14949                                 .callback = intel_dmi_reverse_brightness,
14950                                 .ident = "NCR Corporation",
14951                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
14952                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
14953                                 },
14954                         },
14955                         { }  /* terminating entry */
14956                 },
14957                 .hook = quirk_invert_brightness,
14958         },
14959 };
14960
14961 static struct intel_quirk intel_quirks[] = {
14962         /* Toshiba Protege R-205, S-209 needs pipe A force quirk */
14963         { 0x2592, 0x1179, 0x0001, quirk_pipea_force },
14964
14965         /* ThinkPad T60 needs pipe A force quirk (bug #16494) */
14966         { 0x2782, 0x17aa, 0x201a, quirk_pipea_force },
14967
14968         /* 830 needs to leave pipe A & dpll A up */
14969         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipea_force },
14970
14971         /* 830 needs to leave pipe B & dpll B up */
14972         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipeb_force },
14973
14974         /* Lenovo U160 cannot use SSC on LVDS */
14975         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
14976
14977         /* Sony Vaio Y cannot use SSC on LVDS */
14978         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
14979
14980         /* Acer Aspire 5734Z must invert backlight brightness */
14981         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
14982
14983         /* Acer/eMachines G725 */
14984         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
14985
14986         /* Acer/eMachines e725 */
14987         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
14988
14989         /* Acer/Packard Bell NCL20 */
14990         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
14991
14992         /* Acer Aspire 4736Z */
14993         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
14994
14995         /* Acer Aspire 5336 */
14996         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
14997
14998         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
14999         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
15000
15001         /* Acer C720 Chromebook (Core i3 4005U) */
15002         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
15003
15004         /* Apple Macbook 2,1 (Core 2 T7400) */
15005         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
15006
15007         /* Toshiba CB35 Chromebook (Celeron 2955U) */
15008         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
15009
15010         /* HP Chromebook 14 (Celeron 2955U) */
15011         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
15012
15013         /* Dell Chromebook 11 */
15014         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
15015 };
15016
15017 static void intel_init_quirks(struct drm_device *dev)
15018 {
15019         struct pci_dev *d = dev->pdev;
15020         int i;
15021
15022         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
15023                 struct intel_quirk *q = &intel_quirks[i];
15024
15025                 if (d->device == q->device &&
15026                     (d->subsystem_vendor == q->subsystem_vendor ||
15027                      q->subsystem_vendor == PCI_ANY_ID) &&
15028                     (d->subsystem_device == q->subsystem_device ||
15029                      q->subsystem_device == PCI_ANY_ID))
15030                         q->hook(dev);
15031         }
15032         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
15033                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
15034                         intel_dmi_quirks[i].hook(dev);
15035         }
15036 }
15037
15038 /* Disable the VGA plane that we never use */
15039 static void i915_disable_vga(struct drm_device *dev)
15040 {
15041         struct drm_i915_private *dev_priv = dev->dev_private;
15042         u8 sr1;
15043         u32 vga_reg = i915_vgacntrl_reg(dev);
15044
15045         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
15046         vga_get_uninterruptible(dev->pdev, VGA_RSRC_LEGACY_IO);
15047         outb(SR01, VGA_SR_INDEX);
15048         sr1 = inb(VGA_SR_DATA);
15049         outb(sr1 | 1<<5, VGA_SR_DATA);
15050         vga_put(dev->pdev, VGA_RSRC_LEGACY_IO);
15051         udelay(300);
15052
15053         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
15054         POSTING_READ(vga_reg);
15055 }
15056
15057 void intel_modeset_init_hw(struct drm_device *dev)
15058 {
15059         intel_update_cdclk(dev);
15060         intel_prepare_ddi(dev);
15061         intel_init_clock_gating(dev);
15062         intel_enable_gt_powersave(dev);
15063 }
15064
15065 void intel_modeset_init(struct drm_device *dev)
15066 {
15067         struct drm_i915_private *dev_priv = dev->dev_private;
15068         int sprite, ret;
15069         enum pipe pipe;
15070         struct intel_crtc *crtc;
15071
15072         drm_mode_config_init(dev);
15073
15074         dev->mode_config.min_width = 0;
15075         dev->mode_config.min_height = 0;
15076
15077         dev->mode_config.preferred_depth = 24;
15078         dev->mode_config.prefer_shadow = 1;
15079
15080         dev->mode_config.allow_fb_modifiers = true;
15081
15082         dev->mode_config.funcs = &intel_mode_funcs;
15083
15084         intel_init_quirks(dev);
15085
15086         intel_init_pm(dev);
15087
15088         if (INTEL_INFO(dev)->num_pipes == 0)
15089                 return;
15090
15091         intel_init_display(dev);
15092         intel_init_audio(dev);
15093
15094         if (IS_GEN2(dev)) {
15095                 dev->mode_config.max_width = 2048;
15096                 dev->mode_config.max_height = 2048;
15097         } else if (IS_GEN3(dev)) {
15098                 dev->mode_config.max_width = 4096;
15099                 dev->mode_config.max_height = 4096;
15100         } else {
15101                 dev->mode_config.max_width = 8192;
15102                 dev->mode_config.max_height = 8192;
15103         }
15104
15105         if (IS_845G(dev) || IS_I865G(dev)) {
15106                 dev->mode_config.cursor_width = IS_845G(dev) ? 64 : 512;
15107                 dev->mode_config.cursor_height = 1023;
15108         } else if (IS_GEN2(dev)) {
15109                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
15110                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
15111         } else {
15112                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
15113                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
15114         }
15115
15116         dev->mode_config.fb_base = dev_priv->gtt.mappable_base;
15117
15118         DRM_DEBUG_KMS("%d display pipe%s available.\n",
15119                       INTEL_INFO(dev)->num_pipes,
15120                       INTEL_INFO(dev)->num_pipes > 1 ? "s" : "");
15121
15122         for_each_pipe(dev_priv, pipe) {
15123                 intel_crtc_init(dev, pipe);
15124                 for_each_sprite(dev_priv, pipe, sprite) {
15125                         ret = intel_plane_init(dev, pipe, sprite);
15126                         if (ret)
15127                                 DRM_DEBUG_KMS("pipe %c sprite %c init failed: %d\n",
15128                                               pipe_name(pipe), sprite_name(pipe, sprite), ret);
15129                 }
15130         }
15131
15132         intel_init_dpio(dev);
15133
15134         intel_shared_dpll_init(dev);
15135
15136         /* Just disable it once at startup */
15137         i915_disable_vga(dev);
15138         intel_setup_outputs(dev);
15139
15140         /* Just in case the BIOS is doing something questionable. */
15141         intel_fbc_disable(dev);
15142
15143         drm_modeset_lock_all(dev);
15144         intel_modeset_setup_hw_state(dev, false);
15145         drm_modeset_unlock_all(dev);
15146
15147         for_each_intel_crtc(dev, crtc) {
15148                 if (!crtc->active)
15149                         continue;
15150
15151                 /*
15152                  * Note that reserving the BIOS fb up front prevents us
15153                  * from stuffing other stolen allocations like the ring
15154                  * on top.  This prevents some ugliness at boot time, and
15155                  * can even allow for smooth boot transitions if the BIOS
15156                  * fb is large enough for the active pipe configuration.
15157                  */
15158                 if (dev_priv->display.get_initial_plane_config) {
15159                         dev_priv->display.get_initial_plane_config(crtc,
15160                                                            &crtc->plane_config);
15161                         /*
15162                          * If the fb is shared between multiple heads, we'll
15163                          * just get the first one.
15164                          */
15165                         intel_find_initial_plane_obj(crtc, &crtc->plane_config);
15166                 }
15167         }
15168 }
15169
15170 static void intel_enable_pipe_a(struct drm_device *dev)
15171 {
15172         struct intel_connector *connector;
15173         struct drm_connector *crt = NULL;
15174         struct intel_load_detect_pipe load_detect_temp;
15175         struct drm_modeset_acquire_ctx *ctx = dev->mode_config.acquire_ctx;
15176
15177         /* We can't just switch on the pipe A, we need to set things up with a
15178          * proper mode and output configuration. As a gross hack, enable pipe A
15179          * by enabling the load detect pipe once. */
15180         for_each_intel_connector(dev, connector) {
15181                 if (connector->encoder->type == INTEL_OUTPUT_ANALOG) {
15182                         crt = &connector->base;
15183                         break;
15184                 }
15185         }
15186
15187         if (!crt)
15188                 return;
15189
15190         if (intel_get_load_detect_pipe(crt, NULL, &load_detect_temp, ctx))
15191                 intel_release_load_detect_pipe(crt, &load_detect_temp, ctx);
15192 }
15193
15194 static bool
15195 intel_check_plane_mapping(struct intel_crtc *crtc)
15196 {
15197         struct drm_device *dev = crtc->base.dev;
15198         struct drm_i915_private *dev_priv = dev->dev_private;
15199         u32 reg, val;
15200
15201         if (INTEL_INFO(dev)->num_pipes == 1)
15202                 return true;
15203
15204         reg = DSPCNTR(!crtc->plane);
15205         val = I915_READ(reg);
15206
15207         if ((val & DISPLAY_PLANE_ENABLE) &&
15208             (!!(val & DISPPLANE_SEL_PIPE_MASK) == crtc->pipe))
15209                 return false;
15210
15211         return true;
15212 }
15213
15214 static void intel_sanitize_crtc(struct intel_crtc *crtc)
15215 {
15216         struct drm_device *dev = crtc->base.dev;
15217         struct drm_i915_private *dev_priv = dev->dev_private;
15218         struct intel_encoder *encoder;
15219         u32 reg;
15220         bool enable;
15221
15222         /* Clear any frame start delays used for debugging left by the BIOS */
15223         reg = PIPECONF(crtc->config->cpu_transcoder);
15224         I915_WRITE(reg, I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
15225
15226         /* restore vblank interrupts to correct state */
15227         drm_crtc_vblank_reset(&crtc->base);
15228         if (crtc->active) {
15229                 update_scanline_offset(crtc);
15230                 drm_crtc_vblank_on(&crtc->base);
15231         }
15232
15233         /* We need to sanitize the plane -> pipe mapping first because this will
15234          * disable the crtc (and hence change the state) if it is wrong. Note
15235          * that gen4+ has a fixed plane -> pipe mapping.  */
15236         if (INTEL_INFO(dev)->gen < 4 && !intel_check_plane_mapping(crtc)) {
15237                 bool plane;
15238
15239                 DRM_DEBUG_KMS("[CRTC:%d] wrong plane connection detected!\n",
15240                               crtc->base.base.id);
15241
15242                 /* Pipe has the wrong plane attached and the plane is active.
15243                  * Temporarily change the plane mapping and disable everything
15244                  * ...  */
15245                 plane = crtc->plane;
15246                 to_intel_plane_state(crtc->base.primary->state)->visible = true;
15247                 crtc->plane = !plane;
15248                 intel_crtc_disable_noatomic(&crtc->base);
15249                 crtc->plane = plane;
15250         }
15251
15252         if (dev_priv->quirks & QUIRK_PIPEA_FORCE &&
15253             crtc->pipe == PIPE_A && !crtc->active) {
15254                 /* BIOS forgot to enable pipe A, this mostly happens after
15255                  * resume. Force-enable the pipe to fix this, the update_dpms
15256                  * call below we restore the pipe to the right state, but leave
15257                  * the required bits on. */
15258                 intel_enable_pipe_a(dev);
15259         }
15260
15261         /* Adjust the state of the output pipe according to whether we
15262          * have active connectors/encoders. */
15263         enable = false;
15264         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
15265                 enable |= encoder->connectors_active;
15266
15267         if (!enable)
15268                 intel_crtc_disable_noatomic(&crtc->base);
15269
15270         if (crtc->active != crtc->base.state->active) {
15271
15272                 /* This can happen either due to bugs in the get_hw_state
15273                  * functions or because of calls to intel_crtc_disable_noatomic,
15274                  * or because the pipe is force-enabled due to the
15275                  * pipe A quirk. */
15276                 DRM_DEBUG_KMS("[CRTC:%d] hw state adjusted, was %s, now %s\n",
15277                               crtc->base.base.id,
15278                               crtc->base.state->enable ? "enabled" : "disabled",
15279                               crtc->active ? "enabled" : "disabled");
15280
15281                 crtc->base.state->enable = crtc->active;
15282                 crtc->base.state->active = crtc->active;
15283                 crtc->base.enabled = crtc->active;
15284
15285                 /* Because we only establish the connector -> encoder ->
15286                  * crtc links if something is active, this means the
15287                  * crtc is now deactivated. Break the links. connector
15288                  * -> encoder links are only establish when things are
15289                  *  actually up, hence no need to break them. */
15290                 WARN_ON(crtc->active);
15291
15292                 for_each_encoder_on_crtc(dev, &crtc->base, encoder) {
15293                         WARN_ON(encoder->connectors_active);
15294                         encoder->base.crtc = NULL;
15295                 }
15296         }
15297
15298         if (crtc->active || HAS_GMCH_DISPLAY(dev)) {
15299                 /*
15300                  * We start out with underrun reporting disabled to avoid races.
15301                  * For correct bookkeeping mark this on active crtcs.
15302                  *
15303                  * Also on gmch platforms we dont have any hardware bits to
15304                  * disable the underrun reporting. Which means we need to start
15305                  * out with underrun reporting disabled also on inactive pipes,
15306                  * since otherwise we'll complain about the garbage we read when
15307                  * e.g. coming up after runtime pm.
15308                  *
15309                  * No protection against concurrent access is required - at
15310                  * worst a fifo underrun happens which also sets this to false.
15311                  */
15312                 crtc->cpu_fifo_underrun_disabled = true;
15313                 crtc->pch_fifo_underrun_disabled = true;
15314         }
15315 }
15316
15317 static void intel_sanitize_encoder(struct intel_encoder *encoder)
15318 {
15319         struct intel_connector *connector;
15320         struct drm_device *dev = encoder->base.dev;
15321
15322         /* We need to check both for a crtc link (meaning that the
15323          * encoder is active and trying to read from a pipe) and the
15324          * pipe itself being active. */
15325         bool has_active_crtc = encoder->base.crtc &&
15326                 to_intel_crtc(encoder->base.crtc)->active;
15327
15328         if (encoder->connectors_active && !has_active_crtc) {
15329                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
15330                               encoder->base.base.id,
15331                               encoder->base.name);
15332
15333                 /* Connector is active, but has no active pipe. This is
15334                  * fallout from our resume register restoring. Disable
15335                  * the encoder manually again. */
15336                 if (encoder->base.crtc) {
15337                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
15338                                       encoder->base.base.id,
15339                                       encoder->base.name);
15340                         encoder->disable(encoder);
15341                         if (encoder->post_disable)
15342                                 encoder->post_disable(encoder);
15343                 }
15344                 encoder->base.crtc = NULL;
15345                 encoder->connectors_active = false;
15346
15347                 /* Inconsistent output/port/pipe state happens presumably due to
15348                  * a bug in one of the get_hw_state functions. Or someplace else
15349                  * in our code, like the register restore mess on resume. Clamp
15350                  * things to off as a safer default. */
15351                 for_each_intel_connector(dev, connector) {
15352                         if (connector->encoder != encoder)
15353                                 continue;
15354                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15355                         connector->base.encoder = NULL;
15356                 }
15357         }
15358         /* Enabled encoders without active connectors will be fixed in
15359          * the crtc fixup. */
15360 }
15361
15362 void i915_redisable_vga_power_on(struct drm_device *dev)
15363 {
15364         struct drm_i915_private *dev_priv = dev->dev_private;
15365         u32 vga_reg = i915_vgacntrl_reg(dev);
15366
15367         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
15368                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
15369                 i915_disable_vga(dev);
15370         }
15371 }
15372
15373 void i915_redisable_vga(struct drm_device *dev)
15374 {
15375         struct drm_i915_private *dev_priv = dev->dev_private;
15376
15377         /* This function can be called both from intel_modeset_setup_hw_state or
15378          * at a very early point in our resume sequence, where the power well
15379          * structures are not yet restored. Since this function is at a very
15380          * paranoid "someone might have enabled VGA while we were not looking"
15381          * level, just check if the power well is enabled instead of trying to
15382          * follow the "don't touch the power well if we don't need it" policy
15383          * the rest of the driver uses. */
15384         if (!intel_display_power_is_enabled(dev_priv, POWER_DOMAIN_VGA))
15385                 return;
15386
15387         i915_redisable_vga_power_on(dev);
15388 }
15389
15390 static bool primary_get_hw_state(struct intel_crtc *crtc)
15391 {
15392         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
15393
15394         if (!crtc->active)
15395                 return false;
15396
15397         return I915_READ(DSPCNTR(crtc->plane)) & DISPLAY_PLANE_ENABLE;
15398 }
15399
15400 static void intel_modeset_readout_hw_state(struct drm_device *dev)
15401 {
15402         struct drm_i915_private *dev_priv = dev->dev_private;
15403         enum pipe pipe;
15404         struct intel_crtc *crtc;
15405         struct intel_encoder *encoder;
15406         struct intel_connector *connector;
15407         int i;
15408
15409         for_each_intel_crtc(dev, crtc) {
15410                 struct drm_plane *primary = crtc->base.primary;
15411                 struct intel_plane_state *plane_state;
15412
15413                 memset(crtc->config, 0, sizeof(*crtc->config));
15414                 crtc->config->base.crtc = &crtc->base;
15415
15416                 crtc->config->quirks |= PIPE_CONFIG_QUIRK_INHERITED_MODE;
15417
15418                 crtc->active = dev_priv->display.get_pipe_config(crtc,
15419                                                                  crtc->config);
15420
15421                 crtc->base.state->enable = crtc->active;
15422                 crtc->base.state->active = crtc->active;
15423                 crtc->base.enabled = crtc->active;
15424                 crtc->base.hwmode = crtc->config->base.adjusted_mode;
15425
15426                 plane_state = to_intel_plane_state(primary->state);
15427                 plane_state->visible = primary_get_hw_state(crtc);
15428
15429                 DRM_DEBUG_KMS("[CRTC:%d] hw state readout: %s\n",
15430                               crtc->base.base.id,
15431                               crtc->active ? "enabled" : "disabled");
15432         }
15433
15434         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15435                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15436
15437                 pll->on = pll->get_hw_state(dev_priv, pll,
15438                                             &pll->config.hw_state);
15439                 pll->active = 0;
15440                 pll->config.crtc_mask = 0;
15441                 for_each_intel_crtc(dev, crtc) {
15442                         if (crtc->active && intel_crtc_to_shared_dpll(crtc) == pll) {
15443                                 pll->active++;
15444                                 pll->config.crtc_mask |= 1 << crtc->pipe;
15445                         }
15446                 }
15447
15448                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15449                               pll->name, pll->config.crtc_mask, pll->on);
15450
15451                 if (pll->config.crtc_mask)
15452                         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
15453         }
15454
15455         for_each_intel_encoder(dev, encoder) {
15456                 pipe = 0;
15457
15458                 if (encoder->get_hw_state(encoder, &pipe)) {
15459                         crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
15460                         encoder->base.crtc = &crtc->base;
15461                         encoder->get_config(encoder, crtc->config);
15462                 } else {
15463                         encoder->base.crtc = NULL;
15464                 }
15465
15466                 encoder->connectors_active = false;
15467                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
15468                               encoder->base.base.id,
15469                               encoder->base.name,
15470                               encoder->base.crtc ? "enabled" : "disabled",
15471                               pipe_name(pipe));
15472         }
15473
15474         for_each_intel_connector(dev, connector) {
15475                 if (connector->get_hw_state(connector)) {
15476                         connector->base.dpms = DRM_MODE_DPMS_ON;
15477                         connector->encoder->connectors_active = true;
15478                         connector->base.encoder = &connector->encoder->base;
15479                 } else {
15480                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15481                         connector->base.encoder = NULL;
15482                 }
15483                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
15484                               connector->base.base.id,
15485                               connector->base.name,
15486                               connector->base.encoder ? "enabled" : "disabled");
15487         }
15488 }
15489
15490 /* Scan out the current hw modeset state, sanitizes it and maps it into the drm
15491  * and i915 state tracking structures. */
15492 void intel_modeset_setup_hw_state(struct drm_device *dev,
15493                                   bool force_restore)
15494 {
15495         struct drm_i915_private *dev_priv = dev->dev_private;
15496         enum pipe pipe;
15497         struct intel_crtc *crtc;
15498         struct intel_encoder *encoder;
15499         int i;
15500
15501         intel_modeset_readout_hw_state(dev);
15502
15503         /*
15504          * Now that we have the config, copy it to each CRTC struct
15505          * Note that this could go away if we move to using crtc_config
15506          * checking everywhere.
15507          */
15508         for_each_intel_crtc(dev, crtc) {
15509                 if (crtc->active && i915.fastboot) {
15510                         intel_mode_from_pipe_config(&crtc->base.mode,
15511                                                     crtc->config);
15512                         DRM_DEBUG_KMS("[CRTC:%d] found active mode: ",
15513                                       crtc->base.base.id);
15514                         drm_mode_debug_printmodeline(&crtc->base.mode);
15515                 }
15516         }
15517
15518         /* HW state is read out, now we need to sanitize this mess. */
15519         for_each_intel_encoder(dev, encoder) {
15520                 intel_sanitize_encoder(encoder);
15521         }
15522
15523         for_each_pipe(dev_priv, pipe) {
15524                 crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
15525                 intel_sanitize_crtc(crtc);
15526                 intel_dump_pipe_config(crtc, crtc->config,
15527                                        "[setup_hw_state]");
15528         }
15529
15530         intel_modeset_update_connector_atomic_state(dev);
15531
15532         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15533                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15534
15535                 if (!pll->on || pll->active)
15536                         continue;
15537
15538                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
15539
15540                 pll->disable(dev_priv, pll);
15541                 pll->on = false;
15542         }
15543
15544         if (IS_GEN9(dev))
15545                 skl_wm_get_hw_state(dev);
15546         else if (HAS_PCH_SPLIT(dev))
15547                 ilk_wm_get_hw_state(dev);
15548
15549         if (force_restore) {
15550                 i915_redisable_vga(dev);
15551
15552                 /*
15553                  * We need to use raw interfaces for restoring state to avoid
15554                  * checking (bogus) intermediate states.
15555                  */
15556                 for_each_pipe(dev_priv, pipe) {
15557                         struct drm_crtc *crtc =
15558                                 dev_priv->pipe_to_crtc_mapping[pipe];
15559
15560                         intel_crtc_restore_mode(crtc);
15561                 }
15562         } else {
15563                 intel_modeset_update_staged_output_state(dev);
15564         }
15565
15566         intel_modeset_check_state(dev);
15567 }
15568
15569 void intel_modeset_gem_init(struct drm_device *dev)
15570 {
15571         struct drm_i915_private *dev_priv = dev->dev_private;
15572         struct drm_crtc *c;
15573         struct drm_i915_gem_object *obj;
15574         int ret;
15575
15576         mutex_lock(&dev->struct_mutex);
15577         intel_init_gt_powersave(dev);
15578         mutex_unlock(&dev->struct_mutex);
15579
15580         /*
15581          * There may be no VBT; and if the BIOS enabled SSC we can
15582          * just keep using it to avoid unnecessary flicker.  Whereas if the
15583          * BIOS isn't using it, don't assume it will work even if the VBT
15584          * indicates as much.
15585          */
15586         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
15587                 dev_priv->vbt.lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
15588                                                 DREF_SSC1_ENABLE);
15589
15590         intel_modeset_init_hw(dev);
15591
15592         intel_setup_overlay(dev);
15593
15594         /*
15595          * Make sure any fbs we allocated at startup are properly
15596          * pinned & fenced.  When we do the allocation it's too early
15597          * for this.
15598          */
15599         for_each_crtc(dev, c) {
15600                 obj = intel_fb_obj(c->primary->fb);
15601                 if (obj == NULL)
15602                         continue;
15603
15604                 mutex_lock(&dev->struct_mutex);
15605                 ret = intel_pin_and_fence_fb_obj(c->primary,
15606                                                  c->primary->fb,
15607                                                  c->primary->state,
15608                                                  NULL);
15609                 mutex_unlock(&dev->struct_mutex);
15610                 if (ret) {
15611                         DRM_ERROR("failed to pin boot fb on pipe %d\n",
15612                                   to_intel_crtc(c)->pipe);
15613                         drm_framebuffer_unreference(c->primary->fb);
15614                         c->primary->fb = NULL;
15615                         c->primary->crtc = c->primary->state->crtc = NULL;
15616                         update_state_fb(c->primary);
15617                         c->state->plane_mask &= ~(1 << drm_plane_index(c->primary));
15618                 }
15619         }
15620
15621         intel_backlight_register(dev);
15622 }
15623
15624 void intel_connector_unregister(struct intel_connector *intel_connector)
15625 {
15626         struct drm_connector *connector = &intel_connector->base;
15627
15628         intel_panel_destroy_backlight(connector);
15629         drm_connector_unregister(connector);
15630 }
15631
15632 void intel_modeset_cleanup(struct drm_device *dev)
15633 {
15634         struct drm_i915_private *dev_priv = dev->dev_private;
15635         struct drm_connector *connector;
15636
15637         intel_disable_gt_powersave(dev);
15638
15639         intel_backlight_unregister(dev);
15640
15641         /*
15642          * Interrupts and polling as the first thing to avoid creating havoc.
15643          * Too much stuff here (turning of connectors, ...) would
15644          * experience fancy races otherwise.
15645          */
15646         intel_irq_uninstall(dev_priv);
15647
15648         /*
15649          * Due to the hpd irq storm handling the hotplug work can re-arm the
15650          * poll handlers. Hence disable polling after hpd handling is shut down.
15651          */
15652         drm_kms_helper_poll_fini(dev);
15653
15654         mutex_lock(&dev->struct_mutex);
15655
15656         intel_unregister_dsm_handler();
15657
15658         intel_fbc_disable(dev);
15659
15660         mutex_unlock(&dev->struct_mutex);
15661
15662         /* flush any delayed tasks or pending work */
15663         flush_scheduled_work();
15664
15665         /* destroy the backlight and sysfs files before encoders/connectors */
15666         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
15667                 struct intel_connector *intel_connector;
15668
15669                 intel_connector = to_intel_connector(connector);
15670                 intel_connector->unregister(intel_connector);
15671         }
15672
15673         drm_mode_config_cleanup(dev);
15674
15675         intel_cleanup_overlay(dev);
15676
15677         mutex_lock(&dev->struct_mutex);
15678         intel_cleanup_gt_powersave(dev);
15679         mutex_unlock(&dev->struct_mutex);
15680 }
15681
15682 /*
15683  * Return which encoder is currently attached for connector.
15684  */
15685 struct drm_encoder *intel_best_encoder(struct drm_connector *connector)
15686 {
15687         return &intel_attached_encoder(connector)->base;
15688 }
15689
15690 void intel_connector_attach_encoder(struct intel_connector *connector,
15691                                     struct intel_encoder *encoder)
15692 {
15693         connector->encoder = encoder;
15694         drm_mode_connector_attach_encoder(&connector->base,
15695                                           &encoder->base);
15696 }
15697
15698 /*
15699  * set vga decode state - true == enable VGA decode
15700  */
15701 int intel_modeset_vga_set_state(struct drm_device *dev, bool state)
15702 {
15703         struct drm_i915_private *dev_priv = dev->dev_private;
15704         unsigned reg = INTEL_INFO(dev)->gen >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
15705         u16 gmch_ctrl;
15706
15707         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
15708                 DRM_ERROR("failed to read control word\n");
15709                 return -EIO;
15710         }
15711
15712         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
15713                 return 0;
15714
15715         if (state)
15716                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
15717         else
15718                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
15719
15720         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
15721                 DRM_ERROR("failed to write control word\n");
15722                 return -EIO;
15723         }
15724
15725         return 0;
15726 }
15727
15728 struct intel_display_error_state {
15729
15730         u32 power_well_driver;
15731
15732         int num_transcoders;
15733
15734         struct intel_cursor_error_state {
15735                 u32 control;
15736                 u32 position;
15737                 u32 base;
15738                 u32 size;
15739         } cursor[I915_MAX_PIPES];
15740
15741         struct intel_pipe_error_state {
15742                 bool power_domain_on;
15743                 u32 source;
15744                 u32 stat;
15745         } pipe[I915_MAX_PIPES];
15746
15747         struct intel_plane_error_state {
15748                 u32 control;
15749                 u32 stride;
15750                 u32 size;
15751                 u32 pos;
15752                 u32 addr;
15753                 u32 surface;
15754                 u32 tile_offset;
15755         } plane[I915_MAX_PIPES];
15756
15757         struct intel_transcoder_error_state {
15758                 bool power_domain_on;
15759                 enum transcoder cpu_transcoder;
15760
15761                 u32 conf;
15762
15763                 u32 htotal;
15764                 u32 hblank;
15765                 u32 hsync;
15766                 u32 vtotal;
15767                 u32 vblank;
15768                 u32 vsync;
15769         } transcoder[4];
15770 };
15771
15772 struct intel_display_error_state *
15773 intel_display_capture_error_state(struct drm_device *dev)
15774 {
15775         struct drm_i915_private *dev_priv = dev->dev_private;
15776         struct intel_display_error_state *error;
15777         int transcoders[] = {
15778                 TRANSCODER_A,
15779                 TRANSCODER_B,
15780                 TRANSCODER_C,
15781                 TRANSCODER_EDP,
15782         };
15783         int i;
15784
15785         if (INTEL_INFO(dev)->num_pipes == 0)
15786                 return NULL;
15787
15788         error = kzalloc(sizeof(*error), GFP_ATOMIC);
15789         if (error == NULL)
15790                 return NULL;
15791
15792         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
15793                 error->power_well_driver = I915_READ(HSW_PWR_WELL_DRIVER);
15794
15795         for_each_pipe(dev_priv, i) {
15796                 error->pipe[i].power_domain_on =
15797                         __intel_display_power_is_enabled(dev_priv,
15798                                                          POWER_DOMAIN_PIPE(i));
15799                 if (!error->pipe[i].power_domain_on)
15800                         continue;
15801
15802                 error->cursor[i].control = I915_READ(CURCNTR(i));
15803                 error->cursor[i].position = I915_READ(CURPOS(i));
15804                 error->cursor[i].base = I915_READ(CURBASE(i));
15805
15806                 error->plane[i].control = I915_READ(DSPCNTR(i));
15807                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
15808                 if (INTEL_INFO(dev)->gen <= 3) {
15809                         error->plane[i].size = I915_READ(DSPSIZE(i));
15810                         error->plane[i].pos = I915_READ(DSPPOS(i));
15811                 }
15812                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
15813                         error->plane[i].addr = I915_READ(DSPADDR(i));
15814                 if (INTEL_INFO(dev)->gen >= 4) {
15815                         error->plane[i].surface = I915_READ(DSPSURF(i));
15816                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
15817                 }
15818
15819                 error->pipe[i].source = I915_READ(PIPESRC(i));
15820
15821                 if (HAS_GMCH_DISPLAY(dev))
15822                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
15823         }
15824
15825         error->num_transcoders = INTEL_INFO(dev)->num_pipes;
15826         if (HAS_DDI(dev_priv->dev))
15827                 error->num_transcoders++; /* Account for eDP. */
15828
15829         for (i = 0; i < error->num_transcoders; i++) {
15830                 enum transcoder cpu_transcoder = transcoders[i];
15831
15832                 error->transcoder[i].power_domain_on =
15833                         __intel_display_power_is_enabled(dev_priv,
15834                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
15835                 if (!error->transcoder[i].power_domain_on)
15836                         continue;
15837
15838                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
15839
15840                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
15841                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
15842                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
15843                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
15844                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
15845                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
15846                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
15847         }
15848
15849         return error;
15850 }
15851
15852 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
15853
15854 void
15855 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
15856                                 struct drm_device *dev,
15857                                 struct intel_display_error_state *error)
15858 {
15859         struct drm_i915_private *dev_priv = dev->dev_private;
15860         int i;
15861
15862         if (!error)
15863                 return;
15864
15865         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev)->num_pipes);
15866         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
15867                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
15868                            error->power_well_driver);
15869         for_each_pipe(dev_priv, i) {
15870                 err_printf(m, "Pipe [%d]:\n", i);
15871                 err_printf(m, "  Power: %s\n",
15872                            error->pipe[i].power_domain_on ? "on" : "off");
15873                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
15874                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
15875
15876                 err_printf(m, "Plane [%d]:\n", i);
15877                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
15878                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
15879                 if (INTEL_INFO(dev)->gen <= 3) {
15880                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
15881                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
15882                 }
15883                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
15884                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
15885                 if (INTEL_INFO(dev)->gen >= 4) {
15886                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
15887                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
15888                 }
15889
15890                 err_printf(m, "Cursor [%d]:\n", i);
15891                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
15892                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
15893                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
15894         }
15895
15896         for (i = 0; i < error->num_transcoders; i++) {
15897                 err_printf(m, "CPU transcoder: %c\n",
15898                            transcoder_name(error->transcoder[i].cpu_transcoder));
15899                 err_printf(m, "  Power: %s\n",
15900                            error->transcoder[i].power_domain_on ? "on" : "off");
15901                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
15902                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
15903                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
15904                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
15905                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
15906                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
15907                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
15908         }
15909 }
15910
15911 void intel_modeset_preclose(struct drm_device *dev, struct drm_file *file)
15912 {
15913         struct intel_crtc *crtc;
15914
15915         for_each_intel_crtc(dev, crtc) {
15916                 struct intel_unpin_work *work;
15917
15918                 spin_lock_irq(&dev->event_lock);
15919
15920                 work = crtc->unpin_work;
15921
15922                 if (work && work->event &&
15923                     work->event->base.file_priv == file) {
15924                         kfree(work->event);
15925                         work->event = NULL;
15926                 }
15927
15928                 spin_unlock_irq(&dev->event_lock);
15929         }
15930 }