3c2c76b388b45c8af09f248359d6537d4b72c3e1
[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_framebuffer_init(struct drm_device *dev,
90                                   struct intel_framebuffer *ifb,
91                                   struct drm_mode_fb_cmd2 *mode_cmd,
92                                   struct drm_i915_gem_object *obj);
93 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc);
94 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc);
95 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
96                                          struct intel_link_m_n *m_n,
97                                          struct intel_link_m_n *m2_n2);
98 static void ironlake_set_pipeconf(struct drm_crtc *crtc);
99 static void haswell_set_pipeconf(struct drm_crtc *crtc);
100 static void intel_set_pipe_csc(struct drm_crtc *crtc);
101 static void vlv_prepare_pll(struct intel_crtc *crtc,
102                             const struct intel_crtc_state *pipe_config);
103 static void chv_prepare_pll(struct intel_crtc *crtc,
104                             const struct intel_crtc_state *pipe_config);
105 static void intel_begin_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
106 static void intel_finish_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
107 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
108         struct intel_crtc_state *crtc_state);
109 static int i9xx_get_refclk(const struct intel_crtc_state *crtc_state,
110                            int num_connectors);
111 static void intel_modeset_setup_hw_state(struct drm_device *dev);
112
113 typedef struct {
114         int     min, max;
115 } intel_range_t;
116
117 typedef struct {
118         int     dot_limit;
119         int     p2_slow, p2_fast;
120 } intel_p2_t;
121
122 typedef struct intel_limit intel_limit_t;
123 struct intel_limit {
124         intel_range_t   dot, vco, n, m, m1, m2, p, p1;
125         intel_p2_t          p2;
126 };
127
128 int
129 intel_pch_rawclk(struct drm_device *dev)
130 {
131         struct drm_i915_private *dev_priv = dev->dev_private;
132
133         WARN_ON(!HAS_PCH_SPLIT(dev));
134
135         return I915_READ(PCH_RAWCLK_FREQ) & RAWCLK_FREQ_MASK;
136 }
137
138 static inline u32 /* units of 100MHz */
139 intel_fdi_link_freq(struct drm_device *dev)
140 {
141         if (IS_GEN5(dev)) {
142                 struct drm_i915_private *dev_priv = dev->dev_private;
143                 return (I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK) + 2;
144         } else
145                 return 27;
146 }
147
148 static const intel_limit_t intel_limits_i8xx_dac = {
149         .dot = { .min = 25000, .max = 350000 },
150         .vco = { .min = 908000, .max = 1512000 },
151         .n = { .min = 2, .max = 16 },
152         .m = { .min = 96, .max = 140 },
153         .m1 = { .min = 18, .max = 26 },
154         .m2 = { .min = 6, .max = 16 },
155         .p = { .min = 4, .max = 128 },
156         .p1 = { .min = 2, .max = 33 },
157         .p2 = { .dot_limit = 165000,
158                 .p2_slow = 4, .p2_fast = 2 },
159 };
160
161 static const intel_limit_t intel_limits_i8xx_dvo = {
162         .dot = { .min = 25000, .max = 350000 },
163         .vco = { .min = 908000, .max = 1512000 },
164         .n = { .min = 2, .max = 16 },
165         .m = { .min = 96, .max = 140 },
166         .m1 = { .min = 18, .max = 26 },
167         .m2 = { .min = 6, .max = 16 },
168         .p = { .min = 4, .max = 128 },
169         .p1 = { .min = 2, .max = 33 },
170         .p2 = { .dot_limit = 165000,
171                 .p2_slow = 4, .p2_fast = 4 },
172 };
173
174 static const intel_limit_t intel_limits_i8xx_lvds = {
175         .dot = { .min = 25000, .max = 350000 },
176         .vco = { .min = 908000, .max = 1512000 },
177         .n = { .min = 2, .max = 16 },
178         .m = { .min = 96, .max = 140 },
179         .m1 = { .min = 18, .max = 26 },
180         .m2 = { .min = 6, .max = 16 },
181         .p = { .min = 4, .max = 128 },
182         .p1 = { .min = 1, .max = 6 },
183         .p2 = { .dot_limit = 165000,
184                 .p2_slow = 14, .p2_fast = 7 },
185 };
186
187 static const intel_limit_t intel_limits_i9xx_sdvo = {
188         .dot = { .min = 20000, .max = 400000 },
189         .vco = { .min = 1400000, .max = 2800000 },
190         .n = { .min = 1, .max = 6 },
191         .m = { .min = 70, .max = 120 },
192         .m1 = { .min = 8, .max = 18 },
193         .m2 = { .min = 3, .max = 7 },
194         .p = { .min = 5, .max = 80 },
195         .p1 = { .min = 1, .max = 8 },
196         .p2 = { .dot_limit = 200000,
197                 .p2_slow = 10, .p2_fast = 5 },
198 };
199
200 static const intel_limit_t intel_limits_i9xx_lvds = {
201         .dot = { .min = 20000, .max = 400000 },
202         .vco = { .min = 1400000, .max = 2800000 },
203         .n = { .min = 1, .max = 6 },
204         .m = { .min = 70, .max = 120 },
205         .m1 = { .min = 8, .max = 18 },
206         .m2 = { .min = 3, .max = 7 },
207         .p = { .min = 7, .max = 98 },
208         .p1 = { .min = 1, .max = 8 },
209         .p2 = { .dot_limit = 112000,
210                 .p2_slow = 14, .p2_fast = 7 },
211 };
212
213
214 static const intel_limit_t intel_limits_g4x_sdvo = {
215         .dot = { .min = 25000, .max = 270000 },
216         .vco = { .min = 1750000, .max = 3500000},
217         .n = { .min = 1, .max = 4 },
218         .m = { .min = 104, .max = 138 },
219         .m1 = { .min = 17, .max = 23 },
220         .m2 = { .min = 5, .max = 11 },
221         .p = { .min = 10, .max = 30 },
222         .p1 = { .min = 1, .max = 3},
223         .p2 = { .dot_limit = 270000,
224                 .p2_slow = 10,
225                 .p2_fast = 10
226         },
227 };
228
229 static const intel_limit_t intel_limits_g4x_hdmi = {
230         .dot = { .min = 22000, .max = 400000 },
231         .vco = { .min = 1750000, .max = 3500000},
232         .n = { .min = 1, .max = 4 },
233         .m = { .min = 104, .max = 138 },
234         .m1 = { .min = 16, .max = 23 },
235         .m2 = { .min = 5, .max = 11 },
236         .p = { .min = 5, .max = 80 },
237         .p1 = { .min = 1, .max = 8},
238         .p2 = { .dot_limit = 165000,
239                 .p2_slow = 10, .p2_fast = 5 },
240 };
241
242 static const intel_limit_t intel_limits_g4x_single_channel_lvds = {
243         .dot = { .min = 20000, .max = 115000 },
244         .vco = { .min = 1750000, .max = 3500000 },
245         .n = { .min = 1, .max = 3 },
246         .m = { .min = 104, .max = 138 },
247         .m1 = { .min = 17, .max = 23 },
248         .m2 = { .min = 5, .max = 11 },
249         .p = { .min = 28, .max = 112 },
250         .p1 = { .min = 2, .max = 8 },
251         .p2 = { .dot_limit = 0,
252                 .p2_slow = 14, .p2_fast = 14
253         },
254 };
255
256 static const intel_limit_t intel_limits_g4x_dual_channel_lvds = {
257         .dot = { .min = 80000, .max = 224000 },
258         .vco = { .min = 1750000, .max = 3500000 },
259         .n = { .min = 1, .max = 3 },
260         .m = { .min = 104, .max = 138 },
261         .m1 = { .min = 17, .max = 23 },
262         .m2 = { .min = 5, .max = 11 },
263         .p = { .min = 14, .max = 42 },
264         .p1 = { .min = 2, .max = 6 },
265         .p2 = { .dot_limit = 0,
266                 .p2_slow = 7, .p2_fast = 7
267         },
268 };
269
270 static const intel_limit_t intel_limits_pineview_sdvo = {
271         .dot = { .min = 20000, .max = 400000},
272         .vco = { .min = 1700000, .max = 3500000 },
273         /* Pineview's Ncounter is a ring counter */
274         .n = { .min = 3, .max = 6 },
275         .m = { .min = 2, .max = 256 },
276         /* Pineview only has one combined m divider, which we treat as m2. */
277         .m1 = { .min = 0, .max = 0 },
278         .m2 = { .min = 0, .max = 254 },
279         .p = { .min = 5, .max = 80 },
280         .p1 = { .min = 1, .max = 8 },
281         .p2 = { .dot_limit = 200000,
282                 .p2_slow = 10, .p2_fast = 5 },
283 };
284
285 static const intel_limit_t intel_limits_pineview_lvds = {
286         .dot = { .min = 20000, .max = 400000 },
287         .vco = { .min = 1700000, .max = 3500000 },
288         .n = { .min = 3, .max = 6 },
289         .m = { .min = 2, .max = 256 },
290         .m1 = { .min = 0, .max = 0 },
291         .m2 = { .min = 0, .max = 254 },
292         .p = { .min = 7, .max = 112 },
293         .p1 = { .min = 1, .max = 8 },
294         .p2 = { .dot_limit = 112000,
295                 .p2_slow = 14, .p2_fast = 14 },
296 };
297
298 /* Ironlake / Sandybridge
299  *
300  * We calculate clock using (register_value + 2) for N/M1/M2, so here
301  * the range value for them is (actual_value - 2).
302  */
303 static const intel_limit_t intel_limits_ironlake_dac = {
304         .dot = { .min = 25000, .max = 350000 },
305         .vco = { .min = 1760000, .max = 3510000 },
306         .n = { .min = 1, .max = 5 },
307         .m = { .min = 79, .max = 127 },
308         .m1 = { .min = 12, .max = 22 },
309         .m2 = { .min = 5, .max = 9 },
310         .p = { .min = 5, .max = 80 },
311         .p1 = { .min = 1, .max = 8 },
312         .p2 = { .dot_limit = 225000,
313                 .p2_slow = 10, .p2_fast = 5 },
314 };
315
316 static const intel_limit_t intel_limits_ironlake_single_lvds = {
317         .dot = { .min = 25000, .max = 350000 },
318         .vco = { .min = 1760000, .max = 3510000 },
319         .n = { .min = 1, .max = 3 },
320         .m = { .min = 79, .max = 118 },
321         .m1 = { .min = 12, .max = 22 },
322         .m2 = { .min = 5, .max = 9 },
323         .p = { .min = 28, .max = 112 },
324         .p1 = { .min = 2, .max = 8 },
325         .p2 = { .dot_limit = 225000,
326                 .p2_slow = 14, .p2_fast = 14 },
327 };
328
329 static const intel_limit_t intel_limits_ironlake_dual_lvds = {
330         .dot = { .min = 25000, .max = 350000 },
331         .vco = { .min = 1760000, .max = 3510000 },
332         .n = { .min = 1, .max = 3 },
333         .m = { .min = 79, .max = 127 },
334         .m1 = { .min = 12, .max = 22 },
335         .m2 = { .min = 5, .max = 9 },
336         .p = { .min = 14, .max = 56 },
337         .p1 = { .min = 2, .max = 8 },
338         .p2 = { .dot_limit = 225000,
339                 .p2_slow = 7, .p2_fast = 7 },
340 };
341
342 /* LVDS 100mhz refclk limits. */
343 static const intel_limit_t intel_limits_ironlake_single_lvds_100m = {
344         .dot = { .min = 25000, .max = 350000 },
345         .vco = { .min = 1760000, .max = 3510000 },
346         .n = { .min = 1, .max = 2 },
347         .m = { .min = 79, .max = 126 },
348         .m1 = { .min = 12, .max = 22 },
349         .m2 = { .min = 5, .max = 9 },
350         .p = { .min = 28, .max = 112 },
351         .p1 = { .min = 2, .max = 8 },
352         .p2 = { .dot_limit = 225000,
353                 .p2_slow = 14, .p2_fast = 14 },
354 };
355
356 static const intel_limit_t intel_limits_ironlake_dual_lvds_100m = {
357         .dot = { .min = 25000, .max = 350000 },
358         .vco = { .min = 1760000, .max = 3510000 },
359         .n = { .min = 1, .max = 3 },
360         .m = { .min = 79, .max = 126 },
361         .m1 = { .min = 12, .max = 22 },
362         .m2 = { .min = 5, .max = 9 },
363         .p = { .min = 14, .max = 42 },
364         .p1 = { .min = 2, .max = 6 },
365         .p2 = { .dot_limit = 225000,
366                 .p2_slow = 7, .p2_fast = 7 },
367 };
368
369 static const intel_limit_t intel_limits_vlv = {
370          /*
371           * These are the data rate limits (measured in fast clocks)
372           * since those are the strictest limits we have. The fast
373           * clock and actual rate limits are more relaxed, so checking
374           * them would make no difference.
375           */
376         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
377         .vco = { .min = 4000000, .max = 6000000 },
378         .n = { .min = 1, .max = 7 },
379         .m1 = { .min = 2, .max = 3 },
380         .m2 = { .min = 11, .max = 156 },
381         .p1 = { .min = 2, .max = 3 },
382         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
383 };
384
385 static const intel_limit_t intel_limits_chv = {
386         /*
387          * These are the data rate limits (measured in fast clocks)
388          * since those are the strictest limits we have.  The fast
389          * clock and actual rate limits are more relaxed, so checking
390          * them would make no difference.
391          */
392         .dot = { .min = 25000 * 5, .max = 540000 * 5},
393         .vco = { .min = 4800000, .max = 6480000 },
394         .n = { .min = 1, .max = 1 },
395         .m1 = { .min = 2, .max = 2 },
396         .m2 = { .min = 24 << 22, .max = 175 << 22 },
397         .p1 = { .min = 2, .max = 4 },
398         .p2 = { .p2_slow = 1, .p2_fast = 14 },
399 };
400
401 static const intel_limit_t intel_limits_bxt = {
402         /* FIXME: find real dot limits */
403         .dot = { .min = 0, .max = INT_MAX },
404         .vco = { .min = 4800000, .max = 6700000 },
405         .n = { .min = 1, .max = 1 },
406         .m1 = { .min = 2, .max = 2 },
407         /* FIXME: find real m2 limits */
408         .m2 = { .min = 2 << 22, .max = 255 << 22 },
409         .p1 = { .min = 2, .max = 4 },
410         .p2 = { .p2_slow = 1, .p2_fast = 20 },
411 };
412
413 static bool
414 needs_modeset(struct drm_crtc_state *state)
415 {
416         return drm_atomic_crtc_needs_modeset(state);
417 }
418
419 /**
420  * Returns whether any output on the specified pipe is of the specified type
421  */
422 bool intel_pipe_has_type(struct intel_crtc *crtc, enum intel_output_type type)
423 {
424         struct drm_device *dev = crtc->base.dev;
425         struct intel_encoder *encoder;
426
427         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
428                 if (encoder->type == type)
429                         return true;
430
431         return false;
432 }
433
434 /**
435  * Returns whether any output on the specified pipe will have the specified
436  * type after a staged modeset is complete, i.e., the same as
437  * intel_pipe_has_type() but looking at encoder->new_crtc instead of
438  * encoder->crtc.
439  */
440 static bool intel_pipe_will_have_type(const struct intel_crtc_state *crtc_state,
441                                       int type)
442 {
443         struct drm_atomic_state *state = crtc_state->base.state;
444         struct drm_connector *connector;
445         struct drm_connector_state *connector_state;
446         struct intel_encoder *encoder;
447         int i, num_connectors = 0;
448
449         for_each_connector_in_state(state, connector, connector_state, i) {
450                 if (connector_state->crtc != crtc_state->base.crtc)
451                         continue;
452
453                 num_connectors++;
454
455                 encoder = to_intel_encoder(connector_state->best_encoder);
456                 if (encoder->type == type)
457                         return true;
458         }
459
460         WARN_ON(num_connectors == 0);
461
462         return false;
463 }
464
465 static const intel_limit_t *
466 intel_ironlake_limit(struct intel_crtc_state *crtc_state, int refclk)
467 {
468         struct drm_device *dev = crtc_state->base.crtc->dev;
469         const intel_limit_t *limit;
470
471         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
472                 if (intel_is_dual_link_lvds(dev)) {
473                         if (refclk == 100000)
474                                 limit = &intel_limits_ironlake_dual_lvds_100m;
475                         else
476                                 limit = &intel_limits_ironlake_dual_lvds;
477                 } else {
478                         if (refclk == 100000)
479                                 limit = &intel_limits_ironlake_single_lvds_100m;
480                         else
481                                 limit = &intel_limits_ironlake_single_lvds;
482                 }
483         } else
484                 limit = &intel_limits_ironlake_dac;
485
486         return limit;
487 }
488
489 static const intel_limit_t *
490 intel_g4x_limit(struct intel_crtc_state *crtc_state)
491 {
492         struct drm_device *dev = crtc_state->base.crtc->dev;
493         const intel_limit_t *limit;
494
495         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
496                 if (intel_is_dual_link_lvds(dev))
497                         limit = &intel_limits_g4x_dual_channel_lvds;
498                 else
499                         limit = &intel_limits_g4x_single_channel_lvds;
500         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_HDMI) ||
501                    intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
502                 limit = &intel_limits_g4x_hdmi;
503         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_SDVO)) {
504                 limit = &intel_limits_g4x_sdvo;
505         } else /* The option is for other outputs */
506                 limit = &intel_limits_i9xx_sdvo;
507
508         return limit;
509 }
510
511 static const intel_limit_t *
512 intel_limit(struct intel_crtc_state *crtc_state, int refclk)
513 {
514         struct drm_device *dev = crtc_state->base.crtc->dev;
515         const intel_limit_t *limit;
516
517         if (IS_BROXTON(dev))
518                 limit = &intel_limits_bxt;
519         else if (HAS_PCH_SPLIT(dev))
520                 limit = intel_ironlake_limit(crtc_state, refclk);
521         else if (IS_G4X(dev)) {
522                 limit = intel_g4x_limit(crtc_state);
523         } else if (IS_PINEVIEW(dev)) {
524                 if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
525                         limit = &intel_limits_pineview_lvds;
526                 else
527                         limit = &intel_limits_pineview_sdvo;
528         } else if (IS_CHERRYVIEW(dev)) {
529                 limit = &intel_limits_chv;
530         } else if (IS_VALLEYVIEW(dev)) {
531                 limit = &intel_limits_vlv;
532         } else if (!IS_GEN2(dev)) {
533                 if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
534                         limit = &intel_limits_i9xx_lvds;
535                 else
536                         limit = &intel_limits_i9xx_sdvo;
537         } else {
538                 if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
539                         limit = &intel_limits_i8xx_lvds;
540                 else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_DVO))
541                         limit = &intel_limits_i8xx_dvo;
542                 else
543                         limit = &intel_limits_i8xx_dac;
544         }
545         return limit;
546 }
547
548 /*
549  * Platform specific helpers to calculate the port PLL loopback- (clock.m),
550  * and post-divider (clock.p) values, pre- (clock.vco) and post-divided fast
551  * (clock.dot) clock rates. This fast dot clock is fed to the port's IO logic.
552  * The helpers' return value is the rate of the clock that is fed to the
553  * display engine's pipe which can be the above fast dot clock rate or a
554  * divided-down version of it.
555  */
556 /* m1 is reserved as 0 in Pineview, n is a ring counter */
557 static int pnv_calc_dpll_params(int refclk, intel_clock_t *clock)
558 {
559         clock->m = clock->m2 + 2;
560         clock->p = clock->p1 * clock->p2;
561         if (WARN_ON(clock->n == 0 || clock->p == 0))
562                 return 0;
563         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
564         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
565
566         return clock->dot;
567 }
568
569 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
570 {
571         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
572 }
573
574 static int i9xx_calc_dpll_params(int refclk, intel_clock_t *clock)
575 {
576         clock->m = i9xx_dpll_compute_m(clock);
577         clock->p = clock->p1 * clock->p2;
578         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
579                 return 0;
580         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
581         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
582
583         return clock->dot;
584 }
585
586 static int vlv_calc_dpll_params(int refclk, intel_clock_t *clock)
587 {
588         clock->m = clock->m1 * clock->m2;
589         clock->p = clock->p1 * clock->p2;
590         if (WARN_ON(clock->n == 0 || clock->p == 0))
591                 return 0;
592         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
593         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
594
595         return clock->dot / 5;
596 }
597
598 int chv_calc_dpll_params(int refclk, intel_clock_t *clock)
599 {
600         clock->m = clock->m1 * clock->m2;
601         clock->p = clock->p1 * clock->p2;
602         if (WARN_ON(clock->n == 0 || clock->p == 0))
603                 return 0;
604         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
605                         clock->n << 22);
606         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
607
608         return clock->dot / 5;
609 }
610
611 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
612 /**
613  * Returns whether the given set of divisors are valid for a given refclk with
614  * the given connectors.
615  */
616
617 static bool intel_PLL_is_valid(struct drm_device *dev,
618                                const intel_limit_t *limit,
619                                const intel_clock_t *clock)
620 {
621         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
622                 INTELPllInvalid("n out of range\n");
623         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
624                 INTELPllInvalid("p1 out of range\n");
625         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
626                 INTELPllInvalid("m2 out of range\n");
627         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
628                 INTELPllInvalid("m1 out of range\n");
629
630         if (!IS_PINEVIEW(dev) && !IS_VALLEYVIEW(dev) && !IS_BROXTON(dev))
631                 if (clock->m1 <= clock->m2)
632                         INTELPllInvalid("m1 <= m2\n");
633
634         if (!IS_VALLEYVIEW(dev) && !IS_BROXTON(dev)) {
635                 if (clock->p < limit->p.min || limit->p.max < clock->p)
636                         INTELPllInvalid("p out of range\n");
637                 if (clock->m < limit->m.min || limit->m.max < clock->m)
638                         INTELPllInvalid("m out of range\n");
639         }
640
641         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
642                 INTELPllInvalid("vco out of range\n");
643         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
644          * connector, etc., rather than just a single range.
645          */
646         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
647                 INTELPllInvalid("dot out of range\n");
648
649         return true;
650 }
651
652 static int
653 i9xx_select_p2_div(const intel_limit_t *limit,
654                    const struct intel_crtc_state *crtc_state,
655                    int target)
656 {
657         struct drm_device *dev = crtc_state->base.crtc->dev;
658
659         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
660                 /*
661                  * For LVDS just rely on its current settings for dual-channel.
662                  * We haven't figured out how to reliably set up different
663                  * single/dual channel state, if we even can.
664                  */
665                 if (intel_is_dual_link_lvds(dev))
666                         return limit->p2.p2_fast;
667                 else
668                         return limit->p2.p2_slow;
669         } else {
670                 if (target < limit->p2.dot_limit)
671                         return limit->p2.p2_slow;
672                 else
673                         return limit->p2.p2_fast;
674         }
675 }
676
677 static bool
678 i9xx_find_best_dpll(const intel_limit_t *limit,
679                     struct intel_crtc_state *crtc_state,
680                     int target, int refclk, intel_clock_t *match_clock,
681                     intel_clock_t *best_clock)
682 {
683         struct drm_device *dev = crtc_state->base.crtc->dev;
684         intel_clock_t clock;
685         int err = target;
686
687         memset(best_clock, 0, sizeof(*best_clock));
688
689         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
690
691         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
692              clock.m1++) {
693                 for (clock.m2 = limit->m2.min;
694                      clock.m2 <= limit->m2.max; clock.m2++) {
695                         if (clock.m2 >= clock.m1)
696                                 break;
697                         for (clock.n = limit->n.min;
698                              clock.n <= limit->n.max; clock.n++) {
699                                 for (clock.p1 = limit->p1.min;
700                                         clock.p1 <= limit->p1.max; clock.p1++) {
701                                         int this_err;
702
703                                         i9xx_calc_dpll_params(refclk, &clock);
704                                         if (!intel_PLL_is_valid(dev, limit,
705                                                                 &clock))
706                                                 continue;
707                                         if (match_clock &&
708                                             clock.p != match_clock->p)
709                                                 continue;
710
711                                         this_err = abs(clock.dot - target);
712                                         if (this_err < err) {
713                                                 *best_clock = clock;
714                                                 err = this_err;
715                                         }
716                                 }
717                         }
718                 }
719         }
720
721         return (err != target);
722 }
723
724 static bool
725 pnv_find_best_dpll(const intel_limit_t *limit,
726                    struct intel_crtc_state *crtc_state,
727                    int target, int refclk, intel_clock_t *match_clock,
728                    intel_clock_t *best_clock)
729 {
730         struct drm_device *dev = crtc_state->base.crtc->dev;
731         intel_clock_t clock;
732         int err = target;
733
734         memset(best_clock, 0, sizeof(*best_clock));
735
736         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
737
738         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
739              clock.m1++) {
740                 for (clock.m2 = limit->m2.min;
741                      clock.m2 <= limit->m2.max; clock.m2++) {
742                         for (clock.n = limit->n.min;
743                              clock.n <= limit->n.max; clock.n++) {
744                                 for (clock.p1 = limit->p1.min;
745                                         clock.p1 <= limit->p1.max; clock.p1++) {
746                                         int this_err;
747
748                                         pnv_calc_dpll_params(refclk, &clock);
749                                         if (!intel_PLL_is_valid(dev, limit,
750                                                                 &clock))
751                                                 continue;
752                                         if (match_clock &&
753                                             clock.p != match_clock->p)
754                                                 continue;
755
756                                         this_err = abs(clock.dot - target);
757                                         if (this_err < err) {
758                                                 *best_clock = clock;
759                                                 err = this_err;
760                                         }
761                                 }
762                         }
763                 }
764         }
765
766         return (err != target);
767 }
768
769 static bool
770 g4x_find_best_dpll(const intel_limit_t *limit,
771                    struct intel_crtc_state *crtc_state,
772                    int target, int refclk, intel_clock_t *match_clock,
773                    intel_clock_t *best_clock)
774 {
775         struct drm_device *dev = crtc_state->base.crtc->dev;
776         intel_clock_t clock;
777         int max_n;
778         bool found = false;
779         /* approximately equals target * 0.00585 */
780         int err_most = (target >> 8) + (target >> 9);
781
782         memset(best_clock, 0, sizeof(*best_clock));
783
784         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
785
786         max_n = limit->n.max;
787         /* based on hardware requirement, prefer smaller n to precision */
788         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
789                 /* based on hardware requirement, prefere larger m1,m2 */
790                 for (clock.m1 = limit->m1.max;
791                      clock.m1 >= limit->m1.min; clock.m1--) {
792                         for (clock.m2 = limit->m2.max;
793                              clock.m2 >= limit->m2.min; clock.m2--) {
794                                 for (clock.p1 = limit->p1.max;
795                                      clock.p1 >= limit->p1.min; clock.p1--) {
796                                         int this_err;
797
798                                         i9xx_calc_dpll_params(refclk, &clock);
799                                         if (!intel_PLL_is_valid(dev, limit,
800                                                                 &clock))
801                                                 continue;
802
803                                         this_err = abs(clock.dot - target);
804                                         if (this_err < err_most) {
805                                                 *best_clock = clock;
806                                                 err_most = this_err;
807                                                 max_n = clock.n;
808                                                 found = true;
809                                         }
810                                 }
811                         }
812                 }
813         }
814         return found;
815 }
816
817 /*
818  * Check if the calculated PLL configuration is more optimal compared to the
819  * best configuration and error found so far. Return the calculated error.
820  */
821 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
822                                const intel_clock_t *calculated_clock,
823                                const intel_clock_t *best_clock,
824                                unsigned int best_error_ppm,
825                                unsigned int *error_ppm)
826 {
827         /*
828          * For CHV ignore the error and consider only the P value.
829          * Prefer a bigger P value based on HW requirements.
830          */
831         if (IS_CHERRYVIEW(dev)) {
832                 *error_ppm = 0;
833
834                 return calculated_clock->p > best_clock->p;
835         }
836
837         if (WARN_ON_ONCE(!target_freq))
838                 return false;
839
840         *error_ppm = div_u64(1000000ULL *
841                                 abs(target_freq - calculated_clock->dot),
842                              target_freq);
843         /*
844          * Prefer a better P value over a better (smaller) error if the error
845          * is small. Ensure this preference for future configurations too by
846          * setting the error to 0.
847          */
848         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
849                 *error_ppm = 0;
850
851                 return true;
852         }
853
854         return *error_ppm + 10 < best_error_ppm;
855 }
856
857 static bool
858 vlv_find_best_dpll(const intel_limit_t *limit,
859                    struct intel_crtc_state *crtc_state,
860                    int target, int refclk, intel_clock_t *match_clock,
861                    intel_clock_t *best_clock)
862 {
863         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
864         struct drm_device *dev = crtc->base.dev;
865         intel_clock_t clock;
866         unsigned int bestppm = 1000000;
867         /* min update 19.2 MHz */
868         int max_n = min(limit->n.max, refclk / 19200);
869         bool found = false;
870
871         target *= 5; /* fast clock */
872
873         memset(best_clock, 0, sizeof(*best_clock));
874
875         /* based on hardware requirement, prefer smaller n to precision */
876         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
877                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
878                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
879                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
880                                 clock.p = clock.p1 * clock.p2;
881                                 /* based on hardware requirement, prefer bigger m1,m2 values */
882                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
883                                         unsigned int ppm;
884
885                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
886                                                                      refclk * clock.m1);
887
888                                         vlv_calc_dpll_params(refclk, &clock);
889
890                                         if (!intel_PLL_is_valid(dev, limit,
891                                                                 &clock))
892                                                 continue;
893
894                                         if (!vlv_PLL_is_optimal(dev, target,
895                                                                 &clock,
896                                                                 best_clock,
897                                                                 bestppm, &ppm))
898                                                 continue;
899
900                                         *best_clock = clock;
901                                         bestppm = ppm;
902                                         found = true;
903                                 }
904                         }
905                 }
906         }
907
908         return found;
909 }
910
911 static bool
912 chv_find_best_dpll(const intel_limit_t *limit,
913                    struct intel_crtc_state *crtc_state,
914                    int target, int refclk, intel_clock_t *match_clock,
915                    intel_clock_t *best_clock)
916 {
917         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
918         struct drm_device *dev = crtc->base.dev;
919         unsigned int best_error_ppm;
920         intel_clock_t clock;
921         uint64_t m2;
922         int found = false;
923
924         memset(best_clock, 0, sizeof(*best_clock));
925         best_error_ppm = 1000000;
926
927         /*
928          * Based on hardware doc, the n always set to 1, and m1 always
929          * set to 2.  If requires to support 200Mhz refclk, we need to
930          * revisit this because n may not 1 anymore.
931          */
932         clock.n = 1, clock.m1 = 2;
933         target *= 5;    /* fast clock */
934
935         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
936                 for (clock.p2 = limit->p2.p2_fast;
937                                 clock.p2 >= limit->p2.p2_slow;
938                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
939                         unsigned int error_ppm;
940
941                         clock.p = clock.p1 * clock.p2;
942
943                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
944                                         clock.n) << 22, refclk * clock.m1);
945
946                         if (m2 > INT_MAX/clock.m1)
947                                 continue;
948
949                         clock.m2 = m2;
950
951                         chv_calc_dpll_params(refclk, &clock);
952
953                         if (!intel_PLL_is_valid(dev, limit, &clock))
954                                 continue;
955
956                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
957                                                 best_error_ppm, &error_ppm))
958                                 continue;
959
960                         *best_clock = clock;
961                         best_error_ppm = error_ppm;
962                         found = true;
963                 }
964         }
965
966         return found;
967 }
968
969 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state, int target_clock,
970                         intel_clock_t *best_clock)
971 {
972         int refclk = i9xx_get_refclk(crtc_state, 0);
973
974         return chv_find_best_dpll(intel_limit(crtc_state, refclk), crtc_state,
975                                   target_clock, refclk, NULL, best_clock);
976 }
977
978 bool intel_crtc_active(struct drm_crtc *crtc)
979 {
980         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
981
982         /* Be paranoid as we can arrive here with only partial
983          * state retrieved from the hardware during setup.
984          *
985          * We can ditch the adjusted_mode.crtc_clock check as soon
986          * as Haswell has gained clock readout/fastboot support.
987          *
988          * We can ditch the crtc->primary->fb check as soon as we can
989          * properly reconstruct framebuffers.
990          *
991          * FIXME: The intel_crtc->active here should be switched to
992          * crtc->state->active once we have proper CRTC states wired up
993          * for atomic.
994          */
995         return intel_crtc->active && crtc->primary->state->fb &&
996                 intel_crtc->config->base.adjusted_mode.crtc_clock;
997 }
998
999 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
1000                                              enum pipe pipe)
1001 {
1002         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1003         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1004
1005         return intel_crtc->config->cpu_transcoder;
1006 }
1007
1008 static bool pipe_dsl_stopped(struct drm_device *dev, enum pipe pipe)
1009 {
1010         struct drm_i915_private *dev_priv = dev->dev_private;
1011         u32 reg = PIPEDSL(pipe);
1012         u32 line1, line2;
1013         u32 line_mask;
1014
1015         if (IS_GEN2(dev))
1016                 line_mask = DSL_LINEMASK_GEN2;
1017         else
1018                 line_mask = DSL_LINEMASK_GEN3;
1019
1020         line1 = I915_READ(reg) & line_mask;
1021         msleep(5);
1022         line2 = I915_READ(reg) & line_mask;
1023
1024         return line1 == line2;
1025 }
1026
1027 /*
1028  * intel_wait_for_pipe_off - wait for pipe to turn off
1029  * @crtc: crtc whose pipe to wait for
1030  *
1031  * After disabling a pipe, we can't wait for vblank in the usual way,
1032  * spinning on the vblank interrupt status bit, since we won't actually
1033  * see an interrupt when the pipe is disabled.
1034  *
1035  * On Gen4 and above:
1036  *   wait for the pipe register state bit to turn off
1037  *
1038  * Otherwise:
1039  *   wait for the display line value to settle (it usually
1040  *   ends up stopping at the start of the next frame).
1041  *
1042  */
1043 static void intel_wait_for_pipe_off(struct intel_crtc *crtc)
1044 {
1045         struct drm_device *dev = crtc->base.dev;
1046         struct drm_i915_private *dev_priv = dev->dev_private;
1047         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1048         enum pipe pipe = crtc->pipe;
1049
1050         if (INTEL_INFO(dev)->gen >= 4) {
1051                 int reg = PIPECONF(cpu_transcoder);
1052
1053                 /* Wait for the Pipe State to go off */
1054                 if (wait_for((I915_READ(reg) & I965_PIPECONF_ACTIVE) == 0,
1055                              100))
1056                         WARN(1, "pipe_off wait timed out\n");
1057         } else {
1058                 /* Wait for the display line to settle */
1059                 if (wait_for(pipe_dsl_stopped(dev, pipe), 100))
1060                         WARN(1, "pipe_off wait timed out\n");
1061         }
1062 }
1063
1064 /*
1065  * ibx_digital_port_connected - is the specified port connected?
1066  * @dev_priv: i915 private structure
1067  * @port: the port to test
1068  *
1069  * Returns true if @port is connected, false otherwise.
1070  */
1071 bool ibx_digital_port_connected(struct drm_i915_private *dev_priv,
1072                                 struct intel_digital_port *port)
1073 {
1074         u32 bit;
1075
1076         if (HAS_PCH_IBX(dev_priv->dev)) {
1077                 switch (port->port) {
1078                 case PORT_B:
1079                         bit = SDE_PORTB_HOTPLUG;
1080                         break;
1081                 case PORT_C:
1082                         bit = SDE_PORTC_HOTPLUG;
1083                         break;
1084                 case PORT_D:
1085                         bit = SDE_PORTD_HOTPLUG;
1086                         break;
1087                 default:
1088                         return true;
1089                 }
1090         } else {
1091                 switch (port->port) {
1092                 case PORT_B:
1093                         bit = SDE_PORTB_HOTPLUG_CPT;
1094                         break;
1095                 case PORT_C:
1096                         bit = SDE_PORTC_HOTPLUG_CPT;
1097                         break;
1098                 case PORT_D:
1099                         bit = SDE_PORTD_HOTPLUG_CPT;
1100                         break;
1101                 default:
1102                         return true;
1103                 }
1104         }
1105
1106         return I915_READ(SDEISR) & bit;
1107 }
1108
1109 static const char *state_string(bool enabled)
1110 {
1111         return enabled ? "on" : "off";
1112 }
1113
1114 /* Only for pre-ILK configs */
1115 void assert_pll(struct drm_i915_private *dev_priv,
1116                 enum pipe pipe, bool state)
1117 {
1118         int reg;
1119         u32 val;
1120         bool cur_state;
1121
1122         reg = DPLL(pipe);
1123         val = I915_READ(reg);
1124         cur_state = !!(val & DPLL_VCO_ENABLE);
1125         I915_STATE_WARN(cur_state != state,
1126              "PLL state assertion failure (expected %s, current %s)\n",
1127              state_string(state), state_string(cur_state));
1128 }
1129
1130 /* XXX: the dsi pll is shared between MIPI DSI ports */
1131 static void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1132 {
1133         u32 val;
1134         bool cur_state;
1135
1136         mutex_lock(&dev_priv->sb_lock);
1137         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1138         mutex_unlock(&dev_priv->sb_lock);
1139
1140         cur_state = val & DSI_PLL_VCO_EN;
1141         I915_STATE_WARN(cur_state != state,
1142              "DSI PLL state assertion failure (expected %s, current %s)\n",
1143              state_string(state), state_string(cur_state));
1144 }
1145 #define assert_dsi_pll_enabled(d) assert_dsi_pll(d, true)
1146 #define assert_dsi_pll_disabled(d) assert_dsi_pll(d, false)
1147
1148 struct intel_shared_dpll *
1149 intel_crtc_to_shared_dpll(struct intel_crtc *crtc)
1150 {
1151         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
1152
1153         if (crtc->config->shared_dpll < 0)
1154                 return NULL;
1155
1156         return &dev_priv->shared_dplls[crtc->config->shared_dpll];
1157 }
1158
1159 /* For ILK+ */
1160 void assert_shared_dpll(struct drm_i915_private *dev_priv,
1161                         struct intel_shared_dpll *pll,
1162                         bool state)
1163 {
1164         bool cur_state;
1165         struct intel_dpll_hw_state hw_state;
1166
1167         if (WARN (!pll,
1168                   "asserting DPLL %s with no DPLL\n", state_string(state)))
1169                 return;
1170
1171         cur_state = pll->get_hw_state(dev_priv, pll, &hw_state);
1172         I915_STATE_WARN(cur_state != state,
1173              "%s assertion failure (expected %s, current %s)\n",
1174              pll->name, state_string(state), state_string(cur_state));
1175 }
1176
1177 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1178                           enum pipe pipe, bool state)
1179 {
1180         int reg;
1181         u32 val;
1182         bool cur_state;
1183         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1184                                                                       pipe);
1185
1186         if (HAS_DDI(dev_priv->dev)) {
1187                 /* DDI does not have a specific FDI_TX register */
1188                 reg = TRANS_DDI_FUNC_CTL(cpu_transcoder);
1189                 val = I915_READ(reg);
1190                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1191         } else {
1192                 reg = FDI_TX_CTL(pipe);
1193                 val = I915_READ(reg);
1194                 cur_state = !!(val & FDI_TX_ENABLE);
1195         }
1196         I915_STATE_WARN(cur_state != state,
1197              "FDI TX state assertion failure (expected %s, current %s)\n",
1198              state_string(state), state_string(cur_state));
1199 }
1200 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1201 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1202
1203 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1204                           enum pipe pipe, bool state)
1205 {
1206         int reg;
1207         u32 val;
1208         bool cur_state;
1209
1210         reg = FDI_RX_CTL(pipe);
1211         val = I915_READ(reg);
1212         cur_state = !!(val & FDI_RX_ENABLE);
1213         I915_STATE_WARN(cur_state != state,
1214              "FDI RX state assertion failure (expected %s, current %s)\n",
1215              state_string(state), state_string(cur_state));
1216 }
1217 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1218 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1219
1220 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1221                                       enum pipe pipe)
1222 {
1223         int reg;
1224         u32 val;
1225
1226         /* ILK FDI PLL is always enabled */
1227         if (INTEL_INFO(dev_priv->dev)->gen == 5)
1228                 return;
1229
1230         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1231         if (HAS_DDI(dev_priv->dev))
1232                 return;
1233
1234         reg = FDI_TX_CTL(pipe);
1235         val = I915_READ(reg);
1236         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1237 }
1238
1239 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1240                        enum pipe pipe, bool state)
1241 {
1242         int reg;
1243         u32 val;
1244         bool cur_state;
1245
1246         reg = FDI_RX_CTL(pipe);
1247         val = I915_READ(reg);
1248         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1249         I915_STATE_WARN(cur_state != state,
1250              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1251              state_string(state), state_string(cur_state));
1252 }
1253
1254 void assert_panel_unlocked(struct drm_i915_private *dev_priv,
1255                            enum pipe pipe)
1256 {
1257         struct drm_device *dev = dev_priv->dev;
1258         int pp_reg;
1259         u32 val;
1260         enum pipe panel_pipe = PIPE_A;
1261         bool locked = true;
1262
1263         if (WARN_ON(HAS_DDI(dev)))
1264                 return;
1265
1266         if (HAS_PCH_SPLIT(dev)) {
1267                 u32 port_sel;
1268
1269                 pp_reg = PCH_PP_CONTROL;
1270                 port_sel = I915_READ(PCH_PP_ON_DELAYS) & PANEL_PORT_SELECT_MASK;
1271
1272                 if (port_sel == PANEL_PORT_SELECT_LVDS &&
1273                     I915_READ(PCH_LVDS) & LVDS_PIPEB_SELECT)
1274                         panel_pipe = PIPE_B;
1275                 /* XXX: else fix for eDP */
1276         } else if (IS_VALLEYVIEW(dev)) {
1277                 /* presumably write lock depends on pipe, not port select */
1278                 pp_reg = VLV_PIPE_PP_CONTROL(pipe);
1279                 panel_pipe = pipe;
1280         } else {
1281                 pp_reg = PP_CONTROL;
1282                 if (I915_READ(LVDS) & LVDS_PIPEB_SELECT)
1283                         panel_pipe = PIPE_B;
1284         }
1285
1286         val = I915_READ(pp_reg);
1287         if (!(val & PANEL_POWER_ON) ||
1288             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1289                 locked = false;
1290
1291         I915_STATE_WARN(panel_pipe == pipe && locked,
1292              "panel assertion failure, pipe %c regs locked\n",
1293              pipe_name(pipe));
1294 }
1295
1296 static void assert_cursor(struct drm_i915_private *dev_priv,
1297                           enum pipe pipe, bool state)
1298 {
1299         struct drm_device *dev = dev_priv->dev;
1300         bool cur_state;
1301
1302         if (IS_845G(dev) || IS_I865G(dev))
1303                 cur_state = I915_READ(_CURACNTR) & CURSOR_ENABLE;
1304         else
1305                 cur_state = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
1306
1307         I915_STATE_WARN(cur_state != state,
1308              "cursor on pipe %c assertion failure (expected %s, current %s)\n",
1309              pipe_name(pipe), state_string(state), state_string(cur_state));
1310 }
1311 #define assert_cursor_enabled(d, p) assert_cursor(d, p, true)
1312 #define assert_cursor_disabled(d, p) assert_cursor(d, p, false)
1313
1314 void assert_pipe(struct drm_i915_private *dev_priv,
1315                  enum pipe pipe, bool state)
1316 {
1317         int reg;
1318         u32 val;
1319         bool cur_state;
1320         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1321                                                                       pipe);
1322
1323         /* if we need the pipe quirk it must be always on */
1324         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1325             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1326                 state = true;
1327
1328         if (!intel_display_power_is_enabled(dev_priv,
1329                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder))) {
1330                 cur_state = false;
1331         } else {
1332                 reg = PIPECONF(cpu_transcoder);
1333                 val = I915_READ(reg);
1334                 cur_state = !!(val & PIPECONF_ENABLE);
1335         }
1336
1337         I915_STATE_WARN(cur_state != state,
1338              "pipe %c assertion failure (expected %s, current %s)\n",
1339              pipe_name(pipe), state_string(state), state_string(cur_state));
1340 }
1341
1342 static void assert_plane(struct drm_i915_private *dev_priv,
1343                          enum plane plane, bool state)
1344 {
1345         int reg;
1346         u32 val;
1347         bool cur_state;
1348
1349         reg = DSPCNTR(plane);
1350         val = I915_READ(reg);
1351         cur_state = !!(val & DISPLAY_PLANE_ENABLE);
1352         I915_STATE_WARN(cur_state != state,
1353              "plane %c assertion failure (expected %s, current %s)\n",
1354              plane_name(plane), state_string(state), state_string(cur_state));
1355 }
1356
1357 #define assert_plane_enabled(d, p) assert_plane(d, p, true)
1358 #define assert_plane_disabled(d, p) assert_plane(d, p, false)
1359
1360 static void assert_planes_disabled(struct drm_i915_private *dev_priv,
1361                                    enum pipe pipe)
1362 {
1363         struct drm_device *dev = dev_priv->dev;
1364         int reg, i;
1365         u32 val;
1366         int cur_pipe;
1367
1368         /* Primary planes are fixed to pipes on gen4+ */
1369         if (INTEL_INFO(dev)->gen >= 4) {
1370                 reg = DSPCNTR(pipe);
1371                 val = I915_READ(reg);
1372                 I915_STATE_WARN(val & DISPLAY_PLANE_ENABLE,
1373                      "plane %c assertion failure, should be disabled but not\n",
1374                      plane_name(pipe));
1375                 return;
1376         }
1377
1378         /* Need to check both planes against the pipe */
1379         for_each_pipe(dev_priv, i) {
1380                 reg = DSPCNTR(i);
1381                 val = I915_READ(reg);
1382                 cur_pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
1383                         DISPPLANE_SEL_PIPE_SHIFT;
1384                 I915_STATE_WARN((val & DISPLAY_PLANE_ENABLE) && pipe == cur_pipe,
1385                      "plane %c assertion failure, should be off on pipe %c but is still active\n",
1386                      plane_name(i), pipe_name(pipe));
1387         }
1388 }
1389
1390 static void assert_sprites_disabled(struct drm_i915_private *dev_priv,
1391                                     enum pipe pipe)
1392 {
1393         struct drm_device *dev = dev_priv->dev;
1394         int reg, sprite;
1395         u32 val;
1396
1397         if (INTEL_INFO(dev)->gen >= 9) {
1398                 for_each_sprite(dev_priv, pipe, sprite) {
1399                         val = I915_READ(PLANE_CTL(pipe, sprite));
1400                         I915_STATE_WARN(val & PLANE_CTL_ENABLE,
1401                              "plane %d assertion failure, should be off on pipe %c but is still active\n",
1402                              sprite, pipe_name(pipe));
1403                 }
1404         } else if (IS_VALLEYVIEW(dev)) {
1405                 for_each_sprite(dev_priv, pipe, sprite) {
1406                         reg = SPCNTR(pipe, sprite);
1407                         val = I915_READ(reg);
1408                         I915_STATE_WARN(val & SP_ENABLE,
1409                              "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1410                              sprite_name(pipe, sprite), pipe_name(pipe));
1411                 }
1412         } else if (INTEL_INFO(dev)->gen >= 7) {
1413                 reg = SPRCTL(pipe);
1414                 val = I915_READ(reg);
1415                 I915_STATE_WARN(val & SPRITE_ENABLE,
1416                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1417                      plane_name(pipe), pipe_name(pipe));
1418         } else if (INTEL_INFO(dev)->gen >= 5) {
1419                 reg = DVSCNTR(pipe);
1420                 val = I915_READ(reg);
1421                 I915_STATE_WARN(val & DVS_ENABLE,
1422                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1423                      plane_name(pipe), pipe_name(pipe));
1424         }
1425 }
1426
1427 static void assert_vblank_disabled(struct drm_crtc *crtc)
1428 {
1429         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1430                 drm_crtc_vblank_put(crtc);
1431 }
1432
1433 static void ibx_assert_pch_refclk_enabled(struct drm_i915_private *dev_priv)
1434 {
1435         u32 val;
1436         bool enabled;
1437
1438         I915_STATE_WARN_ON(!(HAS_PCH_IBX(dev_priv->dev) || HAS_PCH_CPT(dev_priv->dev)));
1439
1440         val = I915_READ(PCH_DREF_CONTROL);
1441         enabled = !!(val & (DREF_SSC_SOURCE_MASK | DREF_NONSPREAD_SOURCE_MASK |
1442                             DREF_SUPERSPREAD_SOURCE_MASK));
1443         I915_STATE_WARN(!enabled, "PCH refclk assertion failure, should be active but is disabled\n");
1444 }
1445
1446 static void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1447                                            enum pipe pipe)
1448 {
1449         int reg;
1450         u32 val;
1451         bool enabled;
1452
1453         reg = PCH_TRANSCONF(pipe);
1454         val = I915_READ(reg);
1455         enabled = !!(val & TRANS_ENABLE);
1456         I915_STATE_WARN(enabled,
1457              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1458              pipe_name(pipe));
1459 }
1460
1461 static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1462                             enum pipe pipe, u32 port_sel, u32 val)
1463 {
1464         if ((val & DP_PORT_EN) == 0)
1465                 return false;
1466
1467         if (HAS_PCH_CPT(dev_priv->dev)) {
1468                 u32     trans_dp_ctl_reg = TRANS_DP_CTL(pipe);
1469                 u32     trans_dp_ctl = I915_READ(trans_dp_ctl_reg);
1470                 if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1471                         return false;
1472         } else if (IS_CHERRYVIEW(dev_priv->dev)) {
1473                 if ((val & DP_PIPE_MASK_CHV) != DP_PIPE_SELECT_CHV(pipe))
1474                         return false;
1475         } else {
1476                 if ((val & DP_PIPE_MASK) != (pipe << 30))
1477                         return false;
1478         }
1479         return true;
1480 }
1481
1482 static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1483                               enum pipe pipe, u32 val)
1484 {
1485         if ((val & SDVO_ENABLE) == 0)
1486                 return false;
1487
1488         if (HAS_PCH_CPT(dev_priv->dev)) {
1489                 if ((val & SDVO_PIPE_SEL_MASK_CPT) != SDVO_PIPE_SEL_CPT(pipe))
1490                         return false;
1491         } else if (IS_CHERRYVIEW(dev_priv->dev)) {
1492                 if ((val & SDVO_PIPE_SEL_MASK_CHV) != SDVO_PIPE_SEL_CHV(pipe))
1493                         return false;
1494         } else {
1495                 if ((val & SDVO_PIPE_SEL_MASK) != SDVO_PIPE_SEL(pipe))
1496                         return false;
1497         }
1498         return true;
1499 }
1500
1501 static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1502                               enum pipe pipe, u32 val)
1503 {
1504         if ((val & LVDS_PORT_EN) == 0)
1505                 return false;
1506
1507         if (HAS_PCH_CPT(dev_priv->dev)) {
1508                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1509                         return false;
1510         } else {
1511                 if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1512                         return false;
1513         }
1514         return true;
1515 }
1516
1517 static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1518                               enum pipe pipe, u32 val)
1519 {
1520         if ((val & ADPA_DAC_ENABLE) == 0)
1521                 return false;
1522         if (HAS_PCH_CPT(dev_priv->dev)) {
1523                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1524                         return false;
1525         } else {
1526                 if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1527                         return false;
1528         }
1529         return true;
1530 }
1531
1532 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1533                                    enum pipe pipe, int reg, u32 port_sel)
1534 {
1535         u32 val = I915_READ(reg);
1536         I915_STATE_WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1537              "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1538              reg, pipe_name(pipe));
1539
1540         I915_STATE_WARN(HAS_PCH_IBX(dev_priv->dev) && (val & DP_PORT_EN) == 0
1541              && (val & DP_PIPEB_SELECT),
1542              "IBX PCH dp port still using transcoder B\n");
1543 }
1544
1545 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1546                                      enum pipe pipe, int reg)
1547 {
1548         u32 val = I915_READ(reg);
1549         I915_STATE_WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1550              "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1551              reg, pipe_name(pipe));
1552
1553         I915_STATE_WARN(HAS_PCH_IBX(dev_priv->dev) && (val & SDVO_ENABLE) == 0
1554              && (val & SDVO_PIPE_B_SELECT),
1555              "IBX PCH hdmi port still using transcoder B\n");
1556 }
1557
1558 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1559                                       enum pipe pipe)
1560 {
1561         int reg;
1562         u32 val;
1563
1564         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1565         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1566         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1567
1568         reg = PCH_ADPA;
1569         val = I915_READ(reg);
1570         I915_STATE_WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1571              "PCH VGA enabled on transcoder %c, should be disabled\n",
1572              pipe_name(pipe));
1573
1574         reg = PCH_LVDS;
1575         val = I915_READ(reg);
1576         I915_STATE_WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1577              "PCH LVDS enabled on transcoder %c, should be disabled\n",
1578              pipe_name(pipe));
1579
1580         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIB);
1581         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIC);
1582         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMID);
1583 }
1584
1585 static void vlv_enable_pll(struct intel_crtc *crtc,
1586                            const struct intel_crtc_state *pipe_config)
1587 {
1588         struct drm_device *dev = crtc->base.dev;
1589         struct drm_i915_private *dev_priv = dev->dev_private;
1590         int reg = DPLL(crtc->pipe);
1591         u32 dpll = pipe_config->dpll_hw_state.dpll;
1592
1593         assert_pipe_disabled(dev_priv, crtc->pipe);
1594
1595         /* No really, not for ILK+ */
1596         BUG_ON(!IS_VALLEYVIEW(dev_priv->dev));
1597
1598         /* PLL is protected by panel, make sure we can write it */
1599         if (IS_MOBILE(dev_priv->dev))
1600                 assert_panel_unlocked(dev_priv, crtc->pipe);
1601
1602         I915_WRITE(reg, dpll);
1603         POSTING_READ(reg);
1604         udelay(150);
1605
1606         if (wait_for(((I915_READ(reg) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1607                 DRM_ERROR("DPLL %d failed to lock\n", crtc->pipe);
1608
1609         I915_WRITE(DPLL_MD(crtc->pipe), pipe_config->dpll_hw_state.dpll_md);
1610         POSTING_READ(DPLL_MD(crtc->pipe));
1611
1612         /* We do this three times for luck */
1613         I915_WRITE(reg, dpll);
1614         POSTING_READ(reg);
1615         udelay(150); /* wait for warmup */
1616         I915_WRITE(reg, dpll);
1617         POSTING_READ(reg);
1618         udelay(150); /* wait for warmup */
1619         I915_WRITE(reg, dpll);
1620         POSTING_READ(reg);
1621         udelay(150); /* wait for warmup */
1622 }
1623
1624 static void chv_enable_pll(struct intel_crtc *crtc,
1625                            const struct intel_crtc_state *pipe_config)
1626 {
1627         struct drm_device *dev = crtc->base.dev;
1628         struct drm_i915_private *dev_priv = dev->dev_private;
1629         int pipe = crtc->pipe;
1630         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1631         u32 tmp;
1632
1633         assert_pipe_disabled(dev_priv, crtc->pipe);
1634
1635         BUG_ON(!IS_CHERRYVIEW(dev_priv->dev));
1636
1637         mutex_lock(&dev_priv->sb_lock);
1638
1639         /* Enable back the 10bit clock to display controller */
1640         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1641         tmp |= DPIO_DCLKP_EN;
1642         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1643
1644         mutex_unlock(&dev_priv->sb_lock);
1645
1646         /*
1647          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1648          */
1649         udelay(1);
1650
1651         /* Enable PLL */
1652         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1653
1654         /* Check PLL is locked */
1655         if (wait_for(((I915_READ(DPLL(pipe)) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1656                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1657
1658         /* not sure when this should be written */
1659         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1660         POSTING_READ(DPLL_MD(pipe));
1661 }
1662
1663 static int intel_num_dvo_pipes(struct drm_device *dev)
1664 {
1665         struct intel_crtc *crtc;
1666         int count = 0;
1667
1668         for_each_intel_crtc(dev, crtc)
1669                 count += crtc->base.state->active &&
1670                         intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO);
1671
1672         return count;
1673 }
1674
1675 static void i9xx_enable_pll(struct intel_crtc *crtc)
1676 {
1677         struct drm_device *dev = crtc->base.dev;
1678         struct drm_i915_private *dev_priv = dev->dev_private;
1679         int reg = DPLL(crtc->pipe);
1680         u32 dpll = crtc->config->dpll_hw_state.dpll;
1681
1682         assert_pipe_disabled(dev_priv, crtc->pipe);
1683
1684         /* No really, not for ILK+ */
1685         BUG_ON(INTEL_INFO(dev)->gen >= 5);
1686
1687         /* PLL is protected by panel, make sure we can write it */
1688         if (IS_MOBILE(dev) && !IS_I830(dev))
1689                 assert_panel_unlocked(dev_priv, crtc->pipe);
1690
1691         /* Enable DVO 2x clock on both PLLs if necessary */
1692         if (IS_I830(dev) && intel_num_dvo_pipes(dev) > 0) {
1693                 /*
1694                  * It appears to be important that we don't enable this
1695                  * for the current pipe before otherwise configuring the
1696                  * PLL. No idea how this should be handled if multiple
1697                  * DVO outputs are enabled simultaneosly.
1698                  */
1699                 dpll |= DPLL_DVO_2X_MODE;
1700                 I915_WRITE(DPLL(!crtc->pipe),
1701                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1702         }
1703
1704         /* Wait for the clocks to stabilize. */
1705         POSTING_READ(reg);
1706         udelay(150);
1707
1708         if (INTEL_INFO(dev)->gen >= 4) {
1709                 I915_WRITE(DPLL_MD(crtc->pipe),
1710                            crtc->config->dpll_hw_state.dpll_md);
1711         } else {
1712                 /* The pixel multiplier can only be updated once the
1713                  * DPLL is enabled and the clocks are stable.
1714                  *
1715                  * So write it again.
1716                  */
1717                 I915_WRITE(reg, dpll);
1718         }
1719
1720         /* We do this three times for luck */
1721         I915_WRITE(reg, dpll);
1722         POSTING_READ(reg);
1723         udelay(150); /* wait for warmup */
1724         I915_WRITE(reg, dpll);
1725         POSTING_READ(reg);
1726         udelay(150); /* wait for warmup */
1727         I915_WRITE(reg, dpll);
1728         POSTING_READ(reg);
1729         udelay(150); /* wait for warmup */
1730 }
1731
1732 /**
1733  * i9xx_disable_pll - disable a PLL
1734  * @dev_priv: i915 private structure
1735  * @pipe: pipe PLL to disable
1736  *
1737  * Disable the PLL for @pipe, making sure the pipe is off first.
1738  *
1739  * Note!  This is for pre-ILK only.
1740  */
1741 static void i9xx_disable_pll(struct intel_crtc *crtc)
1742 {
1743         struct drm_device *dev = crtc->base.dev;
1744         struct drm_i915_private *dev_priv = dev->dev_private;
1745         enum pipe pipe = crtc->pipe;
1746
1747         /* Disable DVO 2x clock on both PLLs if necessary */
1748         if (IS_I830(dev) &&
1749             intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO) &&
1750             !intel_num_dvo_pipes(dev)) {
1751                 I915_WRITE(DPLL(PIPE_B),
1752                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1753                 I915_WRITE(DPLL(PIPE_A),
1754                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1755         }
1756
1757         /* Don't disable pipe or pipe PLLs if needed */
1758         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1759             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1760                 return;
1761
1762         /* Make sure the pipe isn't still relying on us */
1763         assert_pipe_disabled(dev_priv, pipe);
1764
1765         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1766         POSTING_READ(DPLL(pipe));
1767 }
1768
1769 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1770 {
1771         u32 val;
1772
1773         /* Make sure the pipe isn't still relying on us */
1774         assert_pipe_disabled(dev_priv, pipe);
1775
1776         /*
1777          * Leave integrated clock source and reference clock enabled for pipe B.
1778          * The latter is needed for VGA hotplug / manual detection.
1779          */
1780         val = DPLL_VGA_MODE_DIS;
1781         if (pipe == PIPE_B)
1782                 val = DPLL_INTEGRATED_CRI_CLK_VLV | DPLL_REF_CLK_ENABLE_VLV;
1783         I915_WRITE(DPLL(pipe), val);
1784         POSTING_READ(DPLL(pipe));
1785
1786 }
1787
1788 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1789 {
1790         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1791         u32 val;
1792
1793         /* Make sure the pipe isn't still relying on us */
1794         assert_pipe_disabled(dev_priv, pipe);
1795
1796         /* Set PLL en = 0 */
1797         val = DPLL_SSC_REF_CLK_CHV |
1798                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1799         if (pipe != PIPE_A)
1800                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1801         I915_WRITE(DPLL(pipe), val);
1802         POSTING_READ(DPLL(pipe));
1803
1804         mutex_lock(&dev_priv->sb_lock);
1805
1806         /* Disable 10bit clock to display controller */
1807         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1808         val &= ~DPIO_DCLKP_EN;
1809         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1810
1811         mutex_unlock(&dev_priv->sb_lock);
1812 }
1813
1814 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1815                          struct intel_digital_port *dport,
1816                          unsigned int expected_mask)
1817 {
1818         u32 port_mask;
1819         int dpll_reg;
1820
1821         switch (dport->port) {
1822         case PORT_B:
1823                 port_mask = DPLL_PORTB_READY_MASK;
1824                 dpll_reg = DPLL(0);
1825                 break;
1826         case PORT_C:
1827                 port_mask = DPLL_PORTC_READY_MASK;
1828                 dpll_reg = DPLL(0);
1829                 expected_mask <<= 4;
1830                 break;
1831         case PORT_D:
1832                 port_mask = DPLL_PORTD_READY_MASK;
1833                 dpll_reg = DPIO_PHY_STATUS;
1834                 break;
1835         default:
1836                 BUG();
1837         }
1838
1839         if (wait_for((I915_READ(dpll_reg) & port_mask) == expected_mask, 1000))
1840                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1841                      port_name(dport->port), I915_READ(dpll_reg) & port_mask, expected_mask);
1842 }
1843
1844 static void intel_prepare_shared_dpll(struct intel_crtc *crtc)
1845 {
1846         struct drm_device *dev = crtc->base.dev;
1847         struct drm_i915_private *dev_priv = dev->dev_private;
1848         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1849
1850         if (WARN_ON(pll == NULL))
1851                 return;
1852
1853         WARN_ON(!pll->config.crtc_mask);
1854         if (pll->active == 0) {
1855                 DRM_DEBUG_DRIVER("setting up %s\n", pll->name);
1856                 WARN_ON(pll->on);
1857                 assert_shared_dpll_disabled(dev_priv, pll);
1858
1859                 pll->mode_set(dev_priv, pll);
1860         }
1861 }
1862
1863 /**
1864  * intel_enable_shared_dpll - enable PCH PLL
1865  * @dev_priv: i915 private structure
1866  * @pipe: pipe PLL to enable
1867  *
1868  * The PCH PLL needs to be enabled before the PCH transcoder, since it
1869  * drives the transcoder clock.
1870  */
1871 static void intel_enable_shared_dpll(struct intel_crtc *crtc)
1872 {
1873         struct drm_device *dev = crtc->base.dev;
1874         struct drm_i915_private *dev_priv = dev->dev_private;
1875         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1876
1877         if (WARN_ON(pll == NULL))
1878                 return;
1879
1880         if (WARN_ON(pll->config.crtc_mask == 0))
1881                 return;
1882
1883         DRM_DEBUG_KMS("enable %s (active %d, on? %d) for crtc %d\n",
1884                       pll->name, pll->active, pll->on,
1885                       crtc->base.base.id);
1886
1887         if (pll->active++) {
1888                 WARN_ON(!pll->on);
1889                 assert_shared_dpll_enabled(dev_priv, pll);
1890                 return;
1891         }
1892         WARN_ON(pll->on);
1893
1894         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
1895
1896         DRM_DEBUG_KMS("enabling %s\n", pll->name);
1897         pll->enable(dev_priv, pll);
1898         pll->on = true;
1899 }
1900
1901 static void intel_disable_shared_dpll(struct intel_crtc *crtc)
1902 {
1903         struct drm_device *dev = crtc->base.dev;
1904         struct drm_i915_private *dev_priv = dev->dev_private;
1905         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1906
1907         /* PCH only available on ILK+ */
1908         if (INTEL_INFO(dev)->gen < 5)
1909                 return;
1910
1911         if (pll == NULL)
1912                 return;
1913
1914         if (WARN_ON(!(pll->config.crtc_mask & (1 << drm_crtc_index(&crtc->base)))))
1915                 return;
1916
1917         DRM_DEBUG_KMS("disable %s (active %d, on? %d) for crtc %d\n",
1918                       pll->name, pll->active, pll->on,
1919                       crtc->base.base.id);
1920
1921         if (WARN_ON(pll->active == 0)) {
1922                 assert_shared_dpll_disabled(dev_priv, pll);
1923                 return;
1924         }
1925
1926         assert_shared_dpll_enabled(dev_priv, pll);
1927         WARN_ON(!pll->on);
1928         if (--pll->active)
1929                 return;
1930
1931         DRM_DEBUG_KMS("disabling %s\n", pll->name);
1932         pll->disable(dev_priv, pll);
1933         pll->on = false;
1934
1935         intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS);
1936 }
1937
1938 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1939                                            enum pipe pipe)
1940 {
1941         struct drm_device *dev = dev_priv->dev;
1942         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1943         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1944         uint32_t reg, val, pipeconf_val;
1945
1946         /* PCH only available on ILK+ */
1947         BUG_ON(!HAS_PCH_SPLIT(dev));
1948
1949         /* Make sure PCH DPLL is enabled */
1950         assert_shared_dpll_enabled(dev_priv,
1951                                    intel_crtc_to_shared_dpll(intel_crtc));
1952
1953         /* FDI must be feeding us bits for PCH ports */
1954         assert_fdi_tx_enabled(dev_priv, pipe);
1955         assert_fdi_rx_enabled(dev_priv, pipe);
1956
1957         if (HAS_PCH_CPT(dev)) {
1958                 /* Workaround: Set the timing override bit before enabling the
1959                  * pch transcoder. */
1960                 reg = TRANS_CHICKEN2(pipe);
1961                 val = I915_READ(reg);
1962                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1963                 I915_WRITE(reg, val);
1964         }
1965
1966         reg = PCH_TRANSCONF(pipe);
1967         val = I915_READ(reg);
1968         pipeconf_val = I915_READ(PIPECONF(pipe));
1969
1970         if (HAS_PCH_IBX(dev_priv->dev)) {
1971                 /*
1972                  * Make the BPC in transcoder be consistent with
1973                  * that in pipeconf reg. For HDMI we must use 8bpc
1974                  * here for both 8bpc and 12bpc.
1975                  */
1976                 val &= ~PIPECONF_BPC_MASK;
1977                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_HDMI))
1978                         val |= PIPECONF_8BPC;
1979                 else
1980                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1981         }
1982
1983         val &= ~TRANS_INTERLACE_MASK;
1984         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1985                 if (HAS_PCH_IBX(dev_priv->dev) &&
1986                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
1987                         val |= TRANS_LEGACY_INTERLACED_ILK;
1988                 else
1989                         val |= TRANS_INTERLACED;
1990         else
1991                 val |= TRANS_PROGRESSIVE;
1992
1993         I915_WRITE(reg, val | TRANS_ENABLE);
1994         if (wait_for(I915_READ(reg) & TRANS_STATE_ENABLE, 100))
1995                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1996 }
1997
1998 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1999                                       enum transcoder cpu_transcoder)
2000 {
2001         u32 val, pipeconf_val;
2002
2003         /* PCH only available on ILK+ */
2004         BUG_ON(!HAS_PCH_SPLIT(dev_priv->dev));
2005
2006         /* FDI must be feeding us bits for PCH ports */
2007         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
2008         assert_fdi_rx_enabled(dev_priv, TRANSCODER_A);
2009
2010         /* Workaround: set timing override bit. */
2011         val = I915_READ(_TRANSA_CHICKEN2);
2012         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
2013         I915_WRITE(_TRANSA_CHICKEN2, val);
2014
2015         val = TRANS_ENABLE;
2016         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
2017
2018         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
2019             PIPECONF_INTERLACED_ILK)
2020                 val |= TRANS_INTERLACED;
2021         else
2022                 val |= TRANS_PROGRESSIVE;
2023
2024         I915_WRITE(LPT_TRANSCONF, val);
2025         if (wait_for(I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE, 100))
2026                 DRM_ERROR("Failed to enable PCH transcoder\n");
2027 }
2028
2029 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
2030                                             enum pipe pipe)
2031 {
2032         struct drm_device *dev = dev_priv->dev;
2033         uint32_t reg, val;
2034
2035         /* FDI relies on the transcoder */
2036         assert_fdi_tx_disabled(dev_priv, pipe);
2037         assert_fdi_rx_disabled(dev_priv, pipe);
2038
2039         /* Ports must be off as well */
2040         assert_pch_ports_disabled(dev_priv, pipe);
2041
2042         reg = PCH_TRANSCONF(pipe);
2043         val = I915_READ(reg);
2044         val &= ~TRANS_ENABLE;
2045         I915_WRITE(reg, val);
2046         /* wait for PCH transcoder off, transcoder state */
2047         if (wait_for((I915_READ(reg) & TRANS_STATE_ENABLE) == 0, 50))
2048                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
2049
2050         if (!HAS_PCH_IBX(dev)) {
2051                 /* Workaround: Clear the timing override chicken bit again. */
2052                 reg = TRANS_CHICKEN2(pipe);
2053                 val = I915_READ(reg);
2054                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
2055                 I915_WRITE(reg, val);
2056         }
2057 }
2058
2059 static void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
2060 {
2061         u32 val;
2062
2063         val = I915_READ(LPT_TRANSCONF);
2064         val &= ~TRANS_ENABLE;
2065         I915_WRITE(LPT_TRANSCONF, val);
2066         /* wait for PCH transcoder off, transcoder state */
2067         if (wait_for((I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE) == 0, 50))
2068                 DRM_ERROR("Failed to disable PCH transcoder\n");
2069
2070         /* Workaround: clear timing override bit. */
2071         val = I915_READ(_TRANSA_CHICKEN2);
2072         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
2073         I915_WRITE(_TRANSA_CHICKEN2, val);
2074 }
2075
2076 /**
2077  * intel_enable_pipe - enable a pipe, asserting requirements
2078  * @crtc: crtc responsible for the pipe
2079  *
2080  * Enable @crtc's pipe, making sure that various hardware specific requirements
2081  * are met, if applicable, e.g. PLL enabled, LVDS pairs enabled, etc.
2082  */
2083 static void intel_enable_pipe(struct intel_crtc *crtc)
2084 {
2085         struct drm_device *dev = crtc->base.dev;
2086         struct drm_i915_private *dev_priv = dev->dev_private;
2087         enum pipe pipe = crtc->pipe;
2088         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
2089                                                                       pipe);
2090         enum pipe pch_transcoder;
2091         int reg;
2092         u32 val;
2093
2094         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
2095
2096         assert_planes_disabled(dev_priv, pipe);
2097         assert_cursor_disabled(dev_priv, pipe);
2098         assert_sprites_disabled(dev_priv, pipe);
2099
2100         if (HAS_PCH_LPT(dev_priv->dev))
2101                 pch_transcoder = TRANSCODER_A;
2102         else
2103                 pch_transcoder = pipe;
2104
2105         /*
2106          * A pipe without a PLL won't actually be able to drive bits from
2107          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
2108          * need the check.
2109          */
2110         if (HAS_GMCH_DISPLAY(dev_priv->dev))
2111                 if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DSI))
2112                         assert_dsi_pll_enabled(dev_priv);
2113                 else
2114                         assert_pll_enabled(dev_priv, pipe);
2115         else {
2116                 if (crtc->config->has_pch_encoder) {
2117                         /* if driving the PCH, we need FDI enabled */
2118                         assert_fdi_rx_pll_enabled(dev_priv, pch_transcoder);
2119                         assert_fdi_tx_pll_enabled(dev_priv,
2120                                                   (enum pipe) cpu_transcoder);
2121                 }
2122                 /* FIXME: assert CPU port conditions for SNB+ */
2123         }
2124
2125         reg = PIPECONF(cpu_transcoder);
2126         val = I915_READ(reg);
2127         if (val & PIPECONF_ENABLE) {
2128                 WARN_ON(!((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
2129                           (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE)));
2130                 return;
2131         }
2132
2133         I915_WRITE(reg, val | PIPECONF_ENABLE);
2134         POSTING_READ(reg);
2135 }
2136
2137 /**
2138  * intel_disable_pipe - disable a pipe, asserting requirements
2139  * @crtc: crtc whose pipes is to be disabled
2140  *
2141  * Disable the pipe of @crtc, making sure that various hardware
2142  * specific requirements are met, if applicable, e.g. plane
2143  * disabled, panel fitter off, etc.
2144  *
2145  * Will wait until the pipe has shut down before returning.
2146  */
2147 static void intel_disable_pipe(struct intel_crtc *crtc)
2148 {
2149         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
2150         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
2151         enum pipe pipe = crtc->pipe;
2152         int reg;
2153         u32 val;
2154
2155         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
2156
2157         /*
2158          * Make sure planes won't keep trying to pump pixels to us,
2159          * or we might hang the display.
2160          */
2161         assert_planes_disabled(dev_priv, pipe);
2162         assert_cursor_disabled(dev_priv, pipe);
2163         assert_sprites_disabled(dev_priv, pipe);
2164
2165         reg = PIPECONF(cpu_transcoder);
2166         val = I915_READ(reg);
2167         if ((val & PIPECONF_ENABLE) == 0)
2168                 return;
2169
2170         /*
2171          * Double wide has implications for planes
2172          * so best keep it disabled when not needed.
2173          */
2174         if (crtc->config->double_wide)
2175                 val &= ~PIPECONF_DOUBLE_WIDE;
2176
2177         /* Don't disable pipe or pipe PLLs if needed */
2178         if (!(pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) &&
2179             !(pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
2180                 val &= ~PIPECONF_ENABLE;
2181
2182         I915_WRITE(reg, val);
2183         if ((val & PIPECONF_ENABLE) == 0)
2184                 intel_wait_for_pipe_off(crtc);
2185 }
2186
2187 static bool need_vtd_wa(struct drm_device *dev)
2188 {
2189 #ifdef CONFIG_INTEL_IOMMU
2190         if (INTEL_INFO(dev)->gen >= 6 && intel_iommu_gfx_mapped)
2191                 return true;
2192 #endif
2193         return false;
2194 }
2195
2196 unsigned int
2197 intel_tile_height(struct drm_device *dev, uint32_t pixel_format,
2198                   uint64_t fb_format_modifier)
2199 {
2200         unsigned int tile_height;
2201         uint32_t pixel_bytes;
2202
2203         switch (fb_format_modifier) {
2204         case DRM_FORMAT_MOD_NONE:
2205                 tile_height = 1;
2206                 break;
2207         case I915_FORMAT_MOD_X_TILED:
2208                 tile_height = IS_GEN2(dev) ? 16 : 8;
2209                 break;
2210         case I915_FORMAT_MOD_Y_TILED:
2211                 tile_height = 32;
2212                 break;
2213         case I915_FORMAT_MOD_Yf_TILED:
2214                 pixel_bytes = drm_format_plane_cpp(pixel_format, 0);
2215                 switch (pixel_bytes) {
2216                 default:
2217                 case 1:
2218                         tile_height = 64;
2219                         break;
2220                 case 2:
2221                 case 4:
2222                         tile_height = 32;
2223                         break;
2224                 case 8:
2225                         tile_height = 16;
2226                         break;
2227                 case 16:
2228                         WARN_ONCE(1,
2229                                   "128-bit pixels are not supported for display!");
2230                         tile_height = 16;
2231                         break;
2232                 }
2233                 break;
2234         default:
2235                 MISSING_CASE(fb_format_modifier);
2236                 tile_height = 1;
2237                 break;
2238         }
2239
2240         return tile_height;
2241 }
2242
2243 unsigned int
2244 intel_fb_align_height(struct drm_device *dev, unsigned int height,
2245                       uint32_t pixel_format, uint64_t fb_format_modifier)
2246 {
2247         return ALIGN(height, intel_tile_height(dev, pixel_format,
2248                                                fb_format_modifier));
2249 }
2250
2251 static int
2252 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view, struct drm_framebuffer *fb,
2253                         const struct drm_plane_state *plane_state)
2254 {
2255         struct intel_rotation_info *info = &view->rotation_info;
2256         unsigned int tile_height, tile_pitch;
2257
2258         *view = i915_ggtt_view_normal;
2259
2260         if (!plane_state)
2261                 return 0;
2262
2263         if (!intel_rotation_90_or_270(plane_state->rotation))
2264                 return 0;
2265
2266         *view = i915_ggtt_view_rotated;
2267
2268         info->height = fb->height;
2269         info->pixel_format = fb->pixel_format;
2270         info->pitch = fb->pitches[0];
2271         info->fb_modifier = fb->modifier[0];
2272
2273         tile_height = intel_tile_height(fb->dev, fb->pixel_format,
2274                                         fb->modifier[0]);
2275         tile_pitch = PAGE_SIZE / tile_height;
2276         info->width_pages = DIV_ROUND_UP(fb->pitches[0], tile_pitch);
2277         info->height_pages = DIV_ROUND_UP(fb->height, tile_height);
2278         info->size = info->width_pages * info->height_pages * PAGE_SIZE;
2279
2280         return 0;
2281 }
2282
2283 static unsigned int intel_linear_alignment(struct drm_i915_private *dev_priv)
2284 {
2285         if (INTEL_INFO(dev_priv)->gen >= 9)
2286                 return 256 * 1024;
2287         else if (IS_BROADWATER(dev_priv) || IS_CRESTLINE(dev_priv) ||
2288                  IS_VALLEYVIEW(dev_priv))
2289                 return 128 * 1024;
2290         else if (INTEL_INFO(dev_priv)->gen >= 4)
2291                 return 4 * 1024;
2292         else
2293                 return 0;
2294 }
2295
2296 int
2297 intel_pin_and_fence_fb_obj(struct drm_plane *plane,
2298                            struct drm_framebuffer *fb,
2299                            const struct drm_plane_state *plane_state,
2300                            struct intel_engine_cs *pipelined,
2301                            struct drm_i915_gem_request **pipelined_request)
2302 {
2303         struct drm_device *dev = fb->dev;
2304         struct drm_i915_private *dev_priv = dev->dev_private;
2305         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2306         struct i915_ggtt_view view;
2307         u32 alignment;
2308         int ret;
2309
2310         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2311
2312         switch (fb->modifier[0]) {
2313         case DRM_FORMAT_MOD_NONE:
2314                 alignment = intel_linear_alignment(dev_priv);
2315                 break;
2316         case I915_FORMAT_MOD_X_TILED:
2317                 if (INTEL_INFO(dev)->gen >= 9)
2318                         alignment = 256 * 1024;
2319                 else {
2320                         /* pin() will align the object as required by fence */
2321                         alignment = 0;
2322                 }
2323                 break;
2324         case I915_FORMAT_MOD_Y_TILED:
2325         case I915_FORMAT_MOD_Yf_TILED:
2326                 if (WARN_ONCE(INTEL_INFO(dev)->gen < 9,
2327                           "Y tiling bo slipped through, driver bug!\n"))
2328                         return -EINVAL;
2329                 alignment = 1 * 1024 * 1024;
2330                 break;
2331         default:
2332                 MISSING_CASE(fb->modifier[0]);
2333                 return -EINVAL;
2334         }
2335
2336         ret = intel_fill_fb_ggtt_view(&view, fb, plane_state);
2337         if (ret)
2338                 return ret;
2339
2340         /* Note that the w/a also requires 64 PTE of padding following the
2341          * bo. We currently fill all unused PTE with the shadow page and so
2342          * we should always have valid PTE following the scanout preventing
2343          * the VT-d warning.
2344          */
2345         if (need_vtd_wa(dev) && alignment < 256 * 1024)
2346                 alignment = 256 * 1024;
2347
2348         /*
2349          * Global gtt pte registers are special registers which actually forward
2350          * writes to a chunk of system memory. Which means that there is no risk
2351          * that the register values disappear as soon as we call
2352          * intel_runtime_pm_put(), so it is correct to wrap only the
2353          * pin/unpin/fence and not more.
2354          */
2355         intel_runtime_pm_get(dev_priv);
2356
2357         dev_priv->mm.interruptible = false;
2358         ret = i915_gem_object_pin_to_display_plane(obj, alignment, pipelined,
2359                                                    pipelined_request, &view);
2360         if (ret)
2361                 goto err_interruptible;
2362
2363         /* Install a fence for tiled scan-out. Pre-i965 always needs a
2364          * fence, whereas 965+ only requires a fence if using
2365          * framebuffer compression.  For simplicity, we always install
2366          * a fence as the cost is not that onerous.
2367          */
2368         ret = i915_gem_object_get_fence(obj);
2369         if (ret == -EDEADLK) {
2370                 /*
2371                  * -EDEADLK means there are no free fences
2372                  * no pending flips.
2373                  *
2374                  * This is propagated to atomic, but it uses
2375                  * -EDEADLK to force a locking recovery, so
2376                  * change the returned error to -EBUSY.
2377                  */
2378                 ret = -EBUSY;
2379                 goto err_unpin;
2380         } else if (ret)
2381                 goto err_unpin;
2382
2383         i915_gem_object_pin_fence(obj);
2384
2385         dev_priv->mm.interruptible = true;
2386         intel_runtime_pm_put(dev_priv);
2387         return 0;
2388
2389 err_unpin:
2390         i915_gem_object_unpin_from_display_plane(obj, &view);
2391 err_interruptible:
2392         dev_priv->mm.interruptible = true;
2393         intel_runtime_pm_put(dev_priv);
2394         return ret;
2395 }
2396
2397 static void intel_unpin_fb_obj(struct drm_framebuffer *fb,
2398                                const struct drm_plane_state *plane_state)
2399 {
2400         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2401         struct i915_ggtt_view view;
2402         int ret;
2403
2404         WARN_ON(!mutex_is_locked(&obj->base.dev->struct_mutex));
2405
2406         ret = intel_fill_fb_ggtt_view(&view, fb, plane_state);
2407         WARN_ONCE(ret, "Couldn't get view from plane state!");
2408
2409         i915_gem_object_unpin_fence(obj);
2410         i915_gem_object_unpin_from_display_plane(obj, &view);
2411 }
2412
2413 /* Computes the linear offset to the base tile and adjusts x, y. bytes per pixel
2414  * is assumed to be a power-of-two. */
2415 unsigned long intel_gen4_compute_page_offset(struct drm_i915_private *dev_priv,
2416                                              int *x, int *y,
2417                                              unsigned int tiling_mode,
2418                                              unsigned int cpp,
2419                                              unsigned int pitch)
2420 {
2421         if (tiling_mode != I915_TILING_NONE) {
2422                 unsigned int tile_rows, tiles;
2423
2424                 tile_rows = *y / 8;
2425                 *y %= 8;
2426
2427                 tiles = *x / (512/cpp);
2428                 *x %= 512/cpp;
2429
2430                 return tile_rows * pitch * 8 + tiles * 4096;
2431         } else {
2432                 unsigned int alignment = intel_linear_alignment(dev_priv) - 1;
2433                 unsigned int offset;
2434
2435                 offset = *y * pitch + *x * cpp;
2436                 *y = (offset & alignment) / pitch;
2437                 *x = ((offset & alignment) - *y * pitch) / cpp;
2438                 return offset & ~alignment;
2439         }
2440 }
2441
2442 static int i9xx_format_to_fourcc(int format)
2443 {
2444         switch (format) {
2445         case DISPPLANE_8BPP:
2446                 return DRM_FORMAT_C8;
2447         case DISPPLANE_BGRX555:
2448                 return DRM_FORMAT_XRGB1555;
2449         case DISPPLANE_BGRX565:
2450                 return DRM_FORMAT_RGB565;
2451         default:
2452         case DISPPLANE_BGRX888:
2453                 return DRM_FORMAT_XRGB8888;
2454         case DISPPLANE_RGBX888:
2455                 return DRM_FORMAT_XBGR8888;
2456         case DISPPLANE_BGRX101010:
2457                 return DRM_FORMAT_XRGB2101010;
2458         case DISPPLANE_RGBX101010:
2459                 return DRM_FORMAT_XBGR2101010;
2460         }
2461 }
2462
2463 static int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2464 {
2465         switch (format) {
2466         case PLANE_CTL_FORMAT_RGB_565:
2467                 return DRM_FORMAT_RGB565;
2468         default:
2469         case PLANE_CTL_FORMAT_XRGB_8888:
2470                 if (rgb_order) {
2471                         if (alpha)
2472                                 return DRM_FORMAT_ABGR8888;
2473                         else
2474                                 return DRM_FORMAT_XBGR8888;
2475                 } else {
2476                         if (alpha)
2477                                 return DRM_FORMAT_ARGB8888;
2478                         else
2479                                 return DRM_FORMAT_XRGB8888;
2480                 }
2481         case PLANE_CTL_FORMAT_XRGB_2101010:
2482                 if (rgb_order)
2483                         return DRM_FORMAT_XBGR2101010;
2484                 else
2485                         return DRM_FORMAT_XRGB2101010;
2486         }
2487 }
2488
2489 static bool
2490 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2491                               struct intel_initial_plane_config *plane_config)
2492 {
2493         struct drm_device *dev = crtc->base.dev;
2494         struct drm_i915_gem_object *obj = NULL;
2495         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2496         struct drm_framebuffer *fb = &plane_config->fb->base;
2497         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2498         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2499                                     PAGE_SIZE);
2500
2501         size_aligned -= base_aligned;
2502
2503         if (plane_config->size == 0)
2504                 return false;
2505
2506         obj = i915_gem_object_create_stolen_for_preallocated(dev,
2507                                                              base_aligned,
2508                                                              base_aligned,
2509                                                              size_aligned);
2510         if (!obj)
2511                 return false;
2512
2513         obj->tiling_mode = plane_config->tiling;
2514         if (obj->tiling_mode == I915_TILING_X)
2515                 obj->stride = fb->pitches[0];
2516
2517         mode_cmd.pixel_format = fb->pixel_format;
2518         mode_cmd.width = fb->width;
2519         mode_cmd.height = fb->height;
2520         mode_cmd.pitches[0] = fb->pitches[0];
2521         mode_cmd.modifier[0] = fb->modifier[0];
2522         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2523
2524         mutex_lock(&dev->struct_mutex);
2525         if (intel_framebuffer_init(dev, to_intel_framebuffer(fb),
2526                                    &mode_cmd, obj)) {
2527                 DRM_DEBUG_KMS("intel fb init failed\n");
2528                 goto out_unref_obj;
2529         }
2530         mutex_unlock(&dev->struct_mutex);
2531
2532         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2533         return true;
2534
2535 out_unref_obj:
2536         drm_gem_object_unreference(&obj->base);
2537         mutex_unlock(&dev->struct_mutex);
2538         return false;
2539 }
2540
2541 /* Update plane->state->fb to match plane->fb after driver-internal updates */
2542 static void
2543 update_state_fb(struct drm_plane *plane)
2544 {
2545         if (plane->fb == plane->state->fb)
2546                 return;
2547
2548         if (plane->state->fb)
2549                 drm_framebuffer_unreference(plane->state->fb);
2550         plane->state->fb = plane->fb;
2551         if (plane->state->fb)
2552                 drm_framebuffer_reference(plane->state->fb);
2553 }
2554
2555 static void
2556 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2557                              struct intel_initial_plane_config *plane_config)
2558 {
2559         struct drm_device *dev = intel_crtc->base.dev;
2560         struct drm_i915_private *dev_priv = dev->dev_private;
2561         struct drm_crtc *c;
2562         struct intel_crtc *i;
2563         struct drm_i915_gem_object *obj;
2564         struct drm_plane *primary = intel_crtc->base.primary;
2565         struct drm_plane_state *plane_state = primary->state;
2566         struct drm_framebuffer *fb;
2567
2568         if (!plane_config->fb)
2569                 return;
2570
2571         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2572                 fb = &plane_config->fb->base;
2573                 goto valid_fb;
2574         }
2575
2576         kfree(plane_config->fb);
2577
2578         /*
2579          * Failed to alloc the obj, check to see if we should share
2580          * an fb with another CRTC instead
2581          */
2582         for_each_crtc(dev, c) {
2583                 i = to_intel_crtc(c);
2584
2585                 if (c == &intel_crtc->base)
2586                         continue;
2587
2588                 if (!i->active)
2589                         continue;
2590
2591                 fb = c->primary->fb;
2592                 if (!fb)
2593                         continue;
2594
2595                 obj = intel_fb_obj(fb);
2596                 if (i915_gem_obj_ggtt_offset(obj) == plane_config->base) {
2597                         drm_framebuffer_reference(fb);
2598                         goto valid_fb;
2599                 }
2600         }
2601
2602         return;
2603
2604 valid_fb:
2605         plane_state->src_x = plane_state->src_y = 0;
2606         plane_state->src_w = fb->width << 16;
2607         plane_state->src_h = fb->height << 16;
2608
2609         plane_state->crtc_x = plane_state->src_y = 0;
2610         plane_state->crtc_w = fb->width;
2611         plane_state->crtc_h = fb->height;
2612
2613         obj = intel_fb_obj(fb);
2614         if (obj->tiling_mode != I915_TILING_NONE)
2615                 dev_priv->preserve_bios_swizzle = true;
2616
2617         drm_framebuffer_reference(fb);
2618         primary->fb = primary->state->fb = fb;
2619         primary->crtc = primary->state->crtc = &intel_crtc->base;
2620         intel_crtc->base.state->plane_mask |= (1 << drm_plane_index(primary));
2621         obj->frontbuffer_bits |= to_intel_plane(primary)->frontbuffer_bit;
2622 }
2623
2624 static void i9xx_update_primary_plane(struct drm_crtc *crtc,
2625                                       struct drm_framebuffer *fb,
2626                                       int x, int y)
2627 {
2628         struct drm_device *dev = crtc->dev;
2629         struct drm_i915_private *dev_priv = dev->dev_private;
2630         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2631         struct drm_plane *primary = crtc->primary;
2632         bool visible = to_intel_plane_state(primary->state)->visible;
2633         struct drm_i915_gem_object *obj;
2634         int plane = intel_crtc->plane;
2635         unsigned long linear_offset;
2636         u32 dspcntr;
2637         u32 reg = DSPCNTR(plane);
2638         int pixel_size;
2639
2640         if (!visible || !fb) {
2641                 I915_WRITE(reg, 0);
2642                 if (INTEL_INFO(dev)->gen >= 4)
2643                         I915_WRITE(DSPSURF(plane), 0);
2644                 else
2645                         I915_WRITE(DSPADDR(plane), 0);
2646                 POSTING_READ(reg);
2647                 return;
2648         }
2649
2650         obj = intel_fb_obj(fb);
2651         if (WARN_ON(obj == NULL))
2652                 return;
2653
2654         pixel_size = drm_format_plane_cpp(fb->pixel_format, 0);
2655
2656         dspcntr = DISPPLANE_GAMMA_ENABLE;
2657
2658         dspcntr |= DISPLAY_PLANE_ENABLE;
2659
2660         if (INTEL_INFO(dev)->gen < 4) {
2661                 if (intel_crtc->pipe == PIPE_B)
2662                         dspcntr |= DISPPLANE_SEL_PIPE_B;
2663
2664                 /* pipesrc and dspsize control the size that is scaled from,
2665                  * which should always be the user's requested size.
2666                  */
2667                 I915_WRITE(DSPSIZE(plane),
2668                            ((intel_crtc->config->pipe_src_h - 1) << 16) |
2669                            (intel_crtc->config->pipe_src_w - 1));
2670                 I915_WRITE(DSPPOS(plane), 0);
2671         } else if (IS_CHERRYVIEW(dev) && plane == PLANE_B) {
2672                 I915_WRITE(PRIMSIZE(plane),
2673                            ((intel_crtc->config->pipe_src_h - 1) << 16) |
2674                            (intel_crtc->config->pipe_src_w - 1));
2675                 I915_WRITE(PRIMPOS(plane), 0);
2676                 I915_WRITE(PRIMCNSTALPHA(plane), 0);
2677         }
2678
2679         switch (fb->pixel_format) {
2680         case DRM_FORMAT_C8:
2681                 dspcntr |= DISPPLANE_8BPP;
2682                 break;
2683         case DRM_FORMAT_XRGB1555:
2684                 dspcntr |= DISPPLANE_BGRX555;
2685                 break;
2686         case DRM_FORMAT_RGB565:
2687                 dspcntr |= DISPPLANE_BGRX565;
2688                 break;
2689         case DRM_FORMAT_XRGB8888:
2690                 dspcntr |= DISPPLANE_BGRX888;
2691                 break;
2692         case DRM_FORMAT_XBGR8888:
2693                 dspcntr |= DISPPLANE_RGBX888;
2694                 break;
2695         case DRM_FORMAT_XRGB2101010:
2696                 dspcntr |= DISPPLANE_BGRX101010;
2697                 break;
2698         case DRM_FORMAT_XBGR2101010:
2699                 dspcntr |= DISPPLANE_RGBX101010;
2700                 break;
2701         default:
2702                 BUG();
2703         }
2704
2705         if (INTEL_INFO(dev)->gen >= 4 &&
2706             obj->tiling_mode != I915_TILING_NONE)
2707                 dspcntr |= DISPPLANE_TILED;
2708
2709         if (IS_G4X(dev))
2710                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2711
2712         linear_offset = y * fb->pitches[0] + x * pixel_size;
2713
2714         if (INTEL_INFO(dev)->gen >= 4) {
2715                 intel_crtc->dspaddr_offset =
2716                         intel_gen4_compute_page_offset(dev_priv,
2717                                                        &x, &y, obj->tiling_mode,
2718                                                        pixel_size,
2719                                                        fb->pitches[0]);
2720                 linear_offset -= intel_crtc->dspaddr_offset;
2721         } else {
2722                 intel_crtc->dspaddr_offset = linear_offset;
2723         }
2724
2725         if (crtc->primary->state->rotation == BIT(DRM_ROTATE_180)) {
2726                 dspcntr |= DISPPLANE_ROTATE_180;
2727
2728                 x += (intel_crtc->config->pipe_src_w - 1);
2729                 y += (intel_crtc->config->pipe_src_h - 1);
2730
2731                 /* Finding the last pixel of the last line of the display
2732                 data and adding to linear_offset*/
2733                 linear_offset +=
2734                         (intel_crtc->config->pipe_src_h - 1) * fb->pitches[0] +
2735                         (intel_crtc->config->pipe_src_w - 1) * pixel_size;
2736         }
2737
2738         I915_WRITE(reg, dspcntr);
2739
2740         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2741         if (INTEL_INFO(dev)->gen >= 4) {
2742                 I915_WRITE(DSPSURF(plane),
2743                            i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2744                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2745                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2746         } else
2747                 I915_WRITE(DSPADDR(plane), i915_gem_obj_ggtt_offset(obj) + linear_offset);
2748         POSTING_READ(reg);
2749 }
2750
2751 static void ironlake_update_primary_plane(struct drm_crtc *crtc,
2752                                           struct drm_framebuffer *fb,
2753                                           int x, int y)
2754 {
2755         struct drm_device *dev = crtc->dev;
2756         struct drm_i915_private *dev_priv = dev->dev_private;
2757         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2758         struct drm_plane *primary = crtc->primary;
2759         bool visible = to_intel_plane_state(primary->state)->visible;
2760         struct drm_i915_gem_object *obj;
2761         int plane = intel_crtc->plane;
2762         unsigned long linear_offset;
2763         u32 dspcntr;
2764         u32 reg = DSPCNTR(plane);
2765         int pixel_size;
2766
2767         if (!visible || !fb) {
2768                 I915_WRITE(reg, 0);
2769                 I915_WRITE(DSPSURF(plane), 0);
2770                 POSTING_READ(reg);
2771                 return;
2772         }
2773
2774         obj = intel_fb_obj(fb);
2775         if (WARN_ON(obj == NULL))
2776                 return;
2777
2778         pixel_size = drm_format_plane_cpp(fb->pixel_format, 0);
2779
2780         dspcntr = DISPPLANE_GAMMA_ENABLE;
2781
2782         dspcntr |= DISPLAY_PLANE_ENABLE;
2783
2784         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
2785                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
2786
2787         switch (fb->pixel_format) {
2788         case DRM_FORMAT_C8:
2789                 dspcntr |= DISPPLANE_8BPP;
2790                 break;
2791         case DRM_FORMAT_RGB565:
2792                 dspcntr |= DISPPLANE_BGRX565;
2793                 break;
2794         case DRM_FORMAT_XRGB8888:
2795                 dspcntr |= DISPPLANE_BGRX888;
2796                 break;
2797         case DRM_FORMAT_XBGR8888:
2798                 dspcntr |= DISPPLANE_RGBX888;
2799                 break;
2800         case DRM_FORMAT_XRGB2101010:
2801                 dspcntr |= DISPPLANE_BGRX101010;
2802                 break;
2803         case DRM_FORMAT_XBGR2101010:
2804                 dspcntr |= DISPPLANE_RGBX101010;
2805                 break;
2806         default:
2807                 BUG();
2808         }
2809
2810         if (obj->tiling_mode != I915_TILING_NONE)
2811                 dspcntr |= DISPPLANE_TILED;
2812
2813         if (!IS_HASWELL(dev) && !IS_BROADWELL(dev))
2814                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2815
2816         linear_offset = y * fb->pitches[0] + x * pixel_size;
2817         intel_crtc->dspaddr_offset =
2818                 intel_gen4_compute_page_offset(dev_priv,
2819                                                &x, &y, obj->tiling_mode,
2820                                                pixel_size,
2821                                                fb->pitches[0]);
2822         linear_offset -= intel_crtc->dspaddr_offset;
2823         if (crtc->primary->state->rotation == BIT(DRM_ROTATE_180)) {
2824                 dspcntr |= DISPPLANE_ROTATE_180;
2825
2826                 if (!IS_HASWELL(dev) && !IS_BROADWELL(dev)) {
2827                         x += (intel_crtc->config->pipe_src_w - 1);
2828                         y += (intel_crtc->config->pipe_src_h - 1);
2829
2830                         /* Finding the last pixel of the last line of the display
2831                         data and adding to linear_offset*/
2832                         linear_offset +=
2833                                 (intel_crtc->config->pipe_src_h - 1) * fb->pitches[0] +
2834                                 (intel_crtc->config->pipe_src_w - 1) * pixel_size;
2835                 }
2836         }
2837
2838         I915_WRITE(reg, dspcntr);
2839
2840         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2841         I915_WRITE(DSPSURF(plane),
2842                    i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2843         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
2844                 I915_WRITE(DSPOFFSET(plane), (y << 16) | x);
2845         } else {
2846                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2847                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2848         }
2849         POSTING_READ(reg);
2850 }
2851
2852 u32 intel_fb_stride_alignment(struct drm_device *dev, uint64_t fb_modifier,
2853                               uint32_t pixel_format)
2854 {
2855         u32 bits_per_pixel = drm_format_plane_cpp(pixel_format, 0) * 8;
2856
2857         /*
2858          * The stride is either expressed as a multiple of 64 bytes
2859          * chunks for linear buffers or in number of tiles for tiled
2860          * buffers.
2861          */
2862         switch (fb_modifier) {
2863         case DRM_FORMAT_MOD_NONE:
2864                 return 64;
2865         case I915_FORMAT_MOD_X_TILED:
2866                 if (INTEL_INFO(dev)->gen == 2)
2867                         return 128;
2868                 return 512;
2869         case I915_FORMAT_MOD_Y_TILED:
2870                 /* No need to check for old gens and Y tiling since this is
2871                  * about the display engine and those will be blocked before
2872                  * we get here.
2873                  */
2874                 return 128;
2875         case I915_FORMAT_MOD_Yf_TILED:
2876                 if (bits_per_pixel == 8)
2877                         return 64;
2878                 else
2879                         return 128;
2880         default:
2881                 MISSING_CASE(fb_modifier);
2882                 return 64;
2883         }
2884 }
2885
2886 unsigned long intel_plane_obj_offset(struct intel_plane *intel_plane,
2887                                      struct drm_i915_gem_object *obj)
2888 {
2889         const struct i915_ggtt_view *view = &i915_ggtt_view_normal;
2890
2891         if (intel_rotation_90_or_270(intel_plane->base.state->rotation))
2892                 view = &i915_ggtt_view_rotated;
2893
2894         return i915_gem_obj_ggtt_offset_view(obj, view);
2895 }
2896
2897 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
2898 {
2899         struct drm_device *dev = intel_crtc->base.dev;
2900         struct drm_i915_private *dev_priv = dev->dev_private;
2901
2902         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
2903         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
2904         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
2905 }
2906
2907 /*
2908  * This function detaches (aka. unbinds) unused scalers in hardware
2909  */
2910 static void skl_detach_scalers(struct intel_crtc *intel_crtc)
2911 {
2912         struct intel_crtc_scaler_state *scaler_state;
2913         int i;
2914
2915         scaler_state = &intel_crtc->config->scaler_state;
2916
2917         /* loop through and disable scalers that aren't in use */
2918         for (i = 0; i < intel_crtc->num_scalers; i++) {
2919                 if (!scaler_state->scalers[i].in_use)
2920                         skl_detach_scaler(intel_crtc, i);
2921         }
2922 }
2923
2924 u32 skl_plane_ctl_format(uint32_t pixel_format)
2925 {
2926         switch (pixel_format) {
2927         case DRM_FORMAT_C8:
2928                 return PLANE_CTL_FORMAT_INDEXED;
2929         case DRM_FORMAT_RGB565:
2930                 return PLANE_CTL_FORMAT_RGB_565;
2931         case DRM_FORMAT_XBGR8888:
2932                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
2933         case DRM_FORMAT_XRGB8888:
2934                 return PLANE_CTL_FORMAT_XRGB_8888;
2935         /*
2936          * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
2937          * to be already pre-multiplied. We need to add a knob (or a different
2938          * DRM_FORMAT) for user-space to configure that.
2939          */
2940         case DRM_FORMAT_ABGR8888:
2941                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX |
2942                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
2943         case DRM_FORMAT_ARGB8888:
2944                 return PLANE_CTL_FORMAT_XRGB_8888 |
2945                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
2946         case DRM_FORMAT_XRGB2101010:
2947                 return PLANE_CTL_FORMAT_XRGB_2101010;
2948         case DRM_FORMAT_XBGR2101010:
2949                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
2950         case DRM_FORMAT_YUYV:
2951                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
2952         case DRM_FORMAT_YVYU:
2953                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
2954         case DRM_FORMAT_UYVY:
2955                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
2956         case DRM_FORMAT_VYUY:
2957                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
2958         default:
2959                 MISSING_CASE(pixel_format);
2960         }
2961
2962         return 0;
2963 }
2964
2965 u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
2966 {
2967         switch (fb_modifier) {
2968         case DRM_FORMAT_MOD_NONE:
2969                 break;
2970         case I915_FORMAT_MOD_X_TILED:
2971                 return PLANE_CTL_TILED_X;
2972         case I915_FORMAT_MOD_Y_TILED:
2973                 return PLANE_CTL_TILED_Y;
2974         case I915_FORMAT_MOD_Yf_TILED:
2975                 return PLANE_CTL_TILED_YF;
2976         default:
2977                 MISSING_CASE(fb_modifier);
2978         }
2979
2980         return 0;
2981 }
2982
2983 u32 skl_plane_ctl_rotation(unsigned int rotation)
2984 {
2985         switch (rotation) {
2986         case BIT(DRM_ROTATE_0):
2987                 break;
2988         /*
2989          * DRM_ROTATE_ is counter clockwise to stay compatible with Xrandr
2990          * while i915 HW rotation is clockwise, thats why this swapping.
2991          */
2992         case BIT(DRM_ROTATE_90):
2993                 return PLANE_CTL_ROTATE_270;
2994         case BIT(DRM_ROTATE_180):
2995                 return PLANE_CTL_ROTATE_180;
2996         case BIT(DRM_ROTATE_270):
2997                 return PLANE_CTL_ROTATE_90;
2998         default:
2999                 MISSING_CASE(rotation);
3000         }
3001
3002         return 0;
3003 }
3004
3005 static void skylake_update_primary_plane(struct drm_crtc *crtc,
3006                                          struct drm_framebuffer *fb,
3007                                          int x, int y)
3008 {
3009         struct drm_device *dev = crtc->dev;
3010         struct drm_i915_private *dev_priv = dev->dev_private;
3011         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3012         struct drm_plane *plane = crtc->primary;
3013         bool visible = to_intel_plane_state(plane->state)->visible;
3014         struct drm_i915_gem_object *obj;
3015         int pipe = intel_crtc->pipe;
3016         u32 plane_ctl, stride_div, stride;
3017         u32 tile_height, plane_offset, plane_size;
3018         unsigned int rotation;
3019         int x_offset, y_offset;
3020         unsigned long surf_addr;
3021         struct intel_crtc_state *crtc_state = intel_crtc->config;
3022         struct intel_plane_state *plane_state;
3023         int src_x = 0, src_y = 0, src_w = 0, src_h = 0;
3024         int dst_x = 0, dst_y = 0, dst_w = 0, dst_h = 0;
3025         int scaler_id = -1;
3026
3027         plane_state = to_intel_plane_state(plane->state);
3028
3029         if (!visible || !fb) {
3030                 I915_WRITE(PLANE_CTL(pipe, 0), 0);
3031                 I915_WRITE(PLANE_SURF(pipe, 0), 0);
3032                 POSTING_READ(PLANE_CTL(pipe, 0));
3033                 return;
3034         }
3035
3036         plane_ctl = PLANE_CTL_ENABLE |
3037                     PLANE_CTL_PIPE_GAMMA_ENABLE |
3038                     PLANE_CTL_PIPE_CSC_ENABLE;
3039
3040         plane_ctl |= skl_plane_ctl_format(fb->pixel_format);
3041         plane_ctl |= skl_plane_ctl_tiling(fb->modifier[0]);
3042         plane_ctl |= PLANE_CTL_PLANE_GAMMA_DISABLE;
3043
3044         rotation = plane->state->rotation;
3045         plane_ctl |= skl_plane_ctl_rotation(rotation);
3046
3047         obj = intel_fb_obj(fb);
3048         stride_div = intel_fb_stride_alignment(dev, fb->modifier[0],
3049                                                fb->pixel_format);
3050         surf_addr = intel_plane_obj_offset(to_intel_plane(plane), obj);
3051
3052         /*
3053          * FIXME: intel_plane_state->src, dst aren't set when transitional
3054          * update_plane helpers are called from legacy paths.
3055          * Once full atomic crtc is available, below check can be avoided.
3056          */
3057         if (drm_rect_width(&plane_state->src)) {
3058                 scaler_id = plane_state->scaler_id;
3059                 src_x = plane_state->src.x1 >> 16;
3060                 src_y = plane_state->src.y1 >> 16;
3061                 src_w = drm_rect_width(&plane_state->src) >> 16;
3062                 src_h = drm_rect_height(&plane_state->src) >> 16;
3063                 dst_x = plane_state->dst.x1;
3064                 dst_y = plane_state->dst.y1;
3065                 dst_w = drm_rect_width(&plane_state->dst);
3066                 dst_h = drm_rect_height(&plane_state->dst);
3067
3068                 WARN_ON(x != src_x || y != src_y);
3069         } else {
3070                 src_w = intel_crtc->config->pipe_src_w;
3071                 src_h = intel_crtc->config->pipe_src_h;
3072         }
3073
3074         if (intel_rotation_90_or_270(rotation)) {
3075                 /* stride = Surface height in tiles */
3076                 tile_height = intel_tile_height(dev, fb->pixel_format,
3077                                                 fb->modifier[0]);
3078                 stride = DIV_ROUND_UP(fb->height, tile_height);
3079                 x_offset = stride * tile_height - y - src_h;
3080                 y_offset = x;
3081                 plane_size = (src_w - 1) << 16 | (src_h - 1);
3082         } else {
3083                 stride = fb->pitches[0] / stride_div;
3084                 x_offset = x;
3085                 y_offset = y;
3086                 plane_size = (src_h - 1) << 16 | (src_w - 1);
3087         }
3088         plane_offset = y_offset << 16 | x_offset;
3089
3090         I915_WRITE(PLANE_CTL(pipe, 0), plane_ctl);
3091         I915_WRITE(PLANE_OFFSET(pipe, 0), plane_offset);
3092         I915_WRITE(PLANE_SIZE(pipe, 0), plane_size);
3093         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
3094
3095         if (scaler_id >= 0) {
3096                 uint32_t ps_ctrl = 0;
3097
3098                 WARN_ON(!dst_w || !dst_h);
3099                 ps_ctrl = PS_SCALER_EN | PS_PLANE_SEL(0) |
3100                         crtc_state->scaler_state.scalers[scaler_id].mode;
3101                 I915_WRITE(SKL_PS_CTRL(pipe, scaler_id), ps_ctrl);
3102                 I915_WRITE(SKL_PS_PWR_GATE(pipe, scaler_id), 0);
3103                 I915_WRITE(SKL_PS_WIN_POS(pipe, scaler_id), (dst_x << 16) | dst_y);
3104                 I915_WRITE(SKL_PS_WIN_SZ(pipe, scaler_id), (dst_w << 16) | dst_h);
3105                 I915_WRITE(PLANE_POS(pipe, 0), 0);
3106         } else {
3107                 I915_WRITE(PLANE_POS(pipe, 0), (dst_y << 16) | dst_x);
3108         }
3109
3110         I915_WRITE(PLANE_SURF(pipe, 0), surf_addr);
3111
3112         POSTING_READ(PLANE_SURF(pipe, 0));
3113 }
3114
3115 /* Assume fb object is pinned & idle & fenced and just update base pointers */
3116 static int
3117 intel_pipe_set_base_atomic(struct drm_crtc *crtc, struct drm_framebuffer *fb,
3118                            int x, int y, enum mode_set_atomic state)
3119 {
3120         struct drm_device *dev = crtc->dev;
3121         struct drm_i915_private *dev_priv = dev->dev_private;
3122
3123         if (dev_priv->fbc.disable_fbc)
3124                 dev_priv->fbc.disable_fbc(dev_priv);
3125
3126         dev_priv->display.update_primary_plane(crtc, fb, x, y);
3127
3128         return 0;
3129 }
3130
3131 static void intel_complete_page_flips(struct drm_device *dev)
3132 {
3133         struct drm_crtc *crtc;
3134
3135         for_each_crtc(dev, crtc) {
3136                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3137                 enum plane plane = intel_crtc->plane;
3138
3139                 intel_prepare_page_flip(dev, plane);
3140                 intel_finish_page_flip_plane(dev, plane);
3141         }
3142 }
3143
3144 static void intel_update_primary_planes(struct drm_device *dev)
3145 {
3146         struct drm_i915_private *dev_priv = dev->dev_private;
3147         struct drm_crtc *crtc;
3148
3149         for_each_crtc(dev, crtc) {
3150                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3151
3152                 drm_modeset_lock(&crtc->mutex, NULL);
3153                 /*
3154                  * FIXME: Once we have proper support for primary planes (and
3155                  * disabling them without disabling the entire crtc) allow again
3156                  * a NULL crtc->primary->fb.
3157                  */
3158                 if (intel_crtc->active && crtc->primary->fb)
3159                         dev_priv->display.update_primary_plane(crtc,
3160                                                                crtc->primary->fb,
3161                                                                crtc->x,
3162                                                                crtc->y);
3163                 drm_modeset_unlock(&crtc->mutex);
3164         }
3165 }
3166
3167 void intel_prepare_reset(struct drm_device *dev)
3168 {
3169         /* no reset support for gen2 */
3170         if (IS_GEN2(dev))
3171                 return;
3172
3173         /* reset doesn't touch the display */
3174         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
3175                 return;
3176
3177         drm_modeset_lock_all(dev);
3178         /*
3179          * Disabling the crtcs gracefully seems nicer. Also the
3180          * g33 docs say we should at least disable all the planes.
3181          */
3182         intel_display_suspend(dev);
3183 }
3184
3185 void intel_finish_reset(struct drm_device *dev)
3186 {
3187         struct drm_i915_private *dev_priv = to_i915(dev);
3188
3189         /*
3190          * Flips in the rings will be nuked by the reset,
3191          * so complete all pending flips so that user space
3192          * will get its events and not get stuck.
3193          */
3194         intel_complete_page_flips(dev);
3195
3196         /* no reset support for gen2 */
3197         if (IS_GEN2(dev))
3198                 return;
3199
3200         /* reset doesn't touch the display */
3201         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev)) {
3202                 /*
3203                  * Flips in the rings have been nuked by the reset,
3204                  * so update the base address of all primary
3205                  * planes to the the last fb to make sure we're
3206                  * showing the correct fb after a reset.
3207                  */
3208                 intel_update_primary_planes(dev);
3209                 return;
3210         }
3211
3212         /*
3213          * The display has been reset as well,
3214          * so need a full re-initialization.
3215          */
3216         intel_runtime_pm_disable_interrupts(dev_priv);
3217         intel_runtime_pm_enable_interrupts(dev_priv);
3218
3219         intel_modeset_init_hw(dev);
3220
3221         spin_lock_irq(&dev_priv->irq_lock);
3222         if (dev_priv->display.hpd_irq_setup)
3223                 dev_priv->display.hpd_irq_setup(dev);
3224         spin_unlock_irq(&dev_priv->irq_lock);
3225
3226         intel_display_resume(dev);
3227
3228         intel_hpd_init(dev_priv);
3229
3230         drm_modeset_unlock_all(dev);
3231 }
3232
3233 static void
3234 intel_finish_fb(struct drm_framebuffer *old_fb)
3235 {
3236         struct drm_i915_gem_object *obj = intel_fb_obj(old_fb);
3237         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
3238         bool was_interruptible = dev_priv->mm.interruptible;
3239         int ret;
3240
3241         /* Big Hammer, we also need to ensure that any pending
3242          * MI_WAIT_FOR_EVENT inside a user batch buffer on the
3243          * current scanout is retired before unpinning the old
3244          * framebuffer. Note that we rely on userspace rendering
3245          * into the buffer attached to the pipe they are waiting
3246          * on. If not, userspace generates a GPU hang with IPEHR
3247          * point to the MI_WAIT_FOR_EVENT.
3248          *
3249          * This should only fail upon a hung GPU, in which case we
3250          * can safely continue.
3251          */
3252         dev_priv->mm.interruptible = false;
3253         ret = i915_gem_object_wait_rendering(obj, true);
3254         dev_priv->mm.interruptible = was_interruptible;
3255
3256         WARN_ON(ret);
3257 }
3258
3259 static bool intel_crtc_has_pending_flip(struct drm_crtc *crtc)
3260 {
3261         struct drm_device *dev = crtc->dev;
3262         struct drm_i915_private *dev_priv = dev->dev_private;
3263         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3264         bool pending;
3265
3266         if (i915_reset_in_progress(&dev_priv->gpu_error) ||
3267             intel_crtc->reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
3268                 return false;
3269
3270         spin_lock_irq(&dev->event_lock);
3271         pending = to_intel_crtc(crtc)->unpin_work != NULL;
3272         spin_unlock_irq(&dev->event_lock);
3273
3274         return pending;
3275 }
3276
3277 static void intel_update_pipe_size(struct intel_crtc *crtc)
3278 {
3279         struct drm_device *dev = crtc->base.dev;
3280         struct drm_i915_private *dev_priv = dev->dev_private;
3281         const struct drm_display_mode *adjusted_mode;
3282
3283         if (!i915.fastboot)
3284                 return;
3285
3286         /*
3287          * Update pipe size and adjust fitter if needed: the reason for this is
3288          * that in compute_mode_changes we check the native mode (not the pfit
3289          * mode) to see if we can flip rather than do a full mode set. In the
3290          * fastboot case, we'll flip, but if we don't update the pipesrc and
3291          * pfit state, we'll end up with a big fb scanned out into the wrong
3292          * sized surface.
3293          *
3294          * To fix this properly, we need to hoist the checks up into
3295          * compute_mode_changes (or above), check the actual pfit state and
3296          * whether the platform allows pfit disable with pipe active, and only
3297          * then update the pipesrc and pfit state, even on the flip path.
3298          */
3299
3300         adjusted_mode = &crtc->config->base.adjusted_mode;
3301
3302         I915_WRITE(PIPESRC(crtc->pipe),
3303                    ((adjusted_mode->crtc_hdisplay - 1) << 16) |
3304                    (adjusted_mode->crtc_vdisplay - 1));
3305         if (!crtc->config->pch_pfit.enabled &&
3306             (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS) ||
3307              intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP))) {
3308                 I915_WRITE(PF_CTL(crtc->pipe), 0);
3309                 I915_WRITE(PF_WIN_POS(crtc->pipe), 0);
3310                 I915_WRITE(PF_WIN_SZ(crtc->pipe), 0);
3311         }
3312         crtc->config->pipe_src_w = adjusted_mode->crtc_hdisplay;
3313         crtc->config->pipe_src_h = adjusted_mode->crtc_vdisplay;
3314 }
3315
3316 static void intel_fdi_normal_train(struct drm_crtc *crtc)
3317 {
3318         struct drm_device *dev = crtc->dev;
3319         struct drm_i915_private *dev_priv = dev->dev_private;
3320         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3321         int pipe = intel_crtc->pipe;
3322         u32 reg, temp;
3323
3324         /* enable normal train */
3325         reg = FDI_TX_CTL(pipe);
3326         temp = I915_READ(reg);
3327         if (IS_IVYBRIDGE(dev)) {
3328                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3329                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3330         } else {
3331                 temp &= ~FDI_LINK_TRAIN_NONE;
3332                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3333         }
3334         I915_WRITE(reg, temp);
3335
3336         reg = FDI_RX_CTL(pipe);
3337         temp = I915_READ(reg);
3338         if (HAS_PCH_CPT(dev)) {
3339                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3340                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3341         } else {
3342                 temp &= ~FDI_LINK_TRAIN_NONE;
3343                 temp |= FDI_LINK_TRAIN_NONE;
3344         }
3345         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3346
3347         /* wait one idle pattern time */
3348         POSTING_READ(reg);
3349         udelay(1000);
3350
3351         /* IVB wants error correction enabled */
3352         if (IS_IVYBRIDGE(dev))
3353                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3354                            FDI_FE_ERRC_ENABLE);
3355 }
3356
3357 /* The FDI link training functions for ILK/Ibexpeak. */
3358 static void ironlake_fdi_link_train(struct drm_crtc *crtc)
3359 {
3360         struct drm_device *dev = crtc->dev;
3361         struct drm_i915_private *dev_priv = dev->dev_private;
3362         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3363         int pipe = intel_crtc->pipe;
3364         u32 reg, temp, tries;
3365
3366         /* FDI needs bits from pipe first */
3367         assert_pipe_enabled(dev_priv, pipe);
3368
3369         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3370            for train result */
3371         reg = FDI_RX_IMR(pipe);
3372         temp = I915_READ(reg);
3373         temp &= ~FDI_RX_SYMBOL_LOCK;
3374         temp &= ~FDI_RX_BIT_LOCK;
3375         I915_WRITE(reg, temp);
3376         I915_READ(reg);
3377         udelay(150);
3378
3379         /* enable CPU FDI TX and PCH FDI RX */
3380         reg = FDI_TX_CTL(pipe);
3381         temp = I915_READ(reg);
3382         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3383         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3384         temp &= ~FDI_LINK_TRAIN_NONE;
3385         temp |= FDI_LINK_TRAIN_PATTERN_1;
3386         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3387
3388         reg = FDI_RX_CTL(pipe);
3389         temp = I915_READ(reg);
3390         temp &= ~FDI_LINK_TRAIN_NONE;
3391         temp |= FDI_LINK_TRAIN_PATTERN_1;
3392         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3393
3394         POSTING_READ(reg);
3395         udelay(150);
3396
3397         /* Ironlake workaround, enable clock pointer after FDI enable*/
3398         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3399         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3400                    FDI_RX_PHASE_SYNC_POINTER_EN);
3401
3402         reg = FDI_RX_IIR(pipe);
3403         for (tries = 0; tries < 5; tries++) {
3404                 temp = I915_READ(reg);
3405                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3406
3407                 if ((temp & FDI_RX_BIT_LOCK)) {
3408                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3409                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3410                         break;
3411                 }
3412         }
3413         if (tries == 5)
3414                 DRM_ERROR("FDI train 1 fail!\n");
3415
3416         /* Train 2 */
3417         reg = FDI_TX_CTL(pipe);
3418         temp = I915_READ(reg);
3419         temp &= ~FDI_LINK_TRAIN_NONE;
3420         temp |= FDI_LINK_TRAIN_PATTERN_2;
3421         I915_WRITE(reg, temp);
3422
3423         reg = FDI_RX_CTL(pipe);
3424         temp = I915_READ(reg);
3425         temp &= ~FDI_LINK_TRAIN_NONE;
3426         temp |= FDI_LINK_TRAIN_PATTERN_2;
3427         I915_WRITE(reg, temp);
3428
3429         POSTING_READ(reg);
3430         udelay(150);
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_SYMBOL_LOCK) {
3438                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3439                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3440                         break;
3441                 }
3442         }
3443         if (tries == 5)
3444                 DRM_ERROR("FDI train 2 fail!\n");
3445
3446         DRM_DEBUG_KMS("FDI train done\n");
3447
3448 }
3449
3450 static const int snb_b_fdi_train_param[] = {
3451         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3452         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3453         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3454         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3455 };
3456
3457 /* The FDI link training functions for SNB/Cougarpoint. */
3458 static void gen6_fdi_link_train(struct drm_crtc *crtc)
3459 {
3460         struct drm_device *dev = crtc->dev;
3461         struct drm_i915_private *dev_priv = dev->dev_private;
3462         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3463         int pipe = intel_crtc->pipe;
3464         u32 reg, temp, i, retry;
3465
3466         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3467            for train result */
3468         reg = FDI_RX_IMR(pipe);
3469         temp = I915_READ(reg);
3470         temp &= ~FDI_RX_SYMBOL_LOCK;
3471         temp &= ~FDI_RX_BIT_LOCK;
3472         I915_WRITE(reg, temp);
3473
3474         POSTING_READ(reg);
3475         udelay(150);
3476
3477         /* enable CPU FDI TX and PCH FDI RX */
3478         reg = FDI_TX_CTL(pipe);
3479         temp = I915_READ(reg);
3480         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3481         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3482         temp &= ~FDI_LINK_TRAIN_NONE;
3483         temp |= FDI_LINK_TRAIN_PATTERN_1;
3484         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3485         /* SNB-B */
3486         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3487         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3488
3489         I915_WRITE(FDI_RX_MISC(pipe),
3490                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3491
3492         reg = FDI_RX_CTL(pipe);
3493         temp = I915_READ(reg);
3494         if (HAS_PCH_CPT(dev)) {
3495                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3496                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3497         } else {
3498                 temp &= ~FDI_LINK_TRAIN_NONE;
3499                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3500         }
3501         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3502
3503         POSTING_READ(reg);
3504         udelay(150);
3505
3506         for (i = 0; i < 4; i++) {
3507                 reg = FDI_TX_CTL(pipe);
3508                 temp = I915_READ(reg);
3509                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3510                 temp |= snb_b_fdi_train_param[i];
3511                 I915_WRITE(reg, temp);
3512
3513                 POSTING_READ(reg);
3514                 udelay(500);
3515
3516                 for (retry = 0; retry < 5; retry++) {
3517                         reg = FDI_RX_IIR(pipe);
3518                         temp = I915_READ(reg);
3519                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3520                         if (temp & FDI_RX_BIT_LOCK) {
3521                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3522                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
3523                                 break;
3524                         }
3525                         udelay(50);
3526                 }
3527                 if (retry < 5)
3528                         break;
3529         }
3530         if (i == 4)
3531                 DRM_ERROR("FDI train 1 fail!\n");
3532
3533         /* Train 2 */
3534         reg = FDI_TX_CTL(pipe);
3535         temp = I915_READ(reg);
3536         temp &= ~FDI_LINK_TRAIN_NONE;
3537         temp |= FDI_LINK_TRAIN_PATTERN_2;
3538         if (IS_GEN6(dev)) {
3539                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3540                 /* SNB-B */
3541                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3542         }
3543         I915_WRITE(reg, temp);
3544
3545         reg = FDI_RX_CTL(pipe);
3546         temp = I915_READ(reg);
3547         if (HAS_PCH_CPT(dev)) {
3548                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3549                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3550         } else {
3551                 temp &= ~FDI_LINK_TRAIN_NONE;
3552                 temp |= FDI_LINK_TRAIN_PATTERN_2;
3553         }
3554         I915_WRITE(reg, temp);
3555
3556         POSTING_READ(reg);
3557         udelay(150);
3558
3559         for (i = 0; i < 4; i++) {
3560                 reg = FDI_TX_CTL(pipe);
3561                 temp = I915_READ(reg);
3562                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3563                 temp |= snb_b_fdi_train_param[i];
3564                 I915_WRITE(reg, temp);
3565
3566                 POSTING_READ(reg);
3567                 udelay(500);
3568
3569                 for (retry = 0; retry < 5; retry++) {
3570                         reg = FDI_RX_IIR(pipe);
3571                         temp = I915_READ(reg);
3572                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3573                         if (temp & FDI_RX_SYMBOL_LOCK) {
3574                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3575                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
3576                                 break;
3577                         }
3578                         udelay(50);
3579                 }
3580                 if (retry < 5)
3581                         break;
3582         }
3583         if (i == 4)
3584                 DRM_ERROR("FDI train 2 fail!\n");
3585
3586         DRM_DEBUG_KMS("FDI train done.\n");
3587 }
3588
3589 /* Manual link training for Ivy Bridge A0 parts */
3590 static void ivb_manual_fdi_link_train(struct drm_crtc *crtc)
3591 {
3592         struct drm_device *dev = crtc->dev;
3593         struct drm_i915_private *dev_priv = dev->dev_private;
3594         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3595         int pipe = intel_crtc->pipe;
3596         u32 reg, temp, i, j;
3597
3598         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3599            for train result */
3600         reg = FDI_RX_IMR(pipe);
3601         temp = I915_READ(reg);
3602         temp &= ~FDI_RX_SYMBOL_LOCK;
3603         temp &= ~FDI_RX_BIT_LOCK;
3604         I915_WRITE(reg, temp);
3605
3606         POSTING_READ(reg);
3607         udelay(150);
3608
3609         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
3610                       I915_READ(FDI_RX_IIR(pipe)));
3611
3612         /* Try each vswing and preemphasis setting twice before moving on */
3613         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
3614                 /* disable first in case we need to retry */
3615                 reg = FDI_TX_CTL(pipe);
3616                 temp = I915_READ(reg);
3617                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
3618                 temp &= ~FDI_TX_ENABLE;
3619                 I915_WRITE(reg, temp);
3620
3621                 reg = FDI_RX_CTL(pipe);
3622                 temp = I915_READ(reg);
3623                 temp &= ~FDI_LINK_TRAIN_AUTO;
3624                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3625                 temp &= ~FDI_RX_ENABLE;
3626                 I915_WRITE(reg, temp);
3627
3628                 /* enable CPU FDI TX and PCH FDI RX */
3629                 reg = FDI_TX_CTL(pipe);
3630                 temp = I915_READ(reg);
3631                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
3632                 temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3633                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
3634                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3635                 temp |= snb_b_fdi_train_param[j/2];
3636                 temp |= FDI_COMPOSITE_SYNC;
3637                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
3638
3639                 I915_WRITE(FDI_RX_MISC(pipe),
3640                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3641
3642                 reg = FDI_RX_CTL(pipe);
3643                 temp = I915_READ(reg);
3644                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3645                 temp |= FDI_COMPOSITE_SYNC;
3646                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
3647
3648                 POSTING_READ(reg);
3649                 udelay(1); /* should be 0.5us */
3650
3651                 for (i = 0; i < 4; i++) {
3652                         reg = FDI_RX_IIR(pipe);
3653                         temp = I915_READ(reg);
3654                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3655
3656                         if (temp & FDI_RX_BIT_LOCK ||
3657                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
3658                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3659                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
3660                                               i);
3661                                 break;
3662                         }
3663                         udelay(1); /* should be 0.5us */
3664                 }
3665                 if (i == 4) {
3666                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
3667                         continue;
3668                 }
3669
3670                 /* Train 2 */
3671                 reg = FDI_TX_CTL(pipe);
3672                 temp = I915_READ(reg);
3673                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3674                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
3675                 I915_WRITE(reg, temp);
3676
3677                 reg = FDI_RX_CTL(pipe);
3678                 temp = I915_READ(reg);
3679                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3680                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3681                 I915_WRITE(reg, temp);
3682
3683                 POSTING_READ(reg);
3684                 udelay(2); /* should be 1.5us */
3685
3686                 for (i = 0; i < 4; i++) {
3687                         reg = FDI_RX_IIR(pipe);
3688                         temp = I915_READ(reg);
3689                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3690
3691                         if (temp & FDI_RX_SYMBOL_LOCK ||
3692                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
3693                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3694                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
3695                                               i);
3696                                 goto train_done;
3697                         }
3698                         udelay(2); /* should be 1.5us */
3699                 }
3700                 if (i == 4)
3701                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
3702         }
3703
3704 train_done:
3705         DRM_DEBUG_KMS("FDI train done.\n");
3706 }
3707
3708 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
3709 {
3710         struct drm_device *dev = intel_crtc->base.dev;
3711         struct drm_i915_private *dev_priv = dev->dev_private;
3712         int pipe = intel_crtc->pipe;
3713         u32 reg, temp;
3714
3715
3716         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
3717         reg = FDI_RX_CTL(pipe);
3718         temp = I915_READ(reg);
3719         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
3720         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3721         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3722         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
3723
3724         POSTING_READ(reg);
3725         udelay(200);
3726
3727         /* Switch from Rawclk to PCDclk */
3728         temp = I915_READ(reg);
3729         I915_WRITE(reg, temp | FDI_PCDCLK);
3730
3731         POSTING_READ(reg);
3732         udelay(200);
3733
3734         /* Enable CPU FDI TX PLL, always on for Ironlake */
3735         reg = FDI_TX_CTL(pipe);
3736         temp = I915_READ(reg);
3737         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
3738                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
3739
3740                 POSTING_READ(reg);
3741                 udelay(100);
3742         }
3743 }
3744
3745 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
3746 {
3747         struct drm_device *dev = intel_crtc->base.dev;
3748         struct drm_i915_private *dev_priv = dev->dev_private;
3749         int pipe = intel_crtc->pipe;
3750         u32 reg, temp;
3751
3752         /* Switch from PCDclk to Rawclk */
3753         reg = FDI_RX_CTL(pipe);
3754         temp = I915_READ(reg);
3755         I915_WRITE(reg, temp & ~FDI_PCDCLK);
3756
3757         /* Disable CPU FDI TX PLL */
3758         reg = FDI_TX_CTL(pipe);
3759         temp = I915_READ(reg);
3760         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
3761
3762         POSTING_READ(reg);
3763         udelay(100);
3764
3765         reg = FDI_RX_CTL(pipe);
3766         temp = I915_READ(reg);
3767         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
3768
3769         /* Wait for the clocks to turn off. */
3770         POSTING_READ(reg);
3771         udelay(100);
3772 }
3773
3774 static void ironlake_fdi_disable(struct drm_crtc *crtc)
3775 {
3776         struct drm_device *dev = crtc->dev;
3777         struct drm_i915_private *dev_priv = dev->dev_private;
3778         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3779         int pipe = intel_crtc->pipe;
3780         u32 reg, temp;
3781
3782         /* disable CPU FDI tx and PCH FDI rx */
3783         reg = FDI_TX_CTL(pipe);
3784         temp = I915_READ(reg);
3785         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
3786         POSTING_READ(reg);
3787
3788         reg = FDI_RX_CTL(pipe);
3789         temp = I915_READ(reg);
3790         temp &= ~(0x7 << 16);
3791         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3792         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
3793
3794         POSTING_READ(reg);
3795         udelay(100);
3796
3797         /* Ironlake workaround, disable clock pointer after downing FDI */
3798         if (HAS_PCH_IBX(dev))
3799                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3800
3801         /* still set train pattern 1 */
3802         reg = FDI_TX_CTL(pipe);
3803         temp = I915_READ(reg);
3804         temp &= ~FDI_LINK_TRAIN_NONE;
3805         temp |= FDI_LINK_TRAIN_PATTERN_1;
3806         I915_WRITE(reg, temp);
3807
3808         reg = FDI_RX_CTL(pipe);
3809         temp = I915_READ(reg);
3810         if (HAS_PCH_CPT(dev)) {
3811                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3812                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3813         } else {
3814                 temp &= ~FDI_LINK_TRAIN_NONE;
3815                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3816         }
3817         /* BPC in FDI rx is consistent with that in PIPECONF */
3818         temp &= ~(0x07 << 16);
3819         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3820         I915_WRITE(reg, temp);
3821
3822         POSTING_READ(reg);
3823         udelay(100);
3824 }
3825
3826 bool intel_has_pending_fb_unpin(struct drm_device *dev)
3827 {
3828         struct intel_crtc *crtc;
3829
3830         /* Note that we don't need to be called with mode_config.lock here
3831          * as our list of CRTC objects is static for the lifetime of the
3832          * device and so cannot disappear as we iterate. Similarly, we can
3833          * happily treat the predicates as racy, atomic checks as userspace
3834          * cannot claim and pin a new fb without at least acquring the
3835          * struct_mutex and so serialising with us.
3836          */
3837         for_each_intel_crtc(dev, crtc) {
3838                 if (atomic_read(&crtc->unpin_work_count) == 0)
3839                         continue;
3840
3841                 if (crtc->unpin_work)
3842                         intel_wait_for_vblank(dev, crtc->pipe);
3843
3844                 return true;
3845         }
3846
3847         return false;
3848 }
3849
3850 static void page_flip_completed(struct intel_crtc *intel_crtc)
3851 {
3852         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
3853         struct intel_unpin_work *work = intel_crtc->unpin_work;
3854
3855         /* ensure that the unpin work is consistent wrt ->pending. */
3856         smp_rmb();
3857         intel_crtc->unpin_work = NULL;
3858
3859         if (work->event)
3860                 drm_send_vblank_event(intel_crtc->base.dev,
3861                                       intel_crtc->pipe,
3862                                       work->event);
3863
3864         drm_crtc_vblank_put(&intel_crtc->base);
3865
3866         wake_up_all(&dev_priv->pending_flip_queue);
3867         queue_work(dev_priv->wq, &work->work);
3868
3869         trace_i915_flip_complete(intel_crtc->plane,
3870                                  work->pending_flip_obj);
3871 }
3872
3873 void intel_crtc_wait_for_pending_flips(struct drm_crtc *crtc)
3874 {
3875         struct drm_device *dev = crtc->dev;
3876         struct drm_i915_private *dev_priv = dev->dev_private;
3877
3878         WARN_ON(waitqueue_active(&dev_priv->pending_flip_queue));
3879         if (WARN_ON(wait_event_timeout(dev_priv->pending_flip_queue,
3880                                        !intel_crtc_has_pending_flip(crtc),
3881                                        60*HZ) == 0)) {
3882                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3883
3884                 spin_lock_irq(&dev->event_lock);
3885                 if (intel_crtc->unpin_work) {
3886                         WARN_ONCE(1, "Removing stuck page flip\n");
3887                         page_flip_completed(intel_crtc);
3888                 }
3889                 spin_unlock_irq(&dev->event_lock);
3890         }
3891
3892         if (crtc->primary->fb) {
3893                 mutex_lock(&dev->struct_mutex);
3894                 intel_finish_fb(crtc->primary->fb);
3895                 mutex_unlock(&dev->struct_mutex);
3896         }
3897 }
3898
3899 /* Program iCLKIP clock to the desired frequency */
3900 static void lpt_program_iclkip(struct drm_crtc *crtc)
3901 {
3902         struct drm_device *dev = crtc->dev;
3903         struct drm_i915_private *dev_priv = dev->dev_private;
3904         int clock = to_intel_crtc(crtc)->config->base.adjusted_mode.crtc_clock;
3905         u32 divsel, phaseinc, auxdiv, phasedir = 0;
3906         u32 temp;
3907
3908         mutex_lock(&dev_priv->sb_lock);
3909
3910         /* It is necessary to ungate the pixclk gate prior to programming
3911          * the divisors, and gate it back when it is done.
3912          */
3913         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
3914
3915         /* Disable SSCCTL */
3916         intel_sbi_write(dev_priv, SBI_SSCCTL6,
3917                         intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK) |
3918                                 SBI_SSCCTL_DISABLE,
3919                         SBI_ICLK);
3920
3921         /* 20MHz is a corner case which is out of range for the 7-bit divisor */
3922         if (clock == 20000) {
3923                 auxdiv = 1;
3924                 divsel = 0x41;
3925                 phaseinc = 0x20;
3926         } else {
3927                 /* The iCLK virtual clock root frequency is in MHz,
3928                  * but the adjusted_mode->crtc_clock in in KHz. To get the
3929                  * divisors, it is necessary to divide one by another, so we
3930                  * convert the virtual clock precision to KHz here for higher
3931                  * precision.
3932                  */
3933                 u32 iclk_virtual_root_freq = 172800 * 1000;
3934                 u32 iclk_pi_range = 64;
3935                 u32 desired_divisor, msb_divisor_value, pi_value;
3936
3937                 desired_divisor = (iclk_virtual_root_freq / clock);
3938                 msb_divisor_value = desired_divisor / iclk_pi_range;
3939                 pi_value = desired_divisor % iclk_pi_range;
3940
3941                 auxdiv = 0;
3942                 divsel = msb_divisor_value - 2;
3943                 phaseinc = pi_value;
3944         }
3945
3946         /* This should not happen with any sane values */
3947         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
3948                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
3949         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
3950                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
3951
3952         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
3953                         clock,
3954                         auxdiv,
3955                         divsel,
3956                         phasedir,
3957                         phaseinc);
3958
3959         /* Program SSCDIVINTPHASE6 */
3960         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
3961         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
3962         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
3963         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
3964         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
3965         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
3966         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
3967         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
3968
3969         /* Program SSCAUXDIV */
3970         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
3971         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
3972         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
3973         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
3974
3975         /* Enable modulator and associated divider */
3976         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3977         temp &= ~SBI_SSCCTL_DISABLE;
3978         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
3979
3980         /* Wait for initialization time */
3981         udelay(24);
3982
3983         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
3984
3985         mutex_unlock(&dev_priv->sb_lock);
3986 }
3987
3988 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
3989                                                 enum pipe pch_transcoder)
3990 {
3991         struct drm_device *dev = crtc->base.dev;
3992         struct drm_i915_private *dev_priv = dev->dev_private;
3993         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
3994
3995         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
3996                    I915_READ(HTOTAL(cpu_transcoder)));
3997         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
3998                    I915_READ(HBLANK(cpu_transcoder)));
3999         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4000                    I915_READ(HSYNC(cpu_transcoder)));
4001
4002         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4003                    I915_READ(VTOTAL(cpu_transcoder)));
4004         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4005                    I915_READ(VBLANK(cpu_transcoder)));
4006         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4007                    I915_READ(VSYNC(cpu_transcoder)));
4008         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4009                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4010 }
4011
4012 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4013 {
4014         struct drm_i915_private *dev_priv = dev->dev_private;
4015         uint32_t temp;
4016
4017         temp = I915_READ(SOUTH_CHICKEN1);
4018         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4019                 return;
4020
4021         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4022         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4023
4024         temp &= ~FDI_BC_BIFURCATION_SELECT;
4025         if (enable)
4026                 temp |= FDI_BC_BIFURCATION_SELECT;
4027
4028         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4029         I915_WRITE(SOUTH_CHICKEN1, temp);
4030         POSTING_READ(SOUTH_CHICKEN1);
4031 }
4032
4033 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4034 {
4035         struct drm_device *dev = intel_crtc->base.dev;
4036
4037         switch (intel_crtc->pipe) {
4038         case PIPE_A:
4039                 break;
4040         case PIPE_B:
4041                 if (intel_crtc->config->fdi_lanes > 2)
4042                         cpt_set_fdi_bc_bifurcation(dev, false);
4043                 else
4044                         cpt_set_fdi_bc_bifurcation(dev, true);
4045
4046                 break;
4047         case PIPE_C:
4048                 cpt_set_fdi_bc_bifurcation(dev, true);
4049
4050                 break;
4051         default:
4052                 BUG();
4053         }
4054 }
4055
4056 /*
4057  * Enable PCH resources required for PCH ports:
4058  *   - PCH PLLs
4059  *   - FDI training & RX/TX
4060  *   - update transcoder timings
4061  *   - DP transcoding bits
4062  *   - transcoder
4063  */
4064 static void ironlake_pch_enable(struct drm_crtc *crtc)
4065 {
4066         struct drm_device *dev = crtc->dev;
4067         struct drm_i915_private *dev_priv = dev->dev_private;
4068         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4069         int pipe = intel_crtc->pipe;
4070         u32 reg, temp;
4071
4072         assert_pch_transcoder_disabled(dev_priv, pipe);
4073
4074         if (IS_IVYBRIDGE(dev))
4075                 ivybridge_update_fdi_bc_bifurcation(intel_crtc);
4076
4077         /* Write the TU size bits before fdi link training, so that error
4078          * detection works. */
4079         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4080                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4081
4082         /* For PCH output, training FDI link */
4083         dev_priv->display.fdi_link_train(crtc);
4084
4085         /* We need to program the right clock selection before writing the pixel
4086          * mutliplier into the DPLL. */
4087         if (HAS_PCH_CPT(dev)) {
4088                 u32 sel;
4089
4090                 temp = I915_READ(PCH_DPLL_SEL);
4091                 temp |= TRANS_DPLL_ENABLE(pipe);
4092                 sel = TRANS_DPLLB_SEL(pipe);
4093                 if (intel_crtc->config->shared_dpll == DPLL_ID_PCH_PLL_B)
4094                         temp |= sel;
4095                 else
4096                         temp &= ~sel;
4097                 I915_WRITE(PCH_DPLL_SEL, temp);
4098         }
4099
4100         /* XXX: pch pll's can be enabled any time before we enable the PCH
4101          * transcoder, and we actually should do this to not upset any PCH
4102          * transcoder that already use the clock when we share it.
4103          *
4104          * Note that enable_shared_dpll tries to do the right thing, but
4105          * get_shared_dpll unconditionally resets the pll - we need that to have
4106          * the right LVDS enable sequence. */
4107         intel_enable_shared_dpll(intel_crtc);
4108
4109         /* set transcoder timing, panel must allow it */
4110         assert_panel_unlocked(dev_priv, pipe);
4111         ironlake_pch_transcoder_set_timings(intel_crtc, pipe);
4112
4113         intel_fdi_normal_train(crtc);
4114
4115         /* For PCH DP, enable TRANS_DP_CTL */
4116         if (HAS_PCH_CPT(dev) && intel_crtc->config->has_dp_encoder) {
4117                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4118                 reg = TRANS_DP_CTL(pipe);
4119                 temp = I915_READ(reg);
4120                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4121                           TRANS_DP_SYNC_MASK |
4122                           TRANS_DP_BPC_MASK);
4123                 temp |= TRANS_DP_OUTPUT_ENABLE;
4124                 temp |= bpc << 9; /* same format but at 11:9 */
4125
4126                 if (crtc->mode.flags & DRM_MODE_FLAG_PHSYNC)
4127                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4128                 if (crtc->mode.flags & DRM_MODE_FLAG_PVSYNC)
4129                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4130
4131                 switch (intel_trans_dp_port_sel(crtc)) {
4132                 case PCH_DP_B:
4133                         temp |= TRANS_DP_PORT_SEL_B;
4134                         break;
4135                 case PCH_DP_C:
4136                         temp |= TRANS_DP_PORT_SEL_C;
4137                         break;
4138                 case PCH_DP_D:
4139                         temp |= TRANS_DP_PORT_SEL_D;
4140                         break;
4141                 default:
4142                         BUG();
4143                 }
4144
4145                 I915_WRITE(reg, temp);
4146         }
4147
4148         ironlake_enable_pch_transcoder(dev_priv, pipe);
4149 }
4150
4151 static void lpt_pch_enable(struct drm_crtc *crtc)
4152 {
4153         struct drm_device *dev = crtc->dev;
4154         struct drm_i915_private *dev_priv = dev->dev_private;
4155         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4156         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4157
4158         assert_pch_transcoder_disabled(dev_priv, TRANSCODER_A);
4159
4160         lpt_program_iclkip(crtc);
4161
4162         /* Set transcoder timing. */
4163         ironlake_pch_transcoder_set_timings(intel_crtc, PIPE_A);
4164
4165         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4166 }
4167
4168 struct intel_shared_dpll *intel_get_shared_dpll(struct intel_crtc *crtc,
4169                                                 struct intel_crtc_state *crtc_state)
4170 {
4171         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
4172         struct intel_shared_dpll *pll;
4173         struct intel_shared_dpll_config *shared_dpll;
4174         enum intel_dpll_id i;
4175
4176         shared_dpll = intel_atomic_get_shared_dpll_state(crtc_state->base.state);
4177
4178         if (HAS_PCH_IBX(dev_priv->dev)) {
4179                 /* Ironlake PCH has a fixed PLL->PCH pipe mapping. */
4180                 i = (enum intel_dpll_id) crtc->pipe;
4181                 pll = &dev_priv->shared_dplls[i];
4182
4183                 DRM_DEBUG_KMS("CRTC:%d using pre-allocated %s\n",
4184                               crtc->base.base.id, pll->name);
4185
4186                 WARN_ON(shared_dpll[i].crtc_mask);
4187
4188                 goto found;
4189         }
4190
4191         if (IS_BROXTON(dev_priv->dev)) {
4192                 /* PLL is attached to port in bxt */
4193                 struct intel_encoder *encoder;
4194                 struct intel_digital_port *intel_dig_port;
4195
4196                 encoder = intel_ddi_get_crtc_new_encoder(crtc_state);
4197                 if (WARN_ON(!encoder))
4198                         return NULL;
4199
4200                 intel_dig_port = enc_to_dig_port(&encoder->base);
4201                 /* 1:1 mapping between ports and PLLs */
4202                 i = (enum intel_dpll_id)intel_dig_port->port;
4203                 pll = &dev_priv->shared_dplls[i];
4204                 DRM_DEBUG_KMS("CRTC:%d using pre-allocated %s\n",
4205                         crtc->base.base.id, pll->name);
4206                 WARN_ON(shared_dpll[i].crtc_mask);
4207
4208                 goto found;
4209         }
4210
4211         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4212                 pll = &dev_priv->shared_dplls[i];
4213
4214                 /* Only want to check enabled timings first */
4215                 if (shared_dpll[i].crtc_mask == 0)
4216                         continue;
4217
4218                 if (memcmp(&crtc_state->dpll_hw_state,
4219                            &shared_dpll[i].hw_state,
4220                            sizeof(crtc_state->dpll_hw_state)) == 0) {
4221                         DRM_DEBUG_KMS("CRTC:%d sharing existing %s (crtc mask 0x%08x, ative %d)\n",
4222                                       crtc->base.base.id, pll->name,
4223                                       shared_dpll[i].crtc_mask,
4224                                       pll->active);
4225                         goto found;
4226                 }
4227         }
4228
4229         /* Ok no matching timings, maybe there's a free one? */
4230         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4231                 pll = &dev_priv->shared_dplls[i];
4232                 if (shared_dpll[i].crtc_mask == 0) {
4233                         DRM_DEBUG_KMS("CRTC:%d allocated %s\n",
4234                                       crtc->base.base.id, pll->name);
4235                         goto found;
4236                 }
4237         }
4238
4239         return NULL;
4240
4241 found:
4242         if (shared_dpll[i].crtc_mask == 0)
4243                 shared_dpll[i].hw_state =
4244                         crtc_state->dpll_hw_state;
4245
4246         crtc_state->shared_dpll = i;
4247         DRM_DEBUG_DRIVER("using %s for pipe %c\n", pll->name,
4248                          pipe_name(crtc->pipe));
4249
4250         shared_dpll[i].crtc_mask |= 1 << crtc->pipe;
4251
4252         return pll;
4253 }
4254
4255 static void intel_shared_dpll_commit(struct drm_atomic_state *state)
4256 {
4257         struct drm_i915_private *dev_priv = to_i915(state->dev);
4258         struct intel_shared_dpll_config *shared_dpll;
4259         struct intel_shared_dpll *pll;
4260         enum intel_dpll_id i;
4261
4262         if (!to_intel_atomic_state(state)->dpll_set)
4263                 return;
4264
4265         shared_dpll = to_intel_atomic_state(state)->shared_dpll;
4266         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4267                 pll = &dev_priv->shared_dplls[i];
4268                 pll->config = shared_dpll[i];
4269         }
4270 }
4271
4272 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4273 {
4274         struct drm_i915_private *dev_priv = dev->dev_private;
4275         int dslreg = PIPEDSL(pipe);
4276         u32 temp;
4277
4278         temp = I915_READ(dslreg);
4279         udelay(500);
4280         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4281                 if (wait_for(I915_READ(dslreg) != temp, 5))
4282                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4283         }
4284 }
4285
4286 static int
4287 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4288                   unsigned scaler_user, int *scaler_id, unsigned int rotation,
4289                   int src_w, int src_h, int dst_w, int dst_h)
4290 {
4291         struct intel_crtc_scaler_state *scaler_state =
4292                 &crtc_state->scaler_state;
4293         struct intel_crtc *intel_crtc =
4294                 to_intel_crtc(crtc_state->base.crtc);
4295         int need_scaling;
4296
4297         need_scaling = intel_rotation_90_or_270(rotation) ?
4298                 (src_h != dst_w || src_w != dst_h):
4299                 (src_w != dst_w || src_h != dst_h);
4300
4301         /*
4302          * if plane is being disabled or scaler is no more required or force detach
4303          *  - free scaler binded to this plane/crtc
4304          *  - in order to do this, update crtc->scaler_usage
4305          *
4306          * Here scaler state in crtc_state is set free so that
4307          * scaler can be assigned to other user. Actual register
4308          * update to free the scaler is done in plane/panel-fit programming.
4309          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4310          */
4311         if (force_detach || !need_scaling) {
4312                 if (*scaler_id >= 0) {
4313                         scaler_state->scaler_users &= ~(1 << scaler_user);
4314                         scaler_state->scalers[*scaler_id].in_use = 0;
4315
4316                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4317                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4318                                 intel_crtc->pipe, scaler_user, *scaler_id,
4319                                 scaler_state->scaler_users);
4320                         *scaler_id = -1;
4321                 }
4322                 return 0;
4323         }
4324
4325         /* range checks */
4326         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4327                 dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4328
4329                 src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4330                 dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H) {
4331                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4332                         "size is out of scaler range\n",
4333                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4334                 return -EINVAL;
4335         }
4336
4337         /* mark this plane as a scaler user in crtc_state */
4338         scaler_state->scaler_users |= (1 << scaler_user);
4339         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4340                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4341                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4342                 scaler_state->scaler_users);
4343
4344         return 0;
4345 }
4346
4347 /**
4348  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4349  *
4350  * @state: crtc's scaler state
4351  *
4352  * Return
4353  *     0 - scaler_usage updated successfully
4354  *    error - requested scaling cannot be supported or other error condition
4355  */
4356 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4357 {
4358         struct intel_crtc *intel_crtc = to_intel_crtc(state->base.crtc);
4359         struct drm_display_mode *adjusted_mode =
4360                 &state->base.adjusted_mode;
4361
4362         DRM_DEBUG_KMS("Updating scaler for [CRTC:%i] scaler_user index %u.%u\n",
4363                       intel_crtc->base.base.id, intel_crtc->pipe, SKL_CRTC_INDEX);
4364
4365         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4366                 &state->scaler_state.scaler_id, DRM_ROTATE_0,
4367                 state->pipe_src_w, state->pipe_src_h,
4368                 adjusted_mode->hdisplay, adjusted_mode->vdisplay);
4369 }
4370
4371 /**
4372  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4373  *
4374  * @state: crtc's scaler state
4375  * @plane_state: atomic plane state to update
4376  *
4377  * Return
4378  *     0 - scaler_usage updated successfully
4379  *    error - requested scaling cannot be supported or other error condition
4380  */
4381 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4382                                    struct intel_plane_state *plane_state)
4383 {
4384
4385         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
4386         struct intel_plane *intel_plane =
4387                 to_intel_plane(plane_state->base.plane);
4388         struct drm_framebuffer *fb = plane_state->base.fb;
4389         int ret;
4390
4391         bool force_detach = !fb || !plane_state->visible;
4392
4393         DRM_DEBUG_KMS("Updating scaler for [PLANE:%d] scaler_user index %u.%u\n",
4394                       intel_plane->base.base.id, intel_crtc->pipe,
4395                       drm_plane_index(&intel_plane->base));
4396
4397         ret = skl_update_scaler(crtc_state, force_detach,
4398                                 drm_plane_index(&intel_plane->base),
4399                                 &plane_state->scaler_id,
4400                                 plane_state->base.rotation,
4401                                 drm_rect_width(&plane_state->src) >> 16,
4402                                 drm_rect_height(&plane_state->src) >> 16,
4403                                 drm_rect_width(&plane_state->dst),
4404                                 drm_rect_height(&plane_state->dst));
4405
4406         if (ret || plane_state->scaler_id < 0)
4407                 return ret;
4408
4409         /* check colorkey */
4410         if (plane_state->ckey.flags != I915_SET_COLORKEY_NONE) {
4411                 DRM_DEBUG_KMS("[PLANE:%d] scaling with color key not allowed",
4412                               intel_plane->base.base.id);
4413                 return -EINVAL;
4414         }
4415
4416         /* Check src format */
4417         switch (fb->pixel_format) {
4418         case DRM_FORMAT_RGB565:
4419         case DRM_FORMAT_XBGR8888:
4420         case DRM_FORMAT_XRGB8888:
4421         case DRM_FORMAT_ABGR8888:
4422         case DRM_FORMAT_ARGB8888:
4423         case DRM_FORMAT_XRGB2101010:
4424         case DRM_FORMAT_XBGR2101010:
4425         case DRM_FORMAT_YUYV:
4426         case DRM_FORMAT_YVYU:
4427         case DRM_FORMAT_UYVY:
4428         case DRM_FORMAT_VYUY:
4429                 break;
4430         default:
4431                 DRM_DEBUG_KMS("[PLANE:%d] FB:%d unsupported scaling format 0x%x\n",
4432                         intel_plane->base.base.id, fb->base.id, fb->pixel_format);
4433                 return -EINVAL;
4434         }
4435
4436         return 0;
4437 }
4438
4439 static void skylake_scaler_disable(struct intel_crtc *crtc)
4440 {
4441         int i;
4442
4443         for (i = 0; i < crtc->num_scalers; i++)
4444                 skl_detach_scaler(crtc, i);
4445 }
4446
4447 static void skylake_pfit_enable(struct intel_crtc *crtc)
4448 {
4449         struct drm_device *dev = crtc->base.dev;
4450         struct drm_i915_private *dev_priv = dev->dev_private;
4451         int pipe = crtc->pipe;
4452         struct intel_crtc_scaler_state *scaler_state =
4453                 &crtc->config->scaler_state;
4454
4455         DRM_DEBUG_KMS("for crtc_state = %p\n", crtc->config);
4456
4457         if (crtc->config->pch_pfit.enabled) {
4458                 int id;
4459
4460                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0)) {
4461                         DRM_ERROR("Requesting pfit without getting a scaler first\n");
4462                         return;
4463                 }
4464
4465                 id = scaler_state->scaler_id;
4466                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4467                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4468                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
4469                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
4470
4471                 DRM_DEBUG_KMS("for crtc_state = %p scaler_id = %d\n", crtc->config, id);
4472         }
4473 }
4474
4475 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4476 {
4477         struct drm_device *dev = crtc->base.dev;
4478         struct drm_i915_private *dev_priv = dev->dev_private;
4479         int pipe = crtc->pipe;
4480
4481         if (crtc->config->pch_pfit.enabled) {
4482                 /* Force use of hard-coded filter coefficients
4483                  * as some pre-programmed values are broken,
4484                  * e.g. x201.
4485                  */
4486                 if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev))
4487                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4488                                                  PF_PIPE_SEL_IVB(pipe));
4489                 else
4490                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4491                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4492                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4493         }
4494 }
4495
4496 void hsw_enable_ips(struct intel_crtc *crtc)
4497 {
4498         struct drm_device *dev = crtc->base.dev;
4499         struct drm_i915_private *dev_priv = dev->dev_private;
4500
4501         if (!crtc->config->ips_enabled)
4502                 return;
4503
4504         /* We can only enable IPS after we enable a plane and wait for a vblank */
4505         intel_wait_for_vblank(dev, crtc->pipe);
4506
4507         assert_plane_enabled(dev_priv, crtc->plane);
4508         if (IS_BROADWELL(dev)) {
4509                 mutex_lock(&dev_priv->rps.hw_lock);
4510                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0xc0000000));
4511                 mutex_unlock(&dev_priv->rps.hw_lock);
4512                 /* Quoting Art Runyan: "its not safe to expect any particular
4513                  * value in IPS_CTL bit 31 after enabling IPS through the
4514                  * mailbox." Moreover, the mailbox may return a bogus state,
4515                  * so we need to just enable it and continue on.
4516                  */
4517         } else {
4518                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4519                 /* The bit only becomes 1 in the next vblank, so this wait here
4520                  * is essentially intel_wait_for_vblank. If we don't have this
4521                  * and don't wait for vblanks until the end of crtc_enable, then
4522                  * the HW state readout code will complain that the expected
4523                  * IPS_CTL value is not the one we read. */
4524                 if (wait_for(I915_READ_NOTRACE(IPS_CTL) & IPS_ENABLE, 50))
4525                         DRM_ERROR("Timed out waiting for IPS enable\n");
4526         }
4527 }
4528
4529 void hsw_disable_ips(struct intel_crtc *crtc)
4530 {
4531         struct drm_device *dev = crtc->base.dev;
4532         struct drm_i915_private *dev_priv = dev->dev_private;
4533
4534         if (!crtc->config->ips_enabled)
4535                 return;
4536
4537         assert_plane_enabled(dev_priv, crtc->plane);
4538         if (IS_BROADWELL(dev)) {
4539                 mutex_lock(&dev_priv->rps.hw_lock);
4540                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4541                 mutex_unlock(&dev_priv->rps.hw_lock);
4542                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4543                 if (wait_for((I915_READ(IPS_CTL) & IPS_ENABLE) == 0, 42))
4544                         DRM_ERROR("Timed out waiting for IPS disable\n");
4545         } else {
4546                 I915_WRITE(IPS_CTL, 0);
4547                 POSTING_READ(IPS_CTL);
4548         }
4549
4550         /* We need to wait for a vblank before we can disable the plane. */
4551         intel_wait_for_vblank(dev, crtc->pipe);
4552 }
4553
4554 /** Loads the palette/gamma unit for the CRTC with the prepared values */
4555 static void intel_crtc_load_lut(struct drm_crtc *crtc)
4556 {
4557         struct drm_device *dev = crtc->dev;
4558         struct drm_i915_private *dev_priv = dev->dev_private;
4559         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4560         enum pipe pipe = intel_crtc->pipe;
4561         int palreg = PALETTE(pipe);
4562         int i;
4563         bool reenable_ips = false;
4564
4565         /* The clocks have to be on to load the palette. */
4566         if (!crtc->state->active)
4567                 return;
4568
4569         if (HAS_GMCH_DISPLAY(dev_priv->dev)) {
4570                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_DSI))
4571                         assert_dsi_pll_enabled(dev_priv);
4572                 else
4573                         assert_pll_enabled(dev_priv, pipe);
4574         }
4575
4576         /* use legacy palette for Ironlake */
4577         if (!HAS_GMCH_DISPLAY(dev))
4578                 palreg = LGC_PALETTE(pipe);
4579
4580         /* Workaround : Do not read or write the pipe palette/gamma data while
4581          * GAMMA_MODE is configured for split gamma and IPS_CTL has IPS enabled.
4582          */
4583         if (IS_HASWELL(dev) && intel_crtc->config->ips_enabled &&
4584             ((I915_READ(GAMMA_MODE(pipe)) & GAMMA_MODE_MODE_MASK) ==
4585              GAMMA_MODE_MODE_SPLIT)) {
4586                 hsw_disable_ips(intel_crtc);
4587                 reenable_ips = true;
4588         }
4589
4590         for (i = 0; i < 256; i++) {
4591                 I915_WRITE(palreg + 4 * i,
4592                            (intel_crtc->lut_r[i] << 16) |
4593                            (intel_crtc->lut_g[i] << 8) |
4594                            intel_crtc->lut_b[i]);
4595         }
4596
4597         if (reenable_ips)
4598                 hsw_enable_ips(intel_crtc);
4599 }
4600
4601 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
4602 {
4603         if (intel_crtc->overlay) {
4604                 struct drm_device *dev = intel_crtc->base.dev;
4605                 struct drm_i915_private *dev_priv = dev->dev_private;
4606
4607                 mutex_lock(&dev->struct_mutex);
4608                 dev_priv->mm.interruptible = false;
4609                 (void) intel_overlay_switch_off(intel_crtc->overlay);
4610                 dev_priv->mm.interruptible = true;
4611                 mutex_unlock(&dev->struct_mutex);
4612         }
4613
4614         /* Let userspace switch the overlay on again. In most cases userspace
4615          * has to recompute where to put it anyway.
4616          */
4617 }
4618
4619 /**
4620  * intel_post_enable_primary - Perform operations after enabling primary plane
4621  * @crtc: the CRTC whose primary plane was just enabled
4622  *
4623  * Performs potentially sleeping operations that must be done after the primary
4624  * plane is enabled, such as updating FBC and IPS.  Note that this may be
4625  * called due to an explicit primary plane update, or due to an implicit
4626  * re-enable that is caused when a sprite plane is updated to no longer
4627  * completely hide the primary plane.
4628  */
4629 static void
4630 intel_post_enable_primary(struct drm_crtc *crtc)
4631 {
4632         struct drm_device *dev = crtc->dev;
4633         struct drm_i915_private *dev_priv = dev->dev_private;
4634         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4635         int pipe = intel_crtc->pipe;
4636
4637         /*
4638          * BDW signals flip done immediately if the plane
4639          * is disabled, even if the plane enable is already
4640          * armed to occur at the next vblank :(
4641          */
4642         if (IS_BROADWELL(dev))
4643                 intel_wait_for_vblank(dev, pipe);
4644
4645         /*
4646          * FIXME IPS should be fine as long as one plane is
4647          * enabled, but in practice it seems to have problems
4648          * when going from primary only to sprite only and vice
4649          * versa.
4650          */
4651         hsw_enable_ips(intel_crtc);
4652
4653         /*
4654          * Gen2 reports pipe underruns whenever all planes are disabled.
4655          * So don't enable underrun reporting before at least some planes
4656          * are enabled.
4657          * FIXME: Need to fix the logic to work when we turn off all planes
4658          * but leave the pipe running.
4659          */
4660         if (IS_GEN2(dev))
4661                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4662
4663         /* Underruns don't raise interrupts, so check manually. */
4664         if (HAS_GMCH_DISPLAY(dev))
4665                 i9xx_check_fifo_underruns(dev_priv);
4666 }
4667
4668 /**
4669  * intel_pre_disable_primary - Perform operations before disabling primary plane
4670  * @crtc: the CRTC whose primary plane is to be disabled
4671  *
4672  * Performs potentially sleeping operations that must be done before the
4673  * primary plane is disabled, such as updating FBC and IPS.  Note that this may
4674  * be called due to an explicit primary plane update, or due to an implicit
4675  * disable that is caused when a sprite plane completely hides the primary
4676  * plane.
4677  */
4678 static void
4679 intel_pre_disable_primary(struct drm_crtc *crtc)
4680 {
4681         struct drm_device *dev = crtc->dev;
4682         struct drm_i915_private *dev_priv = dev->dev_private;
4683         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4684         int pipe = intel_crtc->pipe;
4685
4686         /*
4687          * Gen2 reports pipe underruns whenever all planes are disabled.
4688          * So diasble underrun reporting before all the planes get disabled.
4689          * FIXME: Need to fix the logic to work when we turn off all planes
4690          * but leave the pipe running.
4691          */
4692         if (IS_GEN2(dev))
4693                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4694
4695         /*
4696          * Vblank time updates from the shadow to live plane control register
4697          * are blocked if the memory self-refresh mode is active at that
4698          * moment. So to make sure the plane gets truly disabled, disable
4699          * first the self-refresh mode. The self-refresh enable bit in turn
4700          * will be checked/applied by the HW only at the next frame start
4701          * event which is after the vblank start event, so we need to have a
4702          * wait-for-vblank between disabling the plane and the pipe.
4703          */
4704         if (HAS_GMCH_DISPLAY(dev)) {
4705                 intel_set_memory_cxsr(dev_priv, false);
4706                 dev_priv->wm.vlv.cxsr = false;
4707                 intel_wait_for_vblank(dev, pipe);
4708         }
4709
4710         /*
4711          * FIXME IPS should be fine as long as one plane is
4712          * enabled, but in practice it seems to have problems
4713          * when going from primary only to sprite only and vice
4714          * versa.
4715          */
4716         hsw_disable_ips(intel_crtc);
4717 }
4718
4719 static void intel_post_plane_update(struct intel_crtc *crtc)
4720 {
4721         struct intel_crtc_atomic_commit *atomic = &crtc->atomic;
4722         struct drm_device *dev = crtc->base.dev;
4723         struct drm_i915_private *dev_priv = dev->dev_private;
4724         struct drm_plane *plane;
4725
4726         if (atomic->wait_vblank)
4727                 intel_wait_for_vblank(dev, crtc->pipe);
4728
4729         intel_frontbuffer_flip(dev, atomic->fb_bits);
4730
4731         if (atomic->disable_cxsr)
4732                 crtc->wm.cxsr_allowed = true;
4733
4734         if (crtc->atomic.update_wm_post)
4735                 intel_update_watermarks(&crtc->base);
4736
4737         if (atomic->update_fbc)
4738                 intel_fbc_update(dev_priv);
4739
4740         if (atomic->post_enable_primary)
4741                 intel_post_enable_primary(&crtc->base);
4742
4743         drm_for_each_plane_mask(plane, dev, atomic->update_sprite_watermarks)
4744                 intel_update_sprite_watermarks(plane, &crtc->base,
4745                                                0, 0, 0, false, false);
4746
4747         memset(atomic, 0, sizeof(*atomic));
4748 }
4749
4750 static void intel_pre_plane_update(struct intel_crtc *crtc)
4751 {
4752         struct drm_device *dev = crtc->base.dev;
4753         struct drm_i915_private *dev_priv = dev->dev_private;
4754         struct intel_crtc_atomic_commit *atomic = &crtc->atomic;
4755         struct drm_plane *p;
4756
4757         /* Track fb's for any planes being disabled */
4758         drm_for_each_plane_mask(p, dev, atomic->disabled_planes) {
4759                 struct intel_plane *plane = to_intel_plane(p);
4760
4761                 mutex_lock(&dev->struct_mutex);
4762                 i915_gem_track_fb(intel_fb_obj(plane->base.fb), NULL,
4763                                   plane->frontbuffer_bit);
4764                 mutex_unlock(&dev->struct_mutex);
4765         }
4766
4767         if (atomic->wait_for_flips)
4768                 intel_crtc_wait_for_pending_flips(&crtc->base);
4769
4770         if (atomic->disable_fbc)
4771                 intel_fbc_disable_crtc(crtc);
4772
4773         if (crtc->atomic.disable_ips)
4774                 hsw_disable_ips(crtc);
4775
4776         if (atomic->pre_disable_primary)
4777                 intel_pre_disable_primary(&crtc->base);
4778
4779         if (atomic->disable_cxsr) {
4780                 crtc->wm.cxsr_allowed = false;
4781                 intel_set_memory_cxsr(dev_priv, false);
4782         }
4783 }
4784
4785 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
4786 {
4787         struct drm_device *dev = crtc->dev;
4788         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4789         struct drm_plane *p;
4790         int pipe = intel_crtc->pipe;
4791
4792         intel_crtc_dpms_overlay_disable(intel_crtc);
4793
4794         drm_for_each_plane_mask(p, dev, plane_mask)
4795                 to_intel_plane(p)->disable_plane(p, crtc);
4796
4797         /*
4798          * FIXME: Once we grow proper nuclear flip support out of this we need
4799          * to compute the mask of flip planes precisely. For the time being
4800          * consider this a flip to a NULL plane.
4801          */
4802         intel_frontbuffer_flip(dev, INTEL_FRONTBUFFER_ALL_MASK(pipe));
4803 }
4804
4805 static void ironlake_crtc_enable(struct drm_crtc *crtc)
4806 {
4807         struct drm_device *dev = crtc->dev;
4808         struct drm_i915_private *dev_priv = dev->dev_private;
4809         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4810         struct intel_encoder *encoder;
4811         int pipe = intel_crtc->pipe;
4812
4813         if (WARN_ON(intel_crtc->active))
4814                 return;
4815
4816         if (intel_crtc->config->has_pch_encoder)
4817                 intel_prepare_shared_dpll(intel_crtc);
4818
4819         if (intel_crtc->config->has_dp_encoder)
4820                 intel_dp_set_m_n(intel_crtc, M1_N1);
4821
4822         intel_set_pipe_timings(intel_crtc);
4823
4824         if (intel_crtc->config->has_pch_encoder) {
4825                 intel_cpu_transcoder_set_m_n(intel_crtc,
4826                                      &intel_crtc->config->fdi_m_n, NULL);
4827         }
4828
4829         ironlake_set_pipeconf(crtc);
4830
4831         intel_crtc->active = true;
4832
4833         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4834         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
4835
4836         for_each_encoder_on_crtc(dev, crtc, encoder)
4837                 if (encoder->pre_enable)
4838                         encoder->pre_enable(encoder);
4839
4840         if (intel_crtc->config->has_pch_encoder) {
4841                 /* Note: FDI PLL enabling _must_ be done before we enable the
4842                  * cpu pipes, hence this is separate from all the other fdi/pch
4843                  * enabling. */
4844                 ironlake_fdi_pll_enable(intel_crtc);
4845         } else {
4846                 assert_fdi_tx_disabled(dev_priv, pipe);
4847                 assert_fdi_rx_disabled(dev_priv, pipe);
4848         }
4849
4850         ironlake_pfit_enable(intel_crtc);
4851
4852         /*
4853          * On ILK+ LUT must be loaded before the pipe is running but with
4854          * clocks enabled
4855          */
4856         intel_crtc_load_lut(crtc);
4857
4858         intel_update_watermarks(crtc);
4859         intel_enable_pipe(intel_crtc);
4860
4861         if (intel_crtc->config->has_pch_encoder)
4862                 ironlake_pch_enable(crtc);
4863
4864         assert_vblank_disabled(crtc);
4865         drm_crtc_vblank_on(crtc);
4866
4867         for_each_encoder_on_crtc(dev, crtc, encoder)
4868                 encoder->enable(encoder);
4869
4870         if (HAS_PCH_CPT(dev))
4871                 cpt_verify_modeset(dev, intel_crtc->pipe);
4872 }
4873
4874 /* IPS only exists on ULT machines and is tied to pipe A. */
4875 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
4876 {
4877         return HAS_IPS(crtc->base.dev) && crtc->pipe == PIPE_A;
4878 }
4879
4880 static void haswell_crtc_enable(struct drm_crtc *crtc)
4881 {
4882         struct drm_device *dev = crtc->dev;
4883         struct drm_i915_private *dev_priv = dev->dev_private;
4884         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4885         struct intel_encoder *encoder;
4886         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
4887         struct intel_crtc_state *pipe_config =
4888                 to_intel_crtc_state(crtc->state);
4889
4890         if (WARN_ON(intel_crtc->active))
4891                 return;
4892
4893         if (intel_crtc_to_shared_dpll(intel_crtc))
4894                 intel_enable_shared_dpll(intel_crtc);
4895
4896         if (intel_crtc->config->has_dp_encoder)
4897                 intel_dp_set_m_n(intel_crtc, M1_N1);
4898
4899         intel_set_pipe_timings(intel_crtc);
4900
4901         if (intel_crtc->config->cpu_transcoder != TRANSCODER_EDP) {
4902                 I915_WRITE(PIPE_MULT(intel_crtc->config->cpu_transcoder),
4903                            intel_crtc->config->pixel_multiplier - 1);
4904         }
4905
4906         if (intel_crtc->config->has_pch_encoder) {
4907                 intel_cpu_transcoder_set_m_n(intel_crtc,
4908                                      &intel_crtc->config->fdi_m_n, NULL);
4909         }
4910
4911         haswell_set_pipeconf(crtc);
4912
4913         intel_set_pipe_csc(crtc);
4914
4915         intel_crtc->active = true;
4916
4917         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4918         for_each_encoder_on_crtc(dev, crtc, encoder)
4919                 if (encoder->pre_enable)
4920                         encoder->pre_enable(encoder);
4921
4922         if (intel_crtc->config->has_pch_encoder) {
4923                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4924                                                       true);
4925                 dev_priv->display.fdi_link_train(crtc);
4926         }
4927
4928         intel_ddi_enable_pipe_clock(intel_crtc);
4929
4930         if (INTEL_INFO(dev)->gen == 9)
4931                 skylake_pfit_enable(intel_crtc);
4932         else if (INTEL_INFO(dev)->gen < 9)
4933                 ironlake_pfit_enable(intel_crtc);
4934         else
4935                 MISSING_CASE(INTEL_INFO(dev)->gen);
4936
4937         /*
4938          * On ILK+ LUT must be loaded before the pipe is running but with
4939          * clocks enabled
4940          */
4941         intel_crtc_load_lut(crtc);
4942
4943         intel_ddi_set_pipe_settings(crtc);
4944         intel_ddi_enable_transcoder_func(crtc);
4945
4946         intel_update_watermarks(crtc);
4947         intel_enable_pipe(intel_crtc);
4948
4949         if (intel_crtc->config->has_pch_encoder)
4950                 lpt_pch_enable(crtc);
4951
4952         if (intel_crtc->config->dp_encoder_is_mst)
4953                 intel_ddi_set_vc_payload_alloc(crtc, true);
4954
4955         assert_vblank_disabled(crtc);
4956         drm_crtc_vblank_on(crtc);
4957
4958         for_each_encoder_on_crtc(dev, crtc, encoder) {
4959                 encoder->enable(encoder);
4960                 intel_opregion_notify_encoder(encoder, true);
4961         }
4962
4963         /* If we change the relative order between pipe/planes enabling, we need
4964          * to change the workaround. */
4965         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
4966         if (IS_HASWELL(dev) && hsw_workaround_pipe != INVALID_PIPE) {
4967                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
4968                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
4969         }
4970 }
4971
4972 static void ironlake_pfit_disable(struct intel_crtc *crtc)
4973 {
4974         struct drm_device *dev = crtc->base.dev;
4975         struct drm_i915_private *dev_priv = dev->dev_private;
4976         int pipe = crtc->pipe;
4977
4978         /* To avoid upsetting the power well on haswell only disable the pfit if
4979          * it's in use. The hw state code will make sure we get this right. */
4980         if (crtc->config->pch_pfit.enabled) {
4981                 I915_WRITE(PF_CTL(pipe), 0);
4982                 I915_WRITE(PF_WIN_POS(pipe), 0);
4983                 I915_WRITE(PF_WIN_SZ(pipe), 0);
4984         }
4985 }
4986
4987 static void ironlake_crtc_disable(struct drm_crtc *crtc)
4988 {
4989         struct drm_device *dev = crtc->dev;
4990         struct drm_i915_private *dev_priv = dev->dev_private;
4991         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4992         struct intel_encoder *encoder;
4993         int pipe = intel_crtc->pipe;
4994         u32 reg, temp;
4995
4996         for_each_encoder_on_crtc(dev, crtc, encoder)
4997                 encoder->disable(encoder);
4998
4999         drm_crtc_vblank_off(crtc);
5000         assert_vblank_disabled(crtc);
5001
5002         if (intel_crtc->config->has_pch_encoder)
5003                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5004
5005         intel_disable_pipe(intel_crtc);
5006
5007         ironlake_pfit_disable(intel_crtc);
5008
5009         if (intel_crtc->config->has_pch_encoder)
5010                 ironlake_fdi_disable(crtc);
5011
5012         for_each_encoder_on_crtc(dev, crtc, encoder)
5013                 if (encoder->post_disable)
5014                         encoder->post_disable(encoder);
5015
5016         if (intel_crtc->config->has_pch_encoder) {
5017                 ironlake_disable_pch_transcoder(dev_priv, pipe);
5018
5019                 if (HAS_PCH_CPT(dev)) {
5020                         /* disable TRANS_DP_CTL */
5021                         reg = TRANS_DP_CTL(pipe);
5022                         temp = I915_READ(reg);
5023                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5024                                   TRANS_DP_PORT_SEL_MASK);
5025                         temp |= TRANS_DP_PORT_SEL_NONE;
5026                         I915_WRITE(reg, temp);
5027
5028                         /* disable DPLL_SEL */
5029                         temp = I915_READ(PCH_DPLL_SEL);
5030                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5031                         I915_WRITE(PCH_DPLL_SEL, temp);
5032                 }
5033
5034                 ironlake_fdi_pll_disable(intel_crtc);
5035         }
5036
5037         intel_crtc->active = false;
5038         intel_update_watermarks(crtc);
5039 }
5040
5041 static void haswell_crtc_disable(struct drm_crtc *crtc)
5042 {
5043         struct drm_device *dev = crtc->dev;
5044         struct drm_i915_private *dev_priv = dev->dev_private;
5045         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5046         struct intel_encoder *encoder;
5047         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5048
5049         for_each_encoder_on_crtc(dev, crtc, encoder) {
5050                 intel_opregion_notify_encoder(encoder, false);
5051                 encoder->disable(encoder);
5052         }
5053
5054         drm_crtc_vblank_off(crtc);
5055         assert_vblank_disabled(crtc);
5056
5057         if (intel_crtc->config->has_pch_encoder)
5058                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5059                                                       false);
5060         intel_disable_pipe(intel_crtc);
5061
5062         if (intel_crtc->config->dp_encoder_is_mst)
5063                 intel_ddi_set_vc_payload_alloc(crtc, false);
5064
5065         intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
5066
5067         if (INTEL_INFO(dev)->gen == 9)
5068                 skylake_scaler_disable(intel_crtc);
5069         else if (INTEL_INFO(dev)->gen < 9)
5070                 ironlake_pfit_disable(intel_crtc);
5071         else
5072                 MISSING_CASE(INTEL_INFO(dev)->gen);
5073
5074         intel_ddi_disable_pipe_clock(intel_crtc);
5075
5076         if (intel_crtc->config->has_pch_encoder) {
5077                 lpt_disable_pch_transcoder(dev_priv);
5078                 intel_ddi_fdi_disable(crtc);
5079         }
5080
5081         for_each_encoder_on_crtc(dev, crtc, encoder)
5082                 if (encoder->post_disable)
5083                         encoder->post_disable(encoder);
5084
5085         intel_crtc->active = false;
5086         intel_update_watermarks(crtc);
5087 }
5088
5089 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5090 {
5091         struct drm_device *dev = crtc->base.dev;
5092         struct drm_i915_private *dev_priv = dev->dev_private;
5093         struct intel_crtc_state *pipe_config = crtc->config;
5094
5095         if (!pipe_config->gmch_pfit.control)
5096                 return;
5097
5098         /*
5099          * The panel fitter should only be adjusted whilst the pipe is disabled,
5100          * according to register description and PRM.
5101          */
5102         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5103         assert_pipe_disabled(dev_priv, crtc->pipe);
5104
5105         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5106         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5107
5108         /* Border color in case we don't scale up to the full screen. Black by
5109          * default, change to something else for debugging. */
5110         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5111 }
5112
5113 static enum intel_display_power_domain port_to_power_domain(enum port port)
5114 {
5115         switch (port) {
5116         case PORT_A:
5117         case PORT_E:
5118                 return POWER_DOMAIN_PORT_DDI_A_4_LANES;
5119         case PORT_B:
5120                 return POWER_DOMAIN_PORT_DDI_B_4_LANES;
5121         case PORT_C:
5122                 return POWER_DOMAIN_PORT_DDI_C_4_LANES;
5123         case PORT_D:
5124                 return POWER_DOMAIN_PORT_DDI_D_4_LANES;
5125         default:
5126                 WARN_ON_ONCE(1);
5127                 return POWER_DOMAIN_PORT_OTHER;
5128         }
5129 }
5130
5131 #define for_each_power_domain(domain, mask)                             \
5132         for ((domain) = 0; (domain) < POWER_DOMAIN_NUM; (domain)++)     \
5133                 if ((1 << (domain)) & (mask))
5134
5135 enum intel_display_power_domain
5136 intel_display_port_power_domain(struct intel_encoder *intel_encoder)
5137 {
5138         struct drm_device *dev = intel_encoder->base.dev;
5139         struct intel_digital_port *intel_dig_port;
5140
5141         switch (intel_encoder->type) {
5142         case INTEL_OUTPUT_UNKNOWN:
5143                 /* Only DDI platforms should ever use this output type */
5144                 WARN_ON_ONCE(!HAS_DDI(dev));
5145         case INTEL_OUTPUT_DISPLAYPORT:
5146         case INTEL_OUTPUT_HDMI:
5147         case INTEL_OUTPUT_EDP:
5148                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5149                 return port_to_power_domain(intel_dig_port->port);
5150         case INTEL_OUTPUT_DP_MST:
5151                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5152                 return port_to_power_domain(intel_dig_port->port);
5153         case INTEL_OUTPUT_ANALOG:
5154                 return POWER_DOMAIN_PORT_CRT;
5155         case INTEL_OUTPUT_DSI:
5156                 return POWER_DOMAIN_PORT_DSI;
5157         default:
5158                 return POWER_DOMAIN_PORT_OTHER;
5159         }
5160 }
5161
5162 static unsigned long get_crtc_power_domains(struct drm_crtc *crtc)
5163 {
5164         struct drm_device *dev = crtc->dev;
5165         struct intel_encoder *intel_encoder;
5166         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5167         enum pipe pipe = intel_crtc->pipe;
5168         unsigned long mask;
5169         enum transcoder transcoder;
5170
5171         if (!crtc->state->active)
5172                 return 0;
5173
5174         transcoder = intel_pipe_to_cpu_transcoder(dev->dev_private, pipe);
5175
5176         mask = BIT(POWER_DOMAIN_PIPE(pipe));
5177         mask |= BIT(POWER_DOMAIN_TRANSCODER(transcoder));
5178         if (intel_crtc->config->pch_pfit.enabled ||
5179             intel_crtc->config->pch_pfit.force_thru)
5180                 mask |= BIT(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5181
5182         for_each_encoder_on_crtc(dev, crtc, intel_encoder)
5183                 mask |= BIT(intel_display_port_power_domain(intel_encoder));
5184
5185         return mask;
5186 }
5187
5188 static unsigned long modeset_get_crtc_power_domains(struct drm_crtc *crtc)
5189 {
5190         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
5191         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5192         enum intel_display_power_domain domain;
5193         unsigned long domains, new_domains, old_domains;
5194
5195         old_domains = intel_crtc->enabled_power_domains;
5196         intel_crtc->enabled_power_domains = new_domains = get_crtc_power_domains(crtc);
5197
5198         domains = new_domains & ~old_domains;
5199
5200         for_each_power_domain(domain, domains)
5201                 intel_display_power_get(dev_priv, domain);
5202
5203         return old_domains & ~new_domains;
5204 }
5205
5206 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
5207                                       unsigned long domains)
5208 {
5209         enum intel_display_power_domain domain;
5210
5211         for_each_power_domain(domain, domains)
5212                 intel_display_power_put(dev_priv, domain);
5213 }
5214
5215 static void modeset_update_crtc_power_domains(struct drm_atomic_state *state)
5216 {
5217         struct drm_device *dev = state->dev;
5218         struct drm_i915_private *dev_priv = dev->dev_private;
5219         unsigned long put_domains[I915_MAX_PIPES] = {};
5220         struct drm_crtc_state *crtc_state;
5221         struct drm_crtc *crtc;
5222         int i;
5223
5224         for_each_crtc_in_state(state, crtc, crtc_state, i) {
5225                 if (needs_modeset(crtc->state))
5226                         put_domains[to_intel_crtc(crtc)->pipe] =
5227                                 modeset_get_crtc_power_domains(crtc);
5228         }
5229
5230         if (dev_priv->display.modeset_commit_cdclk) {
5231                 unsigned int cdclk = to_intel_atomic_state(state)->cdclk;
5232
5233                 if (cdclk != dev_priv->cdclk_freq &&
5234                     !WARN_ON(!state->allow_modeset))
5235                         dev_priv->display.modeset_commit_cdclk(state);
5236         }
5237
5238         for (i = 0; i < I915_MAX_PIPES; i++)
5239                 if (put_domains[i])
5240                         modeset_put_power_domains(dev_priv, put_domains[i]);
5241 }
5242
5243 static void intel_update_max_cdclk(struct drm_device *dev)
5244 {
5245         struct drm_i915_private *dev_priv = dev->dev_private;
5246
5247         if (IS_SKYLAKE(dev)) {
5248                 u32 limit = I915_READ(SKL_DFSM) & SKL_DFSM_CDCLK_LIMIT_MASK;
5249
5250                 if (limit == SKL_DFSM_CDCLK_LIMIT_675)
5251                         dev_priv->max_cdclk_freq = 675000;
5252                 else if (limit == SKL_DFSM_CDCLK_LIMIT_540)
5253                         dev_priv->max_cdclk_freq = 540000;
5254                 else if (limit == SKL_DFSM_CDCLK_LIMIT_450)
5255                         dev_priv->max_cdclk_freq = 450000;
5256                 else
5257                         dev_priv->max_cdclk_freq = 337500;
5258         } else if (IS_BROADWELL(dev))  {
5259                 /*
5260                  * FIXME with extra cooling we can allow
5261                  * 540 MHz for ULX and 675 Mhz for ULT.
5262                  * How can we know if extra cooling is
5263                  * available? PCI ID, VTB, something else?
5264                  */
5265                 if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
5266                         dev_priv->max_cdclk_freq = 450000;
5267                 else if (IS_BDW_ULX(dev))
5268                         dev_priv->max_cdclk_freq = 450000;
5269                 else if (IS_BDW_ULT(dev))
5270                         dev_priv->max_cdclk_freq = 540000;
5271                 else
5272                         dev_priv->max_cdclk_freq = 675000;
5273         } else if (IS_CHERRYVIEW(dev)) {
5274                 dev_priv->max_cdclk_freq = 320000;
5275         } else if (IS_VALLEYVIEW(dev)) {
5276                 dev_priv->max_cdclk_freq = 400000;
5277         } else {
5278                 /* otherwise assume cdclk is fixed */
5279                 dev_priv->max_cdclk_freq = dev_priv->cdclk_freq;
5280         }
5281
5282         DRM_DEBUG_DRIVER("Max CD clock rate: %d kHz\n",
5283                          dev_priv->max_cdclk_freq);
5284 }
5285
5286 static void intel_update_cdclk(struct drm_device *dev)
5287 {
5288         struct drm_i915_private *dev_priv = dev->dev_private;
5289
5290         dev_priv->cdclk_freq = dev_priv->display.get_display_clock_speed(dev);
5291         DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz\n",
5292                          dev_priv->cdclk_freq);
5293
5294         /*
5295          * Program the gmbus_freq based on the cdclk frequency.
5296          * BSpec erroneously claims we should aim for 4MHz, but
5297          * in fact 1MHz is the correct frequency.
5298          */
5299         if (IS_VALLEYVIEW(dev)) {
5300                 /*
5301                  * Program the gmbus_freq based on the cdclk frequency.
5302                  * BSpec erroneously claims we should aim for 4MHz, but
5303                  * in fact 1MHz is the correct frequency.
5304                  */
5305                 I915_WRITE(GMBUSFREQ_VLV, DIV_ROUND_UP(dev_priv->cdclk_freq, 1000));
5306         }
5307
5308         if (dev_priv->max_cdclk_freq == 0)
5309                 intel_update_max_cdclk(dev);
5310 }
5311
5312 static void broxton_set_cdclk(struct drm_device *dev, int frequency)
5313 {
5314         struct drm_i915_private *dev_priv = dev->dev_private;
5315         uint32_t divider;
5316         uint32_t ratio;
5317         uint32_t current_freq;
5318         int ret;
5319
5320         /* frequency = 19.2MHz * ratio / 2 / div{1,1.5,2,4} */
5321         switch (frequency) {
5322         case 144000:
5323                 divider = BXT_CDCLK_CD2X_DIV_SEL_4;
5324                 ratio = BXT_DE_PLL_RATIO(60);
5325                 break;
5326         case 288000:
5327                 divider = BXT_CDCLK_CD2X_DIV_SEL_2;
5328                 ratio = BXT_DE_PLL_RATIO(60);
5329                 break;
5330         case 384000:
5331                 divider = BXT_CDCLK_CD2X_DIV_SEL_1_5;
5332                 ratio = BXT_DE_PLL_RATIO(60);
5333                 break;
5334         case 576000:
5335                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5336                 ratio = BXT_DE_PLL_RATIO(60);
5337                 break;
5338         case 624000:
5339                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5340                 ratio = BXT_DE_PLL_RATIO(65);
5341                 break;
5342         case 19200:
5343                 /*
5344                  * Bypass frequency with DE PLL disabled. Init ratio, divider
5345                  * to suppress GCC warning.
5346                  */
5347                 ratio = 0;
5348                 divider = 0;
5349                 break;
5350         default:
5351                 DRM_ERROR("unsupported CDCLK freq %d", frequency);
5352
5353                 return;
5354         }
5355
5356         mutex_lock(&dev_priv->rps.hw_lock);
5357         /* Inform power controller of upcoming frequency change */
5358         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5359                                       0x80000000);
5360         mutex_unlock(&dev_priv->rps.hw_lock);
5361
5362         if (ret) {
5363                 DRM_ERROR("PCode CDCLK freq change notify failed (err %d, freq %d)\n",
5364                           ret, frequency);
5365                 return;
5366         }
5367
5368         current_freq = I915_READ(CDCLK_CTL) & CDCLK_FREQ_DECIMAL_MASK;
5369         /* convert from .1 fixpoint MHz with -1MHz offset to kHz */
5370         current_freq = current_freq * 500 + 1000;
5371
5372         /*
5373          * DE PLL has to be disabled when
5374          * - setting to 19.2MHz (bypass, PLL isn't used)
5375          * - before setting to 624MHz (PLL needs toggling)
5376          * - before setting to any frequency from 624MHz (PLL needs toggling)
5377          */
5378         if (frequency == 19200 || frequency == 624000 ||
5379             current_freq == 624000) {
5380                 I915_WRITE(BXT_DE_PLL_ENABLE, ~BXT_DE_PLL_PLL_ENABLE);
5381                 /* Timeout 200us */
5382                 if (wait_for(!(I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_LOCK),
5383                              1))
5384                         DRM_ERROR("timout waiting for DE PLL unlock\n");
5385         }
5386
5387         if (frequency != 19200) {
5388                 uint32_t val;
5389
5390                 val = I915_READ(BXT_DE_PLL_CTL);
5391                 val &= ~BXT_DE_PLL_RATIO_MASK;
5392                 val |= ratio;
5393                 I915_WRITE(BXT_DE_PLL_CTL, val);
5394
5395                 I915_WRITE(BXT_DE_PLL_ENABLE, BXT_DE_PLL_PLL_ENABLE);
5396                 /* Timeout 200us */
5397                 if (wait_for(I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_LOCK, 1))
5398                         DRM_ERROR("timeout waiting for DE PLL lock\n");
5399
5400                 val = I915_READ(CDCLK_CTL);
5401                 val &= ~BXT_CDCLK_CD2X_DIV_SEL_MASK;
5402                 val |= divider;
5403                 /*
5404                  * Disable SSA Precharge when CD clock frequency < 500 MHz,
5405                  * enable otherwise.
5406                  */
5407                 val &= ~BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5408                 if (frequency >= 500000)
5409                         val |= BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5410
5411                 val &= ~CDCLK_FREQ_DECIMAL_MASK;
5412                 /* convert from kHz to .1 fixpoint MHz with -1MHz offset */
5413                 val |= (frequency - 1000) / 500;
5414                 I915_WRITE(CDCLK_CTL, val);
5415         }
5416
5417         mutex_lock(&dev_priv->rps.hw_lock);
5418         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5419                                       DIV_ROUND_UP(frequency, 25000));
5420         mutex_unlock(&dev_priv->rps.hw_lock);
5421
5422         if (ret) {
5423                 DRM_ERROR("PCode CDCLK freq set failed, (err %d, freq %d)\n",
5424                           ret, frequency);
5425                 return;
5426         }
5427
5428         intel_update_cdclk(dev);
5429 }
5430
5431 void broxton_init_cdclk(struct drm_device *dev)
5432 {
5433         struct drm_i915_private *dev_priv = dev->dev_private;
5434         uint32_t val;
5435
5436         /*
5437          * NDE_RSTWRN_OPT RST PCH Handshake En must always be 0b on BXT
5438          * or else the reset will hang because there is no PCH to respond.
5439          * Move the handshake programming to initialization sequence.
5440          * Previously was left up to BIOS.
5441          */
5442         val = I915_READ(HSW_NDE_RSTWRN_OPT);
5443         val &= ~RESET_PCH_HANDSHAKE_ENABLE;
5444         I915_WRITE(HSW_NDE_RSTWRN_OPT, val);
5445
5446         /* Enable PG1 for cdclk */
5447         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
5448
5449         /* check if cd clock is enabled */
5450         if (I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_PLL_ENABLE) {
5451                 DRM_DEBUG_KMS("Display already initialized\n");
5452                 return;
5453         }
5454
5455         /*
5456          * FIXME:
5457          * - The initial CDCLK needs to be read from VBT.
5458          *   Need to make this change after VBT has changes for BXT.
5459          * - check if setting the max (or any) cdclk freq is really necessary
5460          *   here, it belongs to modeset time
5461          */
5462         broxton_set_cdclk(dev, 624000);
5463
5464         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) | DBUF_POWER_REQUEST);
5465         POSTING_READ(DBUF_CTL);
5466
5467         udelay(10);
5468
5469         if (!(I915_READ(DBUF_CTL) & DBUF_POWER_STATE))
5470                 DRM_ERROR("DBuf power enable timeout!\n");
5471 }
5472
5473 void broxton_uninit_cdclk(struct drm_device *dev)
5474 {
5475         struct drm_i915_private *dev_priv = dev->dev_private;
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 disable timeout!\n");
5484
5485         /* Set minimum (bypass) frequency, in effect turning off the DE PLL */
5486         broxton_set_cdclk(dev, 19200);
5487
5488         intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS);
5489 }
5490
5491 static const struct skl_cdclk_entry {
5492         unsigned int freq;
5493         unsigned int vco;
5494 } skl_cdclk_frequencies[] = {
5495         { .freq = 308570, .vco = 8640 },
5496         { .freq = 337500, .vco = 8100 },
5497         { .freq = 432000, .vco = 8640 },
5498         { .freq = 450000, .vco = 8100 },
5499         { .freq = 540000, .vco = 8100 },
5500         { .freq = 617140, .vco = 8640 },
5501         { .freq = 675000, .vco = 8100 },
5502 };
5503
5504 static unsigned int skl_cdclk_decimal(unsigned int freq)
5505 {
5506         return (freq - 1000) / 500;
5507 }
5508
5509 static unsigned int skl_cdclk_get_vco(unsigned int freq)
5510 {
5511         unsigned int i;
5512
5513         for (i = 0; i < ARRAY_SIZE(skl_cdclk_frequencies); i++) {
5514                 const struct skl_cdclk_entry *e = &skl_cdclk_frequencies[i];
5515
5516                 if (e->freq == freq)
5517                         return e->vco;
5518         }
5519
5520         return 8100;
5521 }
5522
5523 static void
5524 skl_dpll0_enable(struct drm_i915_private *dev_priv, unsigned int required_vco)
5525 {
5526         unsigned int min_freq;
5527         u32 val;
5528
5529         /* select the minimum CDCLK before enabling DPLL 0 */
5530         val = I915_READ(CDCLK_CTL);
5531         val &= ~CDCLK_FREQ_SEL_MASK | ~CDCLK_FREQ_DECIMAL_MASK;
5532         val |= CDCLK_FREQ_337_308;
5533
5534         if (required_vco == 8640)
5535                 min_freq = 308570;
5536         else
5537                 min_freq = 337500;
5538
5539         val = CDCLK_FREQ_337_308 | skl_cdclk_decimal(min_freq);
5540
5541         I915_WRITE(CDCLK_CTL, val);
5542         POSTING_READ(CDCLK_CTL);
5543
5544         /*
5545          * We always enable DPLL0 with the lowest link rate possible, but still
5546          * taking into account the VCO required to operate the eDP panel at the
5547          * desired frequency. The usual DP link rates operate with a VCO of
5548          * 8100 while the eDP 1.4 alternate link rates need a VCO of 8640.
5549          * The modeset code is responsible for the selection of the exact link
5550          * rate later on, with the constraint of choosing a frequency that
5551          * works with required_vco.
5552          */
5553         val = I915_READ(DPLL_CTRL1);
5554
5555         val &= ~(DPLL_CTRL1_HDMI_MODE(SKL_DPLL0) | DPLL_CTRL1_SSC(SKL_DPLL0) |
5556                  DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0));
5557         val |= DPLL_CTRL1_OVERRIDE(SKL_DPLL0);
5558         if (required_vco == 8640)
5559                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1080,
5560                                             SKL_DPLL0);
5561         else
5562                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_810,
5563                                             SKL_DPLL0);
5564
5565         I915_WRITE(DPLL_CTRL1, val);
5566         POSTING_READ(DPLL_CTRL1);
5567
5568         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) | LCPLL_PLL_ENABLE);
5569
5570         if (wait_for(I915_READ(LCPLL1_CTL) & LCPLL_PLL_LOCK, 5))
5571                 DRM_ERROR("DPLL0 not locked\n");
5572 }
5573
5574 static bool skl_cdclk_pcu_ready(struct drm_i915_private *dev_priv)
5575 {
5576         int ret;
5577         u32 val;
5578
5579         /* inform PCU we want to change CDCLK */
5580         val = SKL_CDCLK_PREPARE_FOR_CHANGE;
5581         mutex_lock(&dev_priv->rps.hw_lock);
5582         ret = sandybridge_pcode_read(dev_priv, SKL_PCODE_CDCLK_CONTROL, &val);
5583         mutex_unlock(&dev_priv->rps.hw_lock);
5584
5585         return ret == 0 && (val & SKL_CDCLK_READY_FOR_CHANGE);
5586 }
5587
5588 static bool skl_cdclk_wait_for_pcu_ready(struct drm_i915_private *dev_priv)
5589 {
5590         unsigned int i;
5591
5592         for (i = 0; i < 15; i++) {
5593                 if (skl_cdclk_pcu_ready(dev_priv))
5594                         return true;
5595                 udelay(10);
5596         }
5597
5598         return false;
5599 }
5600
5601 static void skl_set_cdclk(struct drm_i915_private *dev_priv, unsigned int freq)
5602 {
5603         struct drm_device *dev = dev_priv->dev;
5604         u32 freq_select, pcu_ack;
5605
5606         DRM_DEBUG_DRIVER("Changing CDCLK to %dKHz\n", freq);
5607
5608         if (!skl_cdclk_wait_for_pcu_ready(dev_priv)) {
5609                 DRM_ERROR("failed to inform PCU about cdclk change\n");
5610                 return;
5611         }
5612
5613         /* set CDCLK_CTL */
5614         switch(freq) {
5615         case 450000:
5616         case 432000:
5617                 freq_select = CDCLK_FREQ_450_432;
5618                 pcu_ack = 1;
5619                 break;
5620         case 540000:
5621                 freq_select = CDCLK_FREQ_540;
5622                 pcu_ack = 2;
5623                 break;
5624         case 308570:
5625         case 337500:
5626         default:
5627                 freq_select = CDCLK_FREQ_337_308;
5628                 pcu_ack = 0;
5629                 break;
5630         case 617140:
5631         case 675000:
5632                 freq_select = CDCLK_FREQ_675_617;
5633                 pcu_ack = 3;
5634                 break;
5635         }
5636
5637         I915_WRITE(CDCLK_CTL, freq_select | skl_cdclk_decimal(freq));
5638         POSTING_READ(CDCLK_CTL);
5639
5640         /* inform PCU of the change */
5641         mutex_lock(&dev_priv->rps.hw_lock);
5642         sandybridge_pcode_write(dev_priv, SKL_PCODE_CDCLK_CONTROL, pcu_ack);
5643         mutex_unlock(&dev_priv->rps.hw_lock);
5644
5645         intel_update_cdclk(dev);
5646 }
5647
5648 void skl_uninit_cdclk(struct drm_i915_private *dev_priv)
5649 {
5650         /* disable DBUF power */
5651         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) & ~DBUF_POWER_REQUEST);
5652         POSTING_READ(DBUF_CTL);
5653
5654         udelay(10);
5655
5656         if (I915_READ(DBUF_CTL) & DBUF_POWER_STATE)
5657                 DRM_ERROR("DBuf power disable timeout\n");
5658
5659         /* disable DPLL0 */
5660         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) & ~LCPLL_PLL_ENABLE);
5661         if (wait_for(!(I915_READ(LCPLL1_CTL) & LCPLL_PLL_LOCK), 1))
5662                 DRM_ERROR("Couldn't disable DPLL0\n");
5663
5664         intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS);
5665 }
5666
5667 void skl_init_cdclk(struct drm_i915_private *dev_priv)
5668 {
5669         u32 val;
5670         unsigned int required_vco;
5671
5672         /* enable PCH reset handshake */
5673         val = I915_READ(HSW_NDE_RSTWRN_OPT);
5674         I915_WRITE(HSW_NDE_RSTWRN_OPT, val | RESET_PCH_HANDSHAKE_ENABLE);
5675
5676         /* enable PG1 and Misc I/O */
5677         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
5678
5679         /* DPLL0 already enabed !? */
5680         if (I915_READ(LCPLL1_CTL) & LCPLL_PLL_ENABLE) {
5681                 DRM_DEBUG_DRIVER("DPLL0 already running\n");
5682                 return;
5683         }
5684
5685         /* enable DPLL0 */
5686         required_vco = skl_cdclk_get_vco(dev_priv->skl_boot_cdclk);
5687         skl_dpll0_enable(dev_priv, required_vco);
5688
5689         /* set CDCLK to the frequency the BIOS chose */
5690         skl_set_cdclk(dev_priv, dev_priv->skl_boot_cdclk);
5691
5692         /* enable DBUF power */
5693         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) | DBUF_POWER_REQUEST);
5694         POSTING_READ(DBUF_CTL);
5695
5696         udelay(10);
5697
5698         if (!(I915_READ(DBUF_CTL) & DBUF_POWER_STATE))
5699                 DRM_ERROR("DBuf power enable timeout\n");
5700 }
5701
5702 /* returns HPLL frequency in kHz */
5703 static int valleyview_get_vco(struct drm_i915_private *dev_priv)
5704 {
5705         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
5706
5707         /* Obtain SKU information */
5708         mutex_lock(&dev_priv->sb_lock);
5709         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
5710                 CCK_FUSE_HPLL_FREQ_MASK;
5711         mutex_unlock(&dev_priv->sb_lock);
5712
5713         return vco_freq[hpll_freq] * 1000;
5714 }
5715
5716 /* Adjust CDclk dividers to allow high res or save power if possible */
5717 static void valleyview_set_cdclk(struct drm_device *dev, int cdclk)
5718 {
5719         struct drm_i915_private *dev_priv = dev->dev_private;
5720         u32 val, cmd;
5721
5722         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5723                                         != dev_priv->cdclk_freq);
5724
5725         if (cdclk >= 320000) /* jump to highest voltage for 400MHz too */
5726                 cmd = 2;
5727         else if (cdclk == 266667)
5728                 cmd = 1;
5729         else
5730                 cmd = 0;
5731
5732         mutex_lock(&dev_priv->rps.hw_lock);
5733         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5734         val &= ~DSPFREQGUAR_MASK;
5735         val |= (cmd << DSPFREQGUAR_SHIFT);
5736         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5737         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5738                       DSPFREQSTAT_MASK) == (cmd << DSPFREQSTAT_SHIFT),
5739                      50)) {
5740                 DRM_ERROR("timed out waiting for CDclk change\n");
5741         }
5742         mutex_unlock(&dev_priv->rps.hw_lock);
5743
5744         mutex_lock(&dev_priv->sb_lock);
5745
5746         if (cdclk == 400000) {
5747                 u32 divider;
5748
5749                 divider = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5750
5751                 /* adjust cdclk divider */
5752                 val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
5753                 val &= ~DISPLAY_FREQUENCY_VALUES;
5754                 val |= divider;
5755                 vlv_cck_write(dev_priv, CCK_DISPLAY_CLOCK_CONTROL, val);
5756
5757                 if (wait_for((vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL) &
5758                               DISPLAY_FREQUENCY_STATUS) == (divider << DISPLAY_FREQUENCY_STATUS_SHIFT),
5759                              50))
5760                         DRM_ERROR("timed out waiting for CDclk change\n");
5761         }
5762
5763         /* adjust self-refresh exit latency value */
5764         val = vlv_bunit_read(dev_priv, BUNIT_REG_BISOC);
5765         val &= ~0x7f;
5766
5767         /*
5768          * For high bandwidth configs, we set a higher latency in the bunit
5769          * so that the core display fetch happens in time to avoid underruns.
5770          */
5771         if (cdclk == 400000)
5772                 val |= 4500 / 250; /* 4.5 usec */
5773         else
5774                 val |= 3000 / 250; /* 3.0 usec */
5775         vlv_bunit_write(dev_priv, BUNIT_REG_BISOC, val);
5776
5777         mutex_unlock(&dev_priv->sb_lock);
5778
5779         intel_update_cdclk(dev);
5780 }
5781
5782 static void cherryview_set_cdclk(struct drm_device *dev, int cdclk)
5783 {
5784         struct drm_i915_private *dev_priv = dev->dev_private;
5785         u32 val, cmd;
5786
5787         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5788                                                 != dev_priv->cdclk_freq);
5789
5790         switch (cdclk) {
5791         case 333333:
5792         case 320000:
5793         case 266667:
5794         case 200000:
5795                 break;
5796         default:
5797                 MISSING_CASE(cdclk);
5798                 return;
5799         }
5800
5801         /*
5802          * Specs are full of misinformation, but testing on actual
5803          * hardware has shown that we just need to write the desired
5804          * CCK divider into the Punit register.
5805          */
5806         cmd = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5807
5808         mutex_lock(&dev_priv->rps.hw_lock);
5809         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5810         val &= ~DSPFREQGUAR_MASK_CHV;
5811         val |= (cmd << DSPFREQGUAR_SHIFT_CHV);
5812         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5813         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5814                       DSPFREQSTAT_MASK_CHV) == (cmd << DSPFREQSTAT_SHIFT_CHV),
5815                      50)) {
5816                 DRM_ERROR("timed out waiting for CDclk change\n");
5817         }
5818         mutex_unlock(&dev_priv->rps.hw_lock);
5819
5820         intel_update_cdclk(dev);
5821 }
5822
5823 static int valleyview_calc_cdclk(struct drm_i915_private *dev_priv,
5824                                  int max_pixclk)
5825 {
5826         int freq_320 = (dev_priv->hpll_freq <<  1) % 320000 != 0 ? 333333 : 320000;
5827         int limit = IS_CHERRYVIEW(dev_priv) ? 95 : 90;
5828
5829         /*
5830          * Really only a few cases to deal with, as only 4 CDclks are supported:
5831          *   200MHz
5832          *   267MHz
5833          *   320/333MHz (depends on HPLL freq)
5834          *   400MHz (VLV only)
5835          * So we check to see whether we're above 90% (VLV) or 95% (CHV)
5836          * of the lower bin and adjust if needed.
5837          *
5838          * We seem to get an unstable or solid color picture at 200MHz.
5839          * Not sure what's wrong. For now use 200MHz only when all pipes
5840          * are off.
5841          */
5842         if (!IS_CHERRYVIEW(dev_priv) &&
5843             max_pixclk > freq_320*limit/100)
5844                 return 400000;
5845         else if (max_pixclk > 266667*limit/100)
5846                 return freq_320;
5847         else if (max_pixclk > 0)
5848                 return 266667;
5849         else
5850                 return 200000;
5851 }
5852
5853 static int broxton_calc_cdclk(struct drm_i915_private *dev_priv,
5854                               int max_pixclk)
5855 {
5856         /*
5857          * FIXME:
5858          * - remove the guardband, it's not needed on BXT
5859          * - set 19.2MHz bypass frequency if there are no active pipes
5860          */
5861         if (max_pixclk > 576000*9/10)
5862                 return 624000;
5863         else if (max_pixclk > 384000*9/10)
5864                 return 576000;
5865         else if (max_pixclk > 288000*9/10)
5866                 return 384000;
5867         else if (max_pixclk > 144000*9/10)
5868                 return 288000;
5869         else
5870                 return 144000;
5871 }
5872
5873 /* Compute the max pixel clock for new configuration. Uses atomic state if
5874  * that's non-NULL, look at current state otherwise. */
5875 static int intel_mode_max_pixclk(struct drm_device *dev,
5876                                  struct drm_atomic_state *state)
5877 {
5878         struct intel_crtc *intel_crtc;
5879         struct intel_crtc_state *crtc_state;
5880         int max_pixclk = 0;
5881
5882         for_each_intel_crtc(dev, intel_crtc) {
5883                 crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
5884                 if (IS_ERR(crtc_state))
5885                         return PTR_ERR(crtc_state);
5886
5887                 if (!crtc_state->base.enable)
5888                         continue;
5889
5890                 max_pixclk = max(max_pixclk,
5891                                  crtc_state->base.adjusted_mode.crtc_clock);
5892         }
5893
5894         return max_pixclk;
5895 }
5896
5897 static int valleyview_modeset_calc_cdclk(struct drm_atomic_state *state)
5898 {
5899         struct drm_device *dev = state->dev;
5900         struct drm_i915_private *dev_priv = dev->dev_private;
5901         int max_pixclk = intel_mode_max_pixclk(dev, state);
5902
5903         if (max_pixclk < 0)
5904                 return max_pixclk;
5905
5906         to_intel_atomic_state(state)->cdclk =
5907                 valleyview_calc_cdclk(dev_priv, max_pixclk);
5908
5909         return 0;
5910 }
5911
5912 static int broxton_modeset_calc_cdclk(struct drm_atomic_state *state)
5913 {
5914         struct drm_device *dev = state->dev;
5915         struct drm_i915_private *dev_priv = dev->dev_private;
5916         int max_pixclk = intel_mode_max_pixclk(dev, state);
5917
5918         if (max_pixclk < 0)
5919                 return max_pixclk;
5920
5921         to_intel_atomic_state(state)->cdclk =
5922                 broxton_calc_cdclk(dev_priv, max_pixclk);
5923
5924         return 0;
5925 }
5926
5927 static void vlv_program_pfi_credits(struct drm_i915_private *dev_priv)
5928 {
5929         unsigned int credits, default_credits;
5930
5931         if (IS_CHERRYVIEW(dev_priv))
5932                 default_credits = PFI_CREDIT(12);
5933         else
5934                 default_credits = PFI_CREDIT(8);
5935
5936         if (DIV_ROUND_CLOSEST(dev_priv->cdclk_freq, 1000) >= dev_priv->rps.cz_freq) {
5937                 /* CHV suggested value is 31 or 63 */
5938                 if (IS_CHERRYVIEW(dev_priv))
5939                         credits = PFI_CREDIT_63;
5940                 else
5941                         credits = PFI_CREDIT(15);
5942         } else {
5943                 credits = default_credits;
5944         }
5945
5946         /*
5947          * WA - write default credits before re-programming
5948          * FIXME: should we also set the resend bit here?
5949          */
5950         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
5951                    default_credits);
5952
5953         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
5954                    credits | PFI_CREDIT_RESEND);
5955
5956         /*
5957          * FIXME is this guaranteed to clear
5958          * immediately or should we poll for it?
5959          */
5960         WARN_ON(I915_READ(GCI_CONTROL) & PFI_CREDIT_RESEND);
5961 }
5962
5963 static void valleyview_modeset_commit_cdclk(struct drm_atomic_state *old_state)
5964 {
5965         struct drm_device *dev = old_state->dev;
5966         unsigned int req_cdclk = to_intel_atomic_state(old_state)->cdclk;
5967         struct drm_i915_private *dev_priv = dev->dev_private;
5968
5969         /*
5970          * FIXME: We can end up here with all power domains off, yet
5971          * with a CDCLK frequency other than the minimum. To account
5972          * for this take the PIPE-A power domain, which covers the HW
5973          * blocks needed for the following programming. This can be
5974          * removed once it's guaranteed that we get here either with
5975          * the minimum CDCLK set, or the required power domains
5976          * enabled.
5977          */
5978         intel_display_power_get(dev_priv, POWER_DOMAIN_PIPE_A);
5979
5980         if (IS_CHERRYVIEW(dev))
5981                 cherryview_set_cdclk(dev, req_cdclk);
5982         else
5983                 valleyview_set_cdclk(dev, req_cdclk);
5984
5985         vlv_program_pfi_credits(dev_priv);
5986
5987         intel_display_power_put(dev_priv, POWER_DOMAIN_PIPE_A);
5988 }
5989
5990 static void valleyview_crtc_enable(struct drm_crtc *crtc)
5991 {
5992         struct drm_device *dev = crtc->dev;
5993         struct drm_i915_private *dev_priv = to_i915(dev);
5994         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5995         struct intel_encoder *encoder;
5996         int pipe = intel_crtc->pipe;
5997         bool is_dsi;
5998
5999         if (WARN_ON(intel_crtc->active))
6000                 return;
6001
6002         is_dsi = intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_DSI);
6003
6004         if (!is_dsi) {
6005                 if (IS_CHERRYVIEW(dev))
6006                         chv_prepare_pll(intel_crtc, intel_crtc->config);
6007                 else
6008                         vlv_prepare_pll(intel_crtc, intel_crtc->config);
6009         }
6010
6011         if (intel_crtc->config->has_dp_encoder)
6012                 intel_dp_set_m_n(intel_crtc, M1_N1);
6013
6014         intel_set_pipe_timings(intel_crtc);
6015
6016         if (IS_CHERRYVIEW(dev) && pipe == PIPE_B) {
6017                 struct drm_i915_private *dev_priv = dev->dev_private;
6018
6019                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6020                 I915_WRITE(CHV_CANVAS(pipe), 0);
6021         }
6022
6023         i9xx_set_pipeconf(intel_crtc);
6024
6025         intel_crtc->active = true;
6026
6027         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6028
6029         for_each_encoder_on_crtc(dev, crtc, encoder)
6030                 if (encoder->pre_pll_enable)
6031                         encoder->pre_pll_enable(encoder);
6032
6033         if (!is_dsi) {
6034                 if (IS_CHERRYVIEW(dev))
6035                         chv_enable_pll(intel_crtc, intel_crtc->config);
6036                 else
6037                         vlv_enable_pll(intel_crtc, intel_crtc->config);
6038         }
6039
6040         for_each_encoder_on_crtc(dev, crtc, encoder)
6041                 if (encoder->pre_enable)
6042                         encoder->pre_enable(encoder);
6043
6044         i9xx_pfit_enable(intel_crtc);
6045
6046         intel_crtc_load_lut(crtc);
6047
6048         intel_enable_pipe(intel_crtc);
6049
6050         assert_vblank_disabled(crtc);
6051         drm_crtc_vblank_on(crtc);
6052
6053         for_each_encoder_on_crtc(dev, crtc, encoder)
6054                 encoder->enable(encoder);
6055 }
6056
6057 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
6058 {
6059         struct drm_device *dev = crtc->base.dev;
6060         struct drm_i915_private *dev_priv = dev->dev_private;
6061
6062         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
6063         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
6064 }
6065
6066 static void i9xx_crtc_enable(struct drm_crtc *crtc)
6067 {
6068         struct drm_device *dev = crtc->dev;
6069         struct drm_i915_private *dev_priv = to_i915(dev);
6070         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6071         struct intel_encoder *encoder;
6072         int pipe = intel_crtc->pipe;
6073
6074         if (WARN_ON(intel_crtc->active))
6075                 return;
6076
6077         i9xx_set_pll_dividers(intel_crtc);
6078
6079         if (intel_crtc->config->has_dp_encoder)
6080                 intel_dp_set_m_n(intel_crtc, M1_N1);
6081
6082         intel_set_pipe_timings(intel_crtc);
6083
6084         i9xx_set_pipeconf(intel_crtc);
6085
6086         intel_crtc->active = true;
6087
6088         if (!IS_GEN2(dev))
6089                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6090
6091         for_each_encoder_on_crtc(dev, crtc, encoder)
6092                 if (encoder->pre_enable)
6093                         encoder->pre_enable(encoder);
6094
6095         i9xx_enable_pll(intel_crtc);
6096
6097         i9xx_pfit_enable(intel_crtc);
6098
6099         intel_crtc_load_lut(crtc);
6100
6101         intel_update_watermarks(crtc);
6102         intel_enable_pipe(intel_crtc);
6103
6104         assert_vblank_disabled(crtc);
6105         drm_crtc_vblank_on(crtc);
6106
6107         for_each_encoder_on_crtc(dev, crtc, encoder)
6108                 encoder->enable(encoder);
6109 }
6110
6111 static void i9xx_pfit_disable(struct intel_crtc *crtc)
6112 {
6113         struct drm_device *dev = crtc->base.dev;
6114         struct drm_i915_private *dev_priv = dev->dev_private;
6115
6116         if (!crtc->config->gmch_pfit.control)
6117                 return;
6118
6119         assert_pipe_disabled(dev_priv, crtc->pipe);
6120
6121         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
6122                          I915_READ(PFIT_CONTROL));
6123         I915_WRITE(PFIT_CONTROL, 0);
6124 }
6125
6126 static void i9xx_crtc_disable(struct drm_crtc *crtc)
6127 {
6128         struct drm_device *dev = crtc->dev;
6129         struct drm_i915_private *dev_priv = dev->dev_private;
6130         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6131         struct intel_encoder *encoder;
6132         int pipe = intel_crtc->pipe;
6133
6134         /*
6135          * On gen2 planes are double buffered but the pipe isn't, so we must
6136          * wait for planes to fully turn off before disabling the pipe.
6137          * We also need to wait on all gmch platforms because of the
6138          * self-refresh mode constraint explained above.
6139          */
6140         intel_wait_for_vblank(dev, pipe);
6141
6142         for_each_encoder_on_crtc(dev, crtc, encoder)
6143                 encoder->disable(encoder);
6144
6145         drm_crtc_vblank_off(crtc);
6146         assert_vblank_disabled(crtc);
6147
6148         intel_disable_pipe(intel_crtc);
6149
6150         i9xx_pfit_disable(intel_crtc);
6151
6152         for_each_encoder_on_crtc(dev, crtc, encoder)
6153                 if (encoder->post_disable)
6154                         encoder->post_disable(encoder);
6155
6156         if (!intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_DSI)) {
6157                 if (IS_CHERRYVIEW(dev))
6158                         chv_disable_pll(dev_priv, pipe);
6159                 else if (IS_VALLEYVIEW(dev))
6160                         vlv_disable_pll(dev_priv, pipe);
6161                 else
6162                         i9xx_disable_pll(intel_crtc);
6163         }
6164
6165         for_each_encoder_on_crtc(dev, crtc, encoder)
6166                 if (encoder->post_pll_disable)
6167                         encoder->post_pll_disable(encoder);
6168
6169         if (!IS_GEN2(dev))
6170                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6171
6172         intel_crtc->active = false;
6173         intel_update_watermarks(crtc);
6174 }
6175
6176 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc)
6177 {
6178         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6179         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6180         enum intel_display_power_domain domain;
6181         unsigned long domains;
6182
6183         if (!intel_crtc->active)
6184                 return;
6185
6186         if (to_intel_plane_state(crtc->primary->state)->visible) {
6187                 intel_crtc_wait_for_pending_flips(crtc);
6188                 intel_pre_disable_primary(crtc);
6189         }
6190
6191         intel_crtc_disable_planes(crtc, crtc->state->plane_mask);
6192         dev_priv->display.crtc_disable(crtc);
6193         intel_disable_shared_dpll(intel_crtc);
6194
6195         domains = intel_crtc->enabled_power_domains;
6196         for_each_power_domain(domain, domains)
6197                 intel_display_power_put(dev_priv, domain);
6198         intel_crtc->enabled_power_domains = 0;
6199 }
6200
6201 /*
6202  * turn all crtc's off, but do not adjust state
6203  * This has to be paired with a call to intel_modeset_setup_hw_state.
6204  */
6205 int intel_display_suspend(struct drm_device *dev)
6206 {
6207         struct drm_mode_config *config = &dev->mode_config;
6208         struct drm_modeset_acquire_ctx *ctx = config->acquire_ctx;
6209         struct drm_atomic_state *state;
6210         struct drm_crtc *crtc;
6211         unsigned crtc_mask = 0;
6212         int ret = 0;
6213
6214         if (WARN_ON(!ctx))
6215                 return 0;
6216
6217         lockdep_assert_held(&ctx->ww_ctx);
6218         state = drm_atomic_state_alloc(dev);
6219         if (WARN_ON(!state))
6220                 return -ENOMEM;
6221
6222         state->acquire_ctx = ctx;
6223         state->allow_modeset = true;
6224
6225         for_each_crtc(dev, crtc) {
6226                 struct drm_crtc_state *crtc_state =
6227                         drm_atomic_get_crtc_state(state, crtc);
6228
6229                 ret = PTR_ERR_OR_ZERO(crtc_state);
6230                 if (ret)
6231                         goto free;
6232
6233                 if (!crtc_state->active)
6234                         continue;
6235
6236                 crtc_state->active = false;
6237                 crtc_mask |= 1 << drm_crtc_index(crtc);
6238         }
6239
6240         if (crtc_mask) {
6241                 ret = drm_atomic_commit(state);
6242
6243                 if (!ret) {
6244                         for_each_crtc(dev, crtc)
6245                                 if (crtc_mask & (1 << drm_crtc_index(crtc)))
6246                                         crtc->state->active = true;
6247
6248                         return ret;
6249                 }
6250         }
6251
6252 free:
6253         if (ret)
6254                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6255         drm_atomic_state_free(state);
6256         return ret;
6257 }
6258
6259 void intel_encoder_destroy(struct drm_encoder *encoder)
6260 {
6261         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6262
6263         drm_encoder_cleanup(encoder);
6264         kfree(intel_encoder);
6265 }
6266
6267 /* Cross check the actual hw state with our own modeset state tracking (and it's
6268  * internal consistency). */
6269 static void intel_connector_check_state(struct intel_connector *connector)
6270 {
6271         struct drm_crtc *crtc = connector->base.state->crtc;
6272
6273         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6274                       connector->base.base.id,
6275                       connector->base.name);
6276
6277         if (connector->get_hw_state(connector)) {
6278                 struct drm_encoder *encoder = &connector->encoder->base;
6279                 struct drm_connector_state *conn_state = connector->base.state;
6280
6281                 I915_STATE_WARN(!crtc,
6282                          "connector enabled without attached crtc\n");
6283
6284                 if (!crtc)
6285                         return;
6286
6287                 I915_STATE_WARN(!crtc->state->active,
6288                       "connector is active, but attached crtc isn't\n");
6289
6290                 if (!encoder)
6291                         return;
6292
6293                 I915_STATE_WARN(conn_state->best_encoder != encoder,
6294                         "atomic encoder doesn't match attached encoder\n");
6295
6296                 I915_STATE_WARN(conn_state->crtc != encoder->crtc,
6297                         "attached encoder crtc differs from connector crtc\n");
6298         } else {
6299                 I915_STATE_WARN(crtc && crtc->state->active,
6300                         "attached crtc is active, but connector isn't\n");
6301                 I915_STATE_WARN(!crtc && connector->base.state->best_encoder,
6302                         "best encoder set without crtc!\n");
6303         }
6304 }
6305
6306 int intel_connector_init(struct intel_connector *connector)
6307 {
6308         struct drm_connector_state *connector_state;
6309
6310         connector_state = kzalloc(sizeof *connector_state, GFP_KERNEL);
6311         if (!connector_state)
6312                 return -ENOMEM;
6313
6314         connector->base.state = connector_state;
6315         return 0;
6316 }
6317
6318 struct intel_connector *intel_connector_alloc(void)
6319 {
6320         struct intel_connector *connector;
6321
6322         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6323         if (!connector)
6324                 return NULL;
6325
6326         if (intel_connector_init(connector) < 0) {
6327                 kfree(connector);
6328                 return NULL;
6329         }
6330
6331         return connector;
6332 }
6333
6334 /* Simple connector->get_hw_state implementation for encoders that support only
6335  * one connector and no cloning and hence the encoder state determines the state
6336  * of the connector. */
6337 bool intel_connector_get_hw_state(struct intel_connector *connector)
6338 {
6339         enum pipe pipe = 0;
6340         struct intel_encoder *encoder = connector->encoder;
6341
6342         return encoder->get_hw_state(encoder, &pipe);
6343 }
6344
6345 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6346 {
6347         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6348                 return crtc_state->fdi_lanes;
6349
6350         return 0;
6351 }
6352
6353 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6354                                      struct intel_crtc_state *pipe_config)
6355 {
6356         struct drm_atomic_state *state = pipe_config->base.state;
6357         struct intel_crtc *other_crtc;
6358         struct intel_crtc_state *other_crtc_state;
6359
6360         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6361                       pipe_name(pipe), pipe_config->fdi_lanes);
6362         if (pipe_config->fdi_lanes > 4) {
6363                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6364                               pipe_name(pipe), pipe_config->fdi_lanes);
6365                 return -EINVAL;
6366         }
6367
6368         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
6369                 if (pipe_config->fdi_lanes > 2) {
6370                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6371                                       pipe_config->fdi_lanes);
6372                         return -EINVAL;
6373                 } else {
6374                         return 0;
6375                 }
6376         }
6377
6378         if (INTEL_INFO(dev)->num_pipes == 2)
6379                 return 0;
6380
6381         /* Ivybridge 3 pipe is really complicated */
6382         switch (pipe) {
6383         case PIPE_A:
6384                 return 0;
6385         case PIPE_B:
6386                 if (pipe_config->fdi_lanes <= 2)
6387                         return 0;
6388
6389                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_C));
6390                 other_crtc_state =
6391                         intel_atomic_get_crtc_state(state, other_crtc);
6392                 if (IS_ERR(other_crtc_state))
6393                         return PTR_ERR(other_crtc_state);
6394
6395                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6396                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6397                                       pipe_name(pipe), pipe_config->fdi_lanes);
6398                         return -EINVAL;
6399                 }
6400                 return 0;
6401         case PIPE_C:
6402                 if (pipe_config->fdi_lanes > 2) {
6403                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6404                                       pipe_name(pipe), pipe_config->fdi_lanes);
6405                         return -EINVAL;
6406                 }
6407
6408                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_B));
6409                 other_crtc_state =
6410                         intel_atomic_get_crtc_state(state, other_crtc);
6411                 if (IS_ERR(other_crtc_state))
6412                         return PTR_ERR(other_crtc_state);
6413
6414                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6415                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6416                         return -EINVAL;
6417                 }
6418                 return 0;
6419         default:
6420                 BUG();
6421         }
6422 }
6423
6424 #define RETRY 1
6425 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6426                                        struct intel_crtc_state *pipe_config)
6427 {
6428         struct drm_device *dev = intel_crtc->base.dev;
6429         struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6430         int lane, link_bw, fdi_dotclock, ret;
6431         bool needs_recompute = false;
6432
6433 retry:
6434         /* FDI is a binary signal running at ~2.7GHz, encoding
6435          * each output octet as 10 bits. The actual frequency
6436          * is stored as a divider into a 100MHz clock, and the
6437          * mode pixel clock is stored in units of 1KHz.
6438          * Hence the bw of each lane in terms of the mode signal
6439          * is:
6440          */
6441         link_bw = intel_fdi_link_freq(dev) * MHz(100)/KHz(1)/10;
6442
6443         fdi_dotclock = adjusted_mode->crtc_clock;
6444
6445         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6446                                            pipe_config->pipe_bpp);
6447
6448         pipe_config->fdi_lanes = lane;
6449
6450         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6451                                link_bw, &pipe_config->fdi_m_n);
6452
6453         ret = ironlake_check_fdi_lanes(intel_crtc->base.dev,
6454                                        intel_crtc->pipe, pipe_config);
6455         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6456                 pipe_config->pipe_bpp -= 2*3;
6457                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6458                               pipe_config->pipe_bpp);
6459                 needs_recompute = true;
6460                 pipe_config->bw_constrained = true;
6461
6462                 goto retry;
6463         }
6464
6465         if (needs_recompute)
6466                 return RETRY;
6467
6468         return ret;
6469 }
6470
6471 static bool pipe_config_supports_ips(struct drm_i915_private *dev_priv,
6472                                      struct intel_crtc_state *pipe_config)
6473 {
6474         if (pipe_config->pipe_bpp > 24)
6475                 return false;
6476
6477         /* HSW can handle pixel rate up to cdclk? */
6478         if (IS_HASWELL(dev_priv->dev))
6479                 return true;
6480
6481         /*
6482          * We compare against max which means we must take
6483          * the increased cdclk requirement into account when
6484          * calculating the new cdclk.
6485          *
6486          * Should measure whether using a lower cdclk w/o IPS
6487          */
6488         return ilk_pipe_pixel_rate(pipe_config) <=
6489                 dev_priv->max_cdclk_freq * 95 / 100;
6490 }
6491
6492 static void hsw_compute_ips_config(struct intel_crtc *crtc,
6493                                    struct intel_crtc_state *pipe_config)
6494 {
6495         struct drm_device *dev = crtc->base.dev;
6496         struct drm_i915_private *dev_priv = dev->dev_private;
6497
6498         pipe_config->ips_enabled = i915.enable_ips &&
6499                 hsw_crtc_supports_ips(crtc) &&
6500                 pipe_config_supports_ips(dev_priv, pipe_config);
6501 }
6502
6503 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6504                                      struct intel_crtc_state *pipe_config)
6505 {
6506         struct drm_device *dev = crtc->base.dev;
6507         struct drm_i915_private *dev_priv = dev->dev_private;
6508         struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6509
6510         /* FIXME should check pixel clock limits on all platforms */
6511         if (INTEL_INFO(dev)->gen < 4) {
6512                 int clock_limit = dev_priv->max_cdclk_freq;
6513
6514                 /*
6515                  * Enable pixel doubling when the dot clock
6516                  * is > 90% of the (display) core speed.
6517                  *
6518                  * GDG double wide on either pipe,
6519                  * otherwise pipe A only.
6520                  */
6521                 if ((crtc->pipe == PIPE_A || IS_I915G(dev)) &&
6522                     adjusted_mode->crtc_clock > clock_limit * 9 / 10) {
6523                         clock_limit *= 2;
6524                         pipe_config->double_wide = true;
6525                 }
6526
6527                 if (adjusted_mode->crtc_clock > clock_limit * 9 / 10)
6528                         return -EINVAL;
6529         }
6530
6531         /*
6532          * Pipe horizontal size must be even in:
6533          * - DVO ganged mode
6534          * - LVDS dual channel mode
6535          * - Double wide pipe
6536          */
6537         if ((intel_pipe_will_have_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6538              intel_is_dual_link_lvds(dev)) || pipe_config->double_wide)
6539                 pipe_config->pipe_src_w &= ~1;
6540
6541         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6542          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6543          */
6544         if ((INTEL_INFO(dev)->gen > 4 || IS_G4X(dev)) &&
6545                 adjusted_mode->hsync_start == adjusted_mode->hdisplay)
6546                 return -EINVAL;
6547
6548         if (HAS_IPS(dev))
6549                 hsw_compute_ips_config(crtc, pipe_config);
6550
6551         if (pipe_config->has_pch_encoder)
6552                 return ironlake_fdi_compute_config(crtc, pipe_config);
6553
6554         return 0;
6555 }
6556
6557 static int skylake_get_display_clock_speed(struct drm_device *dev)
6558 {
6559         struct drm_i915_private *dev_priv = to_i915(dev);
6560         uint32_t lcpll1 = I915_READ(LCPLL1_CTL);
6561         uint32_t cdctl = I915_READ(CDCLK_CTL);
6562         uint32_t linkrate;
6563
6564         if (!(lcpll1 & LCPLL_PLL_ENABLE))
6565                 return 24000; /* 24MHz is the cd freq with NSSC ref */
6566
6567         if ((cdctl & CDCLK_FREQ_SEL_MASK) == CDCLK_FREQ_540)
6568                 return 540000;
6569
6570         linkrate = (I915_READ(DPLL_CTRL1) &
6571                     DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0)) >> 1;
6572
6573         if (linkrate == DPLL_CTRL1_LINK_RATE_2160 ||
6574             linkrate == DPLL_CTRL1_LINK_RATE_1080) {
6575                 /* vco 8640 */
6576                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6577                 case CDCLK_FREQ_450_432:
6578                         return 432000;
6579                 case CDCLK_FREQ_337_308:
6580                         return 308570;
6581                 case CDCLK_FREQ_675_617:
6582                         return 617140;
6583                 default:
6584                         WARN(1, "Unknown cd freq selection\n");
6585                 }
6586         } else {
6587                 /* vco 8100 */
6588                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6589                 case CDCLK_FREQ_450_432:
6590                         return 450000;
6591                 case CDCLK_FREQ_337_308:
6592                         return 337500;
6593                 case CDCLK_FREQ_675_617:
6594                         return 675000;
6595                 default:
6596                         WARN(1, "Unknown cd freq selection\n");
6597                 }
6598         }
6599
6600         /* error case, do as if DPLL0 isn't enabled */
6601         return 24000;
6602 }
6603
6604 static int broxton_get_display_clock_speed(struct drm_device *dev)
6605 {
6606         struct drm_i915_private *dev_priv = to_i915(dev);
6607         uint32_t cdctl = I915_READ(CDCLK_CTL);
6608         uint32_t pll_ratio = I915_READ(BXT_DE_PLL_CTL) & BXT_DE_PLL_RATIO_MASK;
6609         uint32_t pll_enab = I915_READ(BXT_DE_PLL_ENABLE);
6610         int cdclk;
6611
6612         if (!(pll_enab & BXT_DE_PLL_PLL_ENABLE))
6613                 return 19200;
6614
6615         cdclk = 19200 * pll_ratio / 2;
6616
6617         switch (cdctl & BXT_CDCLK_CD2X_DIV_SEL_MASK) {
6618         case BXT_CDCLK_CD2X_DIV_SEL_1:
6619                 return cdclk;  /* 576MHz or 624MHz */
6620         case BXT_CDCLK_CD2X_DIV_SEL_1_5:
6621                 return cdclk * 2 / 3; /* 384MHz */
6622         case BXT_CDCLK_CD2X_DIV_SEL_2:
6623                 return cdclk / 2; /* 288MHz */
6624         case BXT_CDCLK_CD2X_DIV_SEL_4:
6625                 return cdclk / 4; /* 144MHz */
6626         }
6627
6628         /* error case, do as if DE PLL isn't enabled */
6629         return 19200;
6630 }
6631
6632 static int broadwell_get_display_clock_speed(struct drm_device *dev)
6633 {
6634         struct drm_i915_private *dev_priv = dev->dev_private;
6635         uint32_t lcpll = I915_READ(LCPLL_CTL);
6636         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6637
6638         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6639                 return 800000;
6640         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6641                 return 450000;
6642         else if (freq == LCPLL_CLK_FREQ_450)
6643                 return 450000;
6644         else if (freq == LCPLL_CLK_FREQ_54O_BDW)
6645                 return 540000;
6646         else if (freq == LCPLL_CLK_FREQ_337_5_BDW)
6647                 return 337500;
6648         else
6649                 return 675000;
6650 }
6651
6652 static int haswell_get_display_clock_speed(struct drm_device *dev)
6653 {
6654         struct drm_i915_private *dev_priv = dev->dev_private;
6655         uint32_t lcpll = I915_READ(LCPLL_CTL);
6656         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6657
6658         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6659                 return 800000;
6660         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6661                 return 450000;
6662         else if (freq == LCPLL_CLK_FREQ_450)
6663                 return 450000;
6664         else if (IS_HSW_ULT(dev))
6665                 return 337500;
6666         else
6667                 return 540000;
6668 }
6669
6670 static int valleyview_get_display_clock_speed(struct drm_device *dev)
6671 {
6672         struct drm_i915_private *dev_priv = dev->dev_private;
6673         u32 val;
6674         int divider;
6675
6676         if (dev_priv->hpll_freq == 0)
6677                 dev_priv->hpll_freq = valleyview_get_vco(dev_priv);
6678
6679         mutex_lock(&dev_priv->sb_lock);
6680         val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
6681         mutex_unlock(&dev_priv->sb_lock);
6682
6683         divider = val & DISPLAY_FREQUENCY_VALUES;
6684
6685         WARN((val & DISPLAY_FREQUENCY_STATUS) !=
6686              (divider << DISPLAY_FREQUENCY_STATUS_SHIFT),
6687              "cdclk change in progress\n");
6688
6689         return DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, divider + 1);
6690 }
6691
6692 static int ilk_get_display_clock_speed(struct drm_device *dev)
6693 {
6694         return 450000;
6695 }
6696
6697 static int i945_get_display_clock_speed(struct drm_device *dev)
6698 {
6699         return 400000;
6700 }
6701
6702 static int i915_get_display_clock_speed(struct drm_device *dev)
6703 {
6704         return 333333;
6705 }
6706
6707 static int i9xx_misc_get_display_clock_speed(struct drm_device *dev)
6708 {
6709         return 200000;
6710 }
6711
6712 static int pnv_get_display_clock_speed(struct drm_device *dev)
6713 {
6714         u16 gcfgc = 0;
6715
6716         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6717
6718         switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6719         case GC_DISPLAY_CLOCK_267_MHZ_PNV:
6720                 return 266667;
6721         case GC_DISPLAY_CLOCK_333_MHZ_PNV:
6722                 return 333333;
6723         case GC_DISPLAY_CLOCK_444_MHZ_PNV:
6724                 return 444444;
6725         case GC_DISPLAY_CLOCK_200_MHZ_PNV:
6726                 return 200000;
6727         default:
6728                 DRM_ERROR("Unknown pnv display core clock 0x%04x\n", gcfgc);
6729         case GC_DISPLAY_CLOCK_133_MHZ_PNV:
6730                 return 133333;
6731         case GC_DISPLAY_CLOCK_167_MHZ_PNV:
6732                 return 166667;
6733         }
6734 }
6735
6736 static int i915gm_get_display_clock_speed(struct drm_device *dev)
6737 {
6738         u16 gcfgc = 0;
6739
6740         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6741
6742         if (gcfgc & GC_LOW_FREQUENCY_ENABLE)
6743                 return 133333;
6744         else {
6745                 switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6746                 case GC_DISPLAY_CLOCK_333_MHZ:
6747                         return 333333;
6748                 default:
6749                 case GC_DISPLAY_CLOCK_190_200_MHZ:
6750                         return 190000;
6751                 }
6752         }
6753 }
6754
6755 static int i865_get_display_clock_speed(struct drm_device *dev)
6756 {
6757         return 266667;
6758 }
6759
6760 static int i85x_get_display_clock_speed(struct drm_device *dev)
6761 {
6762         u16 hpllcc = 0;
6763
6764         /*
6765          * 852GM/852GMV only supports 133 MHz and the HPLLCC
6766          * encoding is different :(
6767          * FIXME is this the right way to detect 852GM/852GMV?
6768          */
6769         if (dev->pdev->revision == 0x1)
6770                 return 133333;
6771
6772         pci_bus_read_config_word(dev->pdev->bus,
6773                                  PCI_DEVFN(0, 3), HPLLCC, &hpllcc);
6774
6775         /* Assume that the hardware is in the high speed state.  This
6776          * should be the default.
6777          */
6778         switch (hpllcc & GC_CLOCK_CONTROL_MASK) {
6779         case GC_CLOCK_133_200:
6780         case GC_CLOCK_133_200_2:
6781         case GC_CLOCK_100_200:
6782                 return 200000;
6783         case GC_CLOCK_166_250:
6784                 return 250000;
6785         case GC_CLOCK_100_133:
6786                 return 133333;
6787         case GC_CLOCK_133_266:
6788         case GC_CLOCK_133_266_2:
6789         case GC_CLOCK_166_266:
6790                 return 266667;
6791         }
6792
6793         /* Shouldn't happen */
6794         return 0;
6795 }
6796
6797 static int i830_get_display_clock_speed(struct drm_device *dev)
6798 {
6799         return 133333;
6800 }
6801
6802 static unsigned int intel_hpll_vco(struct drm_device *dev)
6803 {
6804         struct drm_i915_private *dev_priv = dev->dev_private;
6805         static const unsigned int blb_vco[8] = {
6806                 [0] = 3200000,
6807                 [1] = 4000000,
6808                 [2] = 5333333,
6809                 [3] = 4800000,
6810                 [4] = 6400000,
6811         };
6812         static const unsigned int pnv_vco[8] = {
6813                 [0] = 3200000,
6814                 [1] = 4000000,
6815                 [2] = 5333333,
6816                 [3] = 4800000,
6817                 [4] = 2666667,
6818         };
6819         static const unsigned int cl_vco[8] = {
6820                 [0] = 3200000,
6821                 [1] = 4000000,
6822                 [2] = 5333333,
6823                 [3] = 6400000,
6824                 [4] = 3333333,
6825                 [5] = 3566667,
6826                 [6] = 4266667,
6827         };
6828         static const unsigned int elk_vco[8] = {
6829                 [0] = 3200000,
6830                 [1] = 4000000,
6831                 [2] = 5333333,
6832                 [3] = 4800000,
6833         };
6834         static const unsigned int ctg_vco[8] = {
6835                 [0] = 3200000,
6836                 [1] = 4000000,
6837                 [2] = 5333333,
6838                 [3] = 6400000,
6839                 [4] = 2666667,
6840                 [5] = 4266667,
6841         };
6842         const unsigned int *vco_table;
6843         unsigned int vco;
6844         uint8_t tmp = 0;
6845
6846         /* FIXME other chipsets? */
6847         if (IS_GM45(dev))
6848                 vco_table = ctg_vco;
6849         else if (IS_G4X(dev))
6850                 vco_table = elk_vco;
6851         else if (IS_CRESTLINE(dev))
6852                 vco_table = cl_vco;
6853         else if (IS_PINEVIEW(dev))
6854                 vco_table = pnv_vco;
6855         else if (IS_G33(dev))
6856                 vco_table = blb_vco;
6857         else
6858                 return 0;
6859
6860         tmp = I915_READ(IS_MOBILE(dev) ? HPLLVCO_MOBILE : HPLLVCO);
6861
6862         vco = vco_table[tmp & 0x7];
6863         if (vco == 0)
6864                 DRM_ERROR("Bad HPLL VCO (HPLLVCO=0x%02x)\n", tmp);
6865         else
6866                 DRM_DEBUG_KMS("HPLL VCO %u kHz\n", vco);
6867
6868         return vco;
6869 }
6870
6871 static int gm45_get_display_clock_speed(struct drm_device *dev)
6872 {
6873         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
6874         uint16_t tmp = 0;
6875
6876         pci_read_config_word(dev->pdev, GCFGC, &tmp);
6877
6878         cdclk_sel = (tmp >> 12) & 0x1;
6879
6880         switch (vco) {
6881         case 2666667:
6882         case 4000000:
6883         case 5333333:
6884                 return cdclk_sel ? 333333 : 222222;
6885         case 3200000:
6886                 return cdclk_sel ? 320000 : 228571;
6887         default:
6888                 DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u, CFGC=0x%04x\n", vco, tmp);
6889                 return 222222;
6890         }
6891 }
6892
6893 static int i965gm_get_display_clock_speed(struct drm_device *dev)
6894 {
6895         static const uint8_t div_3200[] = { 16, 10,  8 };
6896         static const uint8_t div_4000[] = { 20, 12, 10 };
6897         static const uint8_t div_5333[] = { 24, 16, 14 };
6898         const uint8_t *div_table;
6899         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
6900         uint16_t tmp = 0;
6901
6902         pci_read_config_word(dev->pdev, GCFGC, &tmp);
6903
6904         cdclk_sel = ((tmp >> 8) & 0x1f) - 1;
6905
6906         if (cdclk_sel >= ARRAY_SIZE(div_3200))
6907                 goto fail;
6908
6909         switch (vco) {
6910         case 3200000:
6911                 div_table = div_3200;
6912                 break;
6913         case 4000000:
6914                 div_table = div_4000;
6915                 break;
6916         case 5333333:
6917                 div_table = div_5333;
6918                 break;
6919         default:
6920                 goto fail;
6921         }
6922
6923         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
6924
6925 fail:
6926         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%04x\n", vco, tmp);
6927         return 200000;
6928 }
6929
6930 static int g33_get_display_clock_speed(struct drm_device *dev)
6931 {
6932         static const uint8_t div_3200[] = { 12, 10,  8,  7, 5, 16 };
6933         static const uint8_t div_4000[] = { 14, 12, 10,  8, 6, 20 };
6934         static const uint8_t div_4800[] = { 20, 14, 12, 10, 8, 24 };
6935         static const uint8_t div_5333[] = { 20, 16, 12, 12, 8, 28 };
6936         const uint8_t *div_table;
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 >> 4) & 0x7;
6943
6944         if (cdclk_sel >= ARRAY_SIZE(div_3200))
6945                 goto fail;
6946
6947         switch (vco) {
6948         case 3200000:
6949                 div_table = div_3200;
6950                 break;
6951         case 4000000:
6952                 div_table = div_4000;
6953                 break;
6954         case 4800000:
6955                 div_table = div_4800;
6956                 break;
6957         case 5333333:
6958                 div_table = div_5333;
6959                 break;
6960         default:
6961                 goto fail;
6962         }
6963
6964         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
6965
6966 fail:
6967         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%08x\n", vco, tmp);
6968         return 190476;
6969 }
6970
6971 static void
6972 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
6973 {
6974         while (*num > DATA_LINK_M_N_MASK ||
6975                *den > DATA_LINK_M_N_MASK) {
6976                 *num >>= 1;
6977                 *den >>= 1;
6978         }
6979 }
6980
6981 static void compute_m_n(unsigned int m, unsigned int n,
6982                         uint32_t *ret_m, uint32_t *ret_n)
6983 {
6984         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
6985         *ret_m = div_u64((uint64_t) m * *ret_n, n);
6986         intel_reduce_m_n_ratio(ret_m, ret_n);
6987 }
6988
6989 void
6990 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
6991                        int pixel_clock, int link_clock,
6992                        struct intel_link_m_n *m_n)
6993 {
6994         m_n->tu = 64;
6995
6996         compute_m_n(bits_per_pixel * pixel_clock,
6997                     link_clock * nlanes * 8,
6998                     &m_n->gmch_m, &m_n->gmch_n);
6999
7000         compute_m_n(pixel_clock, link_clock,
7001                     &m_n->link_m, &m_n->link_n);
7002 }
7003
7004 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
7005 {
7006         if (i915.panel_use_ssc >= 0)
7007                 return i915.panel_use_ssc != 0;
7008         return dev_priv->vbt.lvds_use_ssc
7009                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
7010 }
7011
7012 static int i9xx_get_refclk(const struct intel_crtc_state *crtc_state,
7013                            int num_connectors)
7014 {
7015         struct drm_device *dev = crtc_state->base.crtc->dev;
7016         struct drm_i915_private *dev_priv = dev->dev_private;
7017         int refclk;
7018
7019         WARN_ON(!crtc_state->base.state);
7020
7021         if (IS_VALLEYVIEW(dev) || IS_BROXTON(dev)) {
7022                 refclk = 100000;
7023         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7024             intel_panel_use_ssc(dev_priv) && num_connectors < 2) {
7025                 refclk = dev_priv->vbt.lvds_ssc_freq;
7026                 DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7027         } else if (!IS_GEN2(dev)) {
7028                 refclk = 96000;
7029         } else {
7030                 refclk = 48000;
7031         }
7032
7033         return refclk;
7034 }
7035
7036 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
7037 {
7038         return (1 << dpll->n) << 16 | dpll->m2;
7039 }
7040
7041 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
7042 {
7043         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
7044 }
7045
7046 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
7047                                      struct intel_crtc_state *crtc_state,
7048                                      intel_clock_t *reduced_clock)
7049 {
7050         struct drm_device *dev = crtc->base.dev;
7051         u32 fp, fp2 = 0;
7052
7053         if (IS_PINEVIEW(dev)) {
7054                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
7055                 if (reduced_clock)
7056                         fp2 = pnv_dpll_compute_fp(reduced_clock);
7057         } else {
7058                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
7059                 if (reduced_clock)
7060                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
7061         }
7062
7063         crtc_state->dpll_hw_state.fp0 = fp;
7064
7065         crtc->lowfreq_avail = false;
7066         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7067             reduced_clock) {
7068                 crtc_state->dpll_hw_state.fp1 = fp2;
7069                 crtc->lowfreq_avail = true;
7070         } else {
7071                 crtc_state->dpll_hw_state.fp1 = fp;
7072         }
7073 }
7074
7075 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
7076                 pipe)
7077 {
7078         u32 reg_val;
7079
7080         /*
7081          * PLLB opamp always calibrates to max value of 0x3f, force enable it
7082          * and set it to a reasonable value instead.
7083          */
7084         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7085         reg_val &= 0xffffff00;
7086         reg_val |= 0x00000030;
7087         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7088
7089         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7090         reg_val &= 0x8cffffff;
7091         reg_val = 0x8c000000;
7092         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7093
7094         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7095         reg_val &= 0xffffff00;
7096         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7097
7098         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7099         reg_val &= 0x00ffffff;
7100         reg_val |= 0xb0000000;
7101         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7102 }
7103
7104 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
7105                                          struct intel_link_m_n *m_n)
7106 {
7107         struct drm_device *dev = crtc->base.dev;
7108         struct drm_i915_private *dev_priv = dev->dev_private;
7109         int pipe = crtc->pipe;
7110
7111         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7112         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
7113         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
7114         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
7115 }
7116
7117 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
7118                                          struct intel_link_m_n *m_n,
7119                                          struct intel_link_m_n *m2_n2)
7120 {
7121         struct drm_device *dev = crtc->base.dev;
7122         struct drm_i915_private *dev_priv = dev->dev_private;
7123         int pipe = crtc->pipe;
7124         enum transcoder transcoder = crtc->config->cpu_transcoder;
7125
7126         if (INTEL_INFO(dev)->gen >= 5) {
7127                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
7128                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
7129                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
7130                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
7131                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
7132                  * for gen < 8) and if DRRS is supported (to make sure the
7133                  * registers are not unnecessarily accessed).
7134                  */
7135                 if (m2_n2 && (IS_CHERRYVIEW(dev) || INTEL_INFO(dev)->gen < 8) &&
7136                         crtc->config->has_drrs) {
7137                         I915_WRITE(PIPE_DATA_M2(transcoder),
7138                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
7139                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
7140                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
7141                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
7142                 }
7143         } else {
7144                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7145                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
7146                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
7147                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
7148         }
7149 }
7150
7151 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
7152 {
7153         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
7154
7155         if (m_n == M1_N1) {
7156                 dp_m_n = &crtc->config->dp_m_n;
7157                 dp_m2_n2 = &crtc->config->dp_m2_n2;
7158         } else if (m_n == M2_N2) {
7159
7160                 /*
7161                  * M2_N2 registers are not supported. Hence m2_n2 divider value
7162                  * needs to be programmed into M1_N1.
7163                  */
7164                 dp_m_n = &crtc->config->dp_m2_n2;
7165         } else {
7166                 DRM_ERROR("Unsupported divider value\n");
7167                 return;
7168         }
7169
7170         if (crtc->config->has_pch_encoder)
7171                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
7172         else
7173                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
7174 }
7175
7176 static void vlv_compute_dpll(struct intel_crtc *crtc,
7177                              struct intel_crtc_state *pipe_config)
7178 {
7179         u32 dpll, dpll_md;
7180
7181         /*
7182          * Enable DPIO clock input. We should never disable the reference
7183          * clock for pipe B, since VGA hotplug / manual detection depends
7184          * on it.
7185          */
7186         dpll = DPLL_EXT_BUFFER_ENABLE_VLV | DPLL_REF_CLK_ENABLE_VLV |
7187                 DPLL_VGA_MODE_DIS | DPLL_INTEGRATED_REF_CLK_VLV;
7188         /* We should never disable this, set it here for state tracking */
7189         if (crtc->pipe == PIPE_B)
7190                 dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7191         dpll |= DPLL_VCO_ENABLE;
7192         pipe_config->dpll_hw_state.dpll = dpll;
7193
7194         dpll_md = (pipe_config->pixel_multiplier - 1)
7195                 << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7196         pipe_config->dpll_hw_state.dpll_md = dpll_md;
7197 }
7198
7199 static void vlv_prepare_pll(struct intel_crtc *crtc,
7200                             const struct intel_crtc_state *pipe_config)
7201 {
7202         struct drm_device *dev = crtc->base.dev;
7203         struct drm_i915_private *dev_priv = dev->dev_private;
7204         int pipe = crtc->pipe;
7205         u32 mdiv;
7206         u32 bestn, bestm1, bestm2, bestp1, bestp2;
7207         u32 coreclk, reg_val;
7208
7209         mutex_lock(&dev_priv->sb_lock);
7210
7211         bestn = pipe_config->dpll.n;
7212         bestm1 = pipe_config->dpll.m1;
7213         bestm2 = pipe_config->dpll.m2;
7214         bestp1 = pipe_config->dpll.p1;
7215         bestp2 = pipe_config->dpll.p2;
7216
7217         /* See eDP HDMI DPIO driver vbios notes doc */
7218
7219         /* PLL B needs special handling */
7220         if (pipe == PIPE_B)
7221                 vlv_pllb_recal_opamp(dev_priv, pipe);
7222
7223         /* Set up Tx target for periodic Rcomp update */
7224         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
7225
7226         /* Disable target IRef on PLL */
7227         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
7228         reg_val &= 0x00ffffff;
7229         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
7230
7231         /* Disable fast lock */
7232         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
7233
7234         /* Set idtafcrecal before PLL is enabled */
7235         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
7236         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
7237         mdiv |= ((bestn << DPIO_N_SHIFT));
7238         mdiv |= (1 << DPIO_K_SHIFT);
7239
7240         /*
7241          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
7242          * but we don't support that).
7243          * Note: don't use the DAC post divider as it seems unstable.
7244          */
7245         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
7246         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7247
7248         mdiv |= DPIO_ENABLE_CALIBRATION;
7249         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7250
7251         /* Set HBR and RBR LPF coefficients */
7252         if (pipe_config->port_clock == 162000 ||
7253             intel_pipe_has_type(crtc, INTEL_OUTPUT_ANALOG) ||
7254             intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI))
7255                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7256                                  0x009f0003);
7257         else
7258                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7259                                  0x00d0000f);
7260
7261         if (pipe_config->has_dp_encoder) {
7262                 /* Use SSC source */
7263                 if (pipe == PIPE_A)
7264                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7265                                          0x0df40000);
7266                 else
7267                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7268                                          0x0df70000);
7269         } else { /* HDMI or VGA */
7270                 /* Use bend source */
7271                 if (pipe == PIPE_A)
7272                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7273                                          0x0df70000);
7274                 else
7275                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7276                                          0x0df40000);
7277         }
7278
7279         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
7280         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
7281         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DISPLAYPORT) ||
7282             intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP))
7283                 coreclk |= 0x01000000;
7284         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
7285
7286         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
7287         mutex_unlock(&dev_priv->sb_lock);
7288 }
7289
7290 static void chv_compute_dpll(struct intel_crtc *crtc,
7291                              struct intel_crtc_state *pipe_config)
7292 {
7293         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
7294                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS |
7295                 DPLL_VCO_ENABLE;
7296         if (crtc->pipe != PIPE_A)
7297                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7298
7299         pipe_config->dpll_hw_state.dpll_md =
7300                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7301 }
7302
7303 static void chv_prepare_pll(struct intel_crtc *crtc,
7304                             const struct intel_crtc_state *pipe_config)
7305 {
7306         struct drm_device *dev = crtc->base.dev;
7307         struct drm_i915_private *dev_priv = dev->dev_private;
7308         int pipe = crtc->pipe;
7309         int dpll_reg = DPLL(crtc->pipe);
7310         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7311         u32 loopfilter, tribuf_calcntr;
7312         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
7313         u32 dpio_val;
7314         int vco;
7315
7316         bestn = pipe_config->dpll.n;
7317         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
7318         bestm1 = pipe_config->dpll.m1;
7319         bestm2 = pipe_config->dpll.m2 >> 22;
7320         bestp1 = pipe_config->dpll.p1;
7321         bestp2 = pipe_config->dpll.p2;
7322         vco = pipe_config->dpll.vco;
7323         dpio_val = 0;
7324         loopfilter = 0;
7325
7326         /*
7327          * Enable Refclk and SSC
7328          */
7329         I915_WRITE(dpll_reg,
7330                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
7331
7332         mutex_lock(&dev_priv->sb_lock);
7333
7334         /* p1 and p2 divider */
7335         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
7336                         5 << DPIO_CHV_S1_DIV_SHIFT |
7337                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
7338                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
7339                         1 << DPIO_CHV_K_DIV_SHIFT);
7340
7341         /* Feedback post-divider - m2 */
7342         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
7343
7344         /* Feedback refclk divider - n and m1 */
7345         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
7346                         DPIO_CHV_M1_DIV_BY_2 |
7347                         1 << DPIO_CHV_N_DIV_SHIFT);
7348
7349         /* M2 fraction division */
7350         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
7351
7352         /* M2 fraction division enable */
7353         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7354         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
7355         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
7356         if (bestm2_frac)
7357                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
7358         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
7359
7360         /* Program digital lock detect threshold */
7361         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
7362         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
7363                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
7364         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
7365         if (!bestm2_frac)
7366                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
7367         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
7368
7369         /* Loop filter */
7370         if (vco == 5400000) {
7371                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
7372                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
7373                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
7374                 tribuf_calcntr = 0x9;
7375         } else if (vco <= 6200000) {
7376                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
7377                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
7378                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7379                 tribuf_calcntr = 0x9;
7380         } else if (vco <= 6480000) {
7381                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7382                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7383                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7384                 tribuf_calcntr = 0x8;
7385         } else {
7386                 /* Not supported. Apply the same limits as in the max case */
7387                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7388                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7389                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7390                 tribuf_calcntr = 0;
7391         }
7392         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
7393
7394         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
7395         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
7396         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
7397         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
7398
7399         /* AFC Recal */
7400         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
7401                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
7402                         DPIO_AFC_RECAL);
7403
7404         mutex_unlock(&dev_priv->sb_lock);
7405 }
7406
7407 /**
7408  * vlv_force_pll_on - forcibly enable just the PLL
7409  * @dev_priv: i915 private structure
7410  * @pipe: pipe PLL to enable
7411  * @dpll: PLL configuration
7412  *
7413  * Enable the PLL for @pipe using the supplied @dpll config. To be used
7414  * in cases where we need the PLL enabled even when @pipe is not going to
7415  * be enabled.
7416  */
7417 void vlv_force_pll_on(struct drm_device *dev, enum pipe pipe,
7418                       const struct dpll *dpll)
7419 {
7420         struct intel_crtc *crtc =
7421                 to_intel_crtc(intel_get_crtc_for_pipe(dev, pipe));
7422         struct intel_crtc_state pipe_config = {
7423                 .base.crtc = &crtc->base,
7424                 .pixel_multiplier = 1,
7425                 .dpll = *dpll,
7426         };
7427
7428         if (IS_CHERRYVIEW(dev)) {
7429                 chv_compute_dpll(crtc, &pipe_config);
7430                 chv_prepare_pll(crtc, &pipe_config);
7431                 chv_enable_pll(crtc, &pipe_config);
7432         } else {
7433                 vlv_compute_dpll(crtc, &pipe_config);
7434                 vlv_prepare_pll(crtc, &pipe_config);
7435                 vlv_enable_pll(crtc, &pipe_config);
7436         }
7437 }
7438
7439 /**
7440  * vlv_force_pll_off - forcibly disable just the PLL
7441  * @dev_priv: i915 private structure
7442  * @pipe: pipe PLL to disable
7443  *
7444  * Disable the PLL for @pipe. To be used in cases where we need
7445  * the PLL enabled even when @pipe is not going to be enabled.
7446  */
7447 void vlv_force_pll_off(struct drm_device *dev, enum pipe pipe)
7448 {
7449         if (IS_CHERRYVIEW(dev))
7450                 chv_disable_pll(to_i915(dev), pipe);
7451         else
7452                 vlv_disable_pll(to_i915(dev), pipe);
7453 }
7454
7455 static void i9xx_compute_dpll(struct intel_crtc *crtc,
7456                               struct intel_crtc_state *crtc_state,
7457                               intel_clock_t *reduced_clock,
7458                               int num_connectors)
7459 {
7460         struct drm_device *dev = crtc->base.dev;
7461         struct drm_i915_private *dev_priv = dev->dev_private;
7462         u32 dpll;
7463         bool is_sdvo;
7464         struct dpll *clock = &crtc_state->dpll;
7465
7466         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7467
7468         is_sdvo = intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7469                 intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_HDMI);
7470
7471         dpll = DPLL_VGA_MODE_DIS;
7472
7473         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
7474                 dpll |= DPLLB_MODE_LVDS;
7475         else
7476                 dpll |= DPLLB_MODE_DAC_SERIAL;
7477
7478         if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
7479                 dpll |= (crtc_state->pixel_multiplier - 1)
7480                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7481         }
7482
7483         if (is_sdvo)
7484                 dpll |= DPLL_SDVO_HIGH_SPEED;
7485
7486         if (crtc_state->has_dp_encoder)
7487                 dpll |= DPLL_SDVO_HIGH_SPEED;
7488
7489         /* compute bitmask from p1 value */
7490         if (IS_PINEVIEW(dev))
7491                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7492         else {
7493                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7494                 if (IS_G4X(dev) && reduced_clock)
7495                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7496         }
7497         switch (clock->p2) {
7498         case 5:
7499                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7500                 break;
7501         case 7:
7502                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7503                 break;
7504         case 10:
7505                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7506                 break;
7507         case 14:
7508                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7509                 break;
7510         }
7511         if (INTEL_INFO(dev)->gen >= 4)
7512                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7513
7514         if (crtc_state->sdvo_tv_clock)
7515                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7516         else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7517                  intel_panel_use_ssc(dev_priv) && num_connectors < 2)
7518                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7519         else
7520                 dpll |= PLL_REF_INPUT_DREFCLK;
7521
7522         dpll |= DPLL_VCO_ENABLE;
7523         crtc_state->dpll_hw_state.dpll = dpll;
7524
7525         if (INTEL_INFO(dev)->gen >= 4) {
7526                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7527                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7528                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7529         }
7530 }
7531
7532 static void i8xx_compute_dpll(struct intel_crtc *crtc,
7533                               struct intel_crtc_state *crtc_state,
7534                               intel_clock_t *reduced_clock,
7535                               int num_connectors)
7536 {
7537         struct drm_device *dev = crtc->base.dev;
7538         struct drm_i915_private *dev_priv = dev->dev_private;
7539         u32 dpll;
7540         struct dpll *clock = &crtc_state->dpll;
7541
7542         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7543
7544         dpll = DPLL_VGA_MODE_DIS;
7545
7546         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7547                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7548         } else {
7549                 if (clock->p1 == 2)
7550                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7551                 else
7552                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7553                 if (clock->p2 == 4)
7554                         dpll |= PLL_P2_DIVIDE_BY_4;
7555         }
7556
7557         if (!IS_I830(dev) && intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_DVO))
7558                 dpll |= DPLL_DVO_2X_MODE;
7559
7560         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7561                  intel_panel_use_ssc(dev_priv) && num_connectors < 2)
7562                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7563         else
7564                 dpll |= PLL_REF_INPUT_DREFCLK;
7565
7566         dpll |= DPLL_VCO_ENABLE;
7567         crtc_state->dpll_hw_state.dpll = dpll;
7568 }
7569
7570 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
7571 {
7572         struct drm_device *dev = intel_crtc->base.dev;
7573         struct drm_i915_private *dev_priv = dev->dev_private;
7574         enum pipe pipe = intel_crtc->pipe;
7575         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
7576         struct drm_display_mode *adjusted_mode =
7577                 &intel_crtc->config->base.adjusted_mode;
7578         uint32_t crtc_vtotal, crtc_vblank_end;
7579         int vsyncshift = 0;
7580
7581         /* We need to be careful not to changed the adjusted mode, for otherwise
7582          * the hw state checker will get angry at the mismatch. */
7583         crtc_vtotal = adjusted_mode->crtc_vtotal;
7584         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7585
7586         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7587                 /* the chip adds 2 halflines automatically */
7588                 crtc_vtotal -= 1;
7589                 crtc_vblank_end -= 1;
7590
7591                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
7592                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7593                 else
7594                         vsyncshift = adjusted_mode->crtc_hsync_start -
7595                                 adjusted_mode->crtc_htotal / 2;
7596                 if (vsyncshift < 0)
7597                         vsyncshift += adjusted_mode->crtc_htotal;
7598         }
7599
7600         if (INTEL_INFO(dev)->gen > 3)
7601                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7602
7603         I915_WRITE(HTOTAL(cpu_transcoder),
7604                    (adjusted_mode->crtc_hdisplay - 1) |
7605                    ((adjusted_mode->crtc_htotal - 1) << 16));
7606         I915_WRITE(HBLANK(cpu_transcoder),
7607                    (adjusted_mode->crtc_hblank_start - 1) |
7608                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7609         I915_WRITE(HSYNC(cpu_transcoder),
7610                    (adjusted_mode->crtc_hsync_start - 1) |
7611                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7612
7613         I915_WRITE(VTOTAL(cpu_transcoder),
7614                    (adjusted_mode->crtc_vdisplay - 1) |
7615                    ((crtc_vtotal - 1) << 16));
7616         I915_WRITE(VBLANK(cpu_transcoder),
7617                    (adjusted_mode->crtc_vblank_start - 1) |
7618                    ((crtc_vblank_end - 1) << 16));
7619         I915_WRITE(VSYNC(cpu_transcoder),
7620                    (adjusted_mode->crtc_vsync_start - 1) |
7621                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7622
7623         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7624          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7625          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7626          * bits. */
7627         if (IS_HASWELL(dev) && cpu_transcoder == TRANSCODER_EDP &&
7628             (pipe == PIPE_B || pipe == PIPE_C))
7629                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7630
7631         /* pipesrc controls the size that is scaled from, which should
7632          * always be the user's requested size.
7633          */
7634         I915_WRITE(PIPESRC(pipe),
7635                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
7636                    (intel_crtc->config->pipe_src_h - 1));
7637 }
7638
7639 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7640                                    struct intel_crtc_state *pipe_config)
7641 {
7642         struct drm_device *dev = crtc->base.dev;
7643         struct drm_i915_private *dev_priv = dev->dev_private;
7644         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7645         uint32_t tmp;
7646
7647         tmp = I915_READ(HTOTAL(cpu_transcoder));
7648         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7649         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7650         tmp = I915_READ(HBLANK(cpu_transcoder));
7651         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7652         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7653         tmp = I915_READ(HSYNC(cpu_transcoder));
7654         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7655         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7656
7657         tmp = I915_READ(VTOTAL(cpu_transcoder));
7658         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7659         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7660         tmp = I915_READ(VBLANK(cpu_transcoder));
7661         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7662         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7663         tmp = I915_READ(VSYNC(cpu_transcoder));
7664         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7665         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7666
7667         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7668                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7669                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7670                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7671         }
7672
7673         tmp = I915_READ(PIPESRC(crtc->pipe));
7674         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7675         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7676
7677         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7678         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7679 }
7680
7681 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7682                                  struct intel_crtc_state *pipe_config)
7683 {
7684         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7685         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7686         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7687         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7688
7689         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7690         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7691         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7692         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7693
7694         mode->flags = pipe_config->base.adjusted_mode.flags;
7695         mode->type = DRM_MODE_TYPE_DRIVER;
7696
7697         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7698         mode->flags |= pipe_config->base.adjusted_mode.flags;
7699
7700         mode->hsync = drm_mode_hsync(mode);
7701         mode->vrefresh = drm_mode_vrefresh(mode);
7702         drm_mode_set_name(mode);
7703 }
7704
7705 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
7706 {
7707         struct drm_device *dev = intel_crtc->base.dev;
7708         struct drm_i915_private *dev_priv = dev->dev_private;
7709         uint32_t pipeconf;
7710
7711         pipeconf = 0;
7712
7713         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
7714             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
7715                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
7716
7717         if (intel_crtc->config->double_wide)
7718                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7719
7720         /* only g4x and later have fancy bpc/dither controls */
7721         if (IS_G4X(dev) || IS_VALLEYVIEW(dev)) {
7722                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7723                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
7724                         pipeconf |= PIPECONF_DITHER_EN |
7725                                     PIPECONF_DITHER_TYPE_SP;
7726
7727                 switch (intel_crtc->config->pipe_bpp) {
7728                 case 18:
7729                         pipeconf |= PIPECONF_6BPC;
7730                         break;
7731                 case 24:
7732                         pipeconf |= PIPECONF_8BPC;
7733                         break;
7734                 case 30:
7735                         pipeconf |= PIPECONF_10BPC;
7736                         break;
7737                 default:
7738                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7739                         BUG();
7740                 }
7741         }
7742
7743         if (HAS_PIPE_CXSR(dev)) {
7744                 if (intel_crtc->lowfreq_avail) {
7745                         DRM_DEBUG_KMS("enabling CxSR downclocking\n");
7746                         pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
7747                 } else {
7748                         DRM_DEBUG_KMS("disabling CxSR downclocking\n");
7749                 }
7750         }
7751
7752         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7753                 if (INTEL_INFO(dev)->gen < 4 ||
7754                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
7755                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7756                 else
7757                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7758         } else
7759                 pipeconf |= PIPECONF_PROGRESSIVE;
7760
7761         if (IS_VALLEYVIEW(dev) && intel_crtc->config->limited_color_range)
7762                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7763
7764         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
7765         POSTING_READ(PIPECONF(intel_crtc->pipe));
7766 }
7767
7768 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7769                                    struct intel_crtc_state *crtc_state)
7770 {
7771         struct drm_device *dev = crtc->base.dev;
7772         struct drm_i915_private *dev_priv = dev->dev_private;
7773         int refclk, num_connectors = 0;
7774         intel_clock_t clock;
7775         bool ok;
7776         bool is_dsi = false;
7777         struct intel_encoder *encoder;
7778         const intel_limit_t *limit;
7779         struct drm_atomic_state *state = crtc_state->base.state;
7780         struct drm_connector *connector;
7781         struct drm_connector_state *connector_state;
7782         int i;
7783
7784         memset(&crtc_state->dpll_hw_state, 0,
7785                sizeof(crtc_state->dpll_hw_state));
7786
7787         for_each_connector_in_state(state, connector, connector_state, i) {
7788                 if (connector_state->crtc != &crtc->base)
7789                         continue;
7790
7791                 encoder = to_intel_encoder(connector_state->best_encoder);
7792
7793                 switch (encoder->type) {
7794                 case INTEL_OUTPUT_DSI:
7795                         is_dsi = true;
7796                         break;
7797                 default:
7798                         break;
7799                 }
7800
7801                 num_connectors++;
7802         }
7803
7804         if (is_dsi)
7805                 return 0;
7806
7807         if (!crtc_state->clock_set) {
7808                 refclk = i9xx_get_refclk(crtc_state, num_connectors);
7809
7810                 /*
7811                  * Returns a set of divisors for the desired target clock with
7812                  * the given refclk, or FALSE.  The returned values represent
7813                  * the clock equation: reflck * (5 * (m1 + 2) + (m2 + 2)) / (n +
7814                  * 2) / p1 / p2.
7815                  */
7816                 limit = intel_limit(crtc_state, refclk);
7817                 ok = dev_priv->display.find_dpll(limit, crtc_state,
7818                                                  crtc_state->port_clock,
7819                                                  refclk, NULL, &clock);
7820                 if (!ok) {
7821                         DRM_ERROR("Couldn't find PLL settings for mode!\n");
7822                         return -EINVAL;
7823                 }
7824
7825                 /* Compat-code for transition, will disappear. */
7826                 crtc_state->dpll.n = clock.n;
7827                 crtc_state->dpll.m1 = clock.m1;
7828                 crtc_state->dpll.m2 = clock.m2;
7829                 crtc_state->dpll.p1 = clock.p1;
7830                 crtc_state->dpll.p2 = clock.p2;
7831         }
7832
7833         if (IS_GEN2(dev)) {
7834                 i8xx_compute_dpll(crtc, crtc_state, NULL,
7835                                   num_connectors);
7836         } else if (IS_CHERRYVIEW(dev)) {
7837                 chv_compute_dpll(crtc, crtc_state);
7838         } else if (IS_VALLEYVIEW(dev)) {
7839                 vlv_compute_dpll(crtc, crtc_state);
7840         } else {
7841                 i9xx_compute_dpll(crtc, crtc_state, NULL,
7842                                   num_connectors);
7843         }
7844
7845         return 0;
7846 }
7847
7848 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
7849                                  struct intel_crtc_state *pipe_config)
7850 {
7851         struct drm_device *dev = crtc->base.dev;
7852         struct drm_i915_private *dev_priv = dev->dev_private;
7853         uint32_t tmp;
7854
7855         if (INTEL_INFO(dev)->gen <= 3 && (IS_I830(dev) || !IS_MOBILE(dev)))
7856                 return;
7857
7858         tmp = I915_READ(PFIT_CONTROL);
7859         if (!(tmp & PFIT_ENABLE))
7860                 return;
7861
7862         /* Check whether the pfit is attached to our pipe. */
7863         if (INTEL_INFO(dev)->gen < 4) {
7864                 if (crtc->pipe != PIPE_B)
7865                         return;
7866         } else {
7867                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
7868                         return;
7869         }
7870
7871         pipe_config->gmch_pfit.control = tmp;
7872         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
7873         if (INTEL_INFO(dev)->gen < 5)
7874                 pipe_config->gmch_pfit.lvds_border_bits =
7875                         I915_READ(LVDS) & LVDS_BORDER_ENABLE;
7876 }
7877
7878 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
7879                                struct intel_crtc_state *pipe_config)
7880 {
7881         struct drm_device *dev = crtc->base.dev;
7882         struct drm_i915_private *dev_priv = dev->dev_private;
7883         int pipe = pipe_config->cpu_transcoder;
7884         intel_clock_t clock;
7885         u32 mdiv;
7886         int refclk = 100000;
7887
7888         /* In case of MIPI DPLL will not even be used */
7889         if (!(pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE))
7890                 return;
7891
7892         mutex_lock(&dev_priv->sb_lock);
7893         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
7894         mutex_unlock(&dev_priv->sb_lock);
7895
7896         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
7897         clock.m2 = mdiv & DPIO_M2DIV_MASK;
7898         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
7899         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
7900         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
7901
7902         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
7903 }
7904
7905 static void
7906 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
7907                               struct intel_initial_plane_config *plane_config)
7908 {
7909         struct drm_device *dev = crtc->base.dev;
7910         struct drm_i915_private *dev_priv = dev->dev_private;
7911         u32 val, base, offset;
7912         int pipe = crtc->pipe, plane = crtc->plane;
7913         int fourcc, pixel_format;
7914         unsigned int aligned_height;
7915         struct drm_framebuffer *fb;
7916         struct intel_framebuffer *intel_fb;
7917
7918         val = I915_READ(DSPCNTR(plane));
7919         if (!(val & DISPLAY_PLANE_ENABLE))
7920                 return;
7921
7922         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
7923         if (!intel_fb) {
7924                 DRM_DEBUG_KMS("failed to alloc fb\n");
7925                 return;
7926         }
7927
7928         fb = &intel_fb->base;
7929
7930         if (INTEL_INFO(dev)->gen >= 4) {
7931                 if (val & DISPPLANE_TILED) {
7932                         plane_config->tiling = I915_TILING_X;
7933                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
7934                 }
7935         }
7936
7937         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
7938         fourcc = i9xx_format_to_fourcc(pixel_format);
7939         fb->pixel_format = fourcc;
7940         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
7941
7942         if (INTEL_INFO(dev)->gen >= 4) {
7943                 if (plane_config->tiling)
7944                         offset = I915_READ(DSPTILEOFF(plane));
7945                 else
7946                         offset = I915_READ(DSPLINOFF(plane));
7947                 base = I915_READ(DSPSURF(plane)) & 0xfffff000;
7948         } else {
7949                 base = I915_READ(DSPADDR(plane));
7950         }
7951         plane_config->base = base;
7952
7953         val = I915_READ(PIPESRC(pipe));
7954         fb->width = ((val >> 16) & 0xfff) + 1;
7955         fb->height = ((val >> 0) & 0xfff) + 1;
7956
7957         val = I915_READ(DSPSTRIDE(pipe));
7958         fb->pitches[0] = val & 0xffffffc0;
7959
7960         aligned_height = intel_fb_align_height(dev, fb->height,
7961                                                fb->pixel_format,
7962                                                fb->modifier[0]);
7963
7964         plane_config->size = fb->pitches[0] * aligned_height;
7965
7966         DRM_DEBUG_KMS("pipe/plane %c/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
7967                       pipe_name(pipe), plane, fb->width, fb->height,
7968                       fb->bits_per_pixel, base, fb->pitches[0],
7969                       plane_config->size);
7970
7971         plane_config->fb = intel_fb;
7972 }
7973
7974 static void chv_crtc_clock_get(struct intel_crtc *crtc,
7975                                struct intel_crtc_state *pipe_config)
7976 {
7977         struct drm_device *dev = crtc->base.dev;
7978         struct drm_i915_private *dev_priv = dev->dev_private;
7979         int pipe = pipe_config->cpu_transcoder;
7980         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7981         intel_clock_t clock;
7982         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
7983         int refclk = 100000;
7984
7985         mutex_lock(&dev_priv->sb_lock);
7986         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
7987         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
7988         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
7989         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
7990         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7991         mutex_unlock(&dev_priv->sb_lock);
7992
7993         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
7994         clock.m2 = (pll_dw0 & 0xff) << 22;
7995         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
7996                 clock.m2 |= pll_dw2 & 0x3fffff;
7997         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
7998         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
7999         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
8000
8001         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
8002 }
8003
8004 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
8005                                  struct intel_crtc_state *pipe_config)
8006 {
8007         struct drm_device *dev = crtc->base.dev;
8008         struct drm_i915_private *dev_priv = dev->dev_private;
8009         uint32_t tmp;
8010
8011         if (!intel_display_power_is_enabled(dev_priv,
8012                                             POWER_DOMAIN_PIPE(crtc->pipe)))
8013                 return false;
8014
8015         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8016         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
8017
8018         tmp = I915_READ(PIPECONF(crtc->pipe));
8019         if (!(tmp & PIPECONF_ENABLE))
8020                 return false;
8021
8022         if (IS_G4X(dev) || IS_VALLEYVIEW(dev)) {
8023                 switch (tmp & PIPECONF_BPC_MASK) {
8024                 case PIPECONF_6BPC:
8025                         pipe_config->pipe_bpp = 18;
8026                         break;
8027                 case PIPECONF_8BPC:
8028                         pipe_config->pipe_bpp = 24;
8029                         break;
8030                 case PIPECONF_10BPC:
8031                         pipe_config->pipe_bpp = 30;
8032                         break;
8033                 default:
8034                         break;
8035                 }
8036         }
8037
8038         if (IS_VALLEYVIEW(dev) && (tmp & PIPECONF_COLOR_RANGE_SELECT))
8039                 pipe_config->limited_color_range = true;
8040
8041         if (INTEL_INFO(dev)->gen < 4)
8042                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
8043
8044         intel_get_pipe_timings(crtc, pipe_config);
8045
8046         i9xx_get_pfit_config(crtc, pipe_config);
8047
8048         if (INTEL_INFO(dev)->gen >= 4) {
8049                 tmp = I915_READ(DPLL_MD(crtc->pipe));
8050                 pipe_config->pixel_multiplier =
8051                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
8052                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
8053                 pipe_config->dpll_hw_state.dpll_md = tmp;
8054         } else if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
8055                 tmp = I915_READ(DPLL(crtc->pipe));
8056                 pipe_config->pixel_multiplier =
8057                         ((tmp & SDVO_MULTIPLIER_MASK)
8058                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
8059         } else {
8060                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
8061                  * port and will be fixed up in the encoder->get_config
8062                  * function. */
8063                 pipe_config->pixel_multiplier = 1;
8064         }
8065         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
8066         if (!IS_VALLEYVIEW(dev)) {
8067                 /*
8068                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
8069                  * on 830. Filter it out here so that we don't
8070                  * report errors due to that.
8071                  */
8072                 if (IS_I830(dev))
8073                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
8074
8075                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
8076                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
8077         } else {
8078                 /* Mask out read-only status bits. */
8079                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
8080                                                      DPLL_PORTC_READY_MASK |
8081                                                      DPLL_PORTB_READY_MASK);
8082         }
8083
8084         if (IS_CHERRYVIEW(dev))
8085                 chv_crtc_clock_get(crtc, pipe_config);
8086         else if (IS_VALLEYVIEW(dev))
8087                 vlv_crtc_clock_get(crtc, pipe_config);
8088         else
8089                 i9xx_crtc_clock_get(crtc, pipe_config);
8090
8091         return true;
8092 }
8093
8094 static void ironlake_init_pch_refclk(struct drm_device *dev)
8095 {
8096         struct drm_i915_private *dev_priv = dev->dev_private;
8097         struct intel_encoder *encoder;
8098         u32 val, final;
8099         bool has_lvds = false;
8100         bool has_cpu_edp = false;
8101         bool has_panel = false;
8102         bool has_ck505 = false;
8103         bool can_ssc = false;
8104
8105         /* We need to take the global config into account */
8106         for_each_intel_encoder(dev, encoder) {
8107                 switch (encoder->type) {
8108                 case INTEL_OUTPUT_LVDS:
8109                         has_panel = true;
8110                         has_lvds = true;
8111                         break;
8112                 case INTEL_OUTPUT_EDP:
8113                         has_panel = true;
8114                         if (enc_to_dig_port(&encoder->base)->port == PORT_A)
8115                                 has_cpu_edp = true;
8116                         break;
8117                 default:
8118                         break;
8119                 }
8120         }
8121
8122         if (HAS_PCH_IBX(dev)) {
8123                 has_ck505 = dev_priv->vbt.display_clock_mode;
8124                 can_ssc = has_ck505;
8125         } else {
8126                 has_ck505 = false;
8127                 can_ssc = true;
8128         }
8129
8130         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d\n",
8131                       has_panel, has_lvds, has_ck505);
8132
8133         /* Ironlake: try to setup display ref clock before DPLL
8134          * enabling. This is only under driver's control after
8135          * PCH B stepping, previous chipset stepping should be
8136          * ignoring this setting.
8137          */
8138         val = I915_READ(PCH_DREF_CONTROL);
8139
8140         /* As we must carefully and slowly disable/enable each source in turn,
8141          * compute the final state we want first and check if we need to
8142          * make any changes at all.
8143          */
8144         final = val;
8145         final &= ~DREF_NONSPREAD_SOURCE_MASK;
8146         if (has_ck505)
8147                 final |= DREF_NONSPREAD_CK505_ENABLE;
8148         else
8149                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
8150
8151         final &= ~DREF_SSC_SOURCE_MASK;
8152         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8153         final &= ~DREF_SSC1_ENABLE;
8154
8155         if (has_panel) {
8156                 final |= DREF_SSC_SOURCE_ENABLE;
8157
8158                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
8159                         final |= DREF_SSC1_ENABLE;
8160
8161                 if (has_cpu_edp) {
8162                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
8163                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8164                         else
8165                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8166                 } else
8167                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8168         } else {
8169                 final |= DREF_SSC_SOURCE_DISABLE;
8170                 final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8171         }
8172
8173         if (final == val)
8174                 return;
8175
8176         /* Always enable nonspread source */
8177         val &= ~DREF_NONSPREAD_SOURCE_MASK;
8178
8179         if (has_ck505)
8180                 val |= DREF_NONSPREAD_CK505_ENABLE;
8181         else
8182                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
8183
8184         if (has_panel) {
8185                 val &= ~DREF_SSC_SOURCE_MASK;
8186                 val |= DREF_SSC_SOURCE_ENABLE;
8187
8188                 /* SSC must be turned on before enabling the CPU output  */
8189                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8190                         DRM_DEBUG_KMS("Using SSC on panel\n");
8191                         val |= DREF_SSC1_ENABLE;
8192                 } else
8193                         val &= ~DREF_SSC1_ENABLE;
8194
8195                 /* Get SSC going before enabling the outputs */
8196                 I915_WRITE(PCH_DREF_CONTROL, val);
8197                 POSTING_READ(PCH_DREF_CONTROL);
8198                 udelay(200);
8199
8200                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8201
8202                 /* Enable CPU source on CPU attached eDP */
8203                 if (has_cpu_edp) {
8204                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8205                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
8206                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8207                         } else
8208                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8209                 } else
8210                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8211
8212                 I915_WRITE(PCH_DREF_CONTROL, val);
8213                 POSTING_READ(PCH_DREF_CONTROL);
8214                 udelay(200);
8215         } else {
8216                 DRM_DEBUG_KMS("Disabling SSC entirely\n");
8217
8218                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8219
8220                 /* Turn off CPU output */
8221                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8222
8223                 I915_WRITE(PCH_DREF_CONTROL, val);
8224                 POSTING_READ(PCH_DREF_CONTROL);
8225                 udelay(200);
8226
8227                 /* Turn off the SSC source */
8228                 val &= ~DREF_SSC_SOURCE_MASK;
8229                 val |= DREF_SSC_SOURCE_DISABLE;
8230
8231                 /* Turn off SSC1 */
8232                 val &= ~DREF_SSC1_ENABLE;
8233
8234                 I915_WRITE(PCH_DREF_CONTROL, val);
8235                 POSTING_READ(PCH_DREF_CONTROL);
8236                 udelay(200);
8237         }
8238
8239         BUG_ON(val != final);
8240 }
8241
8242 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
8243 {
8244         uint32_t tmp;
8245
8246         tmp = I915_READ(SOUTH_CHICKEN2);
8247         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
8248         I915_WRITE(SOUTH_CHICKEN2, tmp);
8249
8250         if (wait_for_atomic_us(I915_READ(SOUTH_CHICKEN2) &
8251                                FDI_MPHY_IOSFSB_RESET_STATUS, 100))
8252                 DRM_ERROR("FDI mPHY reset assert timeout\n");
8253
8254         tmp = I915_READ(SOUTH_CHICKEN2);
8255         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
8256         I915_WRITE(SOUTH_CHICKEN2, tmp);
8257
8258         if (wait_for_atomic_us((I915_READ(SOUTH_CHICKEN2) &
8259                                 FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
8260                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
8261 }
8262
8263 /* WaMPhyProgramming:hsw */
8264 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
8265 {
8266         uint32_t tmp;
8267
8268         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
8269         tmp &= ~(0xFF << 24);
8270         tmp |= (0x12 << 24);
8271         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
8272
8273         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
8274         tmp |= (1 << 11);
8275         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
8276
8277         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
8278         tmp |= (1 << 11);
8279         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
8280
8281         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
8282         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8283         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
8284
8285         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
8286         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8287         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
8288
8289         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
8290         tmp &= ~(7 << 13);
8291         tmp |= (5 << 13);
8292         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
8293
8294         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
8295         tmp &= ~(7 << 13);
8296         tmp |= (5 << 13);
8297         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
8298
8299         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
8300         tmp &= ~0xFF;
8301         tmp |= 0x1C;
8302         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
8303
8304         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
8305         tmp &= ~0xFF;
8306         tmp |= 0x1C;
8307         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
8308
8309         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
8310         tmp &= ~(0xFF << 16);
8311         tmp |= (0x1C << 16);
8312         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
8313
8314         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
8315         tmp &= ~(0xFF << 16);
8316         tmp |= (0x1C << 16);
8317         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
8318
8319         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8320         tmp |= (1 << 27);
8321         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8322
8323         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8324         tmp |= (1 << 27);
8325         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8326
8327         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8328         tmp &= ~(0xF << 28);
8329         tmp |= (4 << 28);
8330         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8331
8332         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
8333         tmp &= ~(0xF << 28);
8334         tmp |= (4 << 28);
8335         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
8336 }
8337
8338 /* Implements 3 different sequences from BSpec chapter "Display iCLK
8339  * Programming" based on the parameters passed:
8340  * - Sequence to enable CLKOUT_DP
8341  * - Sequence to enable CLKOUT_DP without spread
8342  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
8343  */
8344 static void lpt_enable_clkout_dp(struct drm_device *dev, bool with_spread,
8345                                  bool with_fdi)
8346 {
8347         struct drm_i915_private *dev_priv = dev->dev_private;
8348         uint32_t reg, tmp;
8349
8350         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
8351                 with_spread = true;
8352         if (WARN(dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE &&
8353                  with_fdi, "LP PCH doesn't have FDI\n"))
8354                 with_fdi = false;
8355
8356         mutex_lock(&dev_priv->sb_lock);
8357
8358         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8359         tmp &= ~SBI_SSCCTL_DISABLE;
8360         tmp |= SBI_SSCCTL_PATHALT;
8361         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8362
8363         udelay(24);
8364
8365         if (with_spread) {
8366                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8367                 tmp &= ~SBI_SSCCTL_PATHALT;
8368                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8369
8370                 if (with_fdi) {
8371                         lpt_reset_fdi_mphy(dev_priv);
8372                         lpt_program_fdi_mphy(dev_priv);
8373                 }
8374         }
8375
8376         reg = (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) ?
8377                SBI_GEN0 : SBI_DBUFF0;
8378         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8379         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8380         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8381
8382         mutex_unlock(&dev_priv->sb_lock);
8383 }
8384
8385 /* Sequence to disable CLKOUT_DP */
8386 static void lpt_disable_clkout_dp(struct drm_device *dev)
8387 {
8388         struct drm_i915_private *dev_priv = dev->dev_private;
8389         uint32_t reg, tmp;
8390
8391         mutex_lock(&dev_priv->sb_lock);
8392
8393         reg = (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) ?
8394                SBI_GEN0 : SBI_DBUFF0;
8395         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8396         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8397         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8398
8399         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8400         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8401                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8402                         tmp |= SBI_SSCCTL_PATHALT;
8403                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8404                         udelay(32);
8405                 }
8406                 tmp |= SBI_SSCCTL_DISABLE;
8407                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8408         }
8409
8410         mutex_unlock(&dev_priv->sb_lock);
8411 }
8412
8413 static void lpt_init_pch_refclk(struct drm_device *dev)
8414 {
8415         struct intel_encoder *encoder;
8416         bool has_vga = false;
8417
8418         for_each_intel_encoder(dev, encoder) {
8419                 switch (encoder->type) {
8420                 case INTEL_OUTPUT_ANALOG:
8421                         has_vga = true;
8422                         break;
8423                 default:
8424                         break;
8425                 }
8426         }
8427
8428         if (has_vga)
8429                 lpt_enable_clkout_dp(dev, true, true);
8430         else
8431                 lpt_disable_clkout_dp(dev);
8432 }
8433
8434 /*
8435  * Initialize reference clocks when the driver loads
8436  */
8437 void intel_init_pch_refclk(struct drm_device *dev)
8438 {
8439         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
8440                 ironlake_init_pch_refclk(dev);
8441         else if (HAS_PCH_LPT(dev))
8442                 lpt_init_pch_refclk(dev);
8443 }
8444
8445 static int ironlake_get_refclk(struct intel_crtc_state *crtc_state)
8446 {
8447         struct drm_device *dev = crtc_state->base.crtc->dev;
8448         struct drm_i915_private *dev_priv = dev->dev_private;
8449         struct drm_atomic_state *state = crtc_state->base.state;
8450         struct drm_connector *connector;
8451         struct drm_connector_state *connector_state;
8452         struct intel_encoder *encoder;
8453         int num_connectors = 0, i;
8454         bool is_lvds = false;
8455
8456         for_each_connector_in_state(state, connector, connector_state, i) {
8457                 if (connector_state->crtc != crtc_state->base.crtc)
8458                         continue;
8459
8460                 encoder = to_intel_encoder(connector_state->best_encoder);
8461
8462                 switch (encoder->type) {
8463                 case INTEL_OUTPUT_LVDS:
8464                         is_lvds = true;
8465                         break;
8466                 default:
8467                         break;
8468                 }
8469                 num_connectors++;
8470         }
8471
8472         if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2) {
8473                 DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8474                               dev_priv->vbt.lvds_ssc_freq);
8475                 return dev_priv->vbt.lvds_ssc_freq;
8476         }
8477
8478         return 120000;
8479 }
8480
8481 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
8482 {
8483         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
8484         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8485         int pipe = intel_crtc->pipe;
8486         uint32_t val;
8487
8488         val = 0;
8489
8490         switch (intel_crtc->config->pipe_bpp) {
8491         case 18:
8492                 val |= PIPECONF_6BPC;
8493                 break;
8494         case 24:
8495                 val |= PIPECONF_8BPC;
8496                 break;
8497         case 30:
8498                 val |= PIPECONF_10BPC;
8499                 break;
8500         case 36:
8501                 val |= PIPECONF_12BPC;
8502                 break;
8503         default:
8504                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8505                 BUG();
8506         }
8507
8508         if (intel_crtc->config->dither)
8509                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8510
8511         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8512                 val |= PIPECONF_INTERLACED_ILK;
8513         else
8514                 val |= PIPECONF_PROGRESSIVE;
8515
8516         if (intel_crtc->config->limited_color_range)
8517                 val |= PIPECONF_COLOR_RANGE_SELECT;
8518
8519         I915_WRITE(PIPECONF(pipe), val);
8520         POSTING_READ(PIPECONF(pipe));
8521 }
8522
8523 /*
8524  * Set up the pipe CSC unit.
8525  *
8526  * Currently only full range RGB to limited range RGB conversion
8527  * is supported, but eventually this should handle various
8528  * RGB<->YCbCr scenarios as well.
8529  */
8530 static void intel_set_pipe_csc(struct drm_crtc *crtc)
8531 {
8532         struct drm_device *dev = crtc->dev;
8533         struct drm_i915_private *dev_priv = dev->dev_private;
8534         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8535         int pipe = intel_crtc->pipe;
8536         uint16_t coeff = 0x7800; /* 1.0 */
8537
8538         /*
8539          * TODO: Check what kind of values actually come out of the pipe
8540          * with these coeff/postoff values and adjust to get the best
8541          * accuracy. Perhaps we even need to take the bpc value into
8542          * consideration.
8543          */
8544
8545         if (intel_crtc->config->limited_color_range)
8546                 coeff = ((235 - 16) * (1 << 12) / 255) & 0xff8; /* 0.xxx... */
8547
8548         /*
8549          * GY/GU and RY/RU should be the other way around according
8550          * to BSpec, but reality doesn't agree. Just set them up in
8551          * a way that results in the correct picture.
8552          */
8553         I915_WRITE(PIPE_CSC_COEFF_RY_GY(pipe), coeff << 16);
8554         I915_WRITE(PIPE_CSC_COEFF_BY(pipe), 0);
8555
8556         I915_WRITE(PIPE_CSC_COEFF_RU_GU(pipe), coeff);
8557         I915_WRITE(PIPE_CSC_COEFF_BU(pipe), 0);
8558
8559         I915_WRITE(PIPE_CSC_COEFF_RV_GV(pipe), 0);
8560         I915_WRITE(PIPE_CSC_COEFF_BV(pipe), coeff << 16);
8561
8562         I915_WRITE(PIPE_CSC_PREOFF_HI(pipe), 0);
8563         I915_WRITE(PIPE_CSC_PREOFF_ME(pipe), 0);
8564         I915_WRITE(PIPE_CSC_PREOFF_LO(pipe), 0);
8565
8566         if (INTEL_INFO(dev)->gen > 6) {
8567                 uint16_t postoff = 0;
8568
8569                 if (intel_crtc->config->limited_color_range)
8570                         postoff = (16 * (1 << 12) / 255) & 0x1fff;
8571
8572                 I915_WRITE(PIPE_CSC_POSTOFF_HI(pipe), postoff);
8573                 I915_WRITE(PIPE_CSC_POSTOFF_ME(pipe), postoff);
8574                 I915_WRITE(PIPE_CSC_POSTOFF_LO(pipe), postoff);
8575
8576                 I915_WRITE(PIPE_CSC_MODE(pipe), 0);
8577         } else {
8578                 uint32_t mode = CSC_MODE_YUV_TO_RGB;
8579
8580                 if (intel_crtc->config->limited_color_range)
8581                         mode |= CSC_BLACK_SCREEN_OFFSET;
8582
8583                 I915_WRITE(PIPE_CSC_MODE(pipe), mode);
8584         }
8585 }
8586
8587 static void haswell_set_pipeconf(struct drm_crtc *crtc)
8588 {
8589         struct drm_device *dev = crtc->dev;
8590         struct drm_i915_private *dev_priv = dev->dev_private;
8591         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8592         enum pipe pipe = intel_crtc->pipe;
8593         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8594         uint32_t val;
8595
8596         val = 0;
8597
8598         if (IS_HASWELL(dev) && intel_crtc->config->dither)
8599                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8600
8601         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8602                 val |= PIPECONF_INTERLACED_ILK;
8603         else
8604                 val |= PIPECONF_PROGRESSIVE;
8605
8606         I915_WRITE(PIPECONF(cpu_transcoder), val);
8607         POSTING_READ(PIPECONF(cpu_transcoder));
8608
8609         I915_WRITE(GAMMA_MODE(intel_crtc->pipe), GAMMA_MODE_MODE_8BIT);
8610         POSTING_READ(GAMMA_MODE(intel_crtc->pipe));
8611
8612         if (IS_BROADWELL(dev) || INTEL_INFO(dev)->gen >= 9) {
8613                 val = 0;
8614
8615                 switch (intel_crtc->config->pipe_bpp) {
8616                 case 18:
8617                         val |= PIPEMISC_DITHER_6_BPC;
8618                         break;
8619                 case 24:
8620                         val |= PIPEMISC_DITHER_8_BPC;
8621                         break;
8622                 case 30:
8623                         val |= PIPEMISC_DITHER_10_BPC;
8624                         break;
8625                 case 36:
8626                         val |= PIPEMISC_DITHER_12_BPC;
8627                         break;
8628                 default:
8629                         /* Case prevented by pipe_config_set_bpp. */
8630                         BUG();
8631                 }
8632
8633                 if (intel_crtc->config->dither)
8634                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8635
8636                 I915_WRITE(PIPEMISC(pipe), val);
8637         }
8638 }
8639
8640 static bool ironlake_compute_clocks(struct drm_crtc *crtc,
8641                                     struct intel_crtc_state *crtc_state,
8642                                     intel_clock_t *clock,
8643                                     bool *has_reduced_clock,
8644                                     intel_clock_t *reduced_clock)
8645 {
8646         struct drm_device *dev = crtc->dev;
8647         struct drm_i915_private *dev_priv = dev->dev_private;
8648         int refclk;
8649         const intel_limit_t *limit;
8650         bool ret;
8651
8652         refclk = ironlake_get_refclk(crtc_state);
8653
8654         /*
8655          * Returns a set of divisors for the desired target clock with the given
8656          * refclk, or FALSE.  The returned values represent the clock equation:
8657          * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
8658          */
8659         limit = intel_limit(crtc_state, refclk);
8660         ret = dev_priv->display.find_dpll(limit, crtc_state,
8661                                           crtc_state->port_clock,
8662                                           refclk, NULL, clock);
8663         if (!ret)
8664                 return false;
8665
8666         return true;
8667 }
8668
8669 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8670 {
8671         /*
8672          * Account for spread spectrum to avoid
8673          * oversubscribing the link. Max center spread
8674          * is 2.5%; use 5% for safety's sake.
8675          */
8676         u32 bps = target_clock * bpp * 21 / 20;
8677         return DIV_ROUND_UP(bps, link_bw * 8);
8678 }
8679
8680 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8681 {
8682         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8683 }
8684
8685 static uint32_t ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8686                                       struct intel_crtc_state *crtc_state,
8687                                       u32 *fp,
8688                                       intel_clock_t *reduced_clock, u32 *fp2)
8689 {
8690         struct drm_crtc *crtc = &intel_crtc->base;
8691         struct drm_device *dev = crtc->dev;
8692         struct drm_i915_private *dev_priv = dev->dev_private;
8693         struct drm_atomic_state *state = crtc_state->base.state;
8694         struct drm_connector *connector;
8695         struct drm_connector_state *connector_state;
8696         struct intel_encoder *encoder;
8697         uint32_t dpll;
8698         int factor, num_connectors = 0, i;
8699         bool is_lvds = false, is_sdvo = false;
8700
8701         for_each_connector_in_state(state, connector, connector_state, i) {
8702                 if (connector_state->crtc != crtc_state->base.crtc)
8703                         continue;
8704
8705                 encoder = to_intel_encoder(connector_state->best_encoder);
8706
8707                 switch (encoder->type) {
8708                 case INTEL_OUTPUT_LVDS:
8709                         is_lvds = true;
8710                         break;
8711                 case INTEL_OUTPUT_SDVO:
8712                 case INTEL_OUTPUT_HDMI:
8713                         is_sdvo = true;
8714                         break;
8715                 default:
8716                         break;
8717                 }
8718
8719                 num_connectors++;
8720         }
8721
8722         /* Enable autotuning of the PLL clock (if permissible) */
8723         factor = 21;
8724         if (is_lvds) {
8725                 if ((intel_panel_use_ssc(dev_priv) &&
8726                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8727                     (HAS_PCH_IBX(dev) && intel_is_dual_link_lvds(dev)))
8728                         factor = 25;
8729         } else if (crtc_state->sdvo_tv_clock)
8730                 factor = 20;
8731
8732         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8733                 *fp |= FP_CB_TUNE;
8734
8735         if (fp2 && (reduced_clock->m < factor * reduced_clock->n))
8736                 *fp2 |= FP_CB_TUNE;
8737
8738         dpll = 0;
8739
8740         if (is_lvds)
8741                 dpll |= DPLLB_MODE_LVDS;
8742         else
8743                 dpll |= DPLLB_MODE_DAC_SERIAL;
8744
8745         dpll |= (crtc_state->pixel_multiplier - 1)
8746                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8747
8748         if (is_sdvo)
8749                 dpll |= DPLL_SDVO_HIGH_SPEED;
8750         if (crtc_state->has_dp_encoder)
8751                 dpll |= DPLL_SDVO_HIGH_SPEED;
8752
8753         /* compute bitmask from p1 value */
8754         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8755         /* also FPA1 */
8756         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8757
8758         switch (crtc_state->dpll.p2) {
8759         case 5:
8760                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8761                 break;
8762         case 7:
8763                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8764                 break;
8765         case 10:
8766                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8767                 break;
8768         case 14:
8769                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8770                 break;
8771         }
8772
8773         if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2)
8774                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8775         else
8776                 dpll |= PLL_REF_INPUT_DREFCLK;
8777
8778         return dpll | DPLL_VCO_ENABLE;
8779 }
8780
8781 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
8782                                        struct intel_crtc_state *crtc_state)
8783 {
8784         struct drm_device *dev = crtc->base.dev;
8785         intel_clock_t clock, reduced_clock;
8786         u32 dpll = 0, fp = 0, fp2 = 0;
8787         bool ok, has_reduced_clock = false;
8788         bool is_lvds = false;
8789         struct intel_shared_dpll *pll;
8790
8791         memset(&crtc_state->dpll_hw_state, 0,
8792                sizeof(crtc_state->dpll_hw_state));
8793
8794         is_lvds = intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS);
8795
8796         WARN(!(HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev)),
8797              "Unexpected PCH type %d\n", INTEL_PCH_TYPE(dev));
8798
8799         ok = ironlake_compute_clocks(&crtc->base, crtc_state, &clock,
8800                                      &has_reduced_clock, &reduced_clock);
8801         if (!ok && !crtc_state->clock_set) {
8802                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8803                 return -EINVAL;
8804         }
8805         /* Compat-code for transition, will disappear. */
8806         if (!crtc_state->clock_set) {
8807                 crtc_state->dpll.n = clock.n;
8808                 crtc_state->dpll.m1 = clock.m1;
8809                 crtc_state->dpll.m2 = clock.m2;
8810                 crtc_state->dpll.p1 = clock.p1;
8811                 crtc_state->dpll.p2 = clock.p2;
8812         }
8813
8814         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
8815         if (crtc_state->has_pch_encoder) {
8816                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8817                 if (has_reduced_clock)
8818                         fp2 = i9xx_dpll_compute_fp(&reduced_clock);
8819
8820                 dpll = ironlake_compute_dpll(crtc, crtc_state,
8821                                              &fp, &reduced_clock,
8822                                              has_reduced_clock ? &fp2 : NULL);
8823
8824                 crtc_state->dpll_hw_state.dpll = dpll;
8825                 crtc_state->dpll_hw_state.fp0 = fp;
8826                 if (has_reduced_clock)
8827                         crtc_state->dpll_hw_state.fp1 = fp2;
8828                 else
8829                         crtc_state->dpll_hw_state.fp1 = fp;
8830
8831                 pll = intel_get_shared_dpll(crtc, crtc_state);
8832                 if (pll == NULL) {
8833                         DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
8834                                          pipe_name(crtc->pipe));
8835                         return -EINVAL;
8836                 }
8837         }
8838
8839         if (is_lvds && has_reduced_clock)
8840                 crtc->lowfreq_avail = true;
8841         else
8842                 crtc->lowfreq_avail = false;
8843
8844         return 0;
8845 }
8846
8847 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
8848                                          struct intel_link_m_n *m_n)
8849 {
8850         struct drm_device *dev = crtc->base.dev;
8851         struct drm_i915_private *dev_priv = dev->dev_private;
8852         enum pipe pipe = crtc->pipe;
8853
8854         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
8855         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
8856         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
8857                 & ~TU_SIZE_MASK;
8858         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
8859         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
8860                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8861 }
8862
8863 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
8864                                          enum transcoder transcoder,
8865                                          struct intel_link_m_n *m_n,
8866                                          struct intel_link_m_n *m2_n2)
8867 {
8868         struct drm_device *dev = crtc->base.dev;
8869         struct drm_i915_private *dev_priv = dev->dev_private;
8870         enum pipe pipe = crtc->pipe;
8871
8872         if (INTEL_INFO(dev)->gen >= 5) {
8873                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
8874                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
8875                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
8876                         & ~TU_SIZE_MASK;
8877                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
8878                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
8879                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8880                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
8881                  * gen < 8) and if DRRS is supported (to make sure the
8882                  * registers are not unnecessarily read).
8883                  */
8884                 if (m2_n2 && INTEL_INFO(dev)->gen < 8 &&
8885                         crtc->config->has_drrs) {
8886                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
8887                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
8888                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
8889                                         & ~TU_SIZE_MASK;
8890                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
8891                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
8892                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8893                 }
8894         } else {
8895                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
8896                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
8897                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
8898                         & ~TU_SIZE_MASK;
8899                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
8900                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
8901                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8902         }
8903 }
8904
8905 void intel_dp_get_m_n(struct intel_crtc *crtc,
8906                       struct intel_crtc_state *pipe_config)
8907 {
8908         if (pipe_config->has_pch_encoder)
8909                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
8910         else
8911                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8912                                              &pipe_config->dp_m_n,
8913                                              &pipe_config->dp_m2_n2);
8914 }
8915
8916 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
8917                                         struct intel_crtc_state *pipe_config)
8918 {
8919         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8920                                      &pipe_config->fdi_m_n, NULL);
8921 }
8922
8923 static void skylake_get_pfit_config(struct intel_crtc *crtc,
8924                                     struct intel_crtc_state *pipe_config)
8925 {
8926         struct drm_device *dev = crtc->base.dev;
8927         struct drm_i915_private *dev_priv = dev->dev_private;
8928         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
8929         uint32_t ps_ctrl = 0;
8930         int id = -1;
8931         int i;
8932
8933         /* find scaler attached to this pipe */
8934         for (i = 0; i < crtc->num_scalers; i++) {
8935                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
8936                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
8937                         id = i;
8938                         pipe_config->pch_pfit.enabled = true;
8939                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
8940                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
8941                         break;
8942                 }
8943         }
8944
8945         scaler_state->scaler_id = id;
8946         if (id >= 0) {
8947                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
8948         } else {
8949                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
8950         }
8951 }
8952
8953 static void
8954 skylake_get_initial_plane_config(struct intel_crtc *crtc,
8955                                  struct intel_initial_plane_config *plane_config)
8956 {
8957         struct drm_device *dev = crtc->base.dev;
8958         struct drm_i915_private *dev_priv = dev->dev_private;
8959         u32 val, base, offset, stride_mult, tiling;
8960         int pipe = crtc->pipe;
8961         int fourcc, pixel_format;
8962         unsigned int aligned_height;
8963         struct drm_framebuffer *fb;
8964         struct intel_framebuffer *intel_fb;
8965
8966         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8967         if (!intel_fb) {
8968                 DRM_DEBUG_KMS("failed to alloc fb\n");
8969                 return;
8970         }
8971
8972         fb = &intel_fb->base;
8973
8974         val = I915_READ(PLANE_CTL(pipe, 0));
8975         if (!(val & PLANE_CTL_ENABLE))
8976                 goto error;
8977
8978         pixel_format = val & PLANE_CTL_FORMAT_MASK;
8979         fourcc = skl_format_to_fourcc(pixel_format,
8980                                       val & PLANE_CTL_ORDER_RGBX,
8981                                       val & PLANE_CTL_ALPHA_MASK);
8982         fb->pixel_format = fourcc;
8983         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
8984
8985         tiling = val & PLANE_CTL_TILED_MASK;
8986         switch (tiling) {
8987         case PLANE_CTL_TILED_LINEAR:
8988                 fb->modifier[0] = DRM_FORMAT_MOD_NONE;
8989                 break;
8990         case PLANE_CTL_TILED_X:
8991                 plane_config->tiling = I915_TILING_X;
8992                 fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
8993                 break;
8994         case PLANE_CTL_TILED_Y:
8995                 fb->modifier[0] = I915_FORMAT_MOD_Y_TILED;
8996                 break;
8997         case PLANE_CTL_TILED_YF:
8998                 fb->modifier[0] = I915_FORMAT_MOD_Yf_TILED;
8999                 break;
9000         default:
9001                 MISSING_CASE(tiling);
9002                 goto error;
9003         }
9004
9005         base = I915_READ(PLANE_SURF(pipe, 0)) & 0xfffff000;
9006         plane_config->base = base;
9007
9008         offset = I915_READ(PLANE_OFFSET(pipe, 0));
9009
9010         val = I915_READ(PLANE_SIZE(pipe, 0));
9011         fb->height = ((val >> 16) & 0xfff) + 1;
9012         fb->width = ((val >> 0) & 0x1fff) + 1;
9013
9014         val = I915_READ(PLANE_STRIDE(pipe, 0));
9015         stride_mult = intel_fb_stride_alignment(dev, fb->modifier[0],
9016                                                 fb->pixel_format);
9017         fb->pitches[0] = (val & 0x3ff) * stride_mult;
9018
9019         aligned_height = intel_fb_align_height(dev, fb->height,
9020                                                fb->pixel_format,
9021                                                fb->modifier[0]);
9022
9023         plane_config->size = fb->pitches[0] * aligned_height;
9024
9025         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9026                       pipe_name(pipe), fb->width, fb->height,
9027                       fb->bits_per_pixel, base, fb->pitches[0],
9028                       plane_config->size);
9029
9030         plane_config->fb = intel_fb;
9031         return;
9032
9033 error:
9034         kfree(fb);
9035 }
9036
9037 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
9038                                      struct intel_crtc_state *pipe_config)
9039 {
9040         struct drm_device *dev = crtc->base.dev;
9041         struct drm_i915_private *dev_priv = dev->dev_private;
9042         uint32_t tmp;
9043
9044         tmp = I915_READ(PF_CTL(crtc->pipe));
9045
9046         if (tmp & PF_ENABLE) {
9047                 pipe_config->pch_pfit.enabled = true;
9048                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
9049                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
9050
9051                 /* We currently do not free assignements of panel fitters on
9052                  * ivb/hsw (since we don't use the higher upscaling modes which
9053                  * differentiates them) so just WARN about this case for now. */
9054                 if (IS_GEN7(dev)) {
9055                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
9056                                 PF_PIPE_SEL_IVB(crtc->pipe));
9057                 }
9058         }
9059 }
9060
9061 static void
9062 ironlake_get_initial_plane_config(struct intel_crtc *crtc,
9063                                   struct intel_initial_plane_config *plane_config)
9064 {
9065         struct drm_device *dev = crtc->base.dev;
9066         struct drm_i915_private *dev_priv = dev->dev_private;
9067         u32 val, base, offset;
9068         int pipe = crtc->pipe;
9069         int fourcc, pixel_format;
9070         unsigned int aligned_height;
9071         struct drm_framebuffer *fb;
9072         struct intel_framebuffer *intel_fb;
9073
9074         val = I915_READ(DSPCNTR(pipe));
9075         if (!(val & DISPLAY_PLANE_ENABLE))
9076                 return;
9077
9078         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9079         if (!intel_fb) {
9080                 DRM_DEBUG_KMS("failed to alloc fb\n");
9081                 return;
9082         }
9083
9084         fb = &intel_fb->base;
9085
9086         if (INTEL_INFO(dev)->gen >= 4) {
9087                 if (val & DISPPLANE_TILED) {
9088                         plane_config->tiling = I915_TILING_X;
9089                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9090                 }
9091         }
9092
9093         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
9094         fourcc = i9xx_format_to_fourcc(pixel_format);
9095         fb->pixel_format = fourcc;
9096         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9097
9098         base = I915_READ(DSPSURF(pipe)) & 0xfffff000;
9099         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
9100                 offset = I915_READ(DSPOFFSET(pipe));
9101         } else {
9102                 if (plane_config->tiling)
9103                         offset = I915_READ(DSPTILEOFF(pipe));
9104                 else
9105                         offset = I915_READ(DSPLINOFF(pipe));
9106         }
9107         plane_config->base = base;
9108
9109         val = I915_READ(PIPESRC(pipe));
9110         fb->width = ((val >> 16) & 0xfff) + 1;
9111         fb->height = ((val >> 0) & 0xfff) + 1;
9112
9113         val = I915_READ(DSPSTRIDE(pipe));
9114         fb->pitches[0] = val & 0xffffffc0;
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 }
9129
9130 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
9131                                      struct intel_crtc_state *pipe_config)
9132 {
9133         struct drm_device *dev = crtc->base.dev;
9134         struct drm_i915_private *dev_priv = dev->dev_private;
9135         uint32_t tmp;
9136
9137         if (!intel_display_power_is_enabled(dev_priv,
9138                                             POWER_DOMAIN_PIPE(crtc->pipe)))
9139                 return false;
9140
9141         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9142         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
9143
9144         tmp = I915_READ(PIPECONF(crtc->pipe));
9145         if (!(tmp & PIPECONF_ENABLE))
9146                 return false;
9147
9148         switch (tmp & PIPECONF_BPC_MASK) {
9149         case PIPECONF_6BPC:
9150                 pipe_config->pipe_bpp = 18;
9151                 break;
9152         case PIPECONF_8BPC:
9153                 pipe_config->pipe_bpp = 24;
9154                 break;
9155         case PIPECONF_10BPC:
9156                 pipe_config->pipe_bpp = 30;
9157                 break;
9158         case PIPECONF_12BPC:
9159                 pipe_config->pipe_bpp = 36;
9160                 break;
9161         default:
9162                 break;
9163         }
9164
9165         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
9166                 pipe_config->limited_color_range = true;
9167
9168         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
9169                 struct intel_shared_dpll *pll;
9170
9171                 pipe_config->has_pch_encoder = true;
9172
9173                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
9174                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9175                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9176
9177                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9178
9179                 if (HAS_PCH_IBX(dev_priv->dev)) {
9180                         pipe_config->shared_dpll =
9181                                 (enum intel_dpll_id) crtc->pipe;
9182                 } else {
9183                         tmp = I915_READ(PCH_DPLL_SEL);
9184                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
9185                                 pipe_config->shared_dpll = DPLL_ID_PCH_PLL_B;
9186                         else
9187                                 pipe_config->shared_dpll = DPLL_ID_PCH_PLL_A;
9188                 }
9189
9190                 pll = &dev_priv->shared_dplls[pipe_config->shared_dpll];
9191
9192                 WARN_ON(!pll->get_hw_state(dev_priv, pll,
9193                                            &pipe_config->dpll_hw_state));
9194
9195                 tmp = pipe_config->dpll_hw_state.dpll;
9196                 pipe_config->pixel_multiplier =
9197                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
9198                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
9199
9200                 ironlake_pch_clock_get(crtc, pipe_config);
9201         } else {
9202                 pipe_config->pixel_multiplier = 1;
9203         }
9204
9205         intel_get_pipe_timings(crtc, pipe_config);
9206
9207         ironlake_get_pfit_config(crtc, pipe_config);
9208
9209         return true;
9210 }
9211
9212 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
9213 {
9214         struct drm_device *dev = dev_priv->dev;
9215         struct intel_crtc *crtc;
9216
9217         for_each_intel_crtc(dev, crtc)
9218                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
9219                      pipe_name(crtc->pipe));
9220
9221         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_DRIVER), "Power well on\n");
9222         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
9223         I915_STATE_WARN(I915_READ(WRPLL_CTL1) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
9224         I915_STATE_WARN(I915_READ(WRPLL_CTL2) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
9225         I915_STATE_WARN(I915_READ(PCH_PP_STATUS) & PP_ON, "Panel power on\n");
9226         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
9227              "CPU PWM1 enabled\n");
9228         if (IS_HASWELL(dev))
9229                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
9230                      "CPU PWM2 enabled\n");
9231         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
9232              "PCH PWM1 enabled\n");
9233         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
9234              "Utility pin enabled\n");
9235         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
9236
9237         /*
9238          * In theory we can still leave IRQs enabled, as long as only the HPD
9239          * interrupts remain enabled. We used to check for that, but since it's
9240          * gen-specific and since we only disable LCPLL after we fully disable
9241          * the interrupts, the check below should be enough.
9242          */
9243         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
9244 }
9245
9246 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
9247 {
9248         struct drm_device *dev = dev_priv->dev;
9249
9250         if (IS_HASWELL(dev))
9251                 return I915_READ(D_COMP_HSW);
9252         else
9253                 return I915_READ(D_COMP_BDW);
9254 }
9255
9256 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
9257 {
9258         struct drm_device *dev = dev_priv->dev;
9259
9260         if (IS_HASWELL(dev)) {
9261                 mutex_lock(&dev_priv->rps.hw_lock);
9262                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
9263                                             val))
9264                         DRM_ERROR("Failed to write to D_COMP\n");
9265                 mutex_unlock(&dev_priv->rps.hw_lock);
9266         } else {
9267                 I915_WRITE(D_COMP_BDW, val);
9268                 POSTING_READ(D_COMP_BDW);
9269         }
9270 }
9271
9272 /*
9273  * This function implements pieces of two sequences from BSpec:
9274  * - Sequence for display software to disable LCPLL
9275  * - Sequence for display software to allow package C8+
9276  * The steps implemented here are just the steps that actually touch the LCPLL
9277  * register. Callers should take care of disabling all the display engine
9278  * functions, doing the mode unset, fixing interrupts, etc.
9279  */
9280 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
9281                               bool switch_to_fclk, bool allow_power_down)
9282 {
9283         uint32_t val;
9284
9285         assert_can_disable_lcpll(dev_priv);
9286
9287         val = I915_READ(LCPLL_CTL);
9288
9289         if (switch_to_fclk) {
9290                 val |= LCPLL_CD_SOURCE_FCLK;
9291                 I915_WRITE(LCPLL_CTL, val);
9292
9293                 if (wait_for_atomic_us(I915_READ(LCPLL_CTL) &
9294                                        LCPLL_CD_SOURCE_FCLK_DONE, 1))
9295                         DRM_ERROR("Switching to FCLK failed\n");
9296
9297                 val = I915_READ(LCPLL_CTL);
9298         }
9299
9300         val |= LCPLL_PLL_DISABLE;
9301         I915_WRITE(LCPLL_CTL, val);
9302         POSTING_READ(LCPLL_CTL);
9303
9304         if (wait_for((I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK) == 0, 1))
9305                 DRM_ERROR("LCPLL still locked\n");
9306
9307         val = hsw_read_dcomp(dev_priv);
9308         val |= D_COMP_COMP_DISABLE;
9309         hsw_write_dcomp(dev_priv, val);
9310         ndelay(100);
9311
9312         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
9313                      1))
9314                 DRM_ERROR("D_COMP RCOMP still in progress\n");
9315
9316         if (allow_power_down) {
9317                 val = I915_READ(LCPLL_CTL);
9318                 val |= LCPLL_POWER_DOWN_ALLOW;
9319                 I915_WRITE(LCPLL_CTL, val);
9320                 POSTING_READ(LCPLL_CTL);
9321         }
9322 }
9323
9324 /*
9325  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
9326  * source.
9327  */
9328 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
9329 {
9330         uint32_t val;
9331
9332         val = I915_READ(LCPLL_CTL);
9333
9334         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
9335                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
9336                 return;
9337
9338         /*
9339          * Make sure we're not on PC8 state before disabling PC8, otherwise
9340          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
9341          */
9342         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
9343
9344         if (val & LCPLL_POWER_DOWN_ALLOW) {
9345                 val &= ~LCPLL_POWER_DOWN_ALLOW;
9346                 I915_WRITE(LCPLL_CTL, val);
9347                 POSTING_READ(LCPLL_CTL);
9348         }
9349
9350         val = hsw_read_dcomp(dev_priv);
9351         val |= D_COMP_COMP_FORCE;
9352         val &= ~D_COMP_COMP_DISABLE;
9353         hsw_write_dcomp(dev_priv, val);
9354
9355         val = I915_READ(LCPLL_CTL);
9356         val &= ~LCPLL_PLL_DISABLE;
9357         I915_WRITE(LCPLL_CTL, val);
9358
9359         if (wait_for(I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK, 5))
9360                 DRM_ERROR("LCPLL not locked yet\n");
9361
9362         if (val & LCPLL_CD_SOURCE_FCLK) {
9363                 val = I915_READ(LCPLL_CTL);
9364                 val &= ~LCPLL_CD_SOURCE_FCLK;
9365                 I915_WRITE(LCPLL_CTL, val);
9366
9367                 if (wait_for_atomic_us((I915_READ(LCPLL_CTL) &
9368                                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9369                         DRM_ERROR("Switching back to LCPLL failed\n");
9370         }
9371
9372         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
9373         intel_update_cdclk(dev_priv->dev);
9374 }
9375
9376 /*
9377  * Package states C8 and deeper are really deep PC states that can only be
9378  * reached when all the devices on the system allow it, so even if the graphics
9379  * device allows PC8+, it doesn't mean the system will actually get to these
9380  * states. Our driver only allows PC8+ when going into runtime PM.
9381  *
9382  * The requirements for PC8+ are that all the outputs are disabled, the power
9383  * well is disabled and most interrupts are disabled, and these are also
9384  * requirements for runtime PM. When these conditions are met, we manually do
9385  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
9386  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
9387  * hang the machine.
9388  *
9389  * When we really reach PC8 or deeper states (not just when we allow it) we lose
9390  * the state of some registers, so when we come back from PC8+ we need to
9391  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
9392  * need to take care of the registers kept by RC6. Notice that this happens even
9393  * if we don't put the device in PCI D3 state (which is what currently happens
9394  * because of the runtime PM support).
9395  *
9396  * For more, read "Display Sequences for Package C8" on the hardware
9397  * documentation.
9398  */
9399 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
9400 {
9401         struct drm_device *dev = dev_priv->dev;
9402         uint32_t val;
9403
9404         DRM_DEBUG_KMS("Enabling package C8+\n");
9405
9406         if (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) {
9407                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9408                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
9409                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9410         }
9411
9412         lpt_disable_clkout_dp(dev);
9413         hsw_disable_lcpll(dev_priv, true, true);
9414 }
9415
9416 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
9417 {
9418         struct drm_device *dev = dev_priv->dev;
9419         uint32_t val;
9420
9421         DRM_DEBUG_KMS("Disabling package C8+\n");
9422
9423         hsw_restore_lcpll(dev_priv);
9424         lpt_init_pch_refclk(dev);
9425
9426         if (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) {
9427                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9428                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
9429                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9430         }
9431
9432         intel_prepare_ddi(dev);
9433 }
9434
9435 static void broxton_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9436 {
9437         struct drm_device *dev = old_state->dev;
9438         unsigned int req_cdclk = to_intel_atomic_state(old_state)->cdclk;
9439
9440         broxton_set_cdclk(dev, req_cdclk);
9441 }
9442
9443 /* compute the max rate for new configuration */
9444 static int ilk_max_pixel_rate(struct drm_atomic_state *state)
9445 {
9446         struct intel_crtc *intel_crtc;
9447         struct intel_crtc_state *crtc_state;
9448         int max_pixel_rate = 0;
9449
9450         for_each_intel_crtc(state->dev, intel_crtc) {
9451                 int pixel_rate;
9452
9453                 crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
9454                 if (IS_ERR(crtc_state))
9455                         return PTR_ERR(crtc_state);
9456
9457                 if (!crtc_state->base.enable)
9458                         continue;
9459
9460                 pixel_rate = ilk_pipe_pixel_rate(crtc_state);
9461
9462                 /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
9463                 if (IS_BROADWELL(state->dev) && crtc_state->ips_enabled)
9464                         pixel_rate = DIV_ROUND_UP(pixel_rate * 100, 95);
9465
9466                 max_pixel_rate = max(max_pixel_rate, pixel_rate);
9467         }
9468
9469         return max_pixel_rate;
9470 }
9471
9472 static void broadwell_set_cdclk(struct drm_device *dev, int cdclk)
9473 {
9474         struct drm_i915_private *dev_priv = dev->dev_private;
9475         uint32_t val, data;
9476         int ret;
9477
9478         if (WARN((I915_READ(LCPLL_CTL) &
9479                   (LCPLL_PLL_DISABLE | LCPLL_PLL_LOCK |
9480                    LCPLL_CD_CLOCK_DISABLE | LCPLL_ROOT_CD_CLOCK_DISABLE |
9481                    LCPLL_CD2X_CLOCK_DISABLE | LCPLL_POWER_DOWN_ALLOW |
9482                    LCPLL_CD_SOURCE_FCLK)) != LCPLL_PLL_LOCK,
9483                  "trying to change cdclk frequency with cdclk not enabled\n"))
9484                 return;
9485
9486         mutex_lock(&dev_priv->rps.hw_lock);
9487         ret = sandybridge_pcode_write(dev_priv,
9488                                       BDW_PCODE_DISPLAY_FREQ_CHANGE_REQ, 0x0);
9489         mutex_unlock(&dev_priv->rps.hw_lock);
9490         if (ret) {
9491                 DRM_ERROR("failed to inform pcode about cdclk change\n");
9492                 return;
9493         }
9494
9495         val = I915_READ(LCPLL_CTL);
9496         val |= LCPLL_CD_SOURCE_FCLK;
9497         I915_WRITE(LCPLL_CTL, val);
9498
9499         if (wait_for_atomic_us(I915_READ(LCPLL_CTL) &
9500                                LCPLL_CD_SOURCE_FCLK_DONE, 1))
9501                 DRM_ERROR("Switching to FCLK failed\n");
9502
9503         val = I915_READ(LCPLL_CTL);
9504         val &= ~LCPLL_CLK_FREQ_MASK;
9505
9506         switch (cdclk) {
9507         case 450000:
9508                 val |= LCPLL_CLK_FREQ_450;
9509                 data = 0;
9510                 break;
9511         case 540000:
9512                 val |= LCPLL_CLK_FREQ_54O_BDW;
9513                 data = 1;
9514                 break;
9515         case 337500:
9516                 val |= LCPLL_CLK_FREQ_337_5_BDW;
9517                 data = 2;
9518                 break;
9519         case 675000:
9520                 val |= LCPLL_CLK_FREQ_675_BDW;
9521                 data = 3;
9522                 break;
9523         default:
9524                 WARN(1, "invalid cdclk frequency\n");
9525                 return;
9526         }
9527
9528         I915_WRITE(LCPLL_CTL, val);
9529
9530         val = I915_READ(LCPLL_CTL);
9531         val &= ~LCPLL_CD_SOURCE_FCLK;
9532         I915_WRITE(LCPLL_CTL, val);
9533
9534         if (wait_for_atomic_us((I915_READ(LCPLL_CTL) &
9535                                 LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9536                 DRM_ERROR("Switching back to LCPLL failed\n");
9537
9538         mutex_lock(&dev_priv->rps.hw_lock);
9539         sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ, data);
9540         mutex_unlock(&dev_priv->rps.hw_lock);
9541
9542         intel_update_cdclk(dev);
9543
9544         WARN(cdclk != dev_priv->cdclk_freq,
9545              "cdclk requested %d kHz but got %d kHz\n",
9546              cdclk, dev_priv->cdclk_freq);
9547 }
9548
9549 static int broadwell_modeset_calc_cdclk(struct drm_atomic_state *state)
9550 {
9551         struct drm_i915_private *dev_priv = to_i915(state->dev);
9552         int max_pixclk = ilk_max_pixel_rate(state);
9553         int cdclk;
9554
9555         /*
9556          * FIXME should also account for plane ratio
9557          * once 64bpp pixel formats are supported.
9558          */
9559         if (max_pixclk > 540000)
9560                 cdclk = 675000;
9561         else if (max_pixclk > 450000)
9562                 cdclk = 540000;
9563         else if (max_pixclk > 337500)
9564                 cdclk = 450000;
9565         else
9566                 cdclk = 337500;
9567
9568         /*
9569          * FIXME move the cdclk caclulation to
9570          * compute_config() so we can fail gracegully.
9571          */
9572         if (cdclk > dev_priv->max_cdclk_freq) {
9573                 DRM_ERROR("requested cdclk (%d kHz) exceeds max (%d kHz)\n",
9574                           cdclk, dev_priv->max_cdclk_freq);
9575                 cdclk = dev_priv->max_cdclk_freq;
9576         }
9577
9578         to_intel_atomic_state(state)->cdclk = cdclk;
9579
9580         return 0;
9581 }
9582
9583 static void broadwell_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9584 {
9585         struct drm_device *dev = old_state->dev;
9586         unsigned int req_cdclk = to_intel_atomic_state(old_state)->cdclk;
9587
9588         broadwell_set_cdclk(dev, req_cdclk);
9589 }
9590
9591 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9592                                       struct intel_crtc_state *crtc_state)
9593 {
9594         if (!intel_ddi_pll_select(crtc, crtc_state))
9595                 return -EINVAL;
9596
9597         crtc->lowfreq_avail = false;
9598
9599         return 0;
9600 }
9601
9602 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9603                                 enum port port,
9604                                 struct intel_crtc_state *pipe_config)
9605 {
9606         switch (port) {
9607         case PORT_A:
9608                 pipe_config->ddi_pll_sel = SKL_DPLL0;
9609                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL1;
9610                 break;
9611         case PORT_B:
9612                 pipe_config->ddi_pll_sel = SKL_DPLL1;
9613                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL2;
9614                 break;
9615         case PORT_C:
9616                 pipe_config->ddi_pll_sel = SKL_DPLL2;
9617                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL3;
9618                 break;
9619         default:
9620                 DRM_ERROR("Incorrect port type\n");
9621         }
9622 }
9623
9624 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9625                                 enum port port,
9626                                 struct intel_crtc_state *pipe_config)
9627 {
9628         u32 temp, dpll_ctl1;
9629
9630         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9631         pipe_config->ddi_pll_sel = temp >> (port * 3 + 1);
9632
9633         switch (pipe_config->ddi_pll_sel) {
9634         case SKL_DPLL0:
9635                 /*
9636                  * On SKL the eDP DPLL (DPLL0 as we don't use SSC) is not part
9637                  * of the shared DPLL framework and thus needs to be read out
9638                  * separately
9639                  */
9640                 dpll_ctl1 = I915_READ(DPLL_CTRL1);
9641                 pipe_config->dpll_hw_state.ctrl1 = dpll_ctl1 & 0x3f;
9642                 break;
9643         case SKL_DPLL1:
9644                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL1;
9645                 break;
9646         case SKL_DPLL2:
9647                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL2;
9648                 break;
9649         case SKL_DPLL3:
9650                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL3;
9651                 break;
9652         }
9653 }
9654
9655 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9656                                 enum port port,
9657                                 struct intel_crtc_state *pipe_config)
9658 {
9659         pipe_config->ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9660
9661         switch (pipe_config->ddi_pll_sel) {
9662         case PORT_CLK_SEL_WRPLL1:
9663                 pipe_config->shared_dpll = DPLL_ID_WRPLL1;
9664                 break;
9665         case PORT_CLK_SEL_WRPLL2:
9666                 pipe_config->shared_dpll = DPLL_ID_WRPLL2;
9667                 break;
9668         }
9669 }
9670
9671 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9672                                        struct intel_crtc_state *pipe_config)
9673 {
9674         struct drm_device *dev = crtc->base.dev;
9675         struct drm_i915_private *dev_priv = dev->dev_private;
9676         struct intel_shared_dpll *pll;
9677         enum port port;
9678         uint32_t tmp;
9679
9680         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9681
9682         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9683
9684         if (IS_SKYLAKE(dev))
9685                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
9686         else if (IS_BROXTON(dev))
9687                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
9688         else
9689                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
9690
9691         if (pipe_config->shared_dpll >= 0) {
9692                 pll = &dev_priv->shared_dplls[pipe_config->shared_dpll];
9693
9694                 WARN_ON(!pll->get_hw_state(dev_priv, pll,
9695                                            &pipe_config->dpll_hw_state));
9696         }
9697
9698         /*
9699          * Haswell has only FDI/PCH transcoder A. It is which is connected to
9700          * DDI E. So just check whether this pipe is wired to DDI E and whether
9701          * the PCH transcoder is on.
9702          */
9703         if (INTEL_INFO(dev)->gen < 9 &&
9704             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
9705                 pipe_config->has_pch_encoder = true;
9706
9707                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
9708                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9709                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9710
9711                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9712         }
9713 }
9714
9715 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
9716                                     struct intel_crtc_state *pipe_config)
9717 {
9718         struct drm_device *dev = crtc->base.dev;
9719         struct drm_i915_private *dev_priv = dev->dev_private;
9720         enum intel_display_power_domain pfit_domain;
9721         uint32_t tmp;
9722
9723         if (!intel_display_power_is_enabled(dev_priv,
9724                                          POWER_DOMAIN_PIPE(crtc->pipe)))
9725                 return false;
9726
9727         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9728         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
9729
9730         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
9731         if (tmp & TRANS_DDI_FUNC_ENABLE) {
9732                 enum pipe trans_edp_pipe;
9733                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9734                 default:
9735                         WARN(1, "unknown pipe linked to edp transcoder\n");
9736                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9737                 case TRANS_DDI_EDP_INPUT_A_ON:
9738                         trans_edp_pipe = PIPE_A;
9739                         break;
9740                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
9741                         trans_edp_pipe = PIPE_B;
9742                         break;
9743                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
9744                         trans_edp_pipe = PIPE_C;
9745                         break;
9746                 }
9747
9748                 if (trans_edp_pipe == crtc->pipe)
9749                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
9750         }
9751
9752         if (!intel_display_power_is_enabled(dev_priv,
9753                         POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder)))
9754                 return false;
9755
9756         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
9757         if (!(tmp & PIPECONF_ENABLE))
9758                 return false;
9759
9760         haswell_get_ddi_port_state(crtc, pipe_config);
9761
9762         intel_get_pipe_timings(crtc, pipe_config);
9763
9764         if (INTEL_INFO(dev)->gen >= 9) {
9765                 skl_init_scalers(dev, crtc, pipe_config);
9766         }
9767
9768         pfit_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
9769
9770         if (INTEL_INFO(dev)->gen >= 9) {
9771                 pipe_config->scaler_state.scaler_id = -1;
9772                 pipe_config->scaler_state.scaler_users &= ~(1 << SKL_CRTC_INDEX);
9773         }
9774
9775         if (intel_display_power_is_enabled(dev_priv, pfit_domain)) {
9776                 if (INTEL_INFO(dev)->gen == 9)
9777                         skylake_get_pfit_config(crtc, pipe_config);
9778                 else if (INTEL_INFO(dev)->gen < 9)
9779                         ironlake_get_pfit_config(crtc, pipe_config);
9780                 else
9781                         MISSING_CASE(INTEL_INFO(dev)->gen);
9782         }
9783
9784         if (IS_HASWELL(dev))
9785                 pipe_config->ips_enabled = hsw_crtc_supports_ips(crtc) &&
9786                         (I915_READ(IPS_CTL) & IPS_ENABLE);
9787
9788         if (pipe_config->cpu_transcoder != TRANSCODER_EDP) {
9789                 pipe_config->pixel_multiplier =
9790                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
9791         } else {
9792                 pipe_config->pixel_multiplier = 1;
9793         }
9794
9795         return true;
9796 }
9797
9798 static void i845_update_cursor(struct drm_crtc *crtc, u32 base)
9799 {
9800         struct drm_device *dev = crtc->dev;
9801         struct drm_i915_private *dev_priv = dev->dev_private;
9802         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9803         uint32_t cntl = 0, size = 0;
9804
9805         if (base) {
9806                 unsigned int width = intel_crtc->base.cursor->state->crtc_w;
9807                 unsigned int height = intel_crtc->base.cursor->state->crtc_h;
9808                 unsigned int stride = roundup_pow_of_two(width) * 4;
9809
9810                 switch (stride) {
9811                 default:
9812                         WARN_ONCE(1, "Invalid cursor width/stride, width=%u, stride=%u\n",
9813                                   width, stride);
9814                         stride = 256;
9815                         /* fallthrough */
9816                 case 256:
9817                 case 512:
9818                 case 1024:
9819                 case 2048:
9820                         break;
9821                 }
9822
9823                 cntl |= CURSOR_ENABLE |
9824                         CURSOR_GAMMA_ENABLE |
9825                         CURSOR_FORMAT_ARGB |
9826                         CURSOR_STRIDE(stride);
9827
9828                 size = (height << 12) | width;
9829         }
9830
9831         if (intel_crtc->cursor_cntl != 0 &&
9832             (intel_crtc->cursor_base != base ||
9833              intel_crtc->cursor_size != size ||
9834              intel_crtc->cursor_cntl != cntl)) {
9835                 /* On these chipsets we can only modify the base/size/stride
9836                  * whilst the cursor is disabled.
9837                  */
9838                 I915_WRITE(_CURACNTR, 0);
9839                 POSTING_READ(_CURACNTR);
9840                 intel_crtc->cursor_cntl = 0;
9841         }
9842
9843         if (intel_crtc->cursor_base != base) {
9844                 I915_WRITE(_CURABASE, base);
9845                 intel_crtc->cursor_base = base;
9846         }
9847
9848         if (intel_crtc->cursor_size != size) {
9849                 I915_WRITE(CURSIZE, size);
9850                 intel_crtc->cursor_size = size;
9851         }
9852
9853         if (intel_crtc->cursor_cntl != cntl) {
9854                 I915_WRITE(_CURACNTR, cntl);
9855                 POSTING_READ(_CURACNTR);
9856                 intel_crtc->cursor_cntl = cntl;
9857         }
9858 }
9859
9860 static void i9xx_update_cursor(struct drm_crtc *crtc, u32 base)
9861 {
9862         struct drm_device *dev = crtc->dev;
9863         struct drm_i915_private *dev_priv = dev->dev_private;
9864         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9865         int pipe = intel_crtc->pipe;
9866         uint32_t cntl;
9867
9868         cntl = 0;
9869         if (base) {
9870                 cntl = MCURSOR_GAMMA_ENABLE;
9871                 switch (intel_crtc->base.cursor->state->crtc_w) {
9872                         case 64:
9873                                 cntl |= CURSOR_MODE_64_ARGB_AX;
9874                                 break;
9875                         case 128:
9876                                 cntl |= CURSOR_MODE_128_ARGB_AX;
9877                                 break;
9878                         case 256:
9879                                 cntl |= CURSOR_MODE_256_ARGB_AX;
9880                                 break;
9881                         default:
9882                                 MISSING_CASE(intel_crtc->base.cursor->state->crtc_w);
9883                                 return;
9884                 }
9885                 cntl |= pipe << 28; /* Connect to correct pipe */
9886
9887                 if (IS_HASWELL(dev) || IS_BROADWELL(dev))
9888                         cntl |= CURSOR_PIPE_CSC_ENABLE;
9889         }
9890
9891         if (crtc->cursor->state->rotation == BIT(DRM_ROTATE_180))
9892                 cntl |= CURSOR_ROTATE_180;
9893
9894         if (intel_crtc->cursor_cntl != cntl) {
9895                 I915_WRITE(CURCNTR(pipe), cntl);
9896                 POSTING_READ(CURCNTR(pipe));
9897                 intel_crtc->cursor_cntl = cntl;
9898         }
9899
9900         /* and commit changes on next vblank */
9901         I915_WRITE(CURBASE(pipe), base);
9902         POSTING_READ(CURBASE(pipe));
9903
9904         intel_crtc->cursor_base = base;
9905 }
9906
9907 /* If no-part of the cursor is visible on the framebuffer, then the GPU may hang... */
9908 static void intel_crtc_update_cursor(struct drm_crtc *crtc,
9909                                      bool on)
9910 {
9911         struct drm_device *dev = crtc->dev;
9912         struct drm_i915_private *dev_priv = dev->dev_private;
9913         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9914         int pipe = intel_crtc->pipe;
9915         int x = crtc->cursor_x;
9916         int y = crtc->cursor_y;
9917         u32 base = 0, pos = 0;
9918
9919         if (on)
9920                 base = intel_crtc->cursor_addr;
9921
9922         if (x >= intel_crtc->config->pipe_src_w)
9923                 base = 0;
9924
9925         if (y >= intel_crtc->config->pipe_src_h)
9926                 base = 0;
9927
9928         if (x < 0) {
9929                 if (x + intel_crtc->base.cursor->state->crtc_w <= 0)
9930                         base = 0;
9931
9932                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
9933                 x = -x;
9934         }
9935         pos |= x << CURSOR_X_SHIFT;
9936
9937         if (y < 0) {
9938                 if (y + intel_crtc->base.cursor->state->crtc_h <= 0)
9939                         base = 0;
9940
9941                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
9942                 y = -y;
9943         }
9944         pos |= y << CURSOR_Y_SHIFT;
9945
9946         if (base == 0 && intel_crtc->cursor_base == 0)
9947                 return;
9948
9949         I915_WRITE(CURPOS(pipe), pos);
9950
9951         /* ILK+ do this automagically */
9952         if (HAS_GMCH_DISPLAY(dev) &&
9953             crtc->cursor->state->rotation == BIT(DRM_ROTATE_180)) {
9954                 base += (intel_crtc->base.cursor->state->crtc_h *
9955                         intel_crtc->base.cursor->state->crtc_w - 1) * 4;
9956         }
9957
9958         if (IS_845G(dev) || IS_I865G(dev))
9959                 i845_update_cursor(crtc, base);
9960         else
9961                 i9xx_update_cursor(crtc, base);
9962 }
9963
9964 static bool cursor_size_ok(struct drm_device *dev,
9965                            uint32_t width, uint32_t height)
9966 {
9967         if (width == 0 || height == 0)
9968                 return false;
9969
9970         /*
9971          * 845g/865g are special in that they are only limited by
9972          * the width of their cursors, the height is arbitrary up to
9973          * the precision of the register. Everything else requires
9974          * square cursors, limited to a few power-of-two sizes.
9975          */
9976         if (IS_845G(dev) || IS_I865G(dev)) {
9977                 if ((width & 63) != 0)
9978                         return false;
9979
9980                 if (width > (IS_845G(dev) ? 64 : 512))
9981                         return false;
9982
9983                 if (height > 1023)
9984                         return false;
9985         } else {
9986                 switch (width | height) {
9987                 case 256:
9988                 case 128:
9989                         if (IS_GEN2(dev))
9990                                 return false;
9991                 case 64:
9992                         break;
9993                 default:
9994                         return false;
9995                 }
9996         }
9997
9998         return true;
9999 }
10000
10001 static void intel_crtc_gamma_set(struct drm_crtc *crtc, u16 *red, u16 *green,
10002                                  u16 *blue, uint32_t start, uint32_t size)
10003 {
10004         int end = (start + size > 256) ? 256 : start + size, i;
10005         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10006
10007         for (i = start; i < end; i++) {
10008                 intel_crtc->lut_r[i] = red[i] >> 8;
10009                 intel_crtc->lut_g[i] = green[i] >> 8;
10010                 intel_crtc->lut_b[i] = blue[i] >> 8;
10011         }
10012
10013         intel_crtc_load_lut(crtc);
10014 }
10015
10016 /* VESA 640x480x72Hz mode to set on the pipe */
10017 static struct drm_display_mode load_detect_mode = {
10018         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10019                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10020 };
10021
10022 struct drm_framebuffer *
10023 __intel_framebuffer_create(struct drm_device *dev,
10024                            struct drm_mode_fb_cmd2 *mode_cmd,
10025                            struct drm_i915_gem_object *obj)
10026 {
10027         struct intel_framebuffer *intel_fb;
10028         int ret;
10029
10030         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10031         if (!intel_fb) {
10032                 drm_gem_object_unreference(&obj->base);
10033                 return ERR_PTR(-ENOMEM);
10034         }
10035
10036         ret = intel_framebuffer_init(dev, intel_fb, mode_cmd, obj);
10037         if (ret)
10038                 goto err;
10039
10040         return &intel_fb->base;
10041 err:
10042         drm_gem_object_unreference(&obj->base);
10043         kfree(intel_fb);
10044
10045         return ERR_PTR(ret);
10046 }
10047
10048 static struct drm_framebuffer *
10049 intel_framebuffer_create(struct drm_device *dev,
10050                          struct drm_mode_fb_cmd2 *mode_cmd,
10051                          struct drm_i915_gem_object *obj)
10052 {
10053         struct drm_framebuffer *fb;
10054         int ret;
10055
10056         ret = i915_mutex_lock_interruptible(dev);
10057         if (ret)
10058                 return ERR_PTR(ret);
10059         fb = __intel_framebuffer_create(dev, mode_cmd, obj);
10060         mutex_unlock(&dev->struct_mutex);
10061
10062         return fb;
10063 }
10064
10065 static u32
10066 intel_framebuffer_pitch_for_width(int width, int bpp)
10067 {
10068         u32 pitch = DIV_ROUND_UP(width * bpp, 8);
10069         return ALIGN(pitch, 64);
10070 }
10071
10072 static u32
10073 intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
10074 {
10075         u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
10076         return PAGE_ALIGN(pitch * mode->vdisplay);
10077 }
10078
10079 static struct drm_framebuffer *
10080 intel_framebuffer_create_for_mode(struct drm_device *dev,
10081                                   struct drm_display_mode *mode,
10082                                   int depth, int bpp)
10083 {
10084         struct drm_i915_gem_object *obj;
10085         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
10086
10087         obj = i915_gem_alloc_object(dev,
10088                                     intel_framebuffer_size_for_mode(mode, bpp));
10089         if (obj == NULL)
10090                 return ERR_PTR(-ENOMEM);
10091
10092         mode_cmd.width = mode->hdisplay;
10093         mode_cmd.height = mode->vdisplay;
10094         mode_cmd.pitches[0] = intel_framebuffer_pitch_for_width(mode_cmd.width,
10095                                                                 bpp);
10096         mode_cmd.pixel_format = drm_mode_legacy_fb_format(bpp, depth);
10097
10098         return intel_framebuffer_create(dev, &mode_cmd, obj);
10099 }
10100
10101 static struct drm_framebuffer *
10102 mode_fits_in_fbdev(struct drm_device *dev,
10103                    struct drm_display_mode *mode)
10104 {
10105 #ifdef CONFIG_DRM_I915_FBDEV
10106         struct drm_i915_private *dev_priv = dev->dev_private;
10107         struct drm_i915_gem_object *obj;
10108         struct drm_framebuffer *fb;
10109
10110         if (!dev_priv->fbdev)
10111                 return NULL;
10112
10113         if (!dev_priv->fbdev->fb)
10114                 return NULL;
10115
10116         obj = dev_priv->fbdev->fb->obj;
10117         BUG_ON(!obj);
10118
10119         fb = &dev_priv->fbdev->fb->base;
10120         if (fb->pitches[0] < intel_framebuffer_pitch_for_width(mode->hdisplay,
10121                                                                fb->bits_per_pixel))
10122                 return NULL;
10123
10124         if (obj->base.size < mode->vdisplay * fb->pitches[0])
10125                 return NULL;
10126
10127         return fb;
10128 #else
10129         return NULL;
10130 #endif
10131 }
10132
10133 static int intel_modeset_setup_plane_state(struct drm_atomic_state *state,
10134                                            struct drm_crtc *crtc,
10135                                            struct drm_display_mode *mode,
10136                                            struct drm_framebuffer *fb,
10137                                            int x, int y)
10138 {
10139         struct drm_plane_state *plane_state;
10140         int hdisplay, vdisplay;
10141         int ret;
10142
10143         plane_state = drm_atomic_get_plane_state(state, crtc->primary);
10144         if (IS_ERR(plane_state))
10145                 return PTR_ERR(plane_state);
10146
10147         if (mode)
10148                 drm_crtc_get_hv_timing(mode, &hdisplay, &vdisplay);
10149         else
10150                 hdisplay = vdisplay = 0;
10151
10152         ret = drm_atomic_set_crtc_for_plane(plane_state, fb ? crtc : NULL);
10153         if (ret)
10154                 return ret;
10155         drm_atomic_set_fb_for_plane(plane_state, fb);
10156         plane_state->crtc_x = 0;
10157         plane_state->crtc_y = 0;
10158         plane_state->crtc_w = hdisplay;
10159         plane_state->crtc_h = vdisplay;
10160         plane_state->src_x = x << 16;
10161         plane_state->src_y = y << 16;
10162         plane_state->src_w = hdisplay << 16;
10163         plane_state->src_h = vdisplay << 16;
10164
10165         return 0;
10166 }
10167
10168 bool intel_get_load_detect_pipe(struct drm_connector *connector,
10169                                 struct drm_display_mode *mode,
10170                                 struct intel_load_detect_pipe *old,
10171                                 struct drm_modeset_acquire_ctx *ctx)
10172 {
10173         struct intel_crtc *intel_crtc;
10174         struct intel_encoder *intel_encoder =
10175                 intel_attached_encoder(connector);
10176         struct drm_crtc *possible_crtc;
10177         struct drm_encoder *encoder = &intel_encoder->base;
10178         struct drm_crtc *crtc = NULL;
10179         struct drm_device *dev = encoder->dev;
10180         struct drm_framebuffer *fb;
10181         struct drm_mode_config *config = &dev->mode_config;
10182         struct drm_atomic_state *state = NULL;
10183         struct drm_connector_state *connector_state;
10184         struct intel_crtc_state *crtc_state;
10185         int ret, i = -1;
10186
10187         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10188                       connector->base.id, connector->name,
10189                       encoder->base.id, encoder->name);
10190
10191 retry:
10192         ret = drm_modeset_lock(&config->connection_mutex, ctx);
10193         if (ret)
10194                 goto fail;
10195
10196         /*
10197          * Algorithm gets a little messy:
10198          *
10199          *   - if the connector already has an assigned crtc, use it (but make
10200          *     sure it's on first)
10201          *
10202          *   - try to find the first unused crtc that can drive this connector,
10203          *     and use that if we find one
10204          */
10205
10206         /* See if we already have a CRTC for this connector */
10207         if (encoder->crtc) {
10208                 crtc = encoder->crtc;
10209
10210                 ret = drm_modeset_lock(&crtc->mutex, ctx);
10211                 if (ret)
10212                         goto fail;
10213                 ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
10214                 if (ret)
10215                         goto fail;
10216
10217                 old->dpms_mode = connector->dpms;
10218                 old->load_detect_temp = false;
10219
10220                 /* Make sure the crtc and connector are running */
10221                 if (connector->dpms != DRM_MODE_DPMS_ON)
10222                         connector->funcs->dpms(connector, DRM_MODE_DPMS_ON);
10223
10224                 return true;
10225         }
10226
10227         /* Find an unused one (if possible) */
10228         for_each_crtc(dev, possible_crtc) {
10229                 i++;
10230                 if (!(encoder->possible_crtcs & (1 << i)))
10231                         continue;
10232                 if (possible_crtc->state->enable)
10233                         continue;
10234
10235                 crtc = possible_crtc;
10236                 break;
10237         }
10238
10239         /*
10240          * If we didn't find an unused CRTC, don't use any.
10241          */
10242         if (!crtc) {
10243                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
10244                 goto fail;
10245         }
10246
10247         ret = drm_modeset_lock(&crtc->mutex, ctx);
10248         if (ret)
10249                 goto fail;
10250         ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
10251         if (ret)
10252                 goto fail;
10253
10254         intel_crtc = to_intel_crtc(crtc);
10255         old->dpms_mode = connector->dpms;
10256         old->load_detect_temp = true;
10257         old->release_fb = NULL;
10258
10259         state = drm_atomic_state_alloc(dev);
10260         if (!state)
10261                 return false;
10262
10263         state->acquire_ctx = ctx;
10264
10265         connector_state = drm_atomic_get_connector_state(state, connector);
10266         if (IS_ERR(connector_state)) {
10267                 ret = PTR_ERR(connector_state);
10268                 goto fail;
10269         }
10270
10271         connector_state->crtc = crtc;
10272         connector_state->best_encoder = &intel_encoder->base;
10273
10274         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10275         if (IS_ERR(crtc_state)) {
10276                 ret = PTR_ERR(crtc_state);
10277                 goto fail;
10278         }
10279
10280         crtc_state->base.active = crtc_state->base.enable = true;
10281
10282         if (!mode)
10283                 mode = &load_detect_mode;
10284
10285         /* We need a framebuffer large enough to accommodate all accesses
10286          * that the plane may generate whilst we perform load detection.
10287          * We can not rely on the fbcon either being present (we get called
10288          * during its initialisation to detect all boot displays, or it may
10289          * not even exist) or that it is large enough to satisfy the
10290          * requested mode.
10291          */
10292         fb = mode_fits_in_fbdev(dev, mode);
10293         if (fb == NULL) {
10294                 DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
10295                 fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
10296                 old->release_fb = fb;
10297         } else
10298                 DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
10299         if (IS_ERR(fb)) {
10300                 DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
10301                 goto fail;
10302         }
10303
10304         ret = intel_modeset_setup_plane_state(state, crtc, mode, fb, 0, 0);
10305         if (ret)
10306                 goto fail;
10307
10308         drm_mode_copy(&crtc_state->base.mode, mode);
10309
10310         if (drm_atomic_commit(state)) {
10311                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
10312                 if (old->release_fb)
10313                         old->release_fb->funcs->destroy(old->release_fb);
10314                 goto fail;
10315         }
10316         crtc->primary->crtc = crtc;
10317
10318         /* let the connector get through one full cycle before testing */
10319         intel_wait_for_vblank(dev, intel_crtc->pipe);
10320         return true;
10321
10322 fail:
10323         drm_atomic_state_free(state);
10324         state = NULL;
10325
10326         if (ret == -EDEADLK) {
10327                 drm_modeset_backoff(ctx);
10328                 goto retry;
10329         }
10330
10331         return false;
10332 }
10333
10334 void intel_release_load_detect_pipe(struct drm_connector *connector,
10335                                     struct intel_load_detect_pipe *old,
10336                                     struct drm_modeset_acquire_ctx *ctx)
10337 {
10338         struct drm_device *dev = connector->dev;
10339         struct intel_encoder *intel_encoder =
10340                 intel_attached_encoder(connector);
10341         struct drm_encoder *encoder = &intel_encoder->base;
10342         struct drm_crtc *crtc = encoder->crtc;
10343         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10344         struct drm_atomic_state *state;
10345         struct drm_connector_state *connector_state;
10346         struct intel_crtc_state *crtc_state;
10347         int ret;
10348
10349         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10350                       connector->base.id, connector->name,
10351                       encoder->base.id, encoder->name);
10352
10353         if (old->load_detect_temp) {
10354                 state = drm_atomic_state_alloc(dev);
10355                 if (!state)
10356                         goto fail;
10357
10358                 state->acquire_ctx = ctx;
10359
10360                 connector_state = drm_atomic_get_connector_state(state, connector);
10361                 if (IS_ERR(connector_state))
10362                         goto fail;
10363
10364                 crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10365                 if (IS_ERR(crtc_state))
10366                         goto fail;
10367
10368                 connector_state->best_encoder = NULL;
10369                 connector_state->crtc = NULL;
10370
10371                 crtc_state->base.enable = crtc_state->base.active = false;
10372
10373                 ret = intel_modeset_setup_plane_state(state, crtc, NULL, NULL,
10374                                                       0, 0);
10375                 if (ret)
10376                         goto fail;
10377
10378                 ret = drm_atomic_commit(state);
10379                 if (ret)
10380                         goto fail;
10381
10382                 if (old->release_fb) {
10383                         drm_framebuffer_unregister_private(old->release_fb);
10384                         drm_framebuffer_unreference(old->release_fb);
10385                 }
10386
10387                 return;
10388         }
10389
10390         /* Switch crtc and encoder back off if necessary */
10391         if (old->dpms_mode != DRM_MODE_DPMS_ON)
10392                 connector->funcs->dpms(connector, old->dpms_mode);
10393
10394         return;
10395 fail:
10396         DRM_DEBUG_KMS("Couldn't release load detect pipe.\n");
10397         drm_atomic_state_free(state);
10398 }
10399
10400 static int i9xx_pll_refclk(struct drm_device *dev,
10401                            const struct intel_crtc_state *pipe_config)
10402 {
10403         struct drm_i915_private *dev_priv = dev->dev_private;
10404         u32 dpll = pipe_config->dpll_hw_state.dpll;
10405
10406         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10407                 return dev_priv->vbt.lvds_ssc_freq;
10408         else if (HAS_PCH_SPLIT(dev))
10409                 return 120000;
10410         else if (!IS_GEN2(dev))
10411                 return 96000;
10412         else
10413                 return 48000;
10414 }
10415
10416 /* Returns the clock of the currently programmed mode of the given pipe. */
10417 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
10418                                 struct intel_crtc_state *pipe_config)
10419 {
10420         struct drm_device *dev = crtc->base.dev;
10421         struct drm_i915_private *dev_priv = dev->dev_private;
10422         int pipe = pipe_config->cpu_transcoder;
10423         u32 dpll = pipe_config->dpll_hw_state.dpll;
10424         u32 fp;
10425         intel_clock_t clock;
10426         int port_clock;
10427         int refclk = i9xx_pll_refclk(dev, pipe_config);
10428
10429         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10430                 fp = pipe_config->dpll_hw_state.fp0;
10431         else
10432                 fp = pipe_config->dpll_hw_state.fp1;
10433
10434         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10435         if (IS_PINEVIEW(dev)) {
10436                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10437                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10438         } else {
10439                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10440                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10441         }
10442
10443         if (!IS_GEN2(dev)) {
10444                 if (IS_PINEVIEW(dev))
10445                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10446                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10447                 else
10448                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10449                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10450
10451                 switch (dpll & DPLL_MODE_MASK) {
10452                 case DPLLB_MODE_DAC_SERIAL:
10453                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10454                                 5 : 10;
10455                         break;
10456                 case DPLLB_MODE_LVDS:
10457                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10458                                 7 : 14;
10459                         break;
10460                 default:
10461                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10462                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10463                         return;
10464                 }
10465
10466                 if (IS_PINEVIEW(dev))
10467                         port_clock = pnv_calc_dpll_params(refclk, &clock);
10468                 else
10469                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
10470         } else {
10471                 u32 lvds = IS_I830(dev) ? 0 : I915_READ(LVDS);
10472                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10473
10474                 if (is_lvds) {
10475                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10476                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10477
10478                         if (lvds & LVDS_CLKB_POWER_UP)
10479                                 clock.p2 = 7;
10480                         else
10481                                 clock.p2 = 14;
10482                 } else {
10483                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10484                                 clock.p1 = 2;
10485                         else {
10486                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10487                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10488                         }
10489                         if (dpll & PLL_P2_DIVIDE_BY_4)
10490                                 clock.p2 = 4;
10491                         else
10492                                 clock.p2 = 2;
10493                 }
10494
10495                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10496         }
10497
10498         /*
10499          * This value includes pixel_multiplier. We will use
10500          * port_clock to compute adjusted_mode.crtc_clock in the
10501          * encoder's get_config() function.
10502          */
10503         pipe_config->port_clock = port_clock;
10504 }
10505
10506 int intel_dotclock_calculate(int link_freq,
10507                              const struct intel_link_m_n *m_n)
10508 {
10509         /*
10510          * The calculation for the data clock is:
10511          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10512          * But we want to avoid losing precison if possible, so:
10513          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10514          *
10515          * and the link clock is simpler:
10516          * link_clock = (m * link_clock) / n
10517          */
10518
10519         if (!m_n->link_n)
10520                 return 0;
10521
10522         return div_u64((u64)m_n->link_m * link_freq, m_n->link_n);
10523 }
10524
10525 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10526                                    struct intel_crtc_state *pipe_config)
10527 {
10528         struct drm_device *dev = crtc->base.dev;
10529
10530         /* read out port_clock from the DPLL */
10531         i9xx_crtc_clock_get(crtc, pipe_config);
10532
10533         /*
10534          * This value does not include pixel_multiplier.
10535          * We will check that port_clock and adjusted_mode.crtc_clock
10536          * agree once we know their relationship in the encoder's
10537          * get_config() function.
10538          */
10539         pipe_config->base.adjusted_mode.crtc_clock =
10540                 intel_dotclock_calculate(intel_fdi_link_freq(dev) * 10000,
10541                                          &pipe_config->fdi_m_n);
10542 }
10543
10544 /** Returns the currently programmed mode of the given pipe. */
10545 struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
10546                                              struct drm_crtc *crtc)
10547 {
10548         struct drm_i915_private *dev_priv = dev->dev_private;
10549         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10550         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
10551         struct drm_display_mode *mode;
10552         struct intel_crtc_state pipe_config;
10553         int htot = I915_READ(HTOTAL(cpu_transcoder));
10554         int hsync = I915_READ(HSYNC(cpu_transcoder));
10555         int vtot = I915_READ(VTOTAL(cpu_transcoder));
10556         int vsync = I915_READ(VSYNC(cpu_transcoder));
10557         enum pipe pipe = intel_crtc->pipe;
10558
10559         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10560         if (!mode)
10561                 return NULL;
10562
10563         /*
10564          * Construct a pipe_config sufficient for getting the clock info
10565          * back out of crtc_clock_get.
10566          *
10567          * Note, if LVDS ever uses a non-1 pixel multiplier, we'll need
10568          * to use a real value here instead.
10569          */
10570         pipe_config.cpu_transcoder = (enum transcoder) pipe;
10571         pipe_config.pixel_multiplier = 1;
10572         pipe_config.dpll_hw_state.dpll = I915_READ(DPLL(pipe));
10573         pipe_config.dpll_hw_state.fp0 = I915_READ(FP0(pipe));
10574         pipe_config.dpll_hw_state.fp1 = I915_READ(FP1(pipe));
10575         i9xx_crtc_clock_get(intel_crtc, &pipe_config);
10576
10577         mode->clock = pipe_config.port_clock / pipe_config.pixel_multiplier;
10578         mode->hdisplay = (htot & 0xffff) + 1;
10579         mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
10580         mode->hsync_start = (hsync & 0xffff) + 1;
10581         mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
10582         mode->vdisplay = (vtot & 0xffff) + 1;
10583         mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
10584         mode->vsync_start = (vsync & 0xffff) + 1;
10585         mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
10586
10587         drm_mode_set_name(mode);
10588
10589         return mode;
10590 }
10591
10592 void intel_mark_busy(struct drm_device *dev)
10593 {
10594         struct drm_i915_private *dev_priv = dev->dev_private;
10595
10596         if (dev_priv->mm.busy)
10597                 return;
10598
10599         intel_runtime_pm_get(dev_priv);
10600         i915_update_gfx_val(dev_priv);
10601         if (INTEL_INFO(dev)->gen >= 6)
10602                 gen6_rps_busy(dev_priv);
10603         dev_priv->mm.busy = true;
10604 }
10605
10606 void intel_mark_idle(struct drm_device *dev)
10607 {
10608         struct drm_i915_private *dev_priv = dev->dev_private;
10609
10610         if (!dev_priv->mm.busy)
10611                 return;
10612
10613         dev_priv->mm.busy = false;
10614
10615         if (INTEL_INFO(dev)->gen >= 6)
10616                 gen6_rps_idle(dev->dev_private);
10617
10618         intel_runtime_pm_put(dev_priv);
10619 }
10620
10621 static void intel_crtc_destroy(struct drm_crtc *crtc)
10622 {
10623         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10624         struct drm_device *dev = crtc->dev;
10625         struct intel_unpin_work *work;
10626
10627         spin_lock_irq(&dev->event_lock);
10628         work = intel_crtc->unpin_work;
10629         intel_crtc->unpin_work = NULL;
10630         spin_unlock_irq(&dev->event_lock);
10631
10632         if (work) {
10633                 cancel_work_sync(&work->work);
10634                 kfree(work);
10635         }
10636
10637         drm_crtc_cleanup(crtc);
10638
10639         kfree(intel_crtc);
10640 }
10641
10642 static void intel_unpin_work_fn(struct work_struct *__work)
10643 {
10644         struct intel_unpin_work *work =
10645                 container_of(__work, struct intel_unpin_work, work);
10646         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
10647         struct drm_device *dev = crtc->base.dev;
10648         struct drm_plane *primary = crtc->base.primary;
10649
10650         mutex_lock(&dev->struct_mutex);
10651         intel_unpin_fb_obj(work->old_fb, primary->state);
10652         drm_gem_object_unreference(&work->pending_flip_obj->base);
10653
10654         if (work->flip_queued_req)
10655                 i915_gem_request_assign(&work->flip_queued_req, NULL);
10656         mutex_unlock(&dev->struct_mutex);
10657
10658         intel_frontbuffer_flip_complete(dev, to_intel_plane(primary)->frontbuffer_bit);
10659         drm_framebuffer_unreference(work->old_fb);
10660
10661         BUG_ON(atomic_read(&crtc->unpin_work_count) == 0);
10662         atomic_dec(&crtc->unpin_work_count);
10663
10664         kfree(work);
10665 }
10666
10667 static void do_intel_finish_page_flip(struct drm_device *dev,
10668                                       struct drm_crtc *crtc)
10669 {
10670         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10671         struct intel_unpin_work *work;
10672         unsigned long flags;
10673
10674         /* Ignore early vblank irqs */
10675         if (intel_crtc == NULL)
10676                 return;
10677
10678         /*
10679          * This is called both by irq handlers and the reset code (to complete
10680          * lost pageflips) so needs the full irqsave spinlocks.
10681          */
10682         spin_lock_irqsave(&dev->event_lock, flags);
10683         work = intel_crtc->unpin_work;
10684
10685         /* Ensure we don't miss a work->pending update ... */
10686         smp_rmb();
10687
10688         if (work == NULL || atomic_read(&work->pending) < INTEL_FLIP_COMPLETE) {
10689                 spin_unlock_irqrestore(&dev->event_lock, flags);
10690                 return;
10691         }
10692
10693         page_flip_completed(intel_crtc);
10694
10695         spin_unlock_irqrestore(&dev->event_lock, flags);
10696 }
10697
10698 void intel_finish_page_flip(struct drm_device *dev, int pipe)
10699 {
10700         struct drm_i915_private *dev_priv = dev->dev_private;
10701         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
10702
10703         do_intel_finish_page_flip(dev, crtc);
10704 }
10705
10706 void intel_finish_page_flip_plane(struct drm_device *dev, int plane)
10707 {
10708         struct drm_i915_private *dev_priv = dev->dev_private;
10709         struct drm_crtc *crtc = dev_priv->plane_to_crtc_mapping[plane];
10710
10711         do_intel_finish_page_flip(dev, crtc);
10712 }
10713
10714 /* Is 'a' after or equal to 'b'? */
10715 static bool g4x_flip_count_after_eq(u32 a, u32 b)
10716 {
10717         return !((a - b) & 0x80000000);
10718 }
10719
10720 static bool page_flip_finished(struct intel_crtc *crtc)
10721 {
10722         struct drm_device *dev = crtc->base.dev;
10723         struct drm_i915_private *dev_priv = dev->dev_private;
10724
10725         if (i915_reset_in_progress(&dev_priv->gpu_error) ||
10726             crtc->reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
10727                 return true;
10728
10729         /*
10730          * The relevant registers doen't exist on pre-ctg.
10731          * As the flip done interrupt doesn't trigger for mmio
10732          * flips on gmch platforms, a flip count check isn't
10733          * really needed there. But since ctg has the registers,
10734          * include it in the check anyway.
10735          */
10736         if (INTEL_INFO(dev)->gen < 5 && !IS_G4X(dev))
10737                 return true;
10738
10739         /*
10740          * A DSPSURFLIVE check isn't enough in case the mmio and CS flips
10741          * used the same base address. In that case the mmio flip might
10742          * have completed, but the CS hasn't even executed the flip yet.
10743          *
10744          * A flip count check isn't enough as the CS might have updated
10745          * the base address just after start of vblank, but before we
10746          * managed to process the interrupt. This means we'd complete the
10747          * CS flip too soon.
10748          *
10749          * Combining both checks should get us a good enough result. It may
10750          * still happen that the CS flip has been executed, but has not
10751          * yet actually completed. But in case the base address is the same
10752          * anyway, we don't really care.
10753          */
10754         return (I915_READ(DSPSURFLIVE(crtc->plane)) & ~0xfff) ==
10755                 crtc->unpin_work->gtt_offset &&
10756                 g4x_flip_count_after_eq(I915_READ(PIPE_FLIPCOUNT_GM45(crtc->pipe)),
10757                                     crtc->unpin_work->flip_count);
10758 }
10759
10760 void intel_prepare_page_flip(struct drm_device *dev, int plane)
10761 {
10762         struct drm_i915_private *dev_priv = dev->dev_private;
10763         struct intel_crtc *intel_crtc =
10764                 to_intel_crtc(dev_priv->plane_to_crtc_mapping[plane]);
10765         unsigned long flags;
10766
10767
10768         /*
10769          * This is called both by irq handlers and the reset code (to complete
10770          * lost pageflips) so needs the full irqsave spinlocks.
10771          *
10772          * NB: An MMIO update of the plane base pointer will also
10773          * generate a page-flip completion irq, i.e. every modeset
10774          * is also accompanied by a spurious intel_prepare_page_flip().
10775          */
10776         spin_lock_irqsave(&dev->event_lock, flags);
10777         if (intel_crtc->unpin_work && page_flip_finished(intel_crtc))
10778                 atomic_inc_not_zero(&intel_crtc->unpin_work->pending);
10779         spin_unlock_irqrestore(&dev->event_lock, flags);
10780 }
10781
10782 static inline void intel_mark_page_flip_active(struct intel_crtc *intel_crtc)
10783 {
10784         /* Ensure that the work item is consistent when activating it ... */
10785         smp_wmb();
10786         atomic_set(&intel_crtc->unpin_work->pending, INTEL_FLIP_PENDING);
10787         /* and that it is marked active as soon as the irq could fire. */
10788         smp_wmb();
10789 }
10790
10791 static int intel_gen2_queue_flip(struct drm_device *dev,
10792                                  struct drm_crtc *crtc,
10793                                  struct drm_framebuffer *fb,
10794                                  struct drm_i915_gem_object *obj,
10795                                  struct drm_i915_gem_request *req,
10796                                  uint32_t flags)
10797 {
10798         struct intel_engine_cs *ring = req->ring;
10799         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10800         u32 flip_mask;
10801         int ret;
10802
10803         ret = intel_ring_begin(req, 6);
10804         if (ret)
10805                 return ret;
10806
10807         /* Can't queue multiple flips, so wait for the previous
10808          * one to finish before executing the next.
10809          */
10810         if (intel_crtc->plane)
10811                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
10812         else
10813                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
10814         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
10815         intel_ring_emit(ring, MI_NOOP);
10816         intel_ring_emit(ring, MI_DISPLAY_FLIP |
10817                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
10818         intel_ring_emit(ring, fb->pitches[0]);
10819         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
10820         intel_ring_emit(ring, 0); /* aux display base address, unused */
10821
10822         intel_mark_page_flip_active(intel_crtc);
10823         return 0;
10824 }
10825
10826 static int intel_gen3_queue_flip(struct drm_device *dev,
10827                                  struct drm_crtc *crtc,
10828                                  struct drm_framebuffer *fb,
10829                                  struct drm_i915_gem_object *obj,
10830                                  struct drm_i915_gem_request *req,
10831                                  uint32_t flags)
10832 {
10833         struct intel_engine_cs *ring = req->ring;
10834         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10835         u32 flip_mask;
10836         int ret;
10837
10838         ret = intel_ring_begin(req, 6);
10839         if (ret)
10840                 return ret;
10841
10842         if (intel_crtc->plane)
10843                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
10844         else
10845                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
10846         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
10847         intel_ring_emit(ring, MI_NOOP);
10848         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 |
10849                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
10850         intel_ring_emit(ring, fb->pitches[0]);
10851         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
10852         intel_ring_emit(ring, MI_NOOP);
10853
10854         intel_mark_page_flip_active(intel_crtc);
10855         return 0;
10856 }
10857
10858 static int intel_gen4_queue_flip(struct drm_device *dev,
10859                                  struct drm_crtc *crtc,
10860                                  struct drm_framebuffer *fb,
10861                                  struct drm_i915_gem_object *obj,
10862                                  struct drm_i915_gem_request *req,
10863                                  uint32_t flags)
10864 {
10865         struct intel_engine_cs *ring = req->ring;
10866         struct drm_i915_private *dev_priv = dev->dev_private;
10867         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10868         uint32_t pf, pipesrc;
10869         int ret;
10870
10871         ret = intel_ring_begin(req, 4);
10872         if (ret)
10873                 return ret;
10874
10875         /* i965+ uses the linear or tiled offsets from the
10876          * Display Registers (which do not change across a page-flip)
10877          * so we need only reprogram the base address.
10878          */
10879         intel_ring_emit(ring, MI_DISPLAY_FLIP |
10880                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
10881         intel_ring_emit(ring, fb->pitches[0]);
10882         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset |
10883                         obj->tiling_mode);
10884
10885         /* XXX Enabling the panel-fitter across page-flip is so far
10886          * untested on non-native modes, so ignore it for now.
10887          * pf = I915_READ(pipe == 0 ? PFA_CTL_1 : PFB_CTL_1) & PF_ENABLE;
10888          */
10889         pf = 0;
10890         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
10891         intel_ring_emit(ring, pf | pipesrc);
10892
10893         intel_mark_page_flip_active(intel_crtc);
10894         return 0;
10895 }
10896
10897 static int intel_gen6_queue_flip(struct drm_device *dev,
10898                                  struct drm_crtc *crtc,
10899                                  struct drm_framebuffer *fb,
10900                                  struct drm_i915_gem_object *obj,
10901                                  struct drm_i915_gem_request *req,
10902                                  uint32_t flags)
10903 {
10904         struct intel_engine_cs *ring = req->ring;
10905         struct drm_i915_private *dev_priv = dev->dev_private;
10906         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10907         uint32_t pf, pipesrc;
10908         int ret;
10909
10910         ret = intel_ring_begin(req, 4);
10911         if (ret)
10912                 return ret;
10913
10914         intel_ring_emit(ring, MI_DISPLAY_FLIP |
10915                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
10916         intel_ring_emit(ring, fb->pitches[0] | obj->tiling_mode);
10917         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
10918
10919         /* Contrary to the suggestions in the documentation,
10920          * "Enable Panel Fitter" does not seem to be required when page
10921          * flipping with a non-native mode, and worse causes a normal
10922          * modeset to fail.
10923          * pf = I915_READ(PF_CTL(intel_crtc->pipe)) & PF_ENABLE;
10924          */
10925         pf = 0;
10926         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
10927         intel_ring_emit(ring, pf | pipesrc);
10928
10929         intel_mark_page_flip_active(intel_crtc);
10930         return 0;
10931 }
10932
10933 static int intel_gen7_queue_flip(struct drm_device *dev,
10934                                  struct drm_crtc *crtc,
10935                                  struct drm_framebuffer *fb,
10936                                  struct drm_i915_gem_object *obj,
10937                                  struct drm_i915_gem_request *req,
10938                                  uint32_t flags)
10939 {
10940         struct intel_engine_cs *ring = req->ring;
10941         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10942         uint32_t plane_bit = 0;
10943         int len, ret;
10944
10945         switch (intel_crtc->plane) {
10946         case PLANE_A:
10947                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_A;
10948                 break;
10949         case PLANE_B:
10950                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_B;
10951                 break;
10952         case PLANE_C:
10953                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_C;
10954                 break;
10955         default:
10956                 WARN_ONCE(1, "unknown plane in flip command\n");
10957                 return -ENODEV;
10958         }
10959
10960         len = 4;
10961         if (ring->id == RCS) {
10962                 len += 6;
10963                 /*
10964                  * On Gen 8, SRM is now taking an extra dword to accommodate
10965                  * 48bits addresses, and we need a NOOP for the batch size to
10966                  * stay even.
10967                  */
10968                 if (IS_GEN8(dev))
10969                         len += 2;
10970         }
10971
10972         /*
10973          * BSpec MI_DISPLAY_FLIP for IVB:
10974          * "The full packet must be contained within the same cache line."
10975          *
10976          * Currently the LRI+SRM+MI_DISPLAY_FLIP all fit within the same
10977          * cacheline, if we ever start emitting more commands before
10978          * the MI_DISPLAY_FLIP we may need to first emit everything else,
10979          * then do the cacheline alignment, and finally emit the
10980          * MI_DISPLAY_FLIP.
10981          */
10982         ret = intel_ring_cacheline_align(req);
10983         if (ret)
10984                 return ret;
10985
10986         ret = intel_ring_begin(req, len);
10987         if (ret)
10988                 return ret;
10989
10990         /* Unmask the flip-done completion message. Note that the bspec says that
10991          * we should do this for both the BCS and RCS, and that we must not unmask
10992          * more than one flip event at any time (or ensure that one flip message
10993          * can be sent by waiting for flip-done prior to queueing new flips).
10994          * Experimentation says that BCS works despite DERRMR masking all
10995          * flip-done completion events and that unmasking all planes at once
10996          * for the RCS also doesn't appear to drop events. Setting the DERRMR
10997          * to zero does lead to lockups within MI_DISPLAY_FLIP.
10998          */
10999         if (ring->id == RCS) {
11000                 intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
11001                 intel_ring_emit(ring, DERRMR);
11002                 intel_ring_emit(ring, ~(DERRMR_PIPEA_PRI_FLIP_DONE |
11003                                         DERRMR_PIPEB_PRI_FLIP_DONE |
11004                                         DERRMR_PIPEC_PRI_FLIP_DONE));
11005                 if (IS_GEN8(dev))
11006                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM_GEN8 |
11007                                               MI_SRM_LRM_GLOBAL_GTT);
11008                 else
11009                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM |
11010                                               MI_SRM_LRM_GLOBAL_GTT);
11011                 intel_ring_emit(ring, DERRMR);
11012                 intel_ring_emit(ring, ring->scratch.gtt_offset + 256);
11013                 if (IS_GEN8(dev)) {
11014                         intel_ring_emit(ring, 0);
11015                         intel_ring_emit(ring, MI_NOOP);
11016                 }
11017         }
11018
11019         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 | plane_bit);
11020         intel_ring_emit(ring, (fb->pitches[0] | obj->tiling_mode));
11021         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
11022         intel_ring_emit(ring, (MI_NOOP));
11023
11024         intel_mark_page_flip_active(intel_crtc);
11025         return 0;
11026 }
11027
11028 static bool use_mmio_flip(struct intel_engine_cs *ring,
11029                           struct drm_i915_gem_object *obj)
11030 {
11031         /*
11032          * This is not being used for older platforms, because
11033          * non-availability of flip done interrupt forces us to use
11034          * CS flips. Older platforms derive flip done using some clever
11035          * tricks involving the flip_pending status bits and vblank irqs.
11036          * So using MMIO flips there would disrupt this mechanism.
11037          */
11038
11039         if (ring == NULL)
11040                 return true;
11041
11042         if (INTEL_INFO(ring->dev)->gen < 5)
11043                 return false;
11044
11045         if (i915.use_mmio_flip < 0)
11046                 return false;
11047         else if (i915.use_mmio_flip > 0)
11048                 return true;
11049         else if (i915.enable_execlists)
11050                 return true;
11051         else
11052                 return ring != i915_gem_request_get_ring(obj->last_write_req);
11053 }
11054
11055 static void skl_do_mmio_flip(struct intel_crtc *intel_crtc)
11056 {
11057         struct drm_device *dev = intel_crtc->base.dev;
11058         struct drm_i915_private *dev_priv = dev->dev_private;
11059         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
11060         const enum pipe pipe = intel_crtc->pipe;
11061         u32 ctl, stride;
11062
11063         ctl = I915_READ(PLANE_CTL(pipe, 0));
11064         ctl &= ~PLANE_CTL_TILED_MASK;
11065         switch (fb->modifier[0]) {
11066         case DRM_FORMAT_MOD_NONE:
11067                 break;
11068         case I915_FORMAT_MOD_X_TILED:
11069                 ctl |= PLANE_CTL_TILED_X;
11070                 break;
11071         case I915_FORMAT_MOD_Y_TILED:
11072                 ctl |= PLANE_CTL_TILED_Y;
11073                 break;
11074         case I915_FORMAT_MOD_Yf_TILED:
11075                 ctl |= PLANE_CTL_TILED_YF;
11076                 break;
11077         default:
11078                 MISSING_CASE(fb->modifier[0]);
11079         }
11080
11081         /*
11082          * The stride is either expressed as a multiple of 64 bytes chunks for
11083          * linear buffers or in number of tiles for tiled buffers.
11084          */
11085         stride = fb->pitches[0] /
11086                  intel_fb_stride_alignment(dev, fb->modifier[0],
11087                                            fb->pixel_format);
11088
11089         /*
11090          * Both PLANE_CTL and PLANE_STRIDE are not updated on vblank but on
11091          * PLANE_SURF updates, the update is then guaranteed to be atomic.
11092          */
11093         I915_WRITE(PLANE_CTL(pipe, 0), ctl);
11094         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
11095
11096         I915_WRITE(PLANE_SURF(pipe, 0), intel_crtc->unpin_work->gtt_offset);
11097         POSTING_READ(PLANE_SURF(pipe, 0));
11098 }
11099
11100 static void ilk_do_mmio_flip(struct intel_crtc *intel_crtc)
11101 {
11102         struct drm_device *dev = intel_crtc->base.dev;
11103         struct drm_i915_private *dev_priv = dev->dev_private;
11104         struct intel_framebuffer *intel_fb =
11105                 to_intel_framebuffer(intel_crtc->base.primary->fb);
11106         struct drm_i915_gem_object *obj = intel_fb->obj;
11107         u32 dspcntr;
11108         u32 reg;
11109
11110         reg = DSPCNTR(intel_crtc->plane);
11111         dspcntr = I915_READ(reg);
11112
11113         if (obj->tiling_mode != I915_TILING_NONE)
11114                 dspcntr |= DISPPLANE_TILED;
11115         else
11116                 dspcntr &= ~DISPPLANE_TILED;
11117
11118         I915_WRITE(reg, dspcntr);
11119
11120         I915_WRITE(DSPSURF(intel_crtc->plane),
11121                    intel_crtc->unpin_work->gtt_offset);
11122         POSTING_READ(DSPSURF(intel_crtc->plane));
11123
11124 }
11125
11126 /*
11127  * XXX: This is the temporary way to update the plane registers until we get
11128  * around to using the usual plane update functions for MMIO flips
11129  */
11130 static void intel_do_mmio_flip(struct intel_crtc *intel_crtc)
11131 {
11132         struct drm_device *dev = intel_crtc->base.dev;
11133         u32 start_vbl_count;
11134
11135         intel_mark_page_flip_active(intel_crtc);
11136
11137         intel_pipe_update_start(intel_crtc, &start_vbl_count);
11138
11139         if (INTEL_INFO(dev)->gen >= 9)
11140                 skl_do_mmio_flip(intel_crtc);
11141         else
11142                 /* use_mmio_flip() retricts MMIO flips to ilk+ */
11143                 ilk_do_mmio_flip(intel_crtc);
11144
11145         intel_pipe_update_end(intel_crtc, start_vbl_count);
11146 }
11147
11148 static void intel_mmio_flip_work_func(struct work_struct *work)
11149 {
11150         struct intel_mmio_flip *mmio_flip =
11151                 container_of(work, struct intel_mmio_flip, work);
11152
11153         if (mmio_flip->req)
11154                 WARN_ON(__i915_wait_request(mmio_flip->req,
11155                                             mmio_flip->crtc->reset_counter,
11156                                             false, NULL,
11157                                             &mmio_flip->i915->rps.mmioflips));
11158
11159         intel_do_mmio_flip(mmio_flip->crtc);
11160
11161         i915_gem_request_unreference__unlocked(mmio_flip->req);
11162         kfree(mmio_flip);
11163 }
11164
11165 static int intel_queue_mmio_flip(struct drm_device *dev,
11166                                  struct drm_crtc *crtc,
11167                                  struct drm_framebuffer *fb,
11168                                  struct drm_i915_gem_object *obj,
11169                                  struct intel_engine_cs *ring,
11170                                  uint32_t flags)
11171 {
11172         struct intel_mmio_flip *mmio_flip;
11173
11174         mmio_flip = kmalloc(sizeof(*mmio_flip), GFP_KERNEL);
11175         if (mmio_flip == NULL)
11176                 return -ENOMEM;
11177
11178         mmio_flip->i915 = to_i915(dev);
11179         mmio_flip->req = i915_gem_request_reference(obj->last_write_req);
11180         mmio_flip->crtc = to_intel_crtc(crtc);
11181
11182         INIT_WORK(&mmio_flip->work, intel_mmio_flip_work_func);
11183         schedule_work(&mmio_flip->work);
11184
11185         return 0;
11186 }
11187
11188 static int intel_default_queue_flip(struct drm_device *dev,
11189                                     struct drm_crtc *crtc,
11190                                     struct drm_framebuffer *fb,
11191                                     struct drm_i915_gem_object *obj,
11192                                     struct drm_i915_gem_request *req,
11193                                     uint32_t flags)
11194 {
11195         return -ENODEV;
11196 }
11197
11198 static bool __intel_pageflip_stall_check(struct drm_device *dev,
11199                                          struct drm_crtc *crtc)
11200 {
11201         struct drm_i915_private *dev_priv = dev->dev_private;
11202         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11203         struct intel_unpin_work *work = intel_crtc->unpin_work;
11204         u32 addr;
11205
11206         if (atomic_read(&work->pending) >= INTEL_FLIP_COMPLETE)
11207                 return true;
11208
11209         if (atomic_read(&work->pending) < INTEL_FLIP_PENDING)
11210                 return false;
11211
11212         if (!work->enable_stall_check)
11213                 return false;
11214
11215         if (work->flip_ready_vblank == 0) {
11216                 if (work->flip_queued_req &&
11217                     !i915_gem_request_completed(work->flip_queued_req, true))
11218                         return false;
11219
11220                 work->flip_ready_vblank = drm_crtc_vblank_count(crtc);
11221         }
11222
11223         if (drm_crtc_vblank_count(crtc) - work->flip_ready_vblank < 3)
11224                 return false;
11225
11226         /* Potential stall - if we see that the flip has happened,
11227          * assume a missed interrupt. */
11228         if (INTEL_INFO(dev)->gen >= 4)
11229                 addr = I915_HI_DISPBASE(I915_READ(DSPSURF(intel_crtc->plane)));
11230         else
11231                 addr = I915_READ(DSPADDR(intel_crtc->plane));
11232
11233         /* There is a potential issue here with a false positive after a flip
11234          * to the same address. We could address this by checking for a
11235          * non-incrementing frame counter.
11236          */
11237         return addr == work->gtt_offset;
11238 }
11239
11240 void intel_check_page_flip(struct drm_device *dev, int pipe)
11241 {
11242         struct drm_i915_private *dev_priv = dev->dev_private;
11243         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11244         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11245         struct intel_unpin_work *work;
11246
11247         WARN_ON(!in_interrupt());
11248
11249         if (crtc == NULL)
11250                 return;
11251
11252         spin_lock(&dev->event_lock);
11253         work = intel_crtc->unpin_work;
11254         if (work != NULL && __intel_pageflip_stall_check(dev, crtc)) {
11255                 WARN_ONCE(1, "Kicking stuck page flip: queued at %d, now %d\n",
11256                          work->flip_queued_vblank, drm_vblank_count(dev, pipe));
11257                 page_flip_completed(intel_crtc);
11258                 work = NULL;
11259         }
11260         if (work != NULL &&
11261             drm_vblank_count(dev, pipe) - work->flip_queued_vblank > 1)
11262                 intel_queue_rps_boost_for_request(dev, work->flip_queued_req);
11263         spin_unlock(&dev->event_lock);
11264 }
11265
11266 static int intel_crtc_page_flip(struct drm_crtc *crtc,
11267                                 struct drm_framebuffer *fb,
11268                                 struct drm_pending_vblank_event *event,
11269                                 uint32_t page_flip_flags)
11270 {
11271         struct drm_device *dev = crtc->dev;
11272         struct drm_i915_private *dev_priv = dev->dev_private;
11273         struct drm_framebuffer *old_fb = crtc->primary->fb;
11274         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
11275         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11276         struct drm_plane *primary = crtc->primary;
11277         enum pipe pipe = intel_crtc->pipe;
11278         struct intel_unpin_work *work;
11279         struct intel_engine_cs *ring;
11280         bool mmio_flip;
11281         struct drm_i915_gem_request *request = NULL;
11282         int ret;
11283
11284         /*
11285          * drm_mode_page_flip_ioctl() should already catch this, but double
11286          * check to be safe.  In the future we may enable pageflipping from
11287          * a disabled primary plane.
11288          */
11289         if (WARN_ON(intel_fb_obj(old_fb) == NULL))
11290                 return -EBUSY;
11291
11292         /* Can't change pixel format via MI display flips. */
11293         if (fb->pixel_format != crtc->primary->fb->pixel_format)
11294                 return -EINVAL;
11295
11296         /*
11297          * TILEOFF/LINOFF registers can't be changed via MI display flips.
11298          * Note that pitch changes could also affect these register.
11299          */
11300         if (INTEL_INFO(dev)->gen > 3 &&
11301             (fb->offsets[0] != crtc->primary->fb->offsets[0] ||
11302              fb->pitches[0] != crtc->primary->fb->pitches[0]))
11303                 return -EINVAL;
11304
11305         if (i915_terminally_wedged(&dev_priv->gpu_error))
11306                 goto out_hang;
11307
11308         work = kzalloc(sizeof(*work), GFP_KERNEL);
11309         if (work == NULL)
11310                 return -ENOMEM;
11311
11312         work->event = event;
11313         work->crtc = crtc;
11314         work->old_fb = old_fb;
11315         INIT_WORK(&work->work, intel_unpin_work_fn);
11316
11317         ret = drm_crtc_vblank_get(crtc);
11318         if (ret)
11319                 goto free_work;
11320
11321         /* We borrow the event spin lock for protecting unpin_work */
11322         spin_lock_irq(&dev->event_lock);
11323         if (intel_crtc->unpin_work) {
11324                 /* Before declaring the flip queue wedged, check if
11325                  * the hardware completed the operation behind our backs.
11326                  */
11327                 if (__intel_pageflip_stall_check(dev, crtc)) {
11328                         DRM_DEBUG_DRIVER("flip queue: previous flip completed, continuing\n");
11329                         page_flip_completed(intel_crtc);
11330                 } else {
11331                         DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
11332                         spin_unlock_irq(&dev->event_lock);
11333
11334                         drm_crtc_vblank_put(crtc);
11335                         kfree(work);
11336                         return -EBUSY;
11337                 }
11338         }
11339         intel_crtc->unpin_work = work;
11340         spin_unlock_irq(&dev->event_lock);
11341
11342         if (atomic_read(&intel_crtc->unpin_work_count) >= 2)
11343                 flush_workqueue(dev_priv->wq);
11344
11345         /* Reference the objects for the scheduled work. */
11346         drm_framebuffer_reference(work->old_fb);
11347         drm_gem_object_reference(&obj->base);
11348
11349         crtc->primary->fb = fb;
11350         update_state_fb(crtc->primary);
11351
11352         work->pending_flip_obj = obj;
11353
11354         ret = i915_mutex_lock_interruptible(dev);
11355         if (ret)
11356                 goto cleanup;
11357
11358         atomic_inc(&intel_crtc->unpin_work_count);
11359         intel_crtc->reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
11360
11361         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
11362                 work->flip_count = I915_READ(PIPE_FLIPCOUNT_GM45(pipe)) + 1;
11363
11364         if (IS_VALLEYVIEW(dev)) {
11365                 ring = &dev_priv->ring[BCS];
11366                 if (obj->tiling_mode != intel_fb_obj(work->old_fb)->tiling_mode)
11367                         /* vlv: DISPLAY_FLIP fails to change tiling */
11368                         ring = NULL;
11369         } else if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev)) {
11370                 ring = &dev_priv->ring[BCS];
11371         } else if (INTEL_INFO(dev)->gen >= 7) {
11372                 ring = i915_gem_request_get_ring(obj->last_write_req);
11373                 if (ring == NULL || ring->id != RCS)
11374                         ring = &dev_priv->ring[BCS];
11375         } else {
11376                 ring = &dev_priv->ring[RCS];
11377         }
11378
11379         mmio_flip = use_mmio_flip(ring, obj);
11380
11381         /* When using CS flips, we want to emit semaphores between rings.
11382          * However, when using mmio flips we will create a task to do the
11383          * synchronisation, so all we want here is to pin the framebuffer
11384          * into the display plane and skip any waits.
11385          */
11386         ret = intel_pin_and_fence_fb_obj(crtc->primary, fb,
11387                                          crtc->primary->state,
11388                                          mmio_flip ? i915_gem_request_get_ring(obj->last_write_req) : ring, &request);
11389         if (ret)
11390                 goto cleanup_pending;
11391
11392         work->gtt_offset = intel_plane_obj_offset(to_intel_plane(primary), obj)
11393                                                   + intel_crtc->dspaddr_offset;
11394
11395         if (mmio_flip) {
11396                 ret = intel_queue_mmio_flip(dev, crtc, fb, obj, ring,
11397                                             page_flip_flags);
11398                 if (ret)
11399                         goto cleanup_unpin;
11400
11401                 i915_gem_request_assign(&work->flip_queued_req,
11402                                         obj->last_write_req);
11403         } else {
11404                 if (!request) {
11405                         ret = i915_gem_request_alloc(ring, ring->default_context, &request);
11406                         if (ret)
11407                                 goto cleanup_unpin;
11408                 }
11409
11410                 ret = dev_priv->display.queue_flip(dev, crtc, fb, obj, request,
11411                                                    page_flip_flags);
11412                 if (ret)
11413                         goto cleanup_unpin;
11414
11415                 i915_gem_request_assign(&work->flip_queued_req, request);
11416         }
11417
11418         if (request)
11419                 i915_add_request_no_flush(request);
11420
11421         work->flip_queued_vblank = drm_crtc_vblank_count(crtc);
11422         work->enable_stall_check = true;
11423
11424         i915_gem_track_fb(intel_fb_obj(work->old_fb), obj,
11425                           to_intel_plane(primary)->frontbuffer_bit);
11426         mutex_unlock(&dev->struct_mutex);
11427
11428         intel_fbc_disable_crtc(intel_crtc);
11429         intel_frontbuffer_flip_prepare(dev,
11430                                        to_intel_plane(primary)->frontbuffer_bit);
11431
11432         trace_i915_flip_request(intel_crtc->plane, obj);
11433
11434         return 0;
11435
11436 cleanup_unpin:
11437         intel_unpin_fb_obj(fb, crtc->primary->state);
11438 cleanup_pending:
11439         if (request)
11440                 i915_gem_request_cancel(request);
11441         atomic_dec(&intel_crtc->unpin_work_count);
11442         mutex_unlock(&dev->struct_mutex);
11443 cleanup:
11444         crtc->primary->fb = old_fb;
11445         update_state_fb(crtc->primary);
11446
11447         drm_gem_object_unreference_unlocked(&obj->base);
11448         drm_framebuffer_unreference(work->old_fb);
11449
11450         spin_lock_irq(&dev->event_lock);
11451         intel_crtc->unpin_work = NULL;
11452         spin_unlock_irq(&dev->event_lock);
11453
11454         drm_crtc_vblank_put(crtc);
11455 free_work:
11456         kfree(work);
11457
11458         if (ret == -EIO) {
11459                 struct drm_atomic_state *state;
11460                 struct drm_plane_state *plane_state;
11461
11462 out_hang:
11463                 state = drm_atomic_state_alloc(dev);
11464                 if (!state)
11465                         return -ENOMEM;
11466                 state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
11467
11468 retry:
11469                 plane_state = drm_atomic_get_plane_state(state, primary);
11470                 ret = PTR_ERR_OR_ZERO(plane_state);
11471                 if (!ret) {
11472                         drm_atomic_set_fb_for_plane(plane_state, fb);
11473
11474                         ret = drm_atomic_set_crtc_for_plane(plane_state, crtc);
11475                         if (!ret)
11476                                 ret = drm_atomic_commit(state);
11477                 }
11478
11479                 if (ret == -EDEADLK) {
11480                         drm_modeset_backoff(state->acquire_ctx);
11481                         drm_atomic_state_clear(state);
11482                         goto retry;
11483                 }
11484
11485                 if (ret)
11486                         drm_atomic_state_free(state);
11487
11488                 if (ret == 0 && event) {
11489                         spin_lock_irq(&dev->event_lock);
11490                         drm_send_vblank_event(dev, pipe, event);
11491                         spin_unlock_irq(&dev->event_lock);
11492                 }
11493         }
11494         return ret;
11495 }
11496
11497
11498 /**
11499  * intel_wm_need_update - Check whether watermarks need updating
11500  * @plane: drm plane
11501  * @state: new plane state
11502  *
11503  * Check current plane state versus the new one to determine whether
11504  * watermarks need to be recalculated.
11505  *
11506  * Returns true or false.
11507  */
11508 static bool intel_wm_need_update(struct drm_plane *plane,
11509                                  struct drm_plane_state *state)
11510 {
11511         /* Update watermarks on tiling changes. */
11512         if (!plane->state->fb || !state->fb ||
11513             plane->state->fb->modifier[0] != state->fb->modifier[0] ||
11514             plane->state->rotation != state->rotation)
11515                 return true;
11516
11517         if (plane->state->crtc_w != state->crtc_w)
11518                 return true;
11519
11520         return false;
11521 }
11522
11523 int intel_plane_atomic_calc_changes(struct drm_crtc_state *crtc_state,
11524                                     struct drm_plane_state *plane_state)
11525 {
11526         struct drm_crtc *crtc = crtc_state->crtc;
11527         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11528         struct drm_plane *plane = plane_state->plane;
11529         struct drm_device *dev = crtc->dev;
11530         struct drm_i915_private *dev_priv = dev->dev_private;
11531         struct intel_plane_state *old_plane_state =
11532                 to_intel_plane_state(plane->state);
11533         int idx = intel_crtc->base.base.id, ret;
11534         int i = drm_plane_index(plane);
11535         bool mode_changed = needs_modeset(crtc_state);
11536         bool was_crtc_enabled = crtc->state->active;
11537         bool is_crtc_enabled = crtc_state->active;
11538
11539         bool turn_off, turn_on, visible, was_visible;
11540         struct drm_framebuffer *fb = plane_state->fb;
11541
11542         if (crtc_state && INTEL_INFO(dev)->gen >= 9 &&
11543             plane->type != DRM_PLANE_TYPE_CURSOR) {
11544                 ret = skl_update_scaler_plane(
11545                         to_intel_crtc_state(crtc_state),
11546                         to_intel_plane_state(plane_state));
11547                 if (ret)
11548                         return ret;
11549         }
11550
11551         /*
11552          * Disabling a plane is always okay; we just need to update
11553          * fb tracking in a special way since cleanup_fb() won't
11554          * get called by the plane helpers.
11555          */
11556         if (old_plane_state->base.fb && !fb)
11557                 intel_crtc->atomic.disabled_planes |= 1 << i;
11558
11559         was_visible = old_plane_state->visible;
11560         visible = to_intel_plane_state(plane_state)->visible;
11561
11562         if (!was_crtc_enabled && WARN_ON(was_visible))
11563                 was_visible = false;
11564
11565         if (!is_crtc_enabled && WARN_ON(visible))
11566                 visible = false;
11567
11568         if (!was_visible && !visible)
11569                 return 0;
11570
11571         turn_off = was_visible && (!visible || mode_changed);
11572         turn_on = visible && (!was_visible || mode_changed);
11573
11574         DRM_DEBUG_ATOMIC("[CRTC:%i] has [PLANE:%i] with fb %i\n", idx,
11575                          plane->base.id, fb ? fb->base.id : -1);
11576
11577         DRM_DEBUG_ATOMIC("[PLANE:%i] visible %i -> %i, off %i, on %i, ms %i\n",
11578                          plane->base.id, was_visible, visible,
11579                          turn_off, turn_on, mode_changed);
11580
11581         if (turn_on) {
11582                 intel_crtc->atomic.update_wm_pre = true;
11583                 /* must disable cxsr around plane enable/disable */
11584                 if (plane->type != DRM_PLANE_TYPE_CURSOR) {
11585                         intel_crtc->atomic.disable_cxsr = true;
11586                         /* to potentially re-enable cxsr */
11587                         intel_crtc->atomic.wait_vblank = true;
11588                         intel_crtc->atomic.update_wm_post = true;
11589                 }
11590         } else if (turn_off) {
11591                 intel_crtc->atomic.update_wm_post = true;
11592                 /* must disable cxsr around plane enable/disable */
11593                 if (plane->type != DRM_PLANE_TYPE_CURSOR) {
11594                         if (is_crtc_enabled)
11595                                 intel_crtc->atomic.wait_vblank = true;
11596                         intel_crtc->atomic.disable_cxsr = true;
11597                 }
11598         } else if (intel_wm_need_update(plane, plane_state)) {
11599                 intel_crtc->atomic.update_wm_pre = true;
11600         }
11601
11602         if (visible || was_visible)
11603                 intel_crtc->atomic.fb_bits |=
11604                         to_intel_plane(plane)->frontbuffer_bit;
11605
11606         switch (plane->type) {
11607         case DRM_PLANE_TYPE_PRIMARY:
11608                 intel_crtc->atomic.wait_for_flips = true;
11609                 intel_crtc->atomic.pre_disable_primary = turn_off;
11610                 intel_crtc->atomic.post_enable_primary = turn_on;
11611
11612                 if (turn_off) {
11613                         /*
11614                          * FIXME: Actually if we will still have any other
11615                          * plane enabled on the pipe we could let IPS enabled
11616                          * still, but for now lets consider that when we make
11617                          * primary invisible by setting DSPCNTR to 0 on
11618                          * update_primary_plane function IPS needs to be
11619                          * disable.
11620                          */
11621                         intel_crtc->atomic.disable_ips = true;
11622
11623                         intel_crtc->atomic.disable_fbc = true;
11624                 }
11625
11626                 /*
11627                  * FBC does not work on some platforms for rotated
11628                  * planes, so disable it when rotation is not 0 and
11629                  * update it when rotation is set back to 0.
11630                  *
11631                  * FIXME: This is redundant with the fbc update done in
11632                  * the primary plane enable function except that that
11633                  * one is done too late. We eventually need to unify
11634                  * this.
11635                  */
11636
11637                 if (visible &&
11638                     INTEL_INFO(dev)->gen <= 4 && !IS_G4X(dev) &&
11639                     dev_priv->fbc.crtc == intel_crtc &&
11640                     plane_state->rotation != BIT(DRM_ROTATE_0))
11641                         intel_crtc->atomic.disable_fbc = true;
11642
11643                 /*
11644                  * BDW signals flip done immediately if the plane
11645                  * is disabled, even if the plane enable is already
11646                  * armed to occur at the next vblank :(
11647                  */
11648                 if (turn_on && IS_BROADWELL(dev))
11649                         intel_crtc->atomic.wait_vblank = true;
11650
11651                 intel_crtc->atomic.update_fbc |= visible || mode_changed;
11652                 break;
11653         case DRM_PLANE_TYPE_CURSOR:
11654                 break;
11655         case DRM_PLANE_TYPE_OVERLAY:
11656                 if (turn_off && !mode_changed) {
11657                         intel_crtc->atomic.wait_vblank = true;
11658                         intel_crtc->atomic.update_sprite_watermarks |=
11659                                 1 << i;
11660                 }
11661         }
11662         return 0;
11663 }
11664
11665 static bool encoders_cloneable(const struct intel_encoder *a,
11666                                const struct intel_encoder *b)
11667 {
11668         /* masks could be asymmetric, so check both ways */
11669         return a == b || (a->cloneable & (1 << b->type) &&
11670                           b->cloneable & (1 << a->type));
11671 }
11672
11673 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
11674                                          struct intel_crtc *crtc,
11675                                          struct intel_encoder *encoder)
11676 {
11677         struct intel_encoder *source_encoder;
11678         struct drm_connector *connector;
11679         struct drm_connector_state *connector_state;
11680         int i;
11681
11682         for_each_connector_in_state(state, connector, connector_state, i) {
11683                 if (connector_state->crtc != &crtc->base)
11684                         continue;
11685
11686                 source_encoder =
11687                         to_intel_encoder(connector_state->best_encoder);
11688                 if (!encoders_cloneable(encoder, source_encoder))
11689                         return false;
11690         }
11691
11692         return true;
11693 }
11694
11695 static bool check_encoder_cloning(struct drm_atomic_state *state,
11696                                   struct intel_crtc *crtc)
11697 {
11698         struct intel_encoder *encoder;
11699         struct drm_connector *connector;
11700         struct drm_connector_state *connector_state;
11701         int i;
11702
11703         for_each_connector_in_state(state, connector, connector_state, i) {
11704                 if (connector_state->crtc != &crtc->base)
11705                         continue;
11706
11707                 encoder = to_intel_encoder(connector_state->best_encoder);
11708                 if (!check_single_encoder_cloning(state, crtc, encoder))
11709                         return false;
11710         }
11711
11712         return true;
11713 }
11714
11715 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
11716                                    struct drm_crtc_state *crtc_state)
11717 {
11718         struct drm_device *dev = crtc->dev;
11719         struct drm_i915_private *dev_priv = dev->dev_private;
11720         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11721         struct intel_crtc_state *pipe_config =
11722                 to_intel_crtc_state(crtc_state);
11723         struct drm_atomic_state *state = crtc_state->state;
11724         int ret;
11725         bool mode_changed = needs_modeset(crtc_state);
11726
11727         if (mode_changed && !check_encoder_cloning(state, intel_crtc)) {
11728                 DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
11729                 return -EINVAL;
11730         }
11731
11732         if (mode_changed && !crtc_state->active)
11733                 intel_crtc->atomic.update_wm_post = true;
11734
11735         if (mode_changed && crtc_state->enable &&
11736             dev_priv->display.crtc_compute_clock &&
11737             !WARN_ON(pipe_config->shared_dpll != DPLL_ID_PRIVATE)) {
11738                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
11739                                                            pipe_config);
11740                 if (ret)
11741                         return ret;
11742         }
11743
11744         ret = 0;
11745         if (INTEL_INFO(dev)->gen >= 9) {
11746                 if (mode_changed)
11747                         ret = skl_update_scaler_crtc(pipe_config);
11748
11749                 if (!ret)
11750                         ret = intel_atomic_setup_scalers(dev, intel_crtc,
11751                                                          pipe_config);
11752         }
11753
11754         return ret;
11755 }
11756
11757 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
11758         .mode_set_base_atomic = intel_pipe_set_base_atomic,
11759         .load_lut = intel_crtc_load_lut,
11760         .atomic_begin = intel_begin_crtc_commit,
11761         .atomic_flush = intel_finish_crtc_commit,
11762         .atomic_check = intel_crtc_atomic_check,
11763 };
11764
11765 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
11766 {
11767         struct intel_connector *connector;
11768
11769         for_each_intel_connector(dev, connector) {
11770                 if (connector->base.encoder) {
11771                         connector->base.state->best_encoder =
11772                                 connector->base.encoder;
11773                         connector->base.state->crtc =
11774                                 connector->base.encoder->crtc;
11775                 } else {
11776                         connector->base.state->best_encoder = NULL;
11777                         connector->base.state->crtc = NULL;
11778                 }
11779         }
11780 }
11781
11782 static void
11783 connected_sink_compute_bpp(struct intel_connector *connector,
11784                            struct intel_crtc_state *pipe_config)
11785 {
11786         int bpp = pipe_config->pipe_bpp;
11787
11788         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
11789                 connector->base.base.id,
11790                 connector->base.name);
11791
11792         /* Don't use an invalid EDID bpc value */
11793         if (connector->base.display_info.bpc &&
11794             connector->base.display_info.bpc * 3 < bpp) {
11795                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
11796                               bpp, connector->base.display_info.bpc*3);
11797                 pipe_config->pipe_bpp = connector->base.display_info.bpc*3;
11798         }
11799
11800         /* Clamp bpp to 8 on screens without EDID 1.4 */
11801         if (connector->base.display_info.bpc == 0 && bpp > 24) {
11802                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
11803                               bpp);
11804                 pipe_config->pipe_bpp = 24;
11805         }
11806 }
11807
11808 static int
11809 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
11810                           struct intel_crtc_state *pipe_config)
11811 {
11812         struct drm_device *dev = crtc->base.dev;
11813         struct drm_atomic_state *state;
11814         struct drm_connector *connector;
11815         struct drm_connector_state *connector_state;
11816         int bpp, i;
11817
11818         if ((IS_G4X(dev) || IS_VALLEYVIEW(dev)))
11819                 bpp = 10*3;
11820         else if (INTEL_INFO(dev)->gen >= 5)
11821                 bpp = 12*3;
11822         else
11823                 bpp = 8*3;
11824
11825
11826         pipe_config->pipe_bpp = bpp;
11827
11828         state = pipe_config->base.state;
11829
11830         /* Clamp display bpp to EDID value */
11831         for_each_connector_in_state(state, connector, connector_state, i) {
11832                 if (connector_state->crtc != &crtc->base)
11833                         continue;
11834
11835                 connected_sink_compute_bpp(to_intel_connector(connector),
11836                                            pipe_config);
11837         }
11838
11839         return bpp;
11840 }
11841
11842 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
11843 {
11844         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
11845                         "type: 0x%x flags: 0x%x\n",
11846                 mode->crtc_clock,
11847                 mode->crtc_hdisplay, mode->crtc_hsync_start,
11848                 mode->crtc_hsync_end, mode->crtc_htotal,
11849                 mode->crtc_vdisplay, mode->crtc_vsync_start,
11850                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
11851 }
11852
11853 static void intel_dump_pipe_config(struct intel_crtc *crtc,
11854                                    struct intel_crtc_state *pipe_config,
11855                                    const char *context)
11856 {
11857         struct drm_device *dev = crtc->base.dev;
11858         struct drm_plane *plane;
11859         struct intel_plane *intel_plane;
11860         struct intel_plane_state *state;
11861         struct drm_framebuffer *fb;
11862
11863         DRM_DEBUG_KMS("[CRTC:%d]%s config %p for pipe %c\n", crtc->base.base.id,
11864                       context, pipe_config, pipe_name(crtc->pipe));
11865
11866         DRM_DEBUG_KMS("cpu_transcoder: %c\n", transcoder_name(pipe_config->cpu_transcoder));
11867         DRM_DEBUG_KMS("pipe bpp: %i, dithering: %i\n",
11868                       pipe_config->pipe_bpp, pipe_config->dither);
11869         DRM_DEBUG_KMS("fdi/pch: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
11870                       pipe_config->has_pch_encoder,
11871                       pipe_config->fdi_lanes,
11872                       pipe_config->fdi_m_n.gmch_m, pipe_config->fdi_m_n.gmch_n,
11873                       pipe_config->fdi_m_n.link_m, pipe_config->fdi_m_n.link_n,
11874                       pipe_config->fdi_m_n.tu);
11875         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
11876                       pipe_config->has_dp_encoder,
11877                       pipe_config->lane_count,
11878                       pipe_config->dp_m_n.gmch_m, pipe_config->dp_m_n.gmch_n,
11879                       pipe_config->dp_m_n.link_m, pipe_config->dp_m_n.link_n,
11880                       pipe_config->dp_m_n.tu);
11881
11882         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m2: %u, gmch_n2: %u, link_m2: %u, link_n2: %u, tu2: %u\n",
11883                       pipe_config->has_dp_encoder,
11884                       pipe_config->lane_count,
11885                       pipe_config->dp_m2_n2.gmch_m,
11886                       pipe_config->dp_m2_n2.gmch_n,
11887                       pipe_config->dp_m2_n2.link_m,
11888                       pipe_config->dp_m2_n2.link_n,
11889                       pipe_config->dp_m2_n2.tu);
11890
11891         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
11892                       pipe_config->has_audio,
11893                       pipe_config->has_infoframe);
11894
11895         DRM_DEBUG_KMS("requested mode:\n");
11896         drm_mode_debug_printmodeline(&pipe_config->base.mode);
11897         DRM_DEBUG_KMS("adjusted mode:\n");
11898         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
11899         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
11900         DRM_DEBUG_KMS("port clock: %d\n", pipe_config->port_clock);
11901         DRM_DEBUG_KMS("pipe src size: %dx%d\n",
11902                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
11903         DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
11904                       crtc->num_scalers,
11905                       pipe_config->scaler_state.scaler_users,
11906                       pipe_config->scaler_state.scaler_id);
11907         DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
11908                       pipe_config->gmch_pfit.control,
11909                       pipe_config->gmch_pfit.pgm_ratios,
11910                       pipe_config->gmch_pfit.lvds_border_bits);
11911         DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
11912                       pipe_config->pch_pfit.pos,
11913                       pipe_config->pch_pfit.size,
11914                       pipe_config->pch_pfit.enabled ? "enabled" : "disabled");
11915         DRM_DEBUG_KMS("ips: %i\n", pipe_config->ips_enabled);
11916         DRM_DEBUG_KMS("double wide: %i\n", pipe_config->double_wide);
11917
11918         if (IS_BROXTON(dev)) {
11919                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: ebb0: 0x%x, ebb4: 0x%x,"
11920                               "pll0: 0x%x, pll1: 0x%x, pll2: 0x%x, pll3: 0x%x, "
11921                               "pll6: 0x%x, pll8: 0x%x, pll9: 0x%x, pll10: 0x%x, pcsdw12: 0x%x\n",
11922                               pipe_config->ddi_pll_sel,
11923                               pipe_config->dpll_hw_state.ebb0,
11924                               pipe_config->dpll_hw_state.ebb4,
11925                               pipe_config->dpll_hw_state.pll0,
11926                               pipe_config->dpll_hw_state.pll1,
11927                               pipe_config->dpll_hw_state.pll2,
11928                               pipe_config->dpll_hw_state.pll3,
11929                               pipe_config->dpll_hw_state.pll6,
11930                               pipe_config->dpll_hw_state.pll8,
11931                               pipe_config->dpll_hw_state.pll9,
11932                               pipe_config->dpll_hw_state.pll10,
11933                               pipe_config->dpll_hw_state.pcsdw12);
11934         } else if (IS_SKYLAKE(dev)) {
11935                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: "
11936                               "ctrl1: 0x%x, cfgcr1: 0x%x, cfgcr2: 0x%x\n",
11937                               pipe_config->ddi_pll_sel,
11938                               pipe_config->dpll_hw_state.ctrl1,
11939                               pipe_config->dpll_hw_state.cfgcr1,
11940                               pipe_config->dpll_hw_state.cfgcr2);
11941         } else if (HAS_DDI(dev)) {
11942                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: wrpll: 0x%x\n",
11943                               pipe_config->ddi_pll_sel,
11944                               pipe_config->dpll_hw_state.wrpll);
11945         } else {
11946                 DRM_DEBUG_KMS("dpll_hw_state: dpll: 0x%x, dpll_md: 0x%x, "
11947                               "fp0: 0x%x, fp1: 0x%x\n",
11948                               pipe_config->dpll_hw_state.dpll,
11949                               pipe_config->dpll_hw_state.dpll_md,
11950                               pipe_config->dpll_hw_state.fp0,
11951                               pipe_config->dpll_hw_state.fp1);
11952         }
11953
11954         DRM_DEBUG_KMS("planes on this crtc\n");
11955         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
11956                 intel_plane = to_intel_plane(plane);
11957                 if (intel_plane->pipe != crtc->pipe)
11958                         continue;
11959
11960                 state = to_intel_plane_state(plane->state);
11961                 fb = state->base.fb;
11962                 if (!fb) {
11963                         DRM_DEBUG_KMS("%s PLANE:%d plane: %u.%u idx: %d "
11964                                 "disabled, scaler_id = %d\n",
11965                                 plane->type == DRM_PLANE_TYPE_CURSOR ? "CURSOR" : "STANDARD",
11966                                 plane->base.id, intel_plane->pipe,
11967                                 (crtc->base.primary == plane) ? 0 : intel_plane->plane + 1,
11968                                 drm_plane_index(plane), state->scaler_id);
11969                         continue;
11970                 }
11971
11972                 DRM_DEBUG_KMS("%s PLANE:%d plane: %u.%u idx: %d enabled",
11973                         plane->type == DRM_PLANE_TYPE_CURSOR ? "CURSOR" : "STANDARD",
11974                         plane->base.id, intel_plane->pipe,
11975                         crtc->base.primary == plane ? 0 : intel_plane->plane + 1,
11976                         drm_plane_index(plane));
11977                 DRM_DEBUG_KMS("\tFB:%d, fb = %ux%u format = 0x%x",
11978                         fb->base.id, fb->width, fb->height, fb->pixel_format);
11979                 DRM_DEBUG_KMS("\tscaler:%d src (%u, %u) %ux%u dst (%u, %u) %ux%u\n",
11980                         state->scaler_id,
11981                         state->src.x1 >> 16, state->src.y1 >> 16,
11982                         drm_rect_width(&state->src) >> 16,
11983                         drm_rect_height(&state->src) >> 16,
11984                         state->dst.x1, state->dst.y1,
11985                         drm_rect_width(&state->dst), drm_rect_height(&state->dst));
11986         }
11987 }
11988
11989 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
11990 {
11991         struct drm_device *dev = state->dev;
11992         struct intel_encoder *encoder;
11993         struct drm_connector *connector;
11994         struct drm_connector_state *connector_state;
11995         unsigned int used_ports = 0;
11996         int i;
11997
11998         /*
11999          * Walk the connector list instead of the encoder
12000          * list to detect the problem on ddi platforms
12001          * where there's just one encoder per digital port.
12002          */
12003         for_each_connector_in_state(state, connector, connector_state, i) {
12004                 if (!connector_state->best_encoder)
12005                         continue;
12006
12007                 encoder = to_intel_encoder(connector_state->best_encoder);
12008
12009                 WARN_ON(!connector_state->crtc);
12010
12011                 switch (encoder->type) {
12012                         unsigned int port_mask;
12013                 case INTEL_OUTPUT_UNKNOWN:
12014                         if (WARN_ON(!HAS_DDI(dev)))
12015                                 break;
12016                 case INTEL_OUTPUT_DISPLAYPORT:
12017                 case INTEL_OUTPUT_HDMI:
12018                 case INTEL_OUTPUT_EDP:
12019                         port_mask = 1 << enc_to_dig_port(&encoder->base)->port;
12020
12021                         /* the same port mustn't appear more than once */
12022                         if (used_ports & port_mask)
12023                                 return false;
12024
12025                         used_ports |= port_mask;
12026                 default:
12027                         break;
12028                 }
12029         }
12030
12031         return true;
12032 }
12033
12034 static void
12035 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
12036 {
12037         struct drm_crtc_state tmp_state;
12038         struct intel_crtc_scaler_state scaler_state;
12039         struct intel_dpll_hw_state dpll_hw_state;
12040         enum intel_dpll_id shared_dpll;
12041         uint32_t ddi_pll_sel;
12042         bool force_thru;
12043
12044         /* FIXME: before the switch to atomic started, a new pipe_config was
12045          * kzalloc'd. Code that depends on any field being zero should be
12046          * fixed, so that the crtc_state can be safely duplicated. For now,
12047          * only fields that are know to not cause problems are preserved. */
12048
12049         tmp_state = crtc_state->base;
12050         scaler_state = crtc_state->scaler_state;
12051         shared_dpll = crtc_state->shared_dpll;
12052         dpll_hw_state = crtc_state->dpll_hw_state;
12053         ddi_pll_sel = crtc_state->ddi_pll_sel;
12054         force_thru = crtc_state->pch_pfit.force_thru;
12055
12056         memset(crtc_state, 0, sizeof *crtc_state);
12057
12058         crtc_state->base = tmp_state;
12059         crtc_state->scaler_state = scaler_state;
12060         crtc_state->shared_dpll = shared_dpll;
12061         crtc_state->dpll_hw_state = dpll_hw_state;
12062         crtc_state->ddi_pll_sel = ddi_pll_sel;
12063         crtc_state->pch_pfit.force_thru = force_thru;
12064 }
12065
12066 static int
12067 intel_modeset_pipe_config(struct drm_crtc *crtc,
12068                           struct intel_crtc_state *pipe_config)
12069 {
12070         struct drm_atomic_state *state = pipe_config->base.state;
12071         struct intel_encoder *encoder;
12072         struct drm_connector *connector;
12073         struct drm_connector_state *connector_state;
12074         int base_bpp, ret = -EINVAL;
12075         int i;
12076         bool retry = true;
12077
12078         clear_intel_crtc_state(pipe_config);
12079
12080         pipe_config->cpu_transcoder =
12081                 (enum transcoder) to_intel_crtc(crtc)->pipe;
12082
12083         /*
12084          * Sanitize sync polarity flags based on requested ones. If neither
12085          * positive or negative polarity is requested, treat this as meaning
12086          * negative polarity.
12087          */
12088         if (!(pipe_config->base.adjusted_mode.flags &
12089               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
12090                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
12091
12092         if (!(pipe_config->base.adjusted_mode.flags &
12093               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
12094                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
12095
12096         /* Compute a starting value for pipe_config->pipe_bpp taking the source
12097          * plane pixel format and any sink constraints into account. Returns the
12098          * source plane bpp so that dithering can be selected on mismatches
12099          * after encoders and crtc also have had their say. */
12100         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
12101                                              pipe_config);
12102         if (base_bpp < 0)
12103                 goto fail;
12104
12105         /*
12106          * Determine the real pipe dimensions. Note that stereo modes can
12107          * increase the actual pipe size due to the frame doubling and
12108          * insertion of additional space for blanks between the frame. This
12109          * is stored in the crtc timings. We use the requested mode to do this
12110          * computation to clearly distinguish it from the adjusted mode, which
12111          * can be changed by the connectors in the below retry loop.
12112          */
12113         drm_crtc_get_hv_timing(&pipe_config->base.mode,
12114                                &pipe_config->pipe_src_w,
12115                                &pipe_config->pipe_src_h);
12116
12117 encoder_retry:
12118         /* Ensure the port clock defaults are reset when retrying. */
12119         pipe_config->port_clock = 0;
12120         pipe_config->pixel_multiplier = 1;
12121
12122         /* Fill in default crtc timings, allow encoders to overwrite them. */
12123         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
12124                               CRTC_STEREO_DOUBLE);
12125
12126         /* Pass our mode to the connectors and the CRTC to give them a chance to
12127          * adjust it according to limitations or connector properties, and also
12128          * a chance to reject the mode entirely.
12129          */
12130         for_each_connector_in_state(state, connector, connector_state, i) {
12131                 if (connector_state->crtc != crtc)
12132                         continue;
12133
12134                 encoder = to_intel_encoder(connector_state->best_encoder);
12135
12136                 if (!(encoder->compute_config(encoder, pipe_config))) {
12137                         DRM_DEBUG_KMS("Encoder config failure\n");
12138                         goto fail;
12139                 }
12140         }
12141
12142         /* Set default port clock if not overwritten by the encoder. Needs to be
12143          * done afterwards in case the encoder adjusts the mode. */
12144         if (!pipe_config->port_clock)
12145                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
12146                         * pipe_config->pixel_multiplier;
12147
12148         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
12149         if (ret < 0) {
12150                 DRM_DEBUG_KMS("CRTC fixup failed\n");
12151                 goto fail;
12152         }
12153
12154         if (ret == RETRY) {
12155                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
12156                         ret = -EINVAL;
12157                         goto fail;
12158                 }
12159
12160                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
12161                 retry = false;
12162                 goto encoder_retry;
12163         }
12164
12165         /* Dithering seems to not pass-through bits correctly when it should, so
12166          * only enable it on 6bpc panels. */
12167         pipe_config->dither = pipe_config->pipe_bpp == 6*3;
12168         DRM_DEBUG_KMS("plane bpp: %i, pipe bpp: %i, dithering: %i\n",
12169                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
12170
12171 fail:
12172         return ret;
12173 }
12174
12175 static void
12176 intel_modeset_update_crtc_state(struct drm_atomic_state *state)
12177 {
12178         struct drm_crtc *crtc;
12179         struct drm_crtc_state *crtc_state;
12180         int i;
12181
12182         /* Double check state. */
12183         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12184                 to_intel_crtc(crtc)->config = to_intel_crtc_state(crtc->state);
12185
12186                 /* Update hwmode for vblank functions */
12187                 if (crtc->state->active)
12188                         crtc->hwmode = crtc->state->adjusted_mode;
12189                 else
12190                         crtc->hwmode.crtc_clock = 0;
12191         }
12192 }
12193
12194 static bool intel_fuzzy_clock_check(int clock1, int clock2)
12195 {
12196         int diff;
12197
12198         if (clock1 == clock2)
12199                 return true;
12200
12201         if (!clock1 || !clock2)
12202                 return false;
12203
12204         diff = abs(clock1 - clock2);
12205
12206         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
12207                 return true;
12208
12209         return false;
12210 }
12211
12212 #define for_each_intel_crtc_masked(dev, mask, intel_crtc) \
12213         list_for_each_entry((intel_crtc), \
12214                             &(dev)->mode_config.crtc_list, \
12215                             base.head) \
12216                 if (mask & (1 <<(intel_crtc)->pipe))
12217
12218
12219 static bool
12220 intel_compare_m_n(unsigned int m, unsigned int n,
12221                   unsigned int m2, unsigned int n2,
12222                   bool exact)
12223 {
12224         if (m == m2 && n == n2)
12225                 return true;
12226
12227         if (exact || !m || !n || !m2 || !n2)
12228                 return false;
12229
12230         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
12231
12232         if (m > m2) {
12233                 while (m > m2) {
12234                         m2 <<= 1;
12235                         n2 <<= 1;
12236                 }
12237         } else if (m < m2) {
12238                 while (m < m2) {
12239                         m <<= 1;
12240                         n <<= 1;
12241                 }
12242         }
12243
12244         return m == m2 && n == n2;
12245 }
12246
12247 static bool
12248 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
12249                        struct intel_link_m_n *m2_n2,
12250                        bool adjust)
12251 {
12252         if (m_n->tu == m2_n2->tu &&
12253             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
12254                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
12255             intel_compare_m_n(m_n->link_m, m_n->link_n,
12256                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
12257                 if (adjust)
12258                         *m2_n2 = *m_n;
12259
12260                 return true;
12261         }
12262
12263         return false;
12264 }
12265
12266 static bool
12267 intel_pipe_config_compare(struct drm_device *dev,
12268                           struct intel_crtc_state *current_config,
12269                           struct intel_crtc_state *pipe_config,
12270                           bool adjust)
12271 {
12272         bool ret = true;
12273
12274 #define INTEL_ERR_OR_DBG_KMS(fmt, ...) \
12275         do { \
12276                 if (!adjust) \
12277                         DRM_ERROR(fmt, ##__VA_ARGS__); \
12278                 else \
12279                         DRM_DEBUG_KMS(fmt, ##__VA_ARGS__); \
12280         } while (0)
12281
12282 #define PIPE_CONF_CHECK_X(name) \
12283         if (current_config->name != pipe_config->name) { \
12284                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12285                           "(expected 0x%08x, found 0x%08x)\n", \
12286                           current_config->name, \
12287                           pipe_config->name); \
12288                 ret = false; \
12289         }
12290
12291 #define PIPE_CONF_CHECK_I(name) \
12292         if (current_config->name != pipe_config->name) { \
12293                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12294                           "(expected %i, found %i)\n", \
12295                           current_config->name, \
12296                           pipe_config->name); \
12297                 ret = false; \
12298         }
12299
12300 #define PIPE_CONF_CHECK_M_N(name) \
12301         if (!intel_compare_link_m_n(&current_config->name, \
12302                                     &pipe_config->name,\
12303                                     adjust)) { \
12304                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12305                           "(expected tu %i gmch %i/%i link %i/%i, " \
12306                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12307                           current_config->name.tu, \
12308                           current_config->name.gmch_m, \
12309                           current_config->name.gmch_n, \
12310                           current_config->name.link_m, \
12311                           current_config->name.link_n, \
12312                           pipe_config->name.tu, \
12313                           pipe_config->name.gmch_m, \
12314                           pipe_config->name.gmch_n, \
12315                           pipe_config->name.link_m, \
12316                           pipe_config->name.link_n); \
12317                 ret = false; \
12318         }
12319
12320 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) \
12321         if (!intel_compare_link_m_n(&current_config->name, \
12322                                     &pipe_config->name, adjust) && \
12323             !intel_compare_link_m_n(&current_config->alt_name, \
12324                                     &pipe_config->name, adjust)) { \
12325                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12326                           "(expected tu %i gmch %i/%i link %i/%i, " \
12327                           "or tu %i gmch %i/%i link %i/%i, " \
12328                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12329                           current_config->name.tu, \
12330                           current_config->name.gmch_m, \
12331                           current_config->name.gmch_n, \
12332                           current_config->name.link_m, \
12333                           current_config->name.link_n, \
12334                           current_config->alt_name.tu, \
12335                           current_config->alt_name.gmch_m, \
12336                           current_config->alt_name.gmch_n, \
12337                           current_config->alt_name.link_m, \
12338                           current_config->alt_name.link_n, \
12339                           pipe_config->name.tu, \
12340                           pipe_config->name.gmch_m, \
12341                           pipe_config->name.gmch_n, \
12342                           pipe_config->name.link_m, \
12343                           pipe_config->name.link_n); \
12344                 ret = false; \
12345         }
12346
12347 /* This is required for BDW+ where there is only one set of registers for
12348  * switching between high and low RR.
12349  * This macro can be used whenever a comparison has to be made between one
12350  * hw state and multiple sw state variables.
12351  */
12352 #define PIPE_CONF_CHECK_I_ALT(name, alt_name) \
12353         if ((current_config->name != pipe_config->name) && \
12354                 (current_config->alt_name != pipe_config->name)) { \
12355                         INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12356                                   "(expected %i or %i, found %i)\n", \
12357                                   current_config->name, \
12358                                   current_config->alt_name, \
12359                                   pipe_config->name); \
12360                         ret = false; \
12361         }
12362
12363 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
12364         if ((current_config->name ^ pipe_config->name) & (mask)) { \
12365                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name "(" #mask ") " \
12366                           "(expected %i, found %i)\n", \
12367                           current_config->name & (mask), \
12368                           pipe_config->name & (mask)); \
12369                 ret = false; \
12370         }
12371
12372 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
12373         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
12374                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12375                           "(expected %i, found %i)\n", \
12376                           current_config->name, \
12377                           pipe_config->name); \
12378                 ret = false; \
12379         }
12380
12381 #define PIPE_CONF_QUIRK(quirk)  \
12382         ((current_config->quirks | pipe_config->quirks) & (quirk))
12383
12384         PIPE_CONF_CHECK_I(cpu_transcoder);
12385
12386         PIPE_CONF_CHECK_I(has_pch_encoder);
12387         PIPE_CONF_CHECK_I(fdi_lanes);
12388         PIPE_CONF_CHECK_M_N(fdi_m_n);
12389
12390         PIPE_CONF_CHECK_I(has_dp_encoder);
12391         PIPE_CONF_CHECK_I(lane_count);
12392
12393         if (INTEL_INFO(dev)->gen < 8) {
12394                 PIPE_CONF_CHECK_M_N(dp_m_n);
12395
12396                 PIPE_CONF_CHECK_I(has_drrs);
12397                 if (current_config->has_drrs)
12398                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
12399         } else
12400                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
12401
12402         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
12403         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
12404         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
12405         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
12406         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
12407         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
12408
12409         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
12410         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
12411         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
12412         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
12413         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
12414         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
12415
12416         PIPE_CONF_CHECK_I(pixel_multiplier);
12417         PIPE_CONF_CHECK_I(has_hdmi_sink);
12418         if ((INTEL_INFO(dev)->gen < 8 && !IS_HASWELL(dev)) ||
12419             IS_VALLEYVIEW(dev))
12420                 PIPE_CONF_CHECK_I(limited_color_range);
12421         PIPE_CONF_CHECK_I(has_infoframe);
12422
12423         PIPE_CONF_CHECK_I(has_audio);
12424
12425         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12426                               DRM_MODE_FLAG_INTERLACE);
12427
12428         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
12429                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12430                                       DRM_MODE_FLAG_PHSYNC);
12431                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12432                                       DRM_MODE_FLAG_NHSYNC);
12433                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12434                                       DRM_MODE_FLAG_PVSYNC);
12435                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12436                                       DRM_MODE_FLAG_NVSYNC);
12437         }
12438
12439         PIPE_CONF_CHECK_I(pipe_src_w);
12440         PIPE_CONF_CHECK_I(pipe_src_h);
12441
12442         PIPE_CONF_CHECK_I(gmch_pfit.control);
12443         /* pfit ratios are autocomputed by the hw on gen4+ */
12444         if (INTEL_INFO(dev)->gen < 4)
12445                 PIPE_CONF_CHECK_I(gmch_pfit.pgm_ratios);
12446         PIPE_CONF_CHECK_I(gmch_pfit.lvds_border_bits);
12447
12448         PIPE_CONF_CHECK_I(pch_pfit.enabled);
12449         if (current_config->pch_pfit.enabled) {
12450                 PIPE_CONF_CHECK_I(pch_pfit.pos);
12451                 PIPE_CONF_CHECK_I(pch_pfit.size);
12452         }
12453
12454         PIPE_CONF_CHECK_I(scaler_state.scaler_id);
12455
12456         /* BDW+ don't expose a synchronous way to read the state */
12457         if (IS_HASWELL(dev))
12458                 PIPE_CONF_CHECK_I(ips_enabled);
12459
12460         PIPE_CONF_CHECK_I(double_wide);
12461
12462         PIPE_CONF_CHECK_X(ddi_pll_sel);
12463
12464         PIPE_CONF_CHECK_I(shared_dpll);
12465         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
12466         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
12467         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
12468         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
12469         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
12470         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
12471         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
12472         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
12473
12474         if (IS_G4X(dev) || INTEL_INFO(dev)->gen >= 5)
12475                 PIPE_CONF_CHECK_I(pipe_bpp);
12476
12477         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
12478         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
12479
12480 #undef PIPE_CONF_CHECK_X
12481 #undef PIPE_CONF_CHECK_I
12482 #undef PIPE_CONF_CHECK_I_ALT
12483 #undef PIPE_CONF_CHECK_FLAGS
12484 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
12485 #undef PIPE_CONF_QUIRK
12486 #undef INTEL_ERR_OR_DBG_KMS
12487
12488         return ret;
12489 }
12490
12491 static void check_wm_state(struct drm_device *dev)
12492 {
12493         struct drm_i915_private *dev_priv = dev->dev_private;
12494         struct skl_ddb_allocation hw_ddb, *sw_ddb;
12495         struct intel_crtc *intel_crtc;
12496         int plane;
12497
12498         if (INTEL_INFO(dev)->gen < 9)
12499                 return;
12500
12501         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
12502         sw_ddb = &dev_priv->wm.skl_hw.ddb;
12503
12504         for_each_intel_crtc(dev, intel_crtc) {
12505                 struct skl_ddb_entry *hw_entry, *sw_entry;
12506                 const enum pipe pipe = intel_crtc->pipe;
12507
12508                 if (!intel_crtc->active)
12509                         continue;
12510
12511                 /* planes */
12512                 for_each_plane(dev_priv, pipe, plane) {
12513                         hw_entry = &hw_ddb.plane[pipe][plane];
12514                         sw_entry = &sw_ddb->plane[pipe][plane];
12515
12516                         if (skl_ddb_entry_equal(hw_entry, sw_entry))
12517                                 continue;
12518
12519                         DRM_ERROR("mismatch in DDB state pipe %c plane %d "
12520                                   "(expected (%u,%u), found (%u,%u))\n",
12521                                   pipe_name(pipe), plane + 1,
12522                                   sw_entry->start, sw_entry->end,
12523                                   hw_entry->start, hw_entry->end);
12524                 }
12525
12526                 /* cursor */
12527                 hw_entry = &hw_ddb.cursor[pipe];
12528                 sw_entry = &sw_ddb->cursor[pipe];
12529
12530                 if (skl_ddb_entry_equal(hw_entry, sw_entry))
12531                         continue;
12532
12533                 DRM_ERROR("mismatch in DDB state pipe %c cursor "
12534                           "(expected (%u,%u), found (%u,%u))\n",
12535                           pipe_name(pipe),
12536                           sw_entry->start, sw_entry->end,
12537                           hw_entry->start, hw_entry->end);
12538         }
12539 }
12540
12541 static void
12542 check_connector_state(struct drm_device *dev,
12543                       struct drm_atomic_state *old_state)
12544 {
12545         struct drm_connector_state *old_conn_state;
12546         struct drm_connector *connector;
12547         int i;
12548
12549         for_each_connector_in_state(old_state, connector, old_conn_state, i) {
12550                 struct drm_encoder *encoder = connector->encoder;
12551                 struct drm_connector_state *state = connector->state;
12552
12553                 /* This also checks the encoder/connector hw state with the
12554                  * ->get_hw_state callbacks. */
12555                 intel_connector_check_state(to_intel_connector(connector));
12556
12557                 I915_STATE_WARN(state->best_encoder != encoder,
12558                      "connector's atomic encoder doesn't match legacy encoder\n");
12559         }
12560 }
12561
12562 static void
12563 check_encoder_state(struct drm_device *dev)
12564 {
12565         struct intel_encoder *encoder;
12566         struct intel_connector *connector;
12567
12568         for_each_intel_encoder(dev, encoder) {
12569                 bool enabled = false;
12570                 enum pipe pipe;
12571
12572                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
12573                               encoder->base.base.id,
12574                               encoder->base.name);
12575
12576                 for_each_intel_connector(dev, connector) {
12577                         if (connector->base.state->best_encoder != &encoder->base)
12578                                 continue;
12579                         enabled = true;
12580
12581                         I915_STATE_WARN(connector->base.state->crtc !=
12582                                         encoder->base.crtc,
12583                              "connector's crtc doesn't match encoder crtc\n");
12584                 }
12585
12586                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
12587                      "encoder's enabled state mismatch "
12588                      "(expected %i, found %i)\n",
12589                      !!encoder->base.crtc, enabled);
12590
12591                 if (!encoder->base.crtc) {
12592                         bool active;
12593
12594                         active = encoder->get_hw_state(encoder, &pipe);
12595                         I915_STATE_WARN(active,
12596                              "encoder detached but still enabled on pipe %c.\n",
12597                              pipe_name(pipe));
12598                 }
12599         }
12600 }
12601
12602 static void
12603 check_crtc_state(struct drm_device *dev, struct drm_atomic_state *old_state)
12604 {
12605         struct drm_i915_private *dev_priv = dev->dev_private;
12606         struct intel_encoder *encoder;
12607         struct drm_crtc_state *old_crtc_state;
12608         struct drm_crtc *crtc;
12609         int i;
12610
12611         for_each_crtc_in_state(old_state, crtc, old_crtc_state, i) {
12612                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12613                 struct intel_crtc_state *pipe_config, *sw_config;
12614                 bool active;
12615
12616                 if (!needs_modeset(crtc->state))
12617                         continue;
12618
12619                 __drm_atomic_helper_crtc_destroy_state(crtc, old_crtc_state);
12620                 pipe_config = to_intel_crtc_state(old_crtc_state);
12621                 memset(pipe_config, 0, sizeof(*pipe_config));
12622                 pipe_config->base.crtc = crtc;
12623                 pipe_config->base.state = old_state;
12624
12625                 DRM_DEBUG_KMS("[CRTC:%d]\n",
12626                               crtc->base.id);
12627
12628                 active = dev_priv->display.get_pipe_config(intel_crtc,
12629                                                            pipe_config);
12630
12631                 /* hw state is inconsistent with the pipe quirk */
12632                 if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
12633                     (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
12634                         active = crtc->state->active;
12635
12636                 I915_STATE_WARN(crtc->state->active != active,
12637                      "crtc active state doesn't match with hw state "
12638                      "(expected %i, found %i)\n", crtc->state->active, active);
12639
12640                 I915_STATE_WARN(intel_crtc->active != crtc->state->active,
12641                      "transitional active state does not match atomic hw state "
12642                      "(expected %i, found %i)\n", crtc->state->active, intel_crtc->active);
12643
12644                 for_each_encoder_on_crtc(dev, crtc, encoder) {
12645                         enum pipe pipe;
12646
12647                         active = encoder->get_hw_state(encoder, &pipe);
12648                         I915_STATE_WARN(active != crtc->state->active,
12649                                 "[ENCODER:%i] active %i with crtc active %i\n",
12650                                 encoder->base.base.id, active, crtc->state->active);
12651
12652                         I915_STATE_WARN(active && intel_crtc->pipe != pipe,
12653                                         "Encoder connected to wrong pipe %c\n",
12654                                         pipe_name(pipe));
12655
12656                         if (active)
12657                                 encoder->get_config(encoder, pipe_config);
12658                 }
12659
12660                 if (!crtc->state->active)
12661                         continue;
12662
12663                 sw_config = to_intel_crtc_state(crtc->state);
12664                 if (!intel_pipe_config_compare(dev, sw_config,
12665                                                pipe_config, false)) {
12666                         I915_STATE_WARN(1, "pipe state doesn't match!\n");
12667                         intel_dump_pipe_config(intel_crtc, pipe_config,
12668                                                "[hw state]");
12669                         intel_dump_pipe_config(intel_crtc, sw_config,
12670                                                "[sw state]");
12671                 }
12672         }
12673 }
12674
12675 static void
12676 check_shared_dpll_state(struct drm_device *dev)
12677 {
12678         struct drm_i915_private *dev_priv = dev->dev_private;
12679         struct intel_crtc *crtc;
12680         struct intel_dpll_hw_state dpll_hw_state;
12681         int i;
12682
12683         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
12684                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
12685                 int enabled_crtcs = 0, active_crtcs = 0;
12686                 bool active;
12687
12688                 memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
12689
12690                 DRM_DEBUG_KMS("%s\n", pll->name);
12691
12692                 active = pll->get_hw_state(dev_priv, pll, &dpll_hw_state);
12693
12694                 I915_STATE_WARN(pll->active > hweight32(pll->config.crtc_mask),
12695                      "more active pll users than references: %i vs %i\n",
12696                      pll->active, hweight32(pll->config.crtc_mask));
12697                 I915_STATE_WARN(pll->active && !pll->on,
12698                      "pll in active use but not on in sw tracking\n");
12699                 I915_STATE_WARN(pll->on && !pll->active,
12700                      "pll in on but not on in use in sw tracking\n");
12701                 I915_STATE_WARN(pll->on != active,
12702                      "pll on state mismatch (expected %i, found %i)\n",
12703                      pll->on, active);
12704
12705                 for_each_intel_crtc(dev, crtc) {
12706                         if (crtc->base.state->enable && intel_crtc_to_shared_dpll(crtc) == pll)
12707                                 enabled_crtcs++;
12708                         if (crtc->active && intel_crtc_to_shared_dpll(crtc) == pll)
12709                                 active_crtcs++;
12710                 }
12711                 I915_STATE_WARN(pll->active != active_crtcs,
12712                      "pll active crtcs mismatch (expected %i, found %i)\n",
12713                      pll->active, active_crtcs);
12714                 I915_STATE_WARN(hweight32(pll->config.crtc_mask) != enabled_crtcs,
12715                      "pll enabled crtcs mismatch (expected %i, found %i)\n",
12716                      hweight32(pll->config.crtc_mask), enabled_crtcs);
12717
12718                 I915_STATE_WARN(pll->on && memcmp(&pll->config.hw_state, &dpll_hw_state,
12719                                        sizeof(dpll_hw_state)),
12720                      "pll hw state mismatch\n");
12721         }
12722 }
12723
12724 static void
12725 intel_modeset_check_state(struct drm_device *dev,
12726                           struct drm_atomic_state *old_state)
12727 {
12728         check_wm_state(dev);
12729         check_connector_state(dev, old_state);
12730         check_encoder_state(dev);
12731         check_crtc_state(dev, old_state);
12732         check_shared_dpll_state(dev);
12733 }
12734
12735 void ironlake_check_encoder_dotclock(const struct intel_crtc_state *pipe_config,
12736                                      int dotclock)
12737 {
12738         /*
12739          * FDI already provided one idea for the dotclock.
12740          * Yell if the encoder disagrees.
12741          */
12742         WARN(!intel_fuzzy_clock_check(pipe_config->base.adjusted_mode.crtc_clock, dotclock),
12743              "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
12744              pipe_config->base.adjusted_mode.crtc_clock, dotclock);
12745 }
12746
12747 static void update_scanline_offset(struct intel_crtc *crtc)
12748 {
12749         struct drm_device *dev = crtc->base.dev;
12750
12751         /*
12752          * The scanline counter increments at the leading edge of hsync.
12753          *
12754          * On most platforms it starts counting from vtotal-1 on the
12755          * first active line. That means the scanline counter value is
12756          * always one less than what we would expect. Ie. just after
12757          * start of vblank, which also occurs at start of hsync (on the
12758          * last active line), the scanline counter will read vblank_start-1.
12759          *
12760          * On gen2 the scanline counter starts counting from 1 instead
12761          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
12762          * to keep the value positive), instead of adding one.
12763          *
12764          * On HSW+ the behaviour of the scanline counter depends on the output
12765          * type. For DP ports it behaves like most other platforms, but on HDMI
12766          * there's an extra 1 line difference. So we need to add two instead of
12767          * one to the value.
12768          */
12769         if (IS_GEN2(dev)) {
12770                 const struct drm_display_mode *mode = &crtc->config->base.adjusted_mode;
12771                 int vtotal;
12772
12773                 vtotal = mode->crtc_vtotal;
12774                 if (mode->flags & DRM_MODE_FLAG_INTERLACE)
12775                         vtotal /= 2;
12776
12777                 crtc->scanline_offset = vtotal - 1;
12778         } else if (HAS_DDI(dev) &&
12779                    intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI)) {
12780                 crtc->scanline_offset = 2;
12781         } else
12782                 crtc->scanline_offset = 1;
12783 }
12784
12785 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
12786 {
12787         struct drm_device *dev = state->dev;
12788         struct drm_i915_private *dev_priv = to_i915(dev);
12789         struct intel_shared_dpll_config *shared_dpll = NULL;
12790         struct intel_crtc *intel_crtc;
12791         struct intel_crtc_state *intel_crtc_state;
12792         struct drm_crtc *crtc;
12793         struct drm_crtc_state *crtc_state;
12794         int i;
12795
12796         if (!dev_priv->display.crtc_compute_clock)
12797                 return;
12798
12799         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12800                 int dpll;
12801
12802                 intel_crtc = to_intel_crtc(crtc);
12803                 intel_crtc_state = to_intel_crtc_state(crtc_state);
12804                 dpll = intel_crtc_state->shared_dpll;
12805
12806                 if (!needs_modeset(crtc_state) || dpll == DPLL_ID_PRIVATE)
12807                         continue;
12808
12809                 intel_crtc_state->shared_dpll = DPLL_ID_PRIVATE;
12810
12811                 if (!shared_dpll)
12812                         shared_dpll = intel_atomic_get_shared_dpll_state(state);
12813
12814                 shared_dpll[dpll].crtc_mask &= ~(1 << intel_crtc->pipe);
12815         }
12816 }
12817
12818 /*
12819  * This implements the workaround described in the "notes" section of the mode
12820  * set sequence documentation. When going from no pipes or single pipe to
12821  * multiple pipes, and planes are enabled after the pipe, we need to wait at
12822  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
12823  */
12824 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
12825 {
12826         struct drm_crtc_state *crtc_state;
12827         struct intel_crtc *intel_crtc;
12828         struct drm_crtc *crtc;
12829         struct intel_crtc_state *first_crtc_state = NULL;
12830         struct intel_crtc_state *other_crtc_state = NULL;
12831         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
12832         int i;
12833
12834         /* look at all crtc's that are going to be enabled in during modeset */
12835         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12836                 intel_crtc = to_intel_crtc(crtc);
12837
12838                 if (!crtc_state->active || !needs_modeset(crtc_state))
12839                         continue;
12840
12841                 if (first_crtc_state) {
12842                         other_crtc_state = to_intel_crtc_state(crtc_state);
12843                         break;
12844                 } else {
12845                         first_crtc_state = to_intel_crtc_state(crtc_state);
12846                         first_pipe = intel_crtc->pipe;
12847                 }
12848         }
12849
12850         /* No workaround needed? */
12851         if (!first_crtc_state)
12852                 return 0;
12853
12854         /* w/a possibly needed, check how many crtc's are already enabled. */
12855         for_each_intel_crtc(state->dev, intel_crtc) {
12856                 struct intel_crtc_state *pipe_config;
12857
12858                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
12859                 if (IS_ERR(pipe_config))
12860                         return PTR_ERR(pipe_config);
12861
12862                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
12863
12864                 if (!pipe_config->base.active ||
12865                     needs_modeset(&pipe_config->base))
12866                         continue;
12867
12868                 /* 2 or more enabled crtcs means no need for w/a */
12869                 if (enabled_pipe != INVALID_PIPE)
12870                         return 0;
12871
12872                 enabled_pipe = intel_crtc->pipe;
12873         }
12874
12875         if (enabled_pipe != INVALID_PIPE)
12876                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
12877         else if (other_crtc_state)
12878                 other_crtc_state->hsw_workaround_pipe = first_pipe;
12879
12880         return 0;
12881 }
12882
12883 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
12884 {
12885         struct drm_crtc *crtc;
12886         struct drm_crtc_state *crtc_state;
12887         int ret = 0;
12888
12889         /* add all active pipes to the state */
12890         for_each_crtc(state->dev, crtc) {
12891                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
12892                 if (IS_ERR(crtc_state))
12893                         return PTR_ERR(crtc_state);
12894
12895                 if (!crtc_state->active || needs_modeset(crtc_state))
12896                         continue;
12897
12898                 crtc_state->mode_changed = true;
12899
12900                 ret = drm_atomic_add_affected_connectors(state, crtc);
12901                 if (ret)
12902                         break;
12903
12904                 ret = drm_atomic_add_affected_planes(state, crtc);
12905                 if (ret)
12906                         break;
12907         }
12908
12909         return ret;
12910 }
12911
12912
12913 static int intel_modeset_checks(struct drm_atomic_state *state)
12914 {
12915         struct drm_device *dev = state->dev;
12916         struct drm_i915_private *dev_priv = dev->dev_private;
12917         int ret;
12918
12919         if (!check_digital_port_conflicts(state)) {
12920                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
12921                 return -EINVAL;
12922         }
12923
12924         /*
12925          * See if the config requires any additional preparation, e.g.
12926          * to adjust global state with pipes off.  We need to do this
12927          * here so we can get the modeset_pipe updated config for the new
12928          * mode set on this crtc.  For other crtcs we need to use the
12929          * adjusted_mode bits in the crtc directly.
12930          */
12931         if (dev_priv->display.modeset_calc_cdclk) {
12932                 unsigned int cdclk;
12933
12934                 ret = dev_priv->display.modeset_calc_cdclk(state);
12935
12936                 cdclk = to_intel_atomic_state(state)->cdclk;
12937                 if (!ret && cdclk != dev_priv->cdclk_freq)
12938                         ret = intel_modeset_all_pipes(state);
12939
12940                 if (ret < 0)
12941                         return ret;
12942         } else
12943                 to_intel_atomic_state(state)->cdclk = dev_priv->cdclk_freq;
12944
12945         intel_modeset_clear_plls(state);
12946
12947         if (IS_HASWELL(dev))
12948                 return haswell_mode_set_planes_workaround(state);
12949
12950         return 0;
12951 }
12952
12953 /**
12954  * intel_atomic_check - validate state object
12955  * @dev: drm device
12956  * @state: state to validate
12957  */
12958 static int intel_atomic_check(struct drm_device *dev,
12959                               struct drm_atomic_state *state)
12960 {
12961         struct drm_crtc *crtc;
12962         struct drm_crtc_state *crtc_state;
12963         int ret, i;
12964         bool any_ms = false;
12965
12966         ret = drm_atomic_helper_check_modeset(dev, state);
12967         if (ret)
12968                 return ret;
12969
12970         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12971                 struct intel_crtc_state *pipe_config =
12972                         to_intel_crtc_state(crtc_state);
12973
12974                 /* Catch I915_MODE_FLAG_INHERITED */
12975                 if (crtc_state->mode.private_flags != crtc->state->mode.private_flags)
12976                         crtc_state->mode_changed = true;
12977
12978                 if (!crtc_state->enable) {
12979                         if (needs_modeset(crtc_state))
12980                                 any_ms = true;
12981                         continue;
12982                 }
12983
12984                 if (!needs_modeset(crtc_state))
12985                         continue;
12986
12987                 /* FIXME: For only active_changed we shouldn't need to do any
12988                  * state recomputation at all. */
12989
12990                 ret = drm_atomic_add_affected_connectors(state, crtc);
12991                 if (ret)
12992                         return ret;
12993
12994                 ret = intel_modeset_pipe_config(crtc, pipe_config);
12995                 if (ret)
12996                         return ret;
12997
12998                 if (i915.fastboot &&
12999                     intel_pipe_config_compare(state->dev,
13000                                         to_intel_crtc_state(crtc->state),
13001                                         pipe_config, true)) {
13002                         crtc_state->mode_changed = false;
13003                 }
13004
13005                 if (needs_modeset(crtc_state)) {
13006                         any_ms = true;
13007
13008                         ret = drm_atomic_add_affected_planes(state, crtc);
13009                         if (ret)
13010                                 return ret;
13011                 }
13012
13013                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
13014                                        needs_modeset(crtc_state) ?
13015                                        "[modeset]" : "[fastset]");
13016         }
13017
13018         if (any_ms) {
13019                 ret = intel_modeset_checks(state);
13020
13021                 if (ret)
13022                         return ret;
13023         } else
13024                 to_intel_atomic_state(state)->cdclk =
13025                         to_i915(state->dev)->cdclk_freq;
13026
13027         return drm_atomic_helper_check_planes(state->dev, state);
13028 }
13029
13030 /**
13031  * intel_atomic_commit - commit validated state object
13032  * @dev: DRM device
13033  * @state: the top-level driver state object
13034  * @async: asynchronous commit
13035  *
13036  * This function commits a top-level state object that has been validated
13037  * with drm_atomic_helper_check().
13038  *
13039  * FIXME:  Atomic modeset support for i915 is not yet complete.  At the moment
13040  * we can only handle plane-related operations and do not yet support
13041  * asynchronous commit.
13042  *
13043  * RETURNS
13044  * Zero for success or -errno.
13045  */
13046 static int intel_atomic_commit(struct drm_device *dev,
13047                                struct drm_atomic_state *state,
13048                                bool async)
13049 {
13050         struct drm_i915_private *dev_priv = dev->dev_private;
13051         struct drm_crtc *crtc;
13052         struct drm_crtc_state *crtc_state;
13053         int ret = 0;
13054         int i;
13055         bool any_ms = false;
13056
13057         if (async) {
13058                 DRM_DEBUG_KMS("i915 does not yet support async commit\n");
13059                 return -EINVAL;
13060         }
13061
13062         ret = drm_atomic_helper_prepare_planes(dev, state);
13063         if (ret)
13064                 return ret;
13065
13066         drm_atomic_helper_swap_state(dev, state);
13067
13068         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13069                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13070
13071                 if (!needs_modeset(crtc->state))
13072                         continue;
13073
13074                 any_ms = true;
13075                 intel_pre_plane_update(intel_crtc);
13076
13077                 if (crtc_state->active) {
13078                         intel_crtc_disable_planes(crtc, crtc_state->plane_mask);
13079                         dev_priv->display.crtc_disable(crtc);
13080                         intel_crtc->active = false;
13081                         intel_disable_shared_dpll(intel_crtc);
13082                 }
13083         }
13084
13085         /* Only after disabling all output pipelines that will be changed can we
13086          * update the the output configuration. */
13087         intel_modeset_update_crtc_state(state);
13088
13089         if (any_ms) {
13090                 intel_shared_dpll_commit(state);
13091
13092                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
13093                 modeset_update_crtc_power_domains(state);
13094         }
13095
13096         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
13097         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13098                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13099                 bool modeset = needs_modeset(crtc->state);
13100
13101                 if (modeset && crtc->state->active) {
13102                         update_scanline_offset(to_intel_crtc(crtc));
13103                         dev_priv->display.crtc_enable(crtc);
13104                 }
13105
13106                 if (!modeset)
13107                         intel_pre_plane_update(intel_crtc);
13108
13109                 drm_atomic_helper_commit_planes_on_crtc(crtc_state);
13110                 intel_post_plane_update(intel_crtc);
13111         }
13112
13113         /* FIXME: add subpixel order */
13114
13115         drm_atomic_helper_wait_for_vblanks(dev, state);
13116         drm_atomic_helper_cleanup_planes(dev, state);
13117
13118         if (any_ms)
13119                 intel_modeset_check_state(dev, state);
13120
13121         drm_atomic_state_free(state);
13122
13123         return 0;
13124 }
13125
13126 void intel_crtc_restore_mode(struct drm_crtc *crtc)
13127 {
13128         struct drm_device *dev = crtc->dev;
13129         struct drm_atomic_state *state;
13130         struct drm_crtc_state *crtc_state;
13131         int ret;
13132
13133         state = drm_atomic_state_alloc(dev);
13134         if (!state) {
13135                 DRM_DEBUG_KMS("[CRTC:%d] crtc restore failed, out of memory",
13136                               crtc->base.id);
13137                 return;
13138         }
13139
13140         state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
13141
13142 retry:
13143         crtc_state = drm_atomic_get_crtc_state(state, crtc);
13144         ret = PTR_ERR_OR_ZERO(crtc_state);
13145         if (!ret) {
13146                 if (!crtc_state->active)
13147                         goto out;
13148
13149                 crtc_state->mode_changed = true;
13150                 ret = drm_atomic_commit(state);
13151         }
13152
13153         if (ret == -EDEADLK) {
13154                 drm_atomic_state_clear(state);
13155                 drm_modeset_backoff(state->acquire_ctx);
13156                 goto retry;
13157         }
13158
13159         if (ret)
13160 out:
13161                 drm_atomic_state_free(state);
13162 }
13163
13164 #undef for_each_intel_crtc_masked
13165
13166 static const struct drm_crtc_funcs intel_crtc_funcs = {
13167         .gamma_set = intel_crtc_gamma_set,
13168         .set_config = drm_atomic_helper_set_config,
13169         .destroy = intel_crtc_destroy,
13170         .page_flip = intel_crtc_page_flip,
13171         .atomic_duplicate_state = intel_crtc_duplicate_state,
13172         .atomic_destroy_state = intel_crtc_destroy_state,
13173 };
13174
13175 static bool ibx_pch_dpll_get_hw_state(struct drm_i915_private *dev_priv,
13176                                       struct intel_shared_dpll *pll,
13177                                       struct intel_dpll_hw_state *hw_state)
13178 {
13179         uint32_t val;
13180
13181         if (!intel_display_power_is_enabled(dev_priv, POWER_DOMAIN_PLLS))
13182                 return false;
13183
13184         val = I915_READ(PCH_DPLL(pll->id));
13185         hw_state->dpll = val;
13186         hw_state->fp0 = I915_READ(PCH_FP0(pll->id));
13187         hw_state->fp1 = I915_READ(PCH_FP1(pll->id));
13188
13189         return val & DPLL_VCO_ENABLE;
13190 }
13191
13192 static void ibx_pch_dpll_mode_set(struct drm_i915_private *dev_priv,
13193                                   struct intel_shared_dpll *pll)
13194 {
13195         I915_WRITE(PCH_FP0(pll->id), pll->config.hw_state.fp0);
13196         I915_WRITE(PCH_FP1(pll->id), pll->config.hw_state.fp1);
13197 }
13198
13199 static void ibx_pch_dpll_enable(struct drm_i915_private *dev_priv,
13200                                 struct intel_shared_dpll *pll)
13201 {
13202         /* PCH refclock must be enabled first */
13203         ibx_assert_pch_refclk_enabled(dev_priv);
13204
13205         I915_WRITE(PCH_DPLL(pll->id), pll->config.hw_state.dpll);
13206
13207         /* Wait for the clocks to stabilize. */
13208         POSTING_READ(PCH_DPLL(pll->id));
13209         udelay(150);
13210
13211         /* The pixel multiplier can only be updated once the
13212          * DPLL is enabled and the clocks are stable.
13213          *
13214          * So write it again.
13215          */
13216         I915_WRITE(PCH_DPLL(pll->id), pll->config.hw_state.dpll);
13217         POSTING_READ(PCH_DPLL(pll->id));
13218         udelay(200);
13219 }
13220
13221 static void ibx_pch_dpll_disable(struct drm_i915_private *dev_priv,
13222                                  struct intel_shared_dpll *pll)
13223 {
13224         struct drm_device *dev = dev_priv->dev;
13225         struct intel_crtc *crtc;
13226
13227         /* Make sure no transcoder isn't still depending on us. */
13228         for_each_intel_crtc(dev, crtc) {
13229                 if (intel_crtc_to_shared_dpll(crtc) == pll)
13230                         assert_pch_transcoder_disabled(dev_priv, crtc->pipe);
13231         }
13232
13233         I915_WRITE(PCH_DPLL(pll->id), 0);
13234         POSTING_READ(PCH_DPLL(pll->id));
13235         udelay(200);
13236 }
13237
13238 static char *ibx_pch_dpll_names[] = {
13239         "PCH DPLL A",
13240         "PCH DPLL B",
13241 };
13242
13243 static void ibx_pch_dpll_init(struct drm_device *dev)
13244 {
13245         struct drm_i915_private *dev_priv = dev->dev_private;
13246         int i;
13247
13248         dev_priv->num_shared_dpll = 2;
13249
13250         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
13251                 dev_priv->shared_dplls[i].id = i;
13252                 dev_priv->shared_dplls[i].name = ibx_pch_dpll_names[i];
13253                 dev_priv->shared_dplls[i].mode_set = ibx_pch_dpll_mode_set;
13254                 dev_priv->shared_dplls[i].enable = ibx_pch_dpll_enable;
13255                 dev_priv->shared_dplls[i].disable = ibx_pch_dpll_disable;
13256                 dev_priv->shared_dplls[i].get_hw_state =
13257                         ibx_pch_dpll_get_hw_state;
13258         }
13259 }
13260
13261 static void intel_shared_dpll_init(struct drm_device *dev)
13262 {
13263         struct drm_i915_private *dev_priv = dev->dev_private;
13264
13265         intel_update_cdclk(dev);
13266
13267         if (HAS_DDI(dev))
13268                 intel_ddi_pll_init(dev);
13269         else if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
13270                 ibx_pch_dpll_init(dev);
13271         else
13272                 dev_priv->num_shared_dpll = 0;
13273
13274         BUG_ON(dev_priv->num_shared_dpll > I915_NUM_PLLS);
13275 }
13276
13277 /**
13278  * intel_prepare_plane_fb - Prepare fb for usage on plane
13279  * @plane: drm plane to prepare for
13280  * @fb: framebuffer to prepare for presentation
13281  *
13282  * Prepares a framebuffer for usage on a display plane.  Generally this
13283  * involves pinning the underlying object and updating the frontbuffer tracking
13284  * bits.  Some older platforms need special physical address handling for
13285  * cursor planes.
13286  *
13287  * Returns 0 on success, negative error code on failure.
13288  */
13289 int
13290 intel_prepare_plane_fb(struct drm_plane *plane,
13291                        struct drm_framebuffer *fb,
13292                        const struct drm_plane_state *new_state)
13293 {
13294         struct drm_device *dev = plane->dev;
13295         struct intel_plane *intel_plane = to_intel_plane(plane);
13296         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13297         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->fb);
13298         int ret = 0;
13299
13300         if (!obj)
13301                 return 0;
13302
13303         mutex_lock(&dev->struct_mutex);
13304
13305         if (plane->type == DRM_PLANE_TYPE_CURSOR &&
13306             INTEL_INFO(dev)->cursor_needs_physical) {
13307                 int align = IS_I830(dev) ? 16 * 1024 : 256;
13308                 ret = i915_gem_object_attach_phys(obj, align);
13309                 if (ret)
13310                         DRM_DEBUG_KMS("failed to attach phys object\n");
13311         } else {
13312                 ret = intel_pin_and_fence_fb_obj(plane, fb, new_state, NULL, NULL);
13313         }
13314
13315         if (ret == 0)
13316                 i915_gem_track_fb(old_obj, obj, intel_plane->frontbuffer_bit);
13317
13318         mutex_unlock(&dev->struct_mutex);
13319
13320         return ret;
13321 }
13322
13323 /**
13324  * intel_cleanup_plane_fb - Cleans up an fb after plane use
13325  * @plane: drm plane to clean up for
13326  * @fb: old framebuffer that was on plane
13327  *
13328  * Cleans up a framebuffer that has just been removed from a plane.
13329  */
13330 void
13331 intel_cleanup_plane_fb(struct drm_plane *plane,
13332                        struct drm_framebuffer *fb,
13333                        const struct drm_plane_state *old_state)
13334 {
13335         struct drm_device *dev = plane->dev;
13336         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13337
13338         if (WARN_ON(!obj))
13339                 return;
13340
13341         if (plane->type != DRM_PLANE_TYPE_CURSOR ||
13342             !INTEL_INFO(dev)->cursor_needs_physical) {
13343                 mutex_lock(&dev->struct_mutex);
13344                 intel_unpin_fb_obj(fb, old_state);
13345                 mutex_unlock(&dev->struct_mutex);
13346         }
13347 }
13348
13349 int
13350 skl_max_scale(struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state)
13351 {
13352         int max_scale;
13353         struct drm_device *dev;
13354         struct drm_i915_private *dev_priv;
13355         int crtc_clock, cdclk;
13356
13357         if (!intel_crtc || !crtc_state)
13358                 return DRM_PLANE_HELPER_NO_SCALING;
13359
13360         dev = intel_crtc->base.dev;
13361         dev_priv = dev->dev_private;
13362         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
13363         cdclk = to_intel_atomic_state(crtc_state->base.state)->cdclk;
13364
13365         if (!crtc_clock || !cdclk)
13366                 return DRM_PLANE_HELPER_NO_SCALING;
13367
13368         /*
13369          * skl max scale is lower of:
13370          *    close to 3 but not 3, -1 is for that purpose
13371          *            or
13372          *    cdclk/crtc_clock
13373          */
13374         max_scale = min((1 << 16) * 3 - 1, (1 << 8) * ((cdclk << 8) / crtc_clock));
13375
13376         return max_scale;
13377 }
13378
13379 static int
13380 intel_check_primary_plane(struct drm_plane *plane,
13381                           struct intel_crtc_state *crtc_state,
13382                           struct intel_plane_state *state)
13383 {
13384         struct drm_crtc *crtc = state->base.crtc;
13385         struct drm_framebuffer *fb = state->base.fb;
13386         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
13387         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
13388         bool can_position = false;
13389
13390         /* use scaler when colorkey is not required */
13391         if (INTEL_INFO(plane->dev)->gen >= 9 &&
13392             state->ckey.flags == I915_SET_COLORKEY_NONE) {
13393                 min_scale = 1;
13394                 max_scale = skl_max_scale(to_intel_crtc(crtc), crtc_state);
13395                 can_position = true;
13396         }
13397
13398         return drm_plane_helper_check_update(plane, crtc, fb, &state->src,
13399                                              &state->dst, &state->clip,
13400                                              min_scale, max_scale,
13401                                              can_position, true,
13402                                              &state->visible);
13403 }
13404
13405 static void
13406 intel_commit_primary_plane(struct drm_plane *plane,
13407                            struct intel_plane_state *state)
13408 {
13409         struct drm_crtc *crtc = state->base.crtc;
13410         struct drm_framebuffer *fb = state->base.fb;
13411         struct drm_device *dev = plane->dev;
13412         struct drm_i915_private *dev_priv = dev->dev_private;
13413         struct intel_crtc *intel_crtc;
13414         struct drm_rect *src = &state->src;
13415
13416         crtc = crtc ? crtc : plane->crtc;
13417         intel_crtc = to_intel_crtc(crtc);
13418
13419         plane->fb = fb;
13420         crtc->x = src->x1 >> 16;
13421         crtc->y = src->y1 >> 16;
13422
13423         if (!crtc->state->active)
13424                 return;
13425
13426         if (state->visible)
13427                 /* FIXME: kill this fastboot hack */
13428                 intel_update_pipe_size(intel_crtc);
13429
13430         dev_priv->display.update_primary_plane(crtc, fb, crtc->x, crtc->y);
13431 }
13432
13433 static void
13434 intel_disable_primary_plane(struct drm_plane *plane,
13435                             struct drm_crtc *crtc)
13436 {
13437         struct drm_device *dev = plane->dev;
13438         struct drm_i915_private *dev_priv = dev->dev_private;
13439
13440         dev_priv->display.update_primary_plane(crtc, NULL, 0, 0);
13441 }
13442
13443 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
13444                                     struct drm_crtc_state *old_crtc_state)
13445 {
13446         struct drm_device *dev = crtc->dev;
13447         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13448
13449         if (intel_crtc->atomic.update_wm_pre)
13450                 intel_update_watermarks(crtc);
13451
13452         /* Perform vblank evasion around commit operation */
13453         if (crtc->state->active)
13454                 intel_pipe_update_start(intel_crtc, &intel_crtc->start_vbl_count);
13455
13456         if (!needs_modeset(crtc->state) && INTEL_INFO(dev)->gen >= 9)
13457                 skl_detach_scalers(intel_crtc);
13458 }
13459
13460 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
13461                                      struct drm_crtc_state *old_crtc_state)
13462 {
13463         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13464
13465         if (crtc->state->active)
13466                 intel_pipe_update_end(intel_crtc, intel_crtc->start_vbl_count);
13467 }
13468
13469 /**
13470  * intel_plane_destroy - destroy a plane
13471  * @plane: plane to destroy
13472  *
13473  * Common destruction function for all types of planes (primary, cursor,
13474  * sprite).
13475  */
13476 void intel_plane_destroy(struct drm_plane *plane)
13477 {
13478         struct intel_plane *intel_plane = to_intel_plane(plane);
13479         drm_plane_cleanup(plane);
13480         kfree(intel_plane);
13481 }
13482
13483 const struct drm_plane_funcs intel_plane_funcs = {
13484         .update_plane = drm_atomic_helper_update_plane,
13485         .disable_plane = drm_atomic_helper_disable_plane,
13486         .destroy = intel_plane_destroy,
13487         .set_property = drm_atomic_helper_plane_set_property,
13488         .atomic_get_property = intel_plane_atomic_get_property,
13489         .atomic_set_property = intel_plane_atomic_set_property,
13490         .atomic_duplicate_state = intel_plane_duplicate_state,
13491         .atomic_destroy_state = intel_plane_destroy_state,
13492
13493 };
13494
13495 static struct drm_plane *intel_primary_plane_create(struct drm_device *dev,
13496                                                     int pipe)
13497 {
13498         struct intel_plane *primary;
13499         struct intel_plane_state *state;
13500         const uint32_t *intel_primary_formats;
13501         int num_formats;
13502
13503         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
13504         if (primary == NULL)
13505                 return NULL;
13506
13507         state = intel_create_plane_state(&primary->base);
13508         if (!state) {
13509                 kfree(primary);
13510                 return NULL;
13511         }
13512         primary->base.state = &state->base;
13513
13514         primary->can_scale = false;
13515         primary->max_downscale = 1;
13516         if (INTEL_INFO(dev)->gen >= 9) {
13517                 primary->can_scale = true;
13518                 state->scaler_id = -1;
13519         }
13520         primary->pipe = pipe;
13521         primary->plane = pipe;
13522         primary->frontbuffer_bit = INTEL_FRONTBUFFER_PRIMARY(pipe);
13523         primary->check_plane = intel_check_primary_plane;
13524         primary->commit_plane = intel_commit_primary_plane;
13525         primary->disable_plane = intel_disable_primary_plane;
13526         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4)
13527                 primary->plane = !pipe;
13528
13529         if (INTEL_INFO(dev)->gen >= 9) {
13530                 intel_primary_formats = skl_primary_formats;
13531                 num_formats = ARRAY_SIZE(skl_primary_formats);
13532         } else if (INTEL_INFO(dev)->gen >= 4) {
13533                 intel_primary_formats = i965_primary_formats;
13534                 num_formats = ARRAY_SIZE(i965_primary_formats);
13535         } else {
13536                 intel_primary_formats = i8xx_primary_formats;
13537                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
13538         }
13539
13540         drm_universal_plane_init(dev, &primary->base, 0,
13541                                  &intel_plane_funcs,
13542                                  intel_primary_formats, num_formats,
13543                                  DRM_PLANE_TYPE_PRIMARY);
13544
13545         if (INTEL_INFO(dev)->gen >= 4)
13546                 intel_create_rotation_property(dev, primary);
13547
13548         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
13549
13550         return &primary->base;
13551 }
13552
13553 void intel_create_rotation_property(struct drm_device *dev, struct intel_plane *plane)
13554 {
13555         if (!dev->mode_config.rotation_property) {
13556                 unsigned long flags = BIT(DRM_ROTATE_0) |
13557                         BIT(DRM_ROTATE_180);
13558
13559                 if (INTEL_INFO(dev)->gen >= 9)
13560                         flags |= BIT(DRM_ROTATE_90) | BIT(DRM_ROTATE_270);
13561
13562                 dev->mode_config.rotation_property =
13563                         drm_mode_create_rotation_property(dev, flags);
13564         }
13565         if (dev->mode_config.rotation_property)
13566                 drm_object_attach_property(&plane->base.base,
13567                                 dev->mode_config.rotation_property,
13568                                 plane->base.state->rotation);
13569 }
13570
13571 static int
13572 intel_check_cursor_plane(struct drm_plane *plane,
13573                          struct intel_crtc_state *crtc_state,
13574                          struct intel_plane_state *state)
13575 {
13576         struct drm_crtc *crtc = crtc_state->base.crtc;
13577         struct drm_framebuffer *fb = state->base.fb;
13578         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13579         unsigned stride;
13580         int ret;
13581
13582         ret = drm_plane_helper_check_update(plane, crtc, fb, &state->src,
13583                                             &state->dst, &state->clip,
13584                                             DRM_PLANE_HELPER_NO_SCALING,
13585                                             DRM_PLANE_HELPER_NO_SCALING,
13586                                             true, true, &state->visible);
13587         if (ret)
13588                 return ret;
13589
13590         /* if we want to turn off the cursor ignore width and height */
13591         if (!obj)
13592                 return 0;
13593
13594         /* Check for which cursor types we support */
13595         if (!cursor_size_ok(plane->dev, state->base.crtc_w, state->base.crtc_h)) {
13596                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
13597                           state->base.crtc_w, state->base.crtc_h);
13598                 return -EINVAL;
13599         }
13600
13601         stride = roundup_pow_of_two(state->base.crtc_w) * 4;
13602         if (obj->base.size < stride * state->base.crtc_h) {
13603                 DRM_DEBUG_KMS("buffer is too small\n");
13604                 return -ENOMEM;
13605         }
13606
13607         if (fb->modifier[0] != DRM_FORMAT_MOD_NONE) {
13608                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
13609                 return -EINVAL;
13610         }
13611
13612         return 0;
13613 }
13614
13615 static void
13616 intel_disable_cursor_plane(struct drm_plane *plane,
13617                            struct drm_crtc *crtc)
13618 {
13619         intel_crtc_update_cursor(crtc, false);
13620 }
13621
13622 static void
13623 intel_commit_cursor_plane(struct drm_plane *plane,
13624                           struct intel_plane_state *state)
13625 {
13626         struct drm_crtc *crtc = state->base.crtc;
13627         struct drm_device *dev = plane->dev;
13628         struct intel_crtc *intel_crtc;
13629         struct drm_i915_gem_object *obj = intel_fb_obj(state->base.fb);
13630         uint32_t addr;
13631
13632         crtc = crtc ? crtc : plane->crtc;
13633         intel_crtc = to_intel_crtc(crtc);
13634
13635         plane->fb = state->base.fb;
13636         crtc->cursor_x = state->base.crtc_x;
13637         crtc->cursor_y = state->base.crtc_y;
13638
13639         if (intel_crtc->cursor_bo == obj)
13640                 goto update;
13641
13642         if (!obj)
13643                 addr = 0;
13644         else if (!INTEL_INFO(dev)->cursor_needs_physical)
13645                 addr = i915_gem_obj_ggtt_offset(obj);
13646         else
13647                 addr = obj->phys_handle->busaddr;
13648
13649         intel_crtc->cursor_addr = addr;
13650         intel_crtc->cursor_bo = obj;
13651
13652 update:
13653         if (crtc->state->active)
13654                 intel_crtc_update_cursor(crtc, state->visible);
13655 }
13656
13657 static struct drm_plane *intel_cursor_plane_create(struct drm_device *dev,
13658                                                    int pipe)
13659 {
13660         struct intel_plane *cursor;
13661         struct intel_plane_state *state;
13662
13663         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
13664         if (cursor == NULL)
13665                 return NULL;
13666
13667         state = intel_create_plane_state(&cursor->base);
13668         if (!state) {
13669                 kfree(cursor);
13670                 return NULL;
13671         }
13672         cursor->base.state = &state->base;
13673
13674         cursor->can_scale = false;
13675         cursor->max_downscale = 1;
13676         cursor->pipe = pipe;
13677         cursor->plane = pipe;
13678         cursor->frontbuffer_bit = INTEL_FRONTBUFFER_CURSOR(pipe);
13679         cursor->check_plane = intel_check_cursor_plane;
13680         cursor->commit_plane = intel_commit_cursor_plane;
13681         cursor->disable_plane = intel_disable_cursor_plane;
13682
13683         drm_universal_plane_init(dev, &cursor->base, 0,
13684                                  &intel_plane_funcs,
13685                                  intel_cursor_formats,
13686                                  ARRAY_SIZE(intel_cursor_formats),
13687                                  DRM_PLANE_TYPE_CURSOR);
13688
13689         if (INTEL_INFO(dev)->gen >= 4) {
13690                 if (!dev->mode_config.rotation_property)
13691                         dev->mode_config.rotation_property =
13692                                 drm_mode_create_rotation_property(dev,
13693                                                         BIT(DRM_ROTATE_0) |
13694                                                         BIT(DRM_ROTATE_180));
13695                 if (dev->mode_config.rotation_property)
13696                         drm_object_attach_property(&cursor->base.base,
13697                                 dev->mode_config.rotation_property,
13698                                 state->base.rotation);
13699         }
13700
13701         if (INTEL_INFO(dev)->gen >=9)
13702                 state->scaler_id = -1;
13703
13704         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
13705
13706         return &cursor->base;
13707 }
13708
13709 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
13710         struct intel_crtc_state *crtc_state)
13711 {
13712         int i;
13713         struct intel_scaler *intel_scaler;
13714         struct intel_crtc_scaler_state *scaler_state = &crtc_state->scaler_state;
13715
13716         for (i = 0; i < intel_crtc->num_scalers; i++) {
13717                 intel_scaler = &scaler_state->scalers[i];
13718                 intel_scaler->in_use = 0;
13719                 intel_scaler->mode = PS_SCALER_MODE_DYN;
13720         }
13721
13722         scaler_state->scaler_id = -1;
13723 }
13724
13725 static void intel_crtc_init(struct drm_device *dev, int pipe)
13726 {
13727         struct drm_i915_private *dev_priv = dev->dev_private;
13728         struct intel_crtc *intel_crtc;
13729         struct intel_crtc_state *crtc_state = NULL;
13730         struct drm_plane *primary = NULL;
13731         struct drm_plane *cursor = NULL;
13732         int i, ret;
13733
13734         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
13735         if (intel_crtc == NULL)
13736                 return;
13737
13738         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
13739         if (!crtc_state)
13740                 goto fail;
13741         intel_crtc->config = crtc_state;
13742         intel_crtc->base.state = &crtc_state->base;
13743         crtc_state->base.crtc = &intel_crtc->base;
13744
13745         /* initialize shared scalers */
13746         if (INTEL_INFO(dev)->gen >= 9) {
13747                 if (pipe == PIPE_C)
13748                         intel_crtc->num_scalers = 1;
13749                 else
13750                         intel_crtc->num_scalers = SKL_NUM_SCALERS;
13751
13752                 skl_init_scalers(dev, intel_crtc, crtc_state);
13753         }
13754
13755         primary = intel_primary_plane_create(dev, pipe);
13756         if (!primary)
13757                 goto fail;
13758
13759         cursor = intel_cursor_plane_create(dev, pipe);
13760         if (!cursor)
13761                 goto fail;
13762
13763         ret = drm_crtc_init_with_planes(dev, &intel_crtc->base, primary,
13764                                         cursor, &intel_crtc_funcs);
13765         if (ret)
13766                 goto fail;
13767
13768         drm_mode_crtc_set_gamma_size(&intel_crtc->base, 256);
13769         for (i = 0; i < 256; i++) {
13770                 intel_crtc->lut_r[i] = i;
13771                 intel_crtc->lut_g[i] = i;
13772                 intel_crtc->lut_b[i] = i;
13773         }
13774
13775         /*
13776          * On gen2/3 only plane A can do fbc, but the panel fitter and lvds port
13777          * is hooked to pipe B. Hence we want plane A feeding pipe B.
13778          */
13779         intel_crtc->pipe = pipe;
13780         intel_crtc->plane = pipe;
13781         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4) {
13782                 DRM_DEBUG_KMS("swapping pipes & planes for FBC\n");
13783                 intel_crtc->plane = !pipe;
13784         }
13785
13786         intel_crtc->cursor_base = ~0;
13787         intel_crtc->cursor_cntl = ~0;
13788         intel_crtc->cursor_size = ~0;
13789
13790         intel_crtc->wm.cxsr_allowed = true;
13791
13792         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
13793                dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
13794         dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = &intel_crtc->base;
13795         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = &intel_crtc->base;
13796
13797         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
13798
13799         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
13800         return;
13801
13802 fail:
13803         if (primary)
13804                 drm_plane_cleanup(primary);
13805         if (cursor)
13806                 drm_plane_cleanup(cursor);
13807         kfree(crtc_state);
13808         kfree(intel_crtc);
13809 }
13810
13811 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
13812 {
13813         struct drm_encoder *encoder = connector->base.encoder;
13814         struct drm_device *dev = connector->base.dev;
13815
13816         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
13817
13818         if (!encoder || WARN_ON(!encoder->crtc))
13819                 return INVALID_PIPE;
13820
13821         return to_intel_crtc(encoder->crtc)->pipe;
13822 }
13823
13824 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
13825                                 struct drm_file *file)
13826 {
13827         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
13828         struct drm_crtc *drmmode_crtc;
13829         struct intel_crtc *crtc;
13830
13831         drmmode_crtc = drm_crtc_find(dev, pipe_from_crtc_id->crtc_id);
13832
13833         if (!drmmode_crtc) {
13834                 DRM_ERROR("no such CRTC id\n");
13835                 return -ENOENT;
13836         }
13837
13838         crtc = to_intel_crtc(drmmode_crtc);
13839         pipe_from_crtc_id->pipe = crtc->pipe;
13840
13841         return 0;
13842 }
13843
13844 static int intel_encoder_clones(struct intel_encoder *encoder)
13845 {
13846         struct drm_device *dev = encoder->base.dev;
13847         struct intel_encoder *source_encoder;
13848         int index_mask = 0;
13849         int entry = 0;
13850
13851         for_each_intel_encoder(dev, source_encoder) {
13852                 if (encoders_cloneable(encoder, source_encoder))
13853                         index_mask |= (1 << entry);
13854
13855                 entry++;
13856         }
13857
13858         return index_mask;
13859 }
13860
13861 static bool has_edp_a(struct drm_device *dev)
13862 {
13863         struct drm_i915_private *dev_priv = dev->dev_private;
13864
13865         if (!IS_MOBILE(dev))
13866                 return false;
13867
13868         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
13869                 return false;
13870
13871         if (IS_GEN5(dev) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
13872                 return false;
13873
13874         return true;
13875 }
13876
13877 static bool intel_crt_present(struct drm_device *dev)
13878 {
13879         struct drm_i915_private *dev_priv = dev->dev_private;
13880
13881         if (INTEL_INFO(dev)->gen >= 9)
13882                 return false;
13883
13884         if (IS_HSW_ULT(dev) || IS_BDW_ULT(dev))
13885                 return false;
13886
13887         if (IS_CHERRYVIEW(dev))
13888                 return false;
13889
13890         if (IS_VALLEYVIEW(dev) && !dev_priv->vbt.int_crt_support)
13891                 return false;
13892
13893         return true;
13894 }
13895
13896 static void intel_setup_outputs(struct drm_device *dev)
13897 {
13898         struct drm_i915_private *dev_priv = dev->dev_private;
13899         struct intel_encoder *encoder;
13900         bool dpd_is_edp = false;
13901
13902         intel_lvds_init(dev);
13903
13904         if (intel_crt_present(dev))
13905                 intel_crt_init(dev);
13906
13907         if (IS_BROXTON(dev)) {
13908                 /*
13909                  * FIXME: Broxton doesn't support port detection via the
13910                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
13911                  * detect the ports.
13912                  */
13913                 intel_ddi_init(dev, PORT_A);
13914                 intel_ddi_init(dev, PORT_B);
13915                 intel_ddi_init(dev, PORT_C);
13916         } else if (HAS_DDI(dev)) {
13917                 int found;
13918
13919                 /*
13920                  * Haswell uses DDI functions to detect digital outputs.
13921                  * On SKL pre-D0 the strap isn't connected, so we assume
13922                  * it's there.
13923                  */
13924                 found = I915_READ(DDI_BUF_CTL_A) & DDI_INIT_DISPLAY_DETECTED;
13925                 /* WaIgnoreDDIAStrap: skl */
13926                 if (found || IS_SKYLAKE(dev))
13927                         intel_ddi_init(dev, PORT_A);
13928
13929                 /* DDI B, C and D detection is indicated by the SFUSE_STRAP
13930                  * register */
13931                 found = I915_READ(SFUSE_STRAP);
13932
13933                 if (found & SFUSE_STRAP_DDIB_DETECTED)
13934                         intel_ddi_init(dev, PORT_B);
13935                 if (found & SFUSE_STRAP_DDIC_DETECTED)
13936                         intel_ddi_init(dev, PORT_C);
13937                 if (found & SFUSE_STRAP_DDID_DETECTED)
13938                         intel_ddi_init(dev, PORT_D);
13939         } else if (HAS_PCH_SPLIT(dev)) {
13940                 int found;
13941                 dpd_is_edp = intel_dp_is_edp(dev, PORT_D);
13942
13943                 if (has_edp_a(dev))
13944                         intel_dp_init(dev, DP_A, PORT_A);
13945
13946                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
13947                         /* PCH SDVOB multiplex with HDMIB */
13948                         found = intel_sdvo_init(dev, PCH_SDVOB, true);
13949                         if (!found)
13950                                 intel_hdmi_init(dev, PCH_HDMIB, PORT_B);
13951                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
13952                                 intel_dp_init(dev, PCH_DP_B, PORT_B);
13953                 }
13954
13955                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
13956                         intel_hdmi_init(dev, PCH_HDMIC, PORT_C);
13957
13958                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
13959                         intel_hdmi_init(dev, PCH_HDMID, PORT_D);
13960
13961                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
13962                         intel_dp_init(dev, PCH_DP_C, PORT_C);
13963
13964                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
13965                         intel_dp_init(dev, PCH_DP_D, PORT_D);
13966         } else if (IS_VALLEYVIEW(dev)) {
13967                 /*
13968                  * The DP_DETECTED bit is the latched state of the DDC
13969                  * SDA pin at boot. However since eDP doesn't require DDC
13970                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
13971                  * eDP ports may have been muxed to an alternate function.
13972                  * Thus we can't rely on the DP_DETECTED bit alone to detect
13973                  * eDP ports. Consult the VBT as well as DP_DETECTED to
13974                  * detect eDP ports.
13975                  */
13976                 if (I915_READ(VLV_DISPLAY_BASE + GEN4_HDMIB) & SDVO_DETECTED &&
13977                     !intel_dp_is_edp(dev, PORT_B))
13978                         intel_hdmi_init(dev, VLV_DISPLAY_BASE + GEN4_HDMIB,
13979                                         PORT_B);
13980                 if (I915_READ(VLV_DISPLAY_BASE + DP_B) & DP_DETECTED ||
13981                     intel_dp_is_edp(dev, PORT_B))
13982                         intel_dp_init(dev, VLV_DISPLAY_BASE + DP_B, PORT_B);
13983
13984                 if (I915_READ(VLV_DISPLAY_BASE + GEN4_HDMIC) & SDVO_DETECTED &&
13985                     !intel_dp_is_edp(dev, PORT_C))
13986                         intel_hdmi_init(dev, VLV_DISPLAY_BASE + GEN4_HDMIC,
13987                                         PORT_C);
13988                 if (I915_READ(VLV_DISPLAY_BASE + DP_C) & DP_DETECTED ||
13989                     intel_dp_is_edp(dev, PORT_C))
13990                         intel_dp_init(dev, VLV_DISPLAY_BASE + DP_C, PORT_C);
13991
13992                 if (IS_CHERRYVIEW(dev)) {
13993                         if (I915_READ(VLV_DISPLAY_BASE + CHV_HDMID) & SDVO_DETECTED)
13994                                 intel_hdmi_init(dev, VLV_DISPLAY_BASE + CHV_HDMID,
13995                                                 PORT_D);
13996                         /* eDP not supported on port D, so don't check VBT */
13997                         if (I915_READ(VLV_DISPLAY_BASE + DP_D) & DP_DETECTED)
13998                                 intel_dp_init(dev, VLV_DISPLAY_BASE + DP_D, PORT_D);
13999                 }
14000
14001                 intel_dsi_init(dev);
14002         } else if (!IS_GEN2(dev) && !IS_PINEVIEW(dev)) {
14003                 bool found = false;
14004
14005                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14006                         DRM_DEBUG_KMS("probing SDVOB\n");
14007                         found = intel_sdvo_init(dev, GEN3_SDVOB, true);
14008                         if (!found && IS_G4X(dev)) {
14009                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
14010                                 intel_hdmi_init(dev, GEN4_HDMIB, PORT_B);
14011                         }
14012
14013                         if (!found && IS_G4X(dev))
14014                                 intel_dp_init(dev, DP_B, PORT_B);
14015                 }
14016
14017                 /* Before G4X SDVOC doesn't have its own detect register */
14018
14019                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14020                         DRM_DEBUG_KMS("probing SDVOC\n");
14021                         found = intel_sdvo_init(dev, GEN3_SDVOC, false);
14022                 }
14023
14024                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
14025
14026                         if (IS_G4X(dev)) {
14027                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
14028                                 intel_hdmi_init(dev, GEN4_HDMIC, PORT_C);
14029                         }
14030                         if (IS_G4X(dev))
14031                                 intel_dp_init(dev, DP_C, PORT_C);
14032                 }
14033
14034                 if (IS_G4X(dev) &&
14035                     (I915_READ(DP_D) & DP_DETECTED))
14036                         intel_dp_init(dev, DP_D, PORT_D);
14037         } else if (IS_GEN2(dev))
14038                 intel_dvo_init(dev);
14039
14040         if (SUPPORTS_TV(dev))
14041                 intel_tv_init(dev);
14042
14043         intel_psr_init(dev);
14044
14045         for_each_intel_encoder(dev, encoder) {
14046                 encoder->base.possible_crtcs = encoder->crtc_mask;
14047                 encoder->base.possible_clones =
14048                         intel_encoder_clones(encoder);
14049         }
14050
14051         intel_init_pch_refclk(dev);
14052
14053         drm_helper_move_panel_connectors_to_head(dev);
14054 }
14055
14056 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
14057 {
14058         struct drm_device *dev = fb->dev;
14059         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14060
14061         drm_framebuffer_cleanup(fb);
14062         mutex_lock(&dev->struct_mutex);
14063         WARN_ON(!intel_fb->obj->framebuffer_references--);
14064         drm_gem_object_unreference(&intel_fb->obj->base);
14065         mutex_unlock(&dev->struct_mutex);
14066         kfree(intel_fb);
14067 }
14068
14069 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
14070                                                 struct drm_file *file,
14071                                                 unsigned int *handle)
14072 {
14073         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14074         struct drm_i915_gem_object *obj = intel_fb->obj;
14075
14076         return drm_gem_handle_create(file, &obj->base, handle);
14077 }
14078
14079 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
14080                                         struct drm_file *file,
14081                                         unsigned flags, unsigned color,
14082                                         struct drm_clip_rect *clips,
14083                                         unsigned num_clips)
14084 {
14085         struct drm_device *dev = fb->dev;
14086         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14087         struct drm_i915_gem_object *obj = intel_fb->obj;
14088
14089         mutex_lock(&dev->struct_mutex);
14090         intel_fb_obj_flush(obj, false, ORIGIN_DIRTYFB);
14091         mutex_unlock(&dev->struct_mutex);
14092
14093         return 0;
14094 }
14095
14096 static const struct drm_framebuffer_funcs intel_fb_funcs = {
14097         .destroy = intel_user_framebuffer_destroy,
14098         .create_handle = intel_user_framebuffer_create_handle,
14099         .dirty = intel_user_framebuffer_dirty,
14100 };
14101
14102 static
14103 u32 intel_fb_pitch_limit(struct drm_device *dev, uint64_t fb_modifier,
14104                          uint32_t pixel_format)
14105 {
14106         u32 gen = INTEL_INFO(dev)->gen;
14107
14108         if (gen >= 9) {
14109                 /* "The stride in bytes must not exceed the of the size of 8K
14110                  *  pixels and 32K bytes."
14111                  */
14112                  return min(8192*drm_format_plane_cpp(pixel_format, 0), 32768);
14113         } else if (gen >= 5 && !IS_VALLEYVIEW(dev)) {
14114                 return 32*1024;
14115         } else if (gen >= 4) {
14116                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14117                         return 16*1024;
14118                 else
14119                         return 32*1024;
14120         } else if (gen >= 3) {
14121                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14122                         return 8*1024;
14123                 else
14124                         return 16*1024;
14125         } else {
14126                 /* XXX DSPC is limited to 4k tiled */
14127                 return 8*1024;
14128         }
14129 }
14130
14131 static int intel_framebuffer_init(struct drm_device *dev,
14132                                   struct intel_framebuffer *intel_fb,
14133                                   struct drm_mode_fb_cmd2 *mode_cmd,
14134                                   struct drm_i915_gem_object *obj)
14135 {
14136         unsigned int aligned_height;
14137         int ret;
14138         u32 pitch_limit, stride_alignment;
14139
14140         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
14141
14142         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
14143                 /* Enforce that fb modifier and tiling mode match, but only for
14144                  * X-tiled. This is needed for FBC. */
14145                 if (!!(obj->tiling_mode == I915_TILING_X) !=
14146                     !!(mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED)) {
14147                         DRM_DEBUG("tiling_mode doesn't match fb modifier\n");
14148                         return -EINVAL;
14149                 }
14150         } else {
14151                 if (obj->tiling_mode == I915_TILING_X)
14152                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
14153                 else if (obj->tiling_mode == I915_TILING_Y) {
14154                         DRM_DEBUG("No Y tiling for legacy addfb\n");
14155                         return -EINVAL;
14156                 }
14157         }
14158
14159         /* Passed in modifier sanity checking. */
14160         switch (mode_cmd->modifier[0]) {
14161         case I915_FORMAT_MOD_Y_TILED:
14162         case I915_FORMAT_MOD_Yf_TILED:
14163                 if (INTEL_INFO(dev)->gen < 9) {
14164                         DRM_DEBUG("Unsupported tiling 0x%llx!\n",
14165                                   mode_cmd->modifier[0]);
14166                         return -EINVAL;
14167                 }
14168         case DRM_FORMAT_MOD_NONE:
14169         case I915_FORMAT_MOD_X_TILED:
14170                 break;
14171         default:
14172                 DRM_DEBUG("Unsupported fb modifier 0x%llx!\n",
14173                           mode_cmd->modifier[0]);
14174                 return -EINVAL;
14175         }
14176
14177         stride_alignment = intel_fb_stride_alignment(dev, mode_cmd->modifier[0],
14178                                                      mode_cmd->pixel_format);
14179         if (mode_cmd->pitches[0] & (stride_alignment - 1)) {
14180                 DRM_DEBUG("pitch (%d) must be at least %u byte aligned\n",
14181                           mode_cmd->pitches[0], stride_alignment);
14182                 return -EINVAL;
14183         }
14184
14185         pitch_limit = intel_fb_pitch_limit(dev, mode_cmd->modifier[0],
14186                                            mode_cmd->pixel_format);
14187         if (mode_cmd->pitches[0] > pitch_limit) {
14188                 DRM_DEBUG("%s pitch (%u) must be at less than %d\n",
14189                           mode_cmd->modifier[0] != DRM_FORMAT_MOD_NONE ?
14190                           "tiled" : "linear",
14191                           mode_cmd->pitches[0], pitch_limit);
14192                 return -EINVAL;
14193         }
14194
14195         if (mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED &&
14196             mode_cmd->pitches[0] != obj->stride) {
14197                 DRM_DEBUG("pitch (%d) must match tiling stride (%d)\n",
14198                           mode_cmd->pitches[0], obj->stride);
14199                 return -EINVAL;
14200         }
14201
14202         /* Reject formats not supported by any plane early. */
14203         switch (mode_cmd->pixel_format) {
14204         case DRM_FORMAT_C8:
14205         case DRM_FORMAT_RGB565:
14206         case DRM_FORMAT_XRGB8888:
14207         case DRM_FORMAT_ARGB8888:
14208                 break;
14209         case DRM_FORMAT_XRGB1555:
14210                 if (INTEL_INFO(dev)->gen > 3) {
14211                         DRM_DEBUG("unsupported pixel format: %s\n",
14212                                   drm_get_format_name(mode_cmd->pixel_format));
14213                         return -EINVAL;
14214                 }
14215                 break;
14216         case DRM_FORMAT_ABGR8888:
14217                 if (!IS_VALLEYVIEW(dev) && INTEL_INFO(dev)->gen < 9) {
14218                         DRM_DEBUG("unsupported pixel format: %s\n",
14219                                   drm_get_format_name(mode_cmd->pixel_format));
14220                         return -EINVAL;
14221                 }
14222                 break;
14223         case DRM_FORMAT_XBGR8888:
14224         case DRM_FORMAT_XRGB2101010:
14225         case DRM_FORMAT_XBGR2101010:
14226                 if (INTEL_INFO(dev)->gen < 4) {
14227                         DRM_DEBUG("unsupported pixel format: %s\n",
14228                                   drm_get_format_name(mode_cmd->pixel_format));
14229                         return -EINVAL;
14230                 }
14231                 break;
14232         case DRM_FORMAT_ABGR2101010:
14233                 if (!IS_VALLEYVIEW(dev)) {
14234                         DRM_DEBUG("unsupported pixel format: %s\n",
14235                                   drm_get_format_name(mode_cmd->pixel_format));
14236                         return -EINVAL;
14237                 }
14238                 break;
14239         case DRM_FORMAT_YUYV:
14240         case DRM_FORMAT_UYVY:
14241         case DRM_FORMAT_YVYU:
14242         case DRM_FORMAT_VYUY:
14243                 if (INTEL_INFO(dev)->gen < 5) {
14244                         DRM_DEBUG("unsupported pixel format: %s\n",
14245                                   drm_get_format_name(mode_cmd->pixel_format));
14246                         return -EINVAL;
14247                 }
14248                 break;
14249         default:
14250                 DRM_DEBUG("unsupported pixel format: %s\n",
14251                           drm_get_format_name(mode_cmd->pixel_format));
14252                 return -EINVAL;
14253         }
14254
14255         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14256         if (mode_cmd->offsets[0] != 0)
14257                 return -EINVAL;
14258
14259         aligned_height = intel_fb_align_height(dev, mode_cmd->height,
14260                                                mode_cmd->pixel_format,
14261                                                mode_cmd->modifier[0]);
14262         /* FIXME drm helper for size checks (especially planar formats)? */
14263         if (obj->base.size < aligned_height * mode_cmd->pitches[0])
14264                 return -EINVAL;
14265
14266         drm_helper_mode_fill_fb_struct(&intel_fb->base, mode_cmd);
14267         intel_fb->obj = obj;
14268         intel_fb->obj->framebuffer_references++;
14269
14270         ret = drm_framebuffer_init(dev, &intel_fb->base, &intel_fb_funcs);
14271         if (ret) {
14272                 DRM_ERROR("framebuffer init failed %d\n", ret);
14273                 return ret;
14274         }
14275
14276         return 0;
14277 }
14278
14279 static struct drm_framebuffer *
14280 intel_user_framebuffer_create(struct drm_device *dev,
14281                               struct drm_file *filp,
14282                               struct drm_mode_fb_cmd2 *mode_cmd)
14283 {
14284         struct drm_i915_gem_object *obj;
14285
14286         obj = to_intel_bo(drm_gem_object_lookup(dev, filp,
14287                                                 mode_cmd->handles[0]));
14288         if (&obj->base == NULL)
14289                 return ERR_PTR(-ENOENT);
14290
14291         return intel_framebuffer_create(dev, mode_cmd, obj);
14292 }
14293
14294 #ifndef CONFIG_DRM_I915_FBDEV
14295 static inline void intel_fbdev_output_poll_changed(struct drm_device *dev)
14296 {
14297 }
14298 #endif
14299
14300 static const struct drm_mode_config_funcs intel_mode_funcs = {
14301         .fb_create = intel_user_framebuffer_create,
14302         .output_poll_changed = intel_fbdev_output_poll_changed,
14303         .atomic_check = intel_atomic_check,
14304         .atomic_commit = intel_atomic_commit,
14305         .atomic_state_alloc = intel_atomic_state_alloc,
14306         .atomic_state_clear = intel_atomic_state_clear,
14307 };
14308
14309 /* Set up chip specific display functions */
14310 static void intel_init_display(struct drm_device *dev)
14311 {
14312         struct drm_i915_private *dev_priv = dev->dev_private;
14313
14314         if (HAS_PCH_SPLIT(dev) || IS_G4X(dev))
14315                 dev_priv->display.find_dpll = g4x_find_best_dpll;
14316         else if (IS_CHERRYVIEW(dev))
14317                 dev_priv->display.find_dpll = chv_find_best_dpll;
14318         else if (IS_VALLEYVIEW(dev))
14319                 dev_priv->display.find_dpll = vlv_find_best_dpll;
14320         else if (IS_PINEVIEW(dev))
14321                 dev_priv->display.find_dpll = pnv_find_best_dpll;
14322         else
14323                 dev_priv->display.find_dpll = i9xx_find_best_dpll;
14324
14325         if (INTEL_INFO(dev)->gen >= 9) {
14326                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14327                 dev_priv->display.get_initial_plane_config =
14328                         skylake_get_initial_plane_config;
14329                 dev_priv->display.crtc_compute_clock =
14330                         haswell_crtc_compute_clock;
14331                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14332                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14333                 dev_priv->display.update_primary_plane =
14334                         skylake_update_primary_plane;
14335         } else if (HAS_DDI(dev)) {
14336                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14337                 dev_priv->display.get_initial_plane_config =
14338                         ironlake_get_initial_plane_config;
14339                 dev_priv->display.crtc_compute_clock =
14340                         haswell_crtc_compute_clock;
14341                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14342                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14343                 dev_priv->display.update_primary_plane =
14344                         ironlake_update_primary_plane;
14345         } else if (HAS_PCH_SPLIT(dev)) {
14346                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
14347                 dev_priv->display.get_initial_plane_config =
14348                         ironlake_get_initial_plane_config;
14349                 dev_priv->display.crtc_compute_clock =
14350                         ironlake_crtc_compute_clock;
14351                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
14352                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
14353                 dev_priv->display.update_primary_plane =
14354                         ironlake_update_primary_plane;
14355         } else if (IS_VALLEYVIEW(dev)) {
14356                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14357                 dev_priv->display.get_initial_plane_config =
14358                         i9xx_get_initial_plane_config;
14359                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14360                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14361                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14362                 dev_priv->display.update_primary_plane =
14363                         i9xx_update_primary_plane;
14364         } else {
14365                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14366                 dev_priv->display.get_initial_plane_config =
14367                         i9xx_get_initial_plane_config;
14368                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14369                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14370                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14371                 dev_priv->display.update_primary_plane =
14372                         i9xx_update_primary_plane;
14373         }
14374
14375         /* Returns the core display clock speed */
14376         if (IS_SKYLAKE(dev))
14377                 dev_priv->display.get_display_clock_speed =
14378                         skylake_get_display_clock_speed;
14379         else if (IS_BROXTON(dev))
14380                 dev_priv->display.get_display_clock_speed =
14381                         broxton_get_display_clock_speed;
14382         else if (IS_BROADWELL(dev))
14383                 dev_priv->display.get_display_clock_speed =
14384                         broadwell_get_display_clock_speed;
14385         else if (IS_HASWELL(dev))
14386                 dev_priv->display.get_display_clock_speed =
14387                         haswell_get_display_clock_speed;
14388         else if (IS_VALLEYVIEW(dev))
14389                 dev_priv->display.get_display_clock_speed =
14390                         valleyview_get_display_clock_speed;
14391         else if (IS_GEN5(dev))
14392                 dev_priv->display.get_display_clock_speed =
14393                         ilk_get_display_clock_speed;
14394         else if (IS_I945G(dev) || IS_BROADWATER(dev) ||
14395                  IS_GEN6(dev) || IS_IVYBRIDGE(dev))
14396                 dev_priv->display.get_display_clock_speed =
14397                         i945_get_display_clock_speed;
14398         else if (IS_GM45(dev))
14399                 dev_priv->display.get_display_clock_speed =
14400                         gm45_get_display_clock_speed;
14401         else if (IS_CRESTLINE(dev))
14402                 dev_priv->display.get_display_clock_speed =
14403                         i965gm_get_display_clock_speed;
14404         else if (IS_PINEVIEW(dev))
14405                 dev_priv->display.get_display_clock_speed =
14406                         pnv_get_display_clock_speed;
14407         else if (IS_G33(dev) || IS_G4X(dev))
14408                 dev_priv->display.get_display_clock_speed =
14409                         g33_get_display_clock_speed;
14410         else if (IS_I915G(dev))
14411                 dev_priv->display.get_display_clock_speed =
14412                         i915_get_display_clock_speed;
14413         else if (IS_I945GM(dev) || IS_845G(dev))
14414                 dev_priv->display.get_display_clock_speed =
14415                         i9xx_misc_get_display_clock_speed;
14416         else if (IS_PINEVIEW(dev))
14417                 dev_priv->display.get_display_clock_speed =
14418                         pnv_get_display_clock_speed;
14419         else if (IS_I915GM(dev))
14420                 dev_priv->display.get_display_clock_speed =
14421                         i915gm_get_display_clock_speed;
14422         else if (IS_I865G(dev))
14423                 dev_priv->display.get_display_clock_speed =
14424                         i865_get_display_clock_speed;
14425         else if (IS_I85X(dev))
14426                 dev_priv->display.get_display_clock_speed =
14427                         i85x_get_display_clock_speed;
14428         else { /* 830 */
14429                 WARN(!IS_I830(dev), "Unknown platform. Assuming 133 MHz CDCLK\n");
14430                 dev_priv->display.get_display_clock_speed =
14431                         i830_get_display_clock_speed;
14432         }
14433
14434         if (IS_GEN5(dev)) {
14435                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
14436         } else if (IS_GEN6(dev)) {
14437                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
14438         } else if (IS_IVYBRIDGE(dev)) {
14439                 /* FIXME: detect B0+ stepping and use auto training */
14440                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
14441         } else if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
14442                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
14443                 if (IS_BROADWELL(dev)) {
14444                         dev_priv->display.modeset_commit_cdclk =
14445                                 broadwell_modeset_commit_cdclk;
14446                         dev_priv->display.modeset_calc_cdclk =
14447                                 broadwell_modeset_calc_cdclk;
14448                 }
14449         } else if (IS_VALLEYVIEW(dev)) {
14450                 dev_priv->display.modeset_commit_cdclk =
14451                         valleyview_modeset_commit_cdclk;
14452                 dev_priv->display.modeset_calc_cdclk =
14453                         valleyview_modeset_calc_cdclk;
14454         } else if (IS_BROXTON(dev)) {
14455                 dev_priv->display.modeset_commit_cdclk =
14456                         broxton_modeset_commit_cdclk;
14457                 dev_priv->display.modeset_calc_cdclk =
14458                         broxton_modeset_calc_cdclk;
14459         }
14460
14461         switch (INTEL_INFO(dev)->gen) {
14462         case 2:
14463                 dev_priv->display.queue_flip = intel_gen2_queue_flip;
14464                 break;
14465
14466         case 3:
14467                 dev_priv->display.queue_flip = intel_gen3_queue_flip;
14468                 break;
14469
14470         case 4:
14471         case 5:
14472                 dev_priv->display.queue_flip = intel_gen4_queue_flip;
14473                 break;
14474
14475         case 6:
14476                 dev_priv->display.queue_flip = intel_gen6_queue_flip;
14477                 break;
14478         case 7:
14479         case 8: /* FIXME(BDW): Check that the gen8 RCS flip works. */
14480                 dev_priv->display.queue_flip = intel_gen7_queue_flip;
14481                 break;
14482         case 9:
14483                 /* Drop through - unsupported since execlist only. */
14484         default:
14485                 /* Default just returns -ENODEV to indicate unsupported */
14486                 dev_priv->display.queue_flip = intel_default_queue_flip;
14487         }
14488
14489         intel_panel_init_backlight_funcs(dev);
14490
14491         mutex_init(&dev_priv->pps_mutex);
14492 }
14493
14494 /*
14495  * Some BIOSes insist on assuming the GPU's pipe A is enabled at suspend,
14496  * resume, or other times.  This quirk makes sure that's the case for
14497  * affected systems.
14498  */
14499 static void quirk_pipea_force(struct drm_device *dev)
14500 {
14501         struct drm_i915_private *dev_priv = dev->dev_private;
14502
14503         dev_priv->quirks |= QUIRK_PIPEA_FORCE;
14504         DRM_INFO("applying pipe a force quirk\n");
14505 }
14506
14507 static void quirk_pipeb_force(struct drm_device *dev)
14508 {
14509         struct drm_i915_private *dev_priv = dev->dev_private;
14510
14511         dev_priv->quirks |= QUIRK_PIPEB_FORCE;
14512         DRM_INFO("applying pipe b force quirk\n");
14513 }
14514
14515 /*
14516  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
14517  */
14518 static void quirk_ssc_force_disable(struct drm_device *dev)
14519 {
14520         struct drm_i915_private *dev_priv = dev->dev_private;
14521         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
14522         DRM_INFO("applying lvds SSC disable quirk\n");
14523 }
14524
14525 /*
14526  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
14527  * brightness value
14528  */
14529 static void quirk_invert_brightness(struct drm_device *dev)
14530 {
14531         struct drm_i915_private *dev_priv = dev->dev_private;
14532         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
14533         DRM_INFO("applying inverted panel brightness quirk\n");
14534 }
14535
14536 /* Some VBT's incorrectly indicate no backlight is present */
14537 static void quirk_backlight_present(struct drm_device *dev)
14538 {
14539         struct drm_i915_private *dev_priv = dev->dev_private;
14540         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
14541         DRM_INFO("applying backlight present quirk\n");
14542 }
14543
14544 struct intel_quirk {
14545         int device;
14546         int subsystem_vendor;
14547         int subsystem_device;
14548         void (*hook)(struct drm_device *dev);
14549 };
14550
14551 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
14552 struct intel_dmi_quirk {
14553         void (*hook)(struct drm_device *dev);
14554         const struct dmi_system_id (*dmi_id_list)[];
14555 };
14556
14557 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
14558 {
14559         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
14560         return 1;
14561 }
14562
14563 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
14564         {
14565                 .dmi_id_list = &(const struct dmi_system_id[]) {
14566                         {
14567                                 .callback = intel_dmi_reverse_brightness,
14568                                 .ident = "NCR Corporation",
14569                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
14570                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
14571                                 },
14572                         },
14573                         { }  /* terminating entry */
14574                 },
14575                 .hook = quirk_invert_brightness,
14576         },
14577 };
14578
14579 static struct intel_quirk intel_quirks[] = {
14580         /* Toshiba Protege R-205, S-209 needs pipe A force quirk */
14581         { 0x2592, 0x1179, 0x0001, quirk_pipea_force },
14582
14583         /* ThinkPad T60 needs pipe A force quirk (bug #16494) */
14584         { 0x2782, 0x17aa, 0x201a, quirk_pipea_force },
14585
14586         /* 830 needs to leave pipe A & dpll A up */
14587         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipea_force },
14588
14589         /* 830 needs to leave pipe B & dpll B up */
14590         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipeb_force },
14591
14592         /* Lenovo U160 cannot use SSC on LVDS */
14593         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
14594
14595         /* Sony Vaio Y cannot use SSC on LVDS */
14596         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
14597
14598         /* Acer Aspire 5734Z must invert backlight brightness */
14599         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
14600
14601         /* Acer/eMachines G725 */
14602         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
14603
14604         /* Acer/eMachines e725 */
14605         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
14606
14607         /* Acer/Packard Bell NCL20 */
14608         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
14609
14610         /* Acer Aspire 4736Z */
14611         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
14612
14613         /* Acer Aspire 5336 */
14614         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
14615
14616         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
14617         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
14618
14619         /* Acer C720 Chromebook (Core i3 4005U) */
14620         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
14621
14622         /* Apple Macbook 2,1 (Core 2 T7400) */
14623         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
14624
14625         /* Toshiba CB35 Chromebook (Celeron 2955U) */
14626         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
14627
14628         /* HP Chromebook 14 (Celeron 2955U) */
14629         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
14630
14631         /* Dell Chromebook 11 */
14632         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
14633 };
14634
14635 static void intel_init_quirks(struct drm_device *dev)
14636 {
14637         struct pci_dev *d = dev->pdev;
14638         int i;
14639
14640         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
14641                 struct intel_quirk *q = &intel_quirks[i];
14642
14643                 if (d->device == q->device &&
14644                     (d->subsystem_vendor == q->subsystem_vendor ||
14645                      q->subsystem_vendor == PCI_ANY_ID) &&
14646                     (d->subsystem_device == q->subsystem_device ||
14647                      q->subsystem_device == PCI_ANY_ID))
14648                         q->hook(dev);
14649         }
14650         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
14651                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
14652                         intel_dmi_quirks[i].hook(dev);
14653         }
14654 }
14655
14656 /* Disable the VGA plane that we never use */
14657 static void i915_disable_vga(struct drm_device *dev)
14658 {
14659         struct drm_i915_private *dev_priv = dev->dev_private;
14660         u8 sr1;
14661         u32 vga_reg = i915_vgacntrl_reg(dev);
14662
14663         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
14664         vga_get_uninterruptible(dev->pdev, VGA_RSRC_LEGACY_IO);
14665         outb(SR01, VGA_SR_INDEX);
14666         sr1 = inb(VGA_SR_DATA);
14667         outb(sr1 | 1<<5, VGA_SR_DATA);
14668         vga_put(dev->pdev, VGA_RSRC_LEGACY_IO);
14669         udelay(300);
14670
14671         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
14672         POSTING_READ(vga_reg);
14673 }
14674
14675 void intel_modeset_init_hw(struct drm_device *dev)
14676 {
14677         intel_update_cdclk(dev);
14678         intel_prepare_ddi(dev);
14679         intel_init_clock_gating(dev);
14680         intel_enable_gt_powersave(dev);
14681 }
14682
14683 void intel_modeset_init(struct drm_device *dev)
14684 {
14685         struct drm_i915_private *dev_priv = dev->dev_private;
14686         int sprite, ret;
14687         enum pipe pipe;
14688         struct intel_crtc *crtc;
14689
14690         drm_mode_config_init(dev);
14691
14692         dev->mode_config.min_width = 0;
14693         dev->mode_config.min_height = 0;
14694
14695         dev->mode_config.preferred_depth = 24;
14696         dev->mode_config.prefer_shadow = 1;
14697
14698         dev->mode_config.allow_fb_modifiers = true;
14699
14700         dev->mode_config.funcs = &intel_mode_funcs;
14701
14702         intel_init_quirks(dev);
14703
14704         intel_init_pm(dev);
14705
14706         if (INTEL_INFO(dev)->num_pipes == 0)
14707                 return;
14708
14709         intel_init_display(dev);
14710         intel_init_audio(dev);
14711
14712         if (IS_GEN2(dev)) {
14713                 dev->mode_config.max_width = 2048;
14714                 dev->mode_config.max_height = 2048;
14715         } else if (IS_GEN3(dev)) {
14716                 dev->mode_config.max_width = 4096;
14717                 dev->mode_config.max_height = 4096;
14718         } else {
14719                 dev->mode_config.max_width = 8192;
14720                 dev->mode_config.max_height = 8192;
14721         }
14722
14723         if (IS_845G(dev) || IS_I865G(dev)) {
14724                 dev->mode_config.cursor_width = IS_845G(dev) ? 64 : 512;
14725                 dev->mode_config.cursor_height = 1023;
14726         } else if (IS_GEN2(dev)) {
14727                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
14728                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
14729         } else {
14730                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
14731                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
14732         }
14733
14734         dev->mode_config.fb_base = dev_priv->gtt.mappable_base;
14735
14736         DRM_DEBUG_KMS("%d display pipe%s available.\n",
14737                       INTEL_INFO(dev)->num_pipes,
14738                       INTEL_INFO(dev)->num_pipes > 1 ? "s" : "");
14739
14740         for_each_pipe(dev_priv, pipe) {
14741                 intel_crtc_init(dev, pipe);
14742                 for_each_sprite(dev_priv, pipe, sprite) {
14743                         ret = intel_plane_init(dev, pipe, sprite);
14744                         if (ret)
14745                                 DRM_DEBUG_KMS("pipe %c sprite %c init failed: %d\n",
14746                                               pipe_name(pipe), sprite_name(pipe, sprite), ret);
14747                 }
14748         }
14749
14750         intel_shared_dpll_init(dev);
14751
14752         /* Just disable it once at startup */
14753         i915_disable_vga(dev);
14754         intel_setup_outputs(dev);
14755
14756         /* Just in case the BIOS is doing something questionable. */
14757         intel_fbc_disable(dev_priv);
14758
14759         drm_modeset_lock_all(dev);
14760         intel_modeset_setup_hw_state(dev);
14761         drm_modeset_unlock_all(dev);
14762
14763         for_each_intel_crtc(dev, crtc) {
14764                 struct intel_initial_plane_config plane_config = {};
14765
14766                 if (!crtc->active)
14767                         continue;
14768
14769                 /*
14770                  * Note that reserving the BIOS fb up front prevents us
14771                  * from stuffing other stolen allocations like the ring
14772                  * on top.  This prevents some ugliness at boot time, and
14773                  * can even allow for smooth boot transitions if the BIOS
14774                  * fb is large enough for the active pipe configuration.
14775                  */
14776                 dev_priv->display.get_initial_plane_config(crtc,
14777                                                            &plane_config);
14778
14779                 /*
14780                  * If the fb is shared between multiple heads, we'll
14781                  * just get the first one.
14782                  */
14783                 intel_find_initial_plane_obj(crtc, &plane_config);
14784         }
14785 }
14786
14787 static void intel_enable_pipe_a(struct drm_device *dev)
14788 {
14789         struct intel_connector *connector;
14790         struct drm_connector *crt = NULL;
14791         struct intel_load_detect_pipe load_detect_temp;
14792         struct drm_modeset_acquire_ctx *ctx = dev->mode_config.acquire_ctx;
14793
14794         /* We can't just switch on the pipe A, we need to set things up with a
14795          * proper mode and output configuration. As a gross hack, enable pipe A
14796          * by enabling the load detect pipe once. */
14797         for_each_intel_connector(dev, connector) {
14798                 if (connector->encoder->type == INTEL_OUTPUT_ANALOG) {
14799                         crt = &connector->base;
14800                         break;
14801                 }
14802         }
14803
14804         if (!crt)
14805                 return;
14806
14807         if (intel_get_load_detect_pipe(crt, NULL, &load_detect_temp, ctx))
14808                 intel_release_load_detect_pipe(crt, &load_detect_temp, ctx);
14809 }
14810
14811 static bool
14812 intel_check_plane_mapping(struct intel_crtc *crtc)
14813 {
14814         struct drm_device *dev = crtc->base.dev;
14815         struct drm_i915_private *dev_priv = dev->dev_private;
14816         u32 reg, val;
14817
14818         if (INTEL_INFO(dev)->num_pipes == 1)
14819                 return true;
14820
14821         reg = DSPCNTR(!crtc->plane);
14822         val = I915_READ(reg);
14823
14824         if ((val & DISPLAY_PLANE_ENABLE) &&
14825             (!!(val & DISPPLANE_SEL_PIPE_MASK) == crtc->pipe))
14826                 return false;
14827
14828         return true;
14829 }
14830
14831 static void intel_sanitize_crtc(struct intel_crtc *crtc)
14832 {
14833         struct drm_device *dev = crtc->base.dev;
14834         struct drm_i915_private *dev_priv = dev->dev_private;
14835         struct intel_encoder *encoder;
14836         u32 reg;
14837         bool enable;
14838
14839         /* Clear any frame start delays used for debugging left by the BIOS */
14840         reg = PIPECONF(crtc->config->cpu_transcoder);
14841         I915_WRITE(reg, I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
14842
14843         /* restore vblank interrupts to correct state */
14844         drm_crtc_vblank_reset(&crtc->base);
14845         if (crtc->active) {
14846                 drm_calc_timestamping_constants(&crtc->base, &crtc->base.hwmode);
14847                 update_scanline_offset(crtc);
14848                 drm_crtc_vblank_on(&crtc->base);
14849         }
14850
14851         /* We need to sanitize the plane -> pipe mapping first because this will
14852          * disable the crtc (and hence change the state) if it is wrong. Note
14853          * that gen4+ has a fixed plane -> pipe mapping.  */
14854         if (INTEL_INFO(dev)->gen < 4 && !intel_check_plane_mapping(crtc)) {
14855                 bool plane;
14856
14857                 DRM_DEBUG_KMS("[CRTC:%d] wrong plane connection detected!\n",
14858                               crtc->base.base.id);
14859
14860                 /* Pipe has the wrong plane attached and the plane is active.
14861                  * Temporarily change the plane mapping and disable everything
14862                  * ...  */
14863                 plane = crtc->plane;
14864                 to_intel_plane_state(crtc->base.primary->state)->visible = true;
14865                 crtc->plane = !plane;
14866                 intel_crtc_disable_noatomic(&crtc->base);
14867                 crtc->plane = plane;
14868         }
14869
14870         if (dev_priv->quirks & QUIRK_PIPEA_FORCE &&
14871             crtc->pipe == PIPE_A && !crtc->active) {
14872                 /* BIOS forgot to enable pipe A, this mostly happens after
14873                  * resume. Force-enable the pipe to fix this, the update_dpms
14874                  * call below we restore the pipe to the right state, but leave
14875                  * the required bits on. */
14876                 intel_enable_pipe_a(dev);
14877         }
14878
14879         /* Adjust the state of the output pipe according to whether we
14880          * have active connectors/encoders. */
14881         enable = false;
14882         for_each_encoder_on_crtc(dev, &crtc->base, encoder) {
14883                 enable = true;
14884                 break;
14885         }
14886
14887         if (!enable)
14888                 intel_crtc_disable_noatomic(&crtc->base);
14889
14890         if (crtc->active != crtc->base.state->active) {
14891
14892                 /* This can happen either due to bugs in the get_hw_state
14893                  * functions or because of calls to intel_crtc_disable_noatomic,
14894                  * or because the pipe is force-enabled due to the
14895                  * pipe A quirk. */
14896                 DRM_DEBUG_KMS("[CRTC:%d] hw state adjusted, was %s, now %s\n",
14897                               crtc->base.base.id,
14898                               crtc->base.state->enable ? "enabled" : "disabled",
14899                               crtc->active ? "enabled" : "disabled");
14900
14901                 WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, NULL) < 0);
14902                 crtc->base.state->active = crtc->active;
14903                 crtc->base.enabled = crtc->active;
14904
14905                 /* Because we only establish the connector -> encoder ->
14906                  * crtc links if something is active, this means the
14907                  * crtc is now deactivated. Break the links. connector
14908                  * -> encoder links are only establish when things are
14909                  *  actually up, hence no need to break them. */
14910                 WARN_ON(crtc->active);
14911
14912                 for_each_encoder_on_crtc(dev, &crtc->base, encoder)
14913                         encoder->base.crtc = NULL;
14914         }
14915
14916         if (crtc->active || HAS_GMCH_DISPLAY(dev)) {
14917                 /*
14918                  * We start out with underrun reporting disabled to avoid races.
14919                  * For correct bookkeeping mark this on active crtcs.
14920                  *
14921                  * Also on gmch platforms we dont have any hardware bits to
14922                  * disable the underrun reporting. Which means we need to start
14923                  * out with underrun reporting disabled also on inactive pipes,
14924                  * since otherwise we'll complain about the garbage we read when
14925                  * e.g. coming up after runtime pm.
14926                  *
14927                  * No protection against concurrent access is required - at
14928                  * worst a fifo underrun happens which also sets this to false.
14929                  */
14930                 crtc->cpu_fifo_underrun_disabled = true;
14931                 crtc->pch_fifo_underrun_disabled = true;
14932         }
14933 }
14934
14935 static void intel_sanitize_encoder(struct intel_encoder *encoder)
14936 {
14937         struct intel_connector *connector;
14938         struct drm_device *dev = encoder->base.dev;
14939         bool active = false;
14940
14941         /* We need to check both for a crtc link (meaning that the
14942          * encoder is active and trying to read from a pipe) and the
14943          * pipe itself being active. */
14944         bool has_active_crtc = encoder->base.crtc &&
14945                 to_intel_crtc(encoder->base.crtc)->active;
14946
14947         for_each_intel_connector(dev, connector) {
14948                 if (connector->base.encoder != &encoder->base)
14949                         continue;
14950
14951                 active = true;
14952                 break;
14953         }
14954
14955         if (active && !has_active_crtc) {
14956                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
14957                               encoder->base.base.id,
14958                               encoder->base.name);
14959
14960                 /* Connector is active, but has no active pipe. This is
14961                  * fallout from our resume register restoring. Disable
14962                  * the encoder manually again. */
14963                 if (encoder->base.crtc) {
14964                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
14965                                       encoder->base.base.id,
14966                                       encoder->base.name);
14967                         encoder->disable(encoder);
14968                         if (encoder->post_disable)
14969                                 encoder->post_disable(encoder);
14970                 }
14971                 encoder->base.crtc = NULL;
14972
14973                 /* Inconsistent output/port/pipe state happens presumably due to
14974                  * a bug in one of the get_hw_state functions. Or someplace else
14975                  * in our code, like the register restore mess on resume. Clamp
14976                  * things to off as a safer default. */
14977                 for_each_intel_connector(dev, connector) {
14978                         if (connector->encoder != encoder)
14979                                 continue;
14980                         connector->base.dpms = DRM_MODE_DPMS_OFF;
14981                         connector->base.encoder = NULL;
14982                 }
14983         }
14984         /* Enabled encoders without active connectors will be fixed in
14985          * the crtc fixup. */
14986 }
14987
14988 void i915_redisable_vga_power_on(struct drm_device *dev)
14989 {
14990         struct drm_i915_private *dev_priv = dev->dev_private;
14991         u32 vga_reg = i915_vgacntrl_reg(dev);
14992
14993         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
14994                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
14995                 i915_disable_vga(dev);
14996         }
14997 }
14998
14999 void i915_redisable_vga(struct drm_device *dev)
15000 {
15001         struct drm_i915_private *dev_priv = dev->dev_private;
15002
15003         /* This function can be called both from intel_modeset_setup_hw_state or
15004          * at a very early point in our resume sequence, where the power well
15005          * structures are not yet restored. Since this function is at a very
15006          * paranoid "someone might have enabled VGA while we were not looking"
15007          * level, just check if the power well is enabled instead of trying to
15008          * follow the "don't touch the power well if we don't need it" policy
15009          * the rest of the driver uses. */
15010         if (!intel_display_power_is_enabled(dev_priv, POWER_DOMAIN_VGA))
15011                 return;
15012
15013         i915_redisable_vga_power_on(dev);
15014 }
15015
15016 static bool primary_get_hw_state(struct intel_crtc *crtc)
15017 {
15018         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
15019
15020         return !!(I915_READ(DSPCNTR(crtc->plane)) & DISPLAY_PLANE_ENABLE);
15021 }
15022
15023 static void readout_plane_state(struct intel_crtc *crtc,
15024                                 struct intel_crtc_state *crtc_state)
15025 {
15026         struct intel_plane *p;
15027         struct intel_plane_state *plane_state;
15028         bool active = crtc_state->base.active;
15029
15030         for_each_intel_plane(crtc->base.dev, p) {
15031                 if (crtc->pipe != p->pipe)
15032                         continue;
15033
15034                 plane_state = to_intel_plane_state(p->base.state);
15035
15036                 if (p->base.type == DRM_PLANE_TYPE_PRIMARY)
15037                         plane_state->visible = primary_get_hw_state(crtc);
15038                 else {
15039                         if (active)
15040                                 p->disable_plane(&p->base, &crtc->base);
15041
15042                         plane_state->visible = false;
15043                 }
15044         }
15045 }
15046
15047 static void intel_modeset_readout_hw_state(struct drm_device *dev)
15048 {
15049         struct drm_i915_private *dev_priv = dev->dev_private;
15050         enum pipe pipe;
15051         struct intel_crtc *crtc;
15052         struct intel_encoder *encoder;
15053         struct intel_connector *connector;
15054         int i;
15055
15056         for_each_intel_crtc(dev, crtc) {
15057                 __drm_atomic_helper_crtc_destroy_state(&crtc->base, crtc->base.state);
15058                 memset(crtc->config, 0, sizeof(*crtc->config));
15059                 crtc->config->base.crtc = &crtc->base;
15060
15061                 crtc->active = dev_priv->display.get_pipe_config(crtc,
15062                                                                  crtc->config);
15063
15064                 crtc->base.state->active = crtc->active;
15065                 crtc->base.enabled = crtc->active;
15066
15067                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
15068                 if (crtc->base.state->active) {
15069                         intel_mode_from_pipe_config(&crtc->base.mode, crtc->config);
15070                         intel_mode_from_pipe_config(&crtc->base.state->adjusted_mode, crtc->config);
15071                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
15072
15073                         /*
15074                          * The initial mode needs to be set in order to keep
15075                          * the atomic core happy. It wants a valid mode if the
15076                          * crtc's enabled, so we do the above call.
15077                          *
15078                          * At this point some state updated by the connectors
15079                          * in their ->detect() callback has not run yet, so
15080                          * no recalculation can be done yet.
15081                          *
15082                          * Even if we could do a recalculation and modeset
15083                          * right now it would cause a double modeset if
15084                          * fbdev or userspace chooses a different initial mode.
15085                          *
15086                          * If that happens, someone indicated they wanted a
15087                          * mode change, which means it's safe to do a full
15088                          * recalculation.
15089                          */
15090                         crtc->base.state->mode.private_flags = I915_MODE_FLAG_INHERITED;
15091                 }
15092
15093                 crtc->base.hwmode = crtc->config->base.adjusted_mode;
15094                 readout_plane_state(crtc, to_intel_crtc_state(crtc->base.state));
15095
15096                 DRM_DEBUG_KMS("[CRTC:%d] hw state readout: %s\n",
15097                               crtc->base.base.id,
15098                               crtc->active ? "enabled" : "disabled");
15099         }
15100
15101         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15102                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15103
15104                 pll->on = pll->get_hw_state(dev_priv, pll,
15105                                             &pll->config.hw_state);
15106                 pll->active = 0;
15107                 pll->config.crtc_mask = 0;
15108                 for_each_intel_crtc(dev, crtc) {
15109                         if (crtc->active && intel_crtc_to_shared_dpll(crtc) == pll) {
15110                                 pll->active++;
15111                                 pll->config.crtc_mask |= 1 << crtc->pipe;
15112                         }
15113                 }
15114
15115                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15116                               pll->name, pll->config.crtc_mask, pll->on);
15117
15118                 if (pll->config.crtc_mask)
15119                         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
15120         }
15121
15122         for_each_intel_encoder(dev, encoder) {
15123                 pipe = 0;
15124
15125                 if (encoder->get_hw_state(encoder, &pipe)) {
15126                         crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
15127                         encoder->base.crtc = &crtc->base;
15128                         encoder->get_config(encoder, crtc->config);
15129                 } else {
15130                         encoder->base.crtc = NULL;
15131                 }
15132
15133                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
15134                               encoder->base.base.id,
15135                               encoder->base.name,
15136                               encoder->base.crtc ? "enabled" : "disabled",
15137                               pipe_name(pipe));
15138         }
15139
15140         for_each_intel_connector(dev, connector) {
15141                 if (connector->get_hw_state(connector)) {
15142                         connector->base.dpms = DRM_MODE_DPMS_ON;
15143                         connector->base.encoder = &connector->encoder->base;
15144                 } else {
15145                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15146                         connector->base.encoder = NULL;
15147                 }
15148                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
15149                               connector->base.base.id,
15150                               connector->base.name,
15151                               connector->base.encoder ? "enabled" : "disabled");
15152         }
15153 }
15154
15155 /* Scan out the current hw modeset state,
15156  * and sanitizes it to the current state
15157  */
15158 static void
15159 intel_modeset_setup_hw_state(struct drm_device *dev)
15160 {
15161         struct drm_i915_private *dev_priv = dev->dev_private;
15162         enum pipe pipe;
15163         struct intel_crtc *crtc;
15164         struct intel_encoder *encoder;
15165         int i;
15166
15167         intel_modeset_readout_hw_state(dev);
15168
15169         /* HW state is read out, now we need to sanitize this mess. */
15170         for_each_intel_encoder(dev, encoder) {
15171                 intel_sanitize_encoder(encoder);
15172         }
15173
15174         for_each_pipe(dev_priv, pipe) {
15175                 crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
15176                 intel_sanitize_crtc(crtc);
15177                 intel_dump_pipe_config(crtc, crtc->config,
15178                                        "[setup_hw_state]");
15179         }
15180
15181         intel_modeset_update_connector_atomic_state(dev);
15182
15183         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15184                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15185
15186                 if (!pll->on || pll->active)
15187                         continue;
15188
15189                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
15190
15191                 pll->disable(dev_priv, pll);
15192                 pll->on = false;
15193         }
15194
15195         if (IS_VALLEYVIEW(dev))
15196                 vlv_wm_get_hw_state(dev);
15197         else if (IS_GEN9(dev))
15198                 skl_wm_get_hw_state(dev);
15199         else if (HAS_PCH_SPLIT(dev))
15200                 ilk_wm_get_hw_state(dev);
15201
15202         for_each_intel_crtc(dev, crtc) {
15203                 unsigned long put_domains;
15204
15205                 put_domains = modeset_get_crtc_power_domains(&crtc->base);
15206                 if (WARN_ON(put_domains))
15207                         modeset_put_power_domains(dev_priv, put_domains);
15208         }
15209         intel_display_set_init_power(dev_priv, false);
15210 }
15211
15212 void intel_display_resume(struct drm_device *dev)
15213 {
15214         struct drm_atomic_state *state = drm_atomic_state_alloc(dev);
15215         struct intel_connector *conn;
15216         struct intel_plane *plane;
15217         struct drm_crtc *crtc;
15218         int ret;
15219
15220         if (!state)
15221                 return;
15222
15223         state->acquire_ctx = dev->mode_config.acquire_ctx;
15224
15225         /* preserve complete old state, including dpll */
15226         intel_atomic_get_shared_dpll_state(state);
15227
15228         for_each_crtc(dev, crtc) {
15229                 struct drm_crtc_state *crtc_state =
15230                         drm_atomic_get_crtc_state(state, crtc);
15231
15232                 ret = PTR_ERR_OR_ZERO(crtc_state);
15233                 if (ret)
15234                         goto err;
15235
15236                 /* force a restore */
15237                 crtc_state->mode_changed = true;
15238         }
15239
15240         for_each_intel_plane(dev, plane) {
15241                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_plane_state(state, &plane->base));
15242                 if (ret)
15243                         goto err;
15244         }
15245
15246         for_each_intel_connector(dev, conn) {
15247                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(state, &conn->base));
15248                 if (ret)
15249                         goto err;
15250         }
15251
15252         intel_modeset_setup_hw_state(dev);
15253
15254         i915_redisable_vga(dev);
15255         ret = drm_atomic_commit(state);
15256         if (!ret)
15257                 return;
15258
15259 err:
15260         DRM_ERROR("Restoring old state failed with %i\n", ret);
15261         drm_atomic_state_free(state);
15262 }
15263
15264 void intel_modeset_gem_init(struct drm_device *dev)
15265 {
15266         struct drm_i915_private *dev_priv = dev->dev_private;
15267         struct drm_crtc *c;
15268         struct drm_i915_gem_object *obj;
15269         int ret;
15270
15271         mutex_lock(&dev->struct_mutex);
15272         intel_init_gt_powersave(dev);
15273         mutex_unlock(&dev->struct_mutex);
15274
15275         /*
15276          * There may be no VBT; and if the BIOS enabled SSC we can
15277          * just keep using it to avoid unnecessary flicker.  Whereas if the
15278          * BIOS isn't using it, don't assume it will work even if the VBT
15279          * indicates as much.
15280          */
15281         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
15282                 dev_priv->vbt.lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
15283                                                 DREF_SSC1_ENABLE);
15284
15285         intel_modeset_init_hw(dev);
15286
15287         intel_setup_overlay(dev);
15288
15289         /*
15290          * Make sure any fbs we allocated at startup are properly
15291          * pinned & fenced.  When we do the allocation it's too early
15292          * for this.
15293          */
15294         for_each_crtc(dev, c) {
15295                 obj = intel_fb_obj(c->primary->fb);
15296                 if (obj == NULL)
15297                         continue;
15298
15299                 mutex_lock(&dev->struct_mutex);
15300                 ret = intel_pin_and_fence_fb_obj(c->primary,
15301                                                  c->primary->fb,
15302                                                  c->primary->state,
15303                                                  NULL, NULL);
15304                 mutex_unlock(&dev->struct_mutex);
15305                 if (ret) {
15306                         DRM_ERROR("failed to pin boot fb on pipe %d\n",
15307                                   to_intel_crtc(c)->pipe);
15308                         drm_framebuffer_unreference(c->primary->fb);
15309                         c->primary->fb = NULL;
15310                         c->primary->crtc = c->primary->state->crtc = NULL;
15311                         update_state_fb(c->primary);
15312                         c->state->plane_mask &= ~(1 << drm_plane_index(c->primary));
15313                 }
15314         }
15315
15316         intel_backlight_register(dev);
15317 }
15318
15319 void intel_connector_unregister(struct intel_connector *intel_connector)
15320 {
15321         struct drm_connector *connector = &intel_connector->base;
15322
15323         intel_panel_destroy_backlight(connector);
15324         drm_connector_unregister(connector);
15325 }
15326
15327 void intel_modeset_cleanup(struct drm_device *dev)
15328 {
15329         struct drm_i915_private *dev_priv = dev->dev_private;
15330         struct drm_connector *connector;
15331
15332         intel_disable_gt_powersave(dev);
15333
15334         intel_backlight_unregister(dev);
15335
15336         /*
15337          * Interrupts and polling as the first thing to avoid creating havoc.
15338          * Too much stuff here (turning of connectors, ...) would
15339          * experience fancy races otherwise.
15340          */
15341         intel_irq_uninstall(dev_priv);
15342
15343         /*
15344          * Due to the hpd irq storm handling the hotplug work can re-arm the
15345          * poll handlers. Hence disable polling after hpd handling is shut down.
15346          */
15347         drm_kms_helper_poll_fini(dev);
15348
15349         intel_unregister_dsm_handler();
15350
15351         intel_fbc_disable(dev_priv);
15352
15353         /* flush any delayed tasks or pending work */
15354         flush_scheduled_work();
15355
15356         /* destroy the backlight and sysfs files before encoders/connectors */
15357         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
15358                 struct intel_connector *intel_connector;
15359
15360                 intel_connector = to_intel_connector(connector);
15361                 intel_connector->unregister(intel_connector);
15362         }
15363
15364         drm_mode_config_cleanup(dev);
15365
15366         intel_cleanup_overlay(dev);
15367
15368         mutex_lock(&dev->struct_mutex);
15369         intel_cleanup_gt_powersave(dev);
15370         mutex_unlock(&dev->struct_mutex);
15371 }
15372
15373 /*
15374  * Return which encoder is currently attached for connector.
15375  */
15376 struct drm_encoder *intel_best_encoder(struct drm_connector *connector)
15377 {
15378         return &intel_attached_encoder(connector)->base;
15379 }
15380
15381 void intel_connector_attach_encoder(struct intel_connector *connector,
15382                                     struct intel_encoder *encoder)
15383 {
15384         connector->encoder = encoder;
15385         drm_mode_connector_attach_encoder(&connector->base,
15386                                           &encoder->base);
15387 }
15388
15389 /*
15390  * set vga decode state - true == enable VGA decode
15391  */
15392 int intel_modeset_vga_set_state(struct drm_device *dev, bool state)
15393 {
15394         struct drm_i915_private *dev_priv = dev->dev_private;
15395         unsigned reg = INTEL_INFO(dev)->gen >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
15396         u16 gmch_ctrl;
15397
15398         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
15399                 DRM_ERROR("failed to read control word\n");
15400                 return -EIO;
15401         }
15402
15403         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
15404                 return 0;
15405
15406         if (state)
15407                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
15408         else
15409                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
15410
15411         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
15412                 DRM_ERROR("failed to write control word\n");
15413                 return -EIO;
15414         }
15415
15416         return 0;
15417 }
15418
15419 struct intel_display_error_state {
15420
15421         u32 power_well_driver;
15422
15423         int num_transcoders;
15424
15425         struct intel_cursor_error_state {
15426                 u32 control;
15427                 u32 position;
15428                 u32 base;
15429                 u32 size;
15430         } cursor[I915_MAX_PIPES];
15431
15432         struct intel_pipe_error_state {
15433                 bool power_domain_on;
15434                 u32 source;
15435                 u32 stat;
15436         } pipe[I915_MAX_PIPES];
15437
15438         struct intel_plane_error_state {
15439                 u32 control;
15440                 u32 stride;
15441                 u32 size;
15442                 u32 pos;
15443                 u32 addr;
15444                 u32 surface;
15445                 u32 tile_offset;
15446         } plane[I915_MAX_PIPES];
15447
15448         struct intel_transcoder_error_state {
15449                 bool power_domain_on;
15450                 enum transcoder cpu_transcoder;
15451
15452                 u32 conf;
15453
15454                 u32 htotal;
15455                 u32 hblank;
15456                 u32 hsync;
15457                 u32 vtotal;
15458                 u32 vblank;
15459                 u32 vsync;
15460         } transcoder[4];
15461 };
15462
15463 struct intel_display_error_state *
15464 intel_display_capture_error_state(struct drm_device *dev)
15465 {
15466         struct drm_i915_private *dev_priv = dev->dev_private;
15467         struct intel_display_error_state *error;
15468         int transcoders[] = {
15469                 TRANSCODER_A,
15470                 TRANSCODER_B,
15471                 TRANSCODER_C,
15472                 TRANSCODER_EDP,
15473         };
15474         int i;
15475
15476         if (INTEL_INFO(dev)->num_pipes == 0)
15477                 return NULL;
15478
15479         error = kzalloc(sizeof(*error), GFP_ATOMIC);
15480         if (error == NULL)
15481                 return NULL;
15482
15483         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
15484                 error->power_well_driver = I915_READ(HSW_PWR_WELL_DRIVER);
15485
15486         for_each_pipe(dev_priv, i) {
15487                 error->pipe[i].power_domain_on =
15488                         __intel_display_power_is_enabled(dev_priv,
15489                                                          POWER_DOMAIN_PIPE(i));
15490                 if (!error->pipe[i].power_domain_on)
15491                         continue;
15492
15493                 error->cursor[i].control = I915_READ(CURCNTR(i));
15494                 error->cursor[i].position = I915_READ(CURPOS(i));
15495                 error->cursor[i].base = I915_READ(CURBASE(i));
15496
15497                 error->plane[i].control = I915_READ(DSPCNTR(i));
15498                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
15499                 if (INTEL_INFO(dev)->gen <= 3) {
15500                         error->plane[i].size = I915_READ(DSPSIZE(i));
15501                         error->plane[i].pos = I915_READ(DSPPOS(i));
15502                 }
15503                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
15504                         error->plane[i].addr = I915_READ(DSPADDR(i));
15505                 if (INTEL_INFO(dev)->gen >= 4) {
15506                         error->plane[i].surface = I915_READ(DSPSURF(i));
15507                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
15508                 }
15509
15510                 error->pipe[i].source = I915_READ(PIPESRC(i));
15511
15512                 if (HAS_GMCH_DISPLAY(dev))
15513                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
15514         }
15515
15516         error->num_transcoders = INTEL_INFO(dev)->num_pipes;
15517         if (HAS_DDI(dev_priv->dev))
15518                 error->num_transcoders++; /* Account for eDP. */
15519
15520         for (i = 0; i < error->num_transcoders; i++) {
15521                 enum transcoder cpu_transcoder = transcoders[i];
15522
15523                 error->transcoder[i].power_domain_on =
15524                         __intel_display_power_is_enabled(dev_priv,
15525                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
15526                 if (!error->transcoder[i].power_domain_on)
15527                         continue;
15528
15529                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
15530
15531                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
15532                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
15533                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
15534                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
15535                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
15536                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
15537                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
15538         }
15539
15540         return error;
15541 }
15542
15543 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
15544
15545 void
15546 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
15547                                 struct drm_device *dev,
15548                                 struct intel_display_error_state *error)
15549 {
15550         struct drm_i915_private *dev_priv = dev->dev_private;
15551         int i;
15552
15553         if (!error)
15554                 return;
15555
15556         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev)->num_pipes);
15557         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
15558                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
15559                            error->power_well_driver);
15560         for_each_pipe(dev_priv, i) {
15561                 err_printf(m, "Pipe [%d]:\n", i);
15562                 err_printf(m, "  Power: %s\n",
15563                            error->pipe[i].power_domain_on ? "on" : "off");
15564                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
15565                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
15566
15567                 err_printf(m, "Plane [%d]:\n", i);
15568                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
15569                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
15570                 if (INTEL_INFO(dev)->gen <= 3) {
15571                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
15572                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
15573                 }
15574                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
15575                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
15576                 if (INTEL_INFO(dev)->gen >= 4) {
15577                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
15578                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
15579                 }
15580
15581                 err_printf(m, "Cursor [%d]:\n", i);
15582                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
15583                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
15584                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
15585         }
15586
15587         for (i = 0; i < error->num_transcoders; i++) {
15588                 err_printf(m, "CPU transcoder: %c\n",
15589                            transcoder_name(error->transcoder[i].cpu_transcoder));
15590                 err_printf(m, "  Power: %s\n",
15591                            error->transcoder[i].power_domain_on ? "on" : "off");
15592                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
15593                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
15594                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
15595                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
15596                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
15597                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
15598                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
15599         }
15600 }
15601
15602 void intel_modeset_preclose(struct drm_device *dev, struct drm_file *file)
15603 {
15604         struct intel_crtc *crtc;
15605
15606         for_each_intel_crtc(dev, crtc) {
15607                 struct intel_unpin_work *work;
15608
15609                 spin_lock_irq(&dev->event_lock);
15610
15611                 work = crtc->unpin_work;
15612
15613                 if (work && work->event &&
15614                     work->event->base.file_priv == file) {
15615                         kfree(work->event);
15616                         work->event = NULL;
15617                 }
15618
15619                 spin_unlock_irq(&dev->event_lock);
15620         }
15621 }