drm/i915: Move VLV/CHV prepare_pll later
[cascardo/linux.git] / drivers / gpu / drm / i915 / intel_display.c
1 /*
2  * Copyright © 2006-2007 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *      Eric Anholt <eric@anholt.net>
25  */
26
27 #include <linux/dmi.h>
28 #include <linux/module.h>
29 #include <linux/input.h>
30 #include <linux/i2c.h>
31 #include <linux/kernel.h>
32 #include <linux/slab.h>
33 #include <linux/vgaarb.h>
34 #include <drm/drm_edid.h>
35 #include <drm/drmP.h>
36 #include "intel_drv.h"
37 #include <drm/i915_drm.h>
38 #include "i915_drv.h"
39 #include "i915_trace.h"
40 #include <drm/drm_atomic.h>
41 #include <drm/drm_atomic_helper.h>
42 #include <drm/drm_dp_helper.h>
43 #include <drm/drm_crtc_helper.h>
44 #include <drm/drm_plane_helper.h>
45 #include <drm/drm_rect.h>
46 #include <linux/dma_remapping.h>
47
48 /* Primary plane formats for gen <= 3 */
49 static const uint32_t i8xx_primary_formats[] = {
50         DRM_FORMAT_C8,
51         DRM_FORMAT_RGB565,
52         DRM_FORMAT_XRGB1555,
53         DRM_FORMAT_XRGB8888,
54 };
55
56 /* Primary plane formats for gen >= 4 */
57 static const uint32_t i965_primary_formats[] = {
58         DRM_FORMAT_C8,
59         DRM_FORMAT_RGB565,
60         DRM_FORMAT_XRGB8888,
61         DRM_FORMAT_XBGR8888,
62         DRM_FORMAT_XRGB2101010,
63         DRM_FORMAT_XBGR2101010,
64 };
65
66 static const uint32_t skl_primary_formats[] = {
67         DRM_FORMAT_C8,
68         DRM_FORMAT_RGB565,
69         DRM_FORMAT_XRGB8888,
70         DRM_FORMAT_XBGR8888,
71         DRM_FORMAT_ARGB8888,
72         DRM_FORMAT_ABGR8888,
73         DRM_FORMAT_XRGB2101010,
74         DRM_FORMAT_XBGR2101010,
75 };
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 (intel_crtc->config->has_dp_encoder)
6005                 intel_dp_set_m_n(intel_crtc, M1_N1);
6006
6007         intel_set_pipe_timings(intel_crtc);
6008
6009         if (IS_CHERRYVIEW(dev) && pipe == PIPE_B) {
6010                 struct drm_i915_private *dev_priv = dev->dev_private;
6011
6012                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6013                 I915_WRITE(CHV_CANVAS(pipe), 0);
6014         }
6015
6016         i9xx_set_pipeconf(intel_crtc);
6017
6018         intel_crtc->active = true;
6019
6020         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6021
6022         for_each_encoder_on_crtc(dev, crtc, encoder)
6023                 if (encoder->pre_pll_enable)
6024                         encoder->pre_pll_enable(encoder);
6025
6026         if (!is_dsi) {
6027                 if (IS_CHERRYVIEW(dev)) {
6028                         chv_prepare_pll(intel_crtc, intel_crtc->config);
6029                         chv_enable_pll(intel_crtc, intel_crtc->config);
6030                 } else {
6031                         vlv_prepare_pll(intel_crtc, intel_crtc->config);
6032                         vlv_enable_pll(intel_crtc, intel_crtc->config);
6033                 }
6034         }
6035
6036         for_each_encoder_on_crtc(dev, crtc, encoder)
6037                 if (encoder->pre_enable)
6038                         encoder->pre_enable(encoder);
6039
6040         i9xx_pfit_enable(intel_crtc);
6041
6042         intel_crtc_load_lut(crtc);
6043
6044         intel_enable_pipe(intel_crtc);
6045
6046         assert_vblank_disabled(crtc);
6047         drm_crtc_vblank_on(crtc);
6048
6049         for_each_encoder_on_crtc(dev, crtc, encoder)
6050                 encoder->enable(encoder);
6051 }
6052
6053 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
6054 {
6055         struct drm_device *dev = crtc->base.dev;
6056         struct drm_i915_private *dev_priv = dev->dev_private;
6057
6058         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
6059         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
6060 }
6061
6062 static void i9xx_crtc_enable(struct drm_crtc *crtc)
6063 {
6064         struct drm_device *dev = crtc->dev;
6065         struct drm_i915_private *dev_priv = to_i915(dev);
6066         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6067         struct intel_encoder *encoder;
6068         int pipe = intel_crtc->pipe;
6069
6070         if (WARN_ON(intel_crtc->active))
6071                 return;
6072
6073         i9xx_set_pll_dividers(intel_crtc);
6074
6075         if (intel_crtc->config->has_dp_encoder)
6076                 intel_dp_set_m_n(intel_crtc, M1_N1);
6077
6078         intel_set_pipe_timings(intel_crtc);
6079
6080         i9xx_set_pipeconf(intel_crtc);
6081
6082         intel_crtc->active = true;
6083
6084         if (!IS_GEN2(dev))
6085                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6086
6087         for_each_encoder_on_crtc(dev, crtc, encoder)
6088                 if (encoder->pre_enable)
6089                         encoder->pre_enable(encoder);
6090
6091         i9xx_enable_pll(intel_crtc);
6092
6093         i9xx_pfit_enable(intel_crtc);
6094
6095         intel_crtc_load_lut(crtc);
6096
6097         intel_update_watermarks(crtc);
6098         intel_enable_pipe(intel_crtc);
6099
6100         assert_vblank_disabled(crtc);
6101         drm_crtc_vblank_on(crtc);
6102
6103         for_each_encoder_on_crtc(dev, crtc, encoder)
6104                 encoder->enable(encoder);
6105 }
6106
6107 static void i9xx_pfit_disable(struct intel_crtc *crtc)
6108 {
6109         struct drm_device *dev = crtc->base.dev;
6110         struct drm_i915_private *dev_priv = dev->dev_private;
6111
6112         if (!crtc->config->gmch_pfit.control)
6113                 return;
6114
6115         assert_pipe_disabled(dev_priv, crtc->pipe);
6116
6117         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
6118                          I915_READ(PFIT_CONTROL));
6119         I915_WRITE(PFIT_CONTROL, 0);
6120 }
6121
6122 static void i9xx_crtc_disable(struct drm_crtc *crtc)
6123 {
6124         struct drm_device *dev = crtc->dev;
6125         struct drm_i915_private *dev_priv = dev->dev_private;
6126         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6127         struct intel_encoder *encoder;
6128         int pipe = intel_crtc->pipe;
6129
6130         /*
6131          * On gen2 planes are double buffered but the pipe isn't, so we must
6132          * wait for planes to fully turn off before disabling the pipe.
6133          * We also need to wait on all gmch platforms because of the
6134          * self-refresh mode constraint explained above.
6135          */
6136         intel_wait_for_vblank(dev, pipe);
6137
6138         for_each_encoder_on_crtc(dev, crtc, encoder)
6139                 encoder->disable(encoder);
6140
6141         drm_crtc_vblank_off(crtc);
6142         assert_vblank_disabled(crtc);
6143
6144         intel_disable_pipe(intel_crtc);
6145
6146         i9xx_pfit_disable(intel_crtc);
6147
6148         for_each_encoder_on_crtc(dev, crtc, encoder)
6149                 if (encoder->post_disable)
6150                         encoder->post_disable(encoder);
6151
6152         if (!intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_DSI)) {
6153                 if (IS_CHERRYVIEW(dev))
6154                         chv_disable_pll(dev_priv, pipe);
6155                 else if (IS_VALLEYVIEW(dev))
6156                         vlv_disable_pll(dev_priv, pipe);
6157                 else
6158                         i9xx_disable_pll(intel_crtc);
6159         }
6160
6161         for_each_encoder_on_crtc(dev, crtc, encoder)
6162                 if (encoder->post_pll_disable)
6163                         encoder->post_pll_disable(encoder);
6164
6165         if (!IS_GEN2(dev))
6166                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6167
6168         intel_crtc->active = false;
6169         intel_update_watermarks(crtc);
6170 }
6171
6172 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc)
6173 {
6174         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6175         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6176         enum intel_display_power_domain domain;
6177         unsigned long domains;
6178
6179         if (!intel_crtc->active)
6180                 return;
6181
6182         if (to_intel_plane_state(crtc->primary->state)->visible) {
6183                 intel_crtc_wait_for_pending_flips(crtc);
6184                 intel_pre_disable_primary(crtc);
6185         }
6186
6187         intel_crtc_disable_planes(crtc, crtc->state->plane_mask);
6188         dev_priv->display.crtc_disable(crtc);
6189         intel_disable_shared_dpll(intel_crtc);
6190
6191         domains = intel_crtc->enabled_power_domains;
6192         for_each_power_domain(domain, domains)
6193                 intel_display_power_put(dev_priv, domain);
6194         intel_crtc->enabled_power_domains = 0;
6195 }
6196
6197 /*
6198  * turn all crtc's off, but do not adjust state
6199  * This has to be paired with a call to intel_modeset_setup_hw_state.
6200  */
6201 int intel_display_suspend(struct drm_device *dev)
6202 {
6203         struct drm_mode_config *config = &dev->mode_config;
6204         struct drm_modeset_acquire_ctx *ctx = config->acquire_ctx;
6205         struct drm_atomic_state *state;
6206         struct drm_crtc *crtc;
6207         unsigned crtc_mask = 0;
6208         int ret = 0;
6209
6210         if (WARN_ON(!ctx))
6211                 return 0;
6212
6213         lockdep_assert_held(&ctx->ww_ctx);
6214         state = drm_atomic_state_alloc(dev);
6215         if (WARN_ON(!state))
6216                 return -ENOMEM;
6217
6218         state->acquire_ctx = ctx;
6219         state->allow_modeset = true;
6220
6221         for_each_crtc(dev, crtc) {
6222                 struct drm_crtc_state *crtc_state =
6223                         drm_atomic_get_crtc_state(state, crtc);
6224
6225                 ret = PTR_ERR_OR_ZERO(crtc_state);
6226                 if (ret)
6227                         goto free;
6228
6229                 if (!crtc_state->active)
6230                         continue;
6231
6232                 crtc_state->active = false;
6233                 crtc_mask |= 1 << drm_crtc_index(crtc);
6234         }
6235
6236         if (crtc_mask) {
6237                 ret = drm_atomic_commit(state);
6238
6239                 if (!ret) {
6240                         for_each_crtc(dev, crtc)
6241                                 if (crtc_mask & (1 << drm_crtc_index(crtc)))
6242                                         crtc->state->active = true;
6243
6244                         return ret;
6245                 }
6246         }
6247
6248 free:
6249         if (ret)
6250                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6251         drm_atomic_state_free(state);
6252         return ret;
6253 }
6254
6255 void intel_encoder_destroy(struct drm_encoder *encoder)
6256 {
6257         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6258
6259         drm_encoder_cleanup(encoder);
6260         kfree(intel_encoder);
6261 }
6262
6263 /* Cross check the actual hw state with our own modeset state tracking (and it's
6264  * internal consistency). */
6265 static void intel_connector_check_state(struct intel_connector *connector)
6266 {
6267         struct drm_crtc *crtc = connector->base.state->crtc;
6268
6269         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6270                       connector->base.base.id,
6271                       connector->base.name);
6272
6273         if (connector->get_hw_state(connector)) {
6274                 struct drm_encoder *encoder = &connector->encoder->base;
6275                 struct drm_connector_state *conn_state = connector->base.state;
6276
6277                 I915_STATE_WARN(!crtc,
6278                          "connector enabled without attached crtc\n");
6279
6280                 if (!crtc)
6281                         return;
6282
6283                 I915_STATE_WARN(!crtc->state->active,
6284                       "connector is active, but attached crtc isn't\n");
6285
6286                 if (!encoder)
6287                         return;
6288
6289                 I915_STATE_WARN(conn_state->best_encoder != encoder,
6290                         "atomic encoder doesn't match attached encoder\n");
6291
6292                 I915_STATE_WARN(conn_state->crtc != encoder->crtc,
6293                         "attached encoder crtc differs from connector crtc\n");
6294         } else {
6295                 I915_STATE_WARN(crtc && crtc->state->active,
6296                         "attached crtc is active, but connector isn't\n");
6297                 I915_STATE_WARN(!crtc && connector->base.state->best_encoder,
6298                         "best encoder set without crtc!\n");
6299         }
6300 }
6301
6302 int intel_connector_init(struct intel_connector *connector)
6303 {
6304         struct drm_connector_state *connector_state;
6305
6306         connector_state = kzalloc(sizeof *connector_state, GFP_KERNEL);
6307         if (!connector_state)
6308                 return -ENOMEM;
6309
6310         connector->base.state = connector_state;
6311         return 0;
6312 }
6313
6314 struct intel_connector *intel_connector_alloc(void)
6315 {
6316         struct intel_connector *connector;
6317
6318         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6319         if (!connector)
6320                 return NULL;
6321
6322         if (intel_connector_init(connector) < 0) {
6323                 kfree(connector);
6324                 return NULL;
6325         }
6326
6327         return connector;
6328 }
6329
6330 /* Simple connector->get_hw_state implementation for encoders that support only
6331  * one connector and no cloning and hence the encoder state determines the state
6332  * of the connector. */
6333 bool intel_connector_get_hw_state(struct intel_connector *connector)
6334 {
6335         enum pipe pipe = 0;
6336         struct intel_encoder *encoder = connector->encoder;
6337
6338         return encoder->get_hw_state(encoder, &pipe);
6339 }
6340
6341 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6342 {
6343         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6344                 return crtc_state->fdi_lanes;
6345
6346         return 0;
6347 }
6348
6349 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6350                                      struct intel_crtc_state *pipe_config)
6351 {
6352         struct drm_atomic_state *state = pipe_config->base.state;
6353         struct intel_crtc *other_crtc;
6354         struct intel_crtc_state *other_crtc_state;
6355
6356         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6357                       pipe_name(pipe), pipe_config->fdi_lanes);
6358         if (pipe_config->fdi_lanes > 4) {
6359                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6360                               pipe_name(pipe), pipe_config->fdi_lanes);
6361                 return -EINVAL;
6362         }
6363
6364         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
6365                 if (pipe_config->fdi_lanes > 2) {
6366                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6367                                       pipe_config->fdi_lanes);
6368                         return -EINVAL;
6369                 } else {
6370                         return 0;
6371                 }
6372         }
6373
6374         if (INTEL_INFO(dev)->num_pipes == 2)
6375                 return 0;
6376
6377         /* Ivybridge 3 pipe is really complicated */
6378         switch (pipe) {
6379         case PIPE_A:
6380                 return 0;
6381         case PIPE_B:
6382                 if (pipe_config->fdi_lanes <= 2)
6383                         return 0;
6384
6385                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_C));
6386                 other_crtc_state =
6387                         intel_atomic_get_crtc_state(state, other_crtc);
6388                 if (IS_ERR(other_crtc_state))
6389                         return PTR_ERR(other_crtc_state);
6390
6391                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6392                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6393                                       pipe_name(pipe), pipe_config->fdi_lanes);
6394                         return -EINVAL;
6395                 }
6396                 return 0;
6397         case PIPE_C:
6398                 if (pipe_config->fdi_lanes > 2) {
6399                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6400                                       pipe_name(pipe), pipe_config->fdi_lanes);
6401                         return -EINVAL;
6402                 }
6403
6404                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_B));
6405                 other_crtc_state =
6406                         intel_atomic_get_crtc_state(state, other_crtc);
6407                 if (IS_ERR(other_crtc_state))
6408                         return PTR_ERR(other_crtc_state);
6409
6410                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6411                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6412                         return -EINVAL;
6413                 }
6414                 return 0;
6415         default:
6416                 BUG();
6417         }
6418 }
6419
6420 #define RETRY 1
6421 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6422                                        struct intel_crtc_state *pipe_config)
6423 {
6424         struct drm_device *dev = intel_crtc->base.dev;
6425         struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6426         int lane, link_bw, fdi_dotclock, ret;
6427         bool needs_recompute = false;
6428
6429 retry:
6430         /* FDI is a binary signal running at ~2.7GHz, encoding
6431          * each output octet as 10 bits. The actual frequency
6432          * is stored as a divider into a 100MHz clock, and the
6433          * mode pixel clock is stored in units of 1KHz.
6434          * Hence the bw of each lane in terms of the mode signal
6435          * is:
6436          */
6437         link_bw = intel_fdi_link_freq(dev) * MHz(100)/KHz(1)/10;
6438
6439         fdi_dotclock = adjusted_mode->crtc_clock;
6440
6441         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6442                                            pipe_config->pipe_bpp);
6443
6444         pipe_config->fdi_lanes = lane;
6445
6446         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6447                                link_bw, &pipe_config->fdi_m_n);
6448
6449         ret = ironlake_check_fdi_lanes(intel_crtc->base.dev,
6450                                        intel_crtc->pipe, pipe_config);
6451         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6452                 pipe_config->pipe_bpp -= 2*3;
6453                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6454                               pipe_config->pipe_bpp);
6455                 needs_recompute = true;
6456                 pipe_config->bw_constrained = true;
6457
6458                 goto retry;
6459         }
6460
6461         if (needs_recompute)
6462                 return RETRY;
6463
6464         return ret;
6465 }
6466
6467 static bool pipe_config_supports_ips(struct drm_i915_private *dev_priv,
6468                                      struct intel_crtc_state *pipe_config)
6469 {
6470         if (pipe_config->pipe_bpp > 24)
6471                 return false;
6472
6473         /* HSW can handle pixel rate up to cdclk? */
6474         if (IS_HASWELL(dev_priv->dev))
6475                 return true;
6476
6477         /*
6478          * We compare against max which means we must take
6479          * the increased cdclk requirement into account when
6480          * calculating the new cdclk.
6481          *
6482          * Should measure whether using a lower cdclk w/o IPS
6483          */
6484         return ilk_pipe_pixel_rate(pipe_config) <=
6485                 dev_priv->max_cdclk_freq * 95 / 100;
6486 }
6487
6488 static void hsw_compute_ips_config(struct intel_crtc *crtc,
6489                                    struct intel_crtc_state *pipe_config)
6490 {
6491         struct drm_device *dev = crtc->base.dev;
6492         struct drm_i915_private *dev_priv = dev->dev_private;
6493
6494         pipe_config->ips_enabled = i915.enable_ips &&
6495                 hsw_crtc_supports_ips(crtc) &&
6496                 pipe_config_supports_ips(dev_priv, pipe_config);
6497 }
6498
6499 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6500                                      struct intel_crtc_state *pipe_config)
6501 {
6502         struct drm_device *dev = crtc->base.dev;
6503         struct drm_i915_private *dev_priv = dev->dev_private;
6504         struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6505
6506         /* FIXME should check pixel clock limits on all platforms */
6507         if (INTEL_INFO(dev)->gen < 4) {
6508                 int clock_limit = dev_priv->max_cdclk_freq;
6509
6510                 /*
6511                  * Enable pixel doubling when the dot clock
6512                  * is > 90% of the (display) core speed.
6513                  *
6514                  * GDG double wide on either pipe,
6515                  * otherwise pipe A only.
6516                  */
6517                 if ((crtc->pipe == PIPE_A || IS_I915G(dev)) &&
6518                     adjusted_mode->crtc_clock > clock_limit * 9 / 10) {
6519                         clock_limit *= 2;
6520                         pipe_config->double_wide = true;
6521                 }
6522
6523                 if (adjusted_mode->crtc_clock > clock_limit * 9 / 10)
6524                         return -EINVAL;
6525         }
6526
6527         /*
6528          * Pipe horizontal size must be even in:
6529          * - DVO ganged mode
6530          * - LVDS dual channel mode
6531          * - Double wide pipe
6532          */
6533         if ((intel_pipe_will_have_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6534              intel_is_dual_link_lvds(dev)) || pipe_config->double_wide)
6535                 pipe_config->pipe_src_w &= ~1;
6536
6537         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6538          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6539          */
6540         if ((INTEL_INFO(dev)->gen > 4 || IS_G4X(dev)) &&
6541                 adjusted_mode->hsync_start == adjusted_mode->hdisplay)
6542                 return -EINVAL;
6543
6544         if (HAS_IPS(dev))
6545                 hsw_compute_ips_config(crtc, pipe_config);
6546
6547         if (pipe_config->has_pch_encoder)
6548                 return ironlake_fdi_compute_config(crtc, pipe_config);
6549
6550         return 0;
6551 }
6552
6553 static int skylake_get_display_clock_speed(struct drm_device *dev)
6554 {
6555         struct drm_i915_private *dev_priv = to_i915(dev);
6556         uint32_t lcpll1 = I915_READ(LCPLL1_CTL);
6557         uint32_t cdctl = I915_READ(CDCLK_CTL);
6558         uint32_t linkrate;
6559
6560         if (!(lcpll1 & LCPLL_PLL_ENABLE))
6561                 return 24000; /* 24MHz is the cd freq with NSSC ref */
6562
6563         if ((cdctl & CDCLK_FREQ_SEL_MASK) == CDCLK_FREQ_540)
6564                 return 540000;
6565
6566         linkrate = (I915_READ(DPLL_CTRL1) &
6567                     DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0)) >> 1;
6568
6569         if (linkrate == DPLL_CTRL1_LINK_RATE_2160 ||
6570             linkrate == DPLL_CTRL1_LINK_RATE_1080) {
6571                 /* vco 8640 */
6572                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6573                 case CDCLK_FREQ_450_432:
6574                         return 432000;
6575                 case CDCLK_FREQ_337_308:
6576                         return 308570;
6577                 case CDCLK_FREQ_675_617:
6578                         return 617140;
6579                 default:
6580                         WARN(1, "Unknown cd freq selection\n");
6581                 }
6582         } else {
6583                 /* vco 8100 */
6584                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6585                 case CDCLK_FREQ_450_432:
6586                         return 450000;
6587                 case CDCLK_FREQ_337_308:
6588                         return 337500;
6589                 case CDCLK_FREQ_675_617:
6590                         return 675000;
6591                 default:
6592                         WARN(1, "Unknown cd freq selection\n");
6593                 }
6594         }
6595
6596         /* error case, do as if DPLL0 isn't enabled */
6597         return 24000;
6598 }
6599
6600 static int broxton_get_display_clock_speed(struct drm_device *dev)
6601 {
6602         struct drm_i915_private *dev_priv = to_i915(dev);
6603         uint32_t cdctl = I915_READ(CDCLK_CTL);
6604         uint32_t pll_ratio = I915_READ(BXT_DE_PLL_CTL) & BXT_DE_PLL_RATIO_MASK;
6605         uint32_t pll_enab = I915_READ(BXT_DE_PLL_ENABLE);
6606         int cdclk;
6607
6608         if (!(pll_enab & BXT_DE_PLL_PLL_ENABLE))
6609                 return 19200;
6610
6611         cdclk = 19200 * pll_ratio / 2;
6612
6613         switch (cdctl & BXT_CDCLK_CD2X_DIV_SEL_MASK) {
6614         case BXT_CDCLK_CD2X_DIV_SEL_1:
6615                 return cdclk;  /* 576MHz or 624MHz */
6616         case BXT_CDCLK_CD2X_DIV_SEL_1_5:
6617                 return cdclk * 2 / 3; /* 384MHz */
6618         case BXT_CDCLK_CD2X_DIV_SEL_2:
6619                 return cdclk / 2; /* 288MHz */
6620         case BXT_CDCLK_CD2X_DIV_SEL_4:
6621                 return cdclk / 4; /* 144MHz */
6622         }
6623
6624         /* error case, do as if DE PLL isn't enabled */
6625         return 19200;
6626 }
6627
6628 static int broadwell_get_display_clock_speed(struct drm_device *dev)
6629 {
6630         struct drm_i915_private *dev_priv = dev->dev_private;
6631         uint32_t lcpll = I915_READ(LCPLL_CTL);
6632         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6633
6634         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6635                 return 800000;
6636         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6637                 return 450000;
6638         else if (freq == LCPLL_CLK_FREQ_450)
6639                 return 450000;
6640         else if (freq == LCPLL_CLK_FREQ_54O_BDW)
6641                 return 540000;
6642         else if (freq == LCPLL_CLK_FREQ_337_5_BDW)
6643                 return 337500;
6644         else
6645                 return 675000;
6646 }
6647
6648 static int haswell_get_display_clock_speed(struct drm_device *dev)
6649 {
6650         struct drm_i915_private *dev_priv = dev->dev_private;
6651         uint32_t lcpll = I915_READ(LCPLL_CTL);
6652         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6653
6654         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6655                 return 800000;
6656         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6657                 return 450000;
6658         else if (freq == LCPLL_CLK_FREQ_450)
6659                 return 450000;
6660         else if (IS_HSW_ULT(dev))
6661                 return 337500;
6662         else
6663                 return 540000;
6664 }
6665
6666 static int valleyview_get_display_clock_speed(struct drm_device *dev)
6667 {
6668         struct drm_i915_private *dev_priv = dev->dev_private;
6669         u32 val;
6670         int divider;
6671
6672         if (dev_priv->hpll_freq == 0)
6673                 dev_priv->hpll_freq = valleyview_get_vco(dev_priv);
6674
6675         mutex_lock(&dev_priv->sb_lock);
6676         val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
6677         mutex_unlock(&dev_priv->sb_lock);
6678
6679         divider = val & DISPLAY_FREQUENCY_VALUES;
6680
6681         WARN((val & DISPLAY_FREQUENCY_STATUS) !=
6682              (divider << DISPLAY_FREQUENCY_STATUS_SHIFT),
6683              "cdclk change in progress\n");
6684
6685         return DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, divider + 1);
6686 }
6687
6688 static int ilk_get_display_clock_speed(struct drm_device *dev)
6689 {
6690         return 450000;
6691 }
6692
6693 static int i945_get_display_clock_speed(struct drm_device *dev)
6694 {
6695         return 400000;
6696 }
6697
6698 static int i915_get_display_clock_speed(struct drm_device *dev)
6699 {
6700         return 333333;
6701 }
6702
6703 static int i9xx_misc_get_display_clock_speed(struct drm_device *dev)
6704 {
6705         return 200000;
6706 }
6707
6708 static int pnv_get_display_clock_speed(struct drm_device *dev)
6709 {
6710         u16 gcfgc = 0;
6711
6712         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6713
6714         switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6715         case GC_DISPLAY_CLOCK_267_MHZ_PNV:
6716                 return 266667;
6717         case GC_DISPLAY_CLOCK_333_MHZ_PNV:
6718                 return 333333;
6719         case GC_DISPLAY_CLOCK_444_MHZ_PNV:
6720                 return 444444;
6721         case GC_DISPLAY_CLOCK_200_MHZ_PNV:
6722                 return 200000;
6723         default:
6724                 DRM_ERROR("Unknown pnv display core clock 0x%04x\n", gcfgc);
6725         case GC_DISPLAY_CLOCK_133_MHZ_PNV:
6726                 return 133333;
6727         case GC_DISPLAY_CLOCK_167_MHZ_PNV:
6728                 return 166667;
6729         }
6730 }
6731
6732 static int i915gm_get_display_clock_speed(struct drm_device *dev)
6733 {
6734         u16 gcfgc = 0;
6735
6736         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6737
6738         if (gcfgc & GC_LOW_FREQUENCY_ENABLE)
6739                 return 133333;
6740         else {
6741                 switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6742                 case GC_DISPLAY_CLOCK_333_MHZ:
6743                         return 333333;
6744                 default:
6745                 case GC_DISPLAY_CLOCK_190_200_MHZ:
6746                         return 190000;
6747                 }
6748         }
6749 }
6750
6751 static int i865_get_display_clock_speed(struct drm_device *dev)
6752 {
6753         return 266667;
6754 }
6755
6756 static int i85x_get_display_clock_speed(struct drm_device *dev)
6757 {
6758         u16 hpllcc = 0;
6759
6760         /*
6761          * 852GM/852GMV only supports 133 MHz and the HPLLCC
6762          * encoding is different :(
6763          * FIXME is this the right way to detect 852GM/852GMV?
6764          */
6765         if (dev->pdev->revision == 0x1)
6766                 return 133333;
6767
6768         pci_bus_read_config_word(dev->pdev->bus,
6769                                  PCI_DEVFN(0, 3), HPLLCC, &hpllcc);
6770
6771         /* Assume that the hardware is in the high speed state.  This
6772          * should be the default.
6773          */
6774         switch (hpllcc & GC_CLOCK_CONTROL_MASK) {
6775         case GC_CLOCK_133_200:
6776         case GC_CLOCK_133_200_2:
6777         case GC_CLOCK_100_200:
6778                 return 200000;
6779         case GC_CLOCK_166_250:
6780                 return 250000;
6781         case GC_CLOCK_100_133:
6782                 return 133333;
6783         case GC_CLOCK_133_266:
6784         case GC_CLOCK_133_266_2:
6785         case GC_CLOCK_166_266:
6786                 return 266667;
6787         }
6788
6789         /* Shouldn't happen */
6790         return 0;
6791 }
6792
6793 static int i830_get_display_clock_speed(struct drm_device *dev)
6794 {
6795         return 133333;
6796 }
6797
6798 static unsigned int intel_hpll_vco(struct drm_device *dev)
6799 {
6800         struct drm_i915_private *dev_priv = dev->dev_private;
6801         static const unsigned int blb_vco[8] = {
6802                 [0] = 3200000,
6803                 [1] = 4000000,
6804                 [2] = 5333333,
6805                 [3] = 4800000,
6806                 [4] = 6400000,
6807         };
6808         static const unsigned int pnv_vco[8] = {
6809                 [0] = 3200000,
6810                 [1] = 4000000,
6811                 [2] = 5333333,
6812                 [3] = 4800000,
6813                 [4] = 2666667,
6814         };
6815         static const unsigned int cl_vco[8] = {
6816                 [0] = 3200000,
6817                 [1] = 4000000,
6818                 [2] = 5333333,
6819                 [3] = 6400000,
6820                 [4] = 3333333,
6821                 [5] = 3566667,
6822                 [6] = 4266667,
6823         };
6824         static const unsigned int elk_vco[8] = {
6825                 [0] = 3200000,
6826                 [1] = 4000000,
6827                 [2] = 5333333,
6828                 [3] = 4800000,
6829         };
6830         static const unsigned int ctg_vco[8] = {
6831                 [0] = 3200000,
6832                 [1] = 4000000,
6833                 [2] = 5333333,
6834                 [3] = 6400000,
6835                 [4] = 2666667,
6836                 [5] = 4266667,
6837         };
6838         const unsigned int *vco_table;
6839         unsigned int vco;
6840         uint8_t tmp = 0;
6841
6842         /* FIXME other chipsets? */
6843         if (IS_GM45(dev))
6844                 vco_table = ctg_vco;
6845         else if (IS_G4X(dev))
6846                 vco_table = elk_vco;
6847         else if (IS_CRESTLINE(dev))
6848                 vco_table = cl_vco;
6849         else if (IS_PINEVIEW(dev))
6850                 vco_table = pnv_vco;
6851         else if (IS_G33(dev))
6852                 vco_table = blb_vco;
6853         else
6854                 return 0;
6855
6856         tmp = I915_READ(IS_MOBILE(dev) ? HPLLVCO_MOBILE : HPLLVCO);
6857
6858         vco = vco_table[tmp & 0x7];
6859         if (vco == 0)
6860                 DRM_ERROR("Bad HPLL VCO (HPLLVCO=0x%02x)\n", tmp);
6861         else
6862                 DRM_DEBUG_KMS("HPLL VCO %u kHz\n", vco);
6863
6864         return vco;
6865 }
6866
6867 static int gm45_get_display_clock_speed(struct drm_device *dev)
6868 {
6869         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
6870         uint16_t tmp = 0;
6871
6872         pci_read_config_word(dev->pdev, GCFGC, &tmp);
6873
6874         cdclk_sel = (tmp >> 12) & 0x1;
6875
6876         switch (vco) {
6877         case 2666667:
6878         case 4000000:
6879         case 5333333:
6880                 return cdclk_sel ? 333333 : 222222;
6881         case 3200000:
6882                 return cdclk_sel ? 320000 : 228571;
6883         default:
6884                 DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u, CFGC=0x%04x\n", vco, tmp);
6885                 return 222222;
6886         }
6887 }
6888
6889 static int i965gm_get_display_clock_speed(struct drm_device *dev)
6890 {
6891         static const uint8_t div_3200[] = { 16, 10,  8 };
6892         static const uint8_t div_4000[] = { 20, 12, 10 };
6893         static const uint8_t div_5333[] = { 24, 16, 14 };
6894         const uint8_t *div_table;
6895         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
6896         uint16_t tmp = 0;
6897
6898         pci_read_config_word(dev->pdev, GCFGC, &tmp);
6899
6900         cdclk_sel = ((tmp >> 8) & 0x1f) - 1;
6901
6902         if (cdclk_sel >= ARRAY_SIZE(div_3200))
6903                 goto fail;
6904
6905         switch (vco) {
6906         case 3200000:
6907                 div_table = div_3200;
6908                 break;
6909         case 4000000:
6910                 div_table = div_4000;
6911                 break;
6912         case 5333333:
6913                 div_table = div_5333;
6914                 break;
6915         default:
6916                 goto fail;
6917         }
6918
6919         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
6920
6921 fail:
6922         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%04x\n", vco, tmp);
6923         return 200000;
6924 }
6925
6926 static int g33_get_display_clock_speed(struct drm_device *dev)
6927 {
6928         static const uint8_t div_3200[] = { 12, 10,  8,  7, 5, 16 };
6929         static const uint8_t div_4000[] = { 14, 12, 10,  8, 6, 20 };
6930         static const uint8_t div_4800[] = { 20, 14, 12, 10, 8, 24 };
6931         static const uint8_t div_5333[] = { 20, 16, 12, 12, 8, 28 };
6932         const uint8_t *div_table;
6933         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
6934         uint16_t tmp = 0;
6935
6936         pci_read_config_word(dev->pdev, GCFGC, &tmp);
6937
6938         cdclk_sel = (tmp >> 4) & 0x7;
6939
6940         if (cdclk_sel >= ARRAY_SIZE(div_3200))
6941                 goto fail;
6942
6943         switch (vco) {
6944         case 3200000:
6945                 div_table = div_3200;
6946                 break;
6947         case 4000000:
6948                 div_table = div_4000;
6949                 break;
6950         case 4800000:
6951                 div_table = div_4800;
6952                 break;
6953         case 5333333:
6954                 div_table = div_5333;
6955                 break;
6956         default:
6957                 goto fail;
6958         }
6959
6960         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
6961
6962 fail:
6963         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%08x\n", vco, tmp);
6964         return 190476;
6965 }
6966
6967 static void
6968 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
6969 {
6970         while (*num > DATA_LINK_M_N_MASK ||
6971                *den > DATA_LINK_M_N_MASK) {
6972                 *num >>= 1;
6973                 *den >>= 1;
6974         }
6975 }
6976
6977 static void compute_m_n(unsigned int m, unsigned int n,
6978                         uint32_t *ret_m, uint32_t *ret_n)
6979 {
6980         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
6981         *ret_m = div_u64((uint64_t) m * *ret_n, n);
6982         intel_reduce_m_n_ratio(ret_m, ret_n);
6983 }
6984
6985 void
6986 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
6987                        int pixel_clock, int link_clock,
6988                        struct intel_link_m_n *m_n)
6989 {
6990         m_n->tu = 64;
6991
6992         compute_m_n(bits_per_pixel * pixel_clock,
6993                     link_clock * nlanes * 8,
6994                     &m_n->gmch_m, &m_n->gmch_n);
6995
6996         compute_m_n(pixel_clock, link_clock,
6997                     &m_n->link_m, &m_n->link_n);
6998 }
6999
7000 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
7001 {
7002         if (i915.panel_use_ssc >= 0)
7003                 return i915.panel_use_ssc != 0;
7004         return dev_priv->vbt.lvds_use_ssc
7005                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
7006 }
7007
7008 static int i9xx_get_refclk(const struct intel_crtc_state *crtc_state,
7009                            int num_connectors)
7010 {
7011         struct drm_device *dev = crtc_state->base.crtc->dev;
7012         struct drm_i915_private *dev_priv = dev->dev_private;
7013         int refclk;
7014
7015         WARN_ON(!crtc_state->base.state);
7016
7017         if (IS_VALLEYVIEW(dev) || IS_BROXTON(dev)) {
7018                 refclk = 100000;
7019         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7020             intel_panel_use_ssc(dev_priv) && num_connectors < 2) {
7021                 refclk = dev_priv->vbt.lvds_ssc_freq;
7022                 DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7023         } else if (!IS_GEN2(dev)) {
7024                 refclk = 96000;
7025         } else {
7026                 refclk = 48000;
7027         }
7028
7029         return refclk;
7030 }
7031
7032 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
7033 {
7034         return (1 << dpll->n) << 16 | dpll->m2;
7035 }
7036
7037 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
7038 {
7039         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
7040 }
7041
7042 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
7043                                      struct intel_crtc_state *crtc_state,
7044                                      intel_clock_t *reduced_clock)
7045 {
7046         struct drm_device *dev = crtc->base.dev;
7047         u32 fp, fp2 = 0;
7048
7049         if (IS_PINEVIEW(dev)) {
7050                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
7051                 if (reduced_clock)
7052                         fp2 = pnv_dpll_compute_fp(reduced_clock);
7053         } else {
7054                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
7055                 if (reduced_clock)
7056                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
7057         }
7058
7059         crtc_state->dpll_hw_state.fp0 = fp;
7060
7061         crtc->lowfreq_avail = false;
7062         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7063             reduced_clock) {
7064                 crtc_state->dpll_hw_state.fp1 = fp2;
7065                 crtc->lowfreq_avail = true;
7066         } else {
7067                 crtc_state->dpll_hw_state.fp1 = fp;
7068         }
7069 }
7070
7071 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
7072                 pipe)
7073 {
7074         u32 reg_val;
7075
7076         /*
7077          * PLLB opamp always calibrates to max value of 0x3f, force enable it
7078          * and set it to a reasonable value instead.
7079          */
7080         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7081         reg_val &= 0xffffff00;
7082         reg_val |= 0x00000030;
7083         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7084
7085         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7086         reg_val &= 0x8cffffff;
7087         reg_val = 0x8c000000;
7088         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7089
7090         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7091         reg_val &= 0xffffff00;
7092         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7093
7094         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7095         reg_val &= 0x00ffffff;
7096         reg_val |= 0xb0000000;
7097         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7098 }
7099
7100 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
7101                                          struct intel_link_m_n *m_n)
7102 {
7103         struct drm_device *dev = crtc->base.dev;
7104         struct drm_i915_private *dev_priv = dev->dev_private;
7105         int pipe = crtc->pipe;
7106
7107         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7108         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
7109         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
7110         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
7111 }
7112
7113 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
7114                                          struct intel_link_m_n *m_n,
7115                                          struct intel_link_m_n *m2_n2)
7116 {
7117         struct drm_device *dev = crtc->base.dev;
7118         struct drm_i915_private *dev_priv = dev->dev_private;
7119         int pipe = crtc->pipe;
7120         enum transcoder transcoder = crtc->config->cpu_transcoder;
7121
7122         if (INTEL_INFO(dev)->gen >= 5) {
7123                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
7124                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
7125                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
7126                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
7127                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
7128                  * for gen < 8) and if DRRS is supported (to make sure the
7129                  * registers are not unnecessarily accessed).
7130                  */
7131                 if (m2_n2 && (IS_CHERRYVIEW(dev) || INTEL_INFO(dev)->gen < 8) &&
7132                         crtc->config->has_drrs) {
7133                         I915_WRITE(PIPE_DATA_M2(transcoder),
7134                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
7135                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
7136                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
7137                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
7138                 }
7139         } else {
7140                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7141                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
7142                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
7143                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
7144         }
7145 }
7146
7147 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
7148 {
7149         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
7150
7151         if (m_n == M1_N1) {
7152                 dp_m_n = &crtc->config->dp_m_n;
7153                 dp_m2_n2 = &crtc->config->dp_m2_n2;
7154         } else if (m_n == M2_N2) {
7155
7156                 /*
7157                  * M2_N2 registers are not supported. Hence m2_n2 divider value
7158                  * needs to be programmed into M1_N1.
7159                  */
7160                 dp_m_n = &crtc->config->dp_m2_n2;
7161         } else {
7162                 DRM_ERROR("Unsupported divider value\n");
7163                 return;
7164         }
7165
7166         if (crtc->config->has_pch_encoder)
7167                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
7168         else
7169                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
7170 }
7171
7172 static void vlv_compute_dpll(struct intel_crtc *crtc,
7173                              struct intel_crtc_state *pipe_config)
7174 {
7175         u32 dpll, dpll_md;
7176
7177         /*
7178          * Enable DPIO clock input. We should never disable the reference
7179          * clock for pipe B, since VGA hotplug / manual detection depends
7180          * on it.
7181          */
7182         dpll = DPLL_EXT_BUFFER_ENABLE_VLV | DPLL_REF_CLK_ENABLE_VLV |
7183                 DPLL_VGA_MODE_DIS | DPLL_INTEGRATED_REF_CLK_VLV;
7184         /* We should never disable this, set it here for state tracking */
7185         if (crtc->pipe == PIPE_B)
7186                 dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7187         dpll |= DPLL_VCO_ENABLE;
7188         pipe_config->dpll_hw_state.dpll = dpll;
7189
7190         dpll_md = (pipe_config->pixel_multiplier - 1)
7191                 << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7192         pipe_config->dpll_hw_state.dpll_md = dpll_md;
7193 }
7194
7195 static void vlv_prepare_pll(struct intel_crtc *crtc,
7196                             const struct intel_crtc_state *pipe_config)
7197 {
7198         struct drm_device *dev = crtc->base.dev;
7199         struct drm_i915_private *dev_priv = dev->dev_private;
7200         int pipe = crtc->pipe;
7201         u32 mdiv;
7202         u32 bestn, bestm1, bestm2, bestp1, bestp2;
7203         u32 coreclk, reg_val;
7204
7205         mutex_lock(&dev_priv->sb_lock);
7206
7207         bestn = pipe_config->dpll.n;
7208         bestm1 = pipe_config->dpll.m1;
7209         bestm2 = pipe_config->dpll.m2;
7210         bestp1 = pipe_config->dpll.p1;
7211         bestp2 = pipe_config->dpll.p2;
7212
7213         /* See eDP HDMI DPIO driver vbios notes doc */
7214
7215         /* PLL B needs special handling */
7216         if (pipe == PIPE_B)
7217                 vlv_pllb_recal_opamp(dev_priv, pipe);
7218
7219         /* Set up Tx target for periodic Rcomp update */
7220         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
7221
7222         /* Disable target IRef on PLL */
7223         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
7224         reg_val &= 0x00ffffff;
7225         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
7226
7227         /* Disable fast lock */
7228         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
7229
7230         /* Set idtafcrecal before PLL is enabled */
7231         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
7232         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
7233         mdiv |= ((bestn << DPIO_N_SHIFT));
7234         mdiv |= (1 << DPIO_K_SHIFT);
7235
7236         /*
7237          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
7238          * but we don't support that).
7239          * Note: don't use the DAC post divider as it seems unstable.
7240          */
7241         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
7242         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7243
7244         mdiv |= DPIO_ENABLE_CALIBRATION;
7245         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7246
7247         /* Set HBR and RBR LPF coefficients */
7248         if (pipe_config->port_clock == 162000 ||
7249             intel_pipe_has_type(crtc, INTEL_OUTPUT_ANALOG) ||
7250             intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI))
7251                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7252                                  0x009f0003);
7253         else
7254                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7255                                  0x00d0000f);
7256
7257         if (pipe_config->has_dp_encoder) {
7258                 /* Use SSC source */
7259                 if (pipe == PIPE_A)
7260                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7261                                          0x0df40000);
7262                 else
7263                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7264                                          0x0df70000);
7265         } else { /* HDMI or VGA */
7266                 /* Use bend source */
7267                 if (pipe == PIPE_A)
7268                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7269                                          0x0df70000);
7270                 else
7271                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7272                                          0x0df40000);
7273         }
7274
7275         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
7276         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
7277         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DISPLAYPORT) ||
7278             intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP))
7279                 coreclk |= 0x01000000;
7280         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
7281
7282         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
7283         mutex_unlock(&dev_priv->sb_lock);
7284 }
7285
7286 static void chv_compute_dpll(struct intel_crtc *crtc,
7287                              struct intel_crtc_state *pipe_config)
7288 {
7289         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
7290                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS |
7291                 DPLL_VCO_ENABLE;
7292         if (crtc->pipe != PIPE_A)
7293                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7294
7295         pipe_config->dpll_hw_state.dpll_md =
7296                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7297 }
7298
7299 static void chv_prepare_pll(struct intel_crtc *crtc,
7300                             const struct intel_crtc_state *pipe_config)
7301 {
7302         struct drm_device *dev = crtc->base.dev;
7303         struct drm_i915_private *dev_priv = dev->dev_private;
7304         int pipe = crtc->pipe;
7305         int dpll_reg = DPLL(crtc->pipe);
7306         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7307         u32 loopfilter, tribuf_calcntr;
7308         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
7309         u32 dpio_val;
7310         int vco;
7311
7312         bestn = pipe_config->dpll.n;
7313         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
7314         bestm1 = pipe_config->dpll.m1;
7315         bestm2 = pipe_config->dpll.m2 >> 22;
7316         bestp1 = pipe_config->dpll.p1;
7317         bestp2 = pipe_config->dpll.p2;
7318         vco = pipe_config->dpll.vco;
7319         dpio_val = 0;
7320         loopfilter = 0;
7321
7322         /*
7323          * Enable Refclk and SSC
7324          */
7325         I915_WRITE(dpll_reg,
7326                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
7327
7328         mutex_lock(&dev_priv->sb_lock);
7329
7330         /* p1 and p2 divider */
7331         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
7332                         5 << DPIO_CHV_S1_DIV_SHIFT |
7333                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
7334                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
7335                         1 << DPIO_CHV_K_DIV_SHIFT);
7336
7337         /* Feedback post-divider - m2 */
7338         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
7339
7340         /* Feedback refclk divider - n and m1 */
7341         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
7342                         DPIO_CHV_M1_DIV_BY_2 |
7343                         1 << DPIO_CHV_N_DIV_SHIFT);
7344
7345         /* M2 fraction division */
7346         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
7347
7348         /* M2 fraction division enable */
7349         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7350         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
7351         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
7352         if (bestm2_frac)
7353                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
7354         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
7355
7356         /* Program digital lock detect threshold */
7357         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
7358         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
7359                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
7360         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
7361         if (!bestm2_frac)
7362                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
7363         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
7364
7365         /* Loop filter */
7366         if (vco == 5400000) {
7367                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
7368                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
7369                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
7370                 tribuf_calcntr = 0x9;
7371         } else if (vco <= 6200000) {
7372                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
7373                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
7374                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7375                 tribuf_calcntr = 0x9;
7376         } else if (vco <= 6480000) {
7377                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7378                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7379                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7380                 tribuf_calcntr = 0x8;
7381         } else {
7382                 /* Not supported. Apply the same limits as in the max case */
7383                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7384                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7385                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7386                 tribuf_calcntr = 0;
7387         }
7388         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
7389
7390         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
7391         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
7392         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
7393         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
7394
7395         /* AFC Recal */
7396         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
7397                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
7398                         DPIO_AFC_RECAL);
7399
7400         mutex_unlock(&dev_priv->sb_lock);
7401 }
7402
7403 /**
7404  * vlv_force_pll_on - forcibly enable just the PLL
7405  * @dev_priv: i915 private structure
7406  * @pipe: pipe PLL to enable
7407  * @dpll: PLL configuration
7408  *
7409  * Enable the PLL for @pipe using the supplied @dpll config. To be used
7410  * in cases where we need the PLL enabled even when @pipe is not going to
7411  * be enabled.
7412  */
7413 void vlv_force_pll_on(struct drm_device *dev, enum pipe pipe,
7414                       const struct dpll *dpll)
7415 {
7416         struct intel_crtc *crtc =
7417                 to_intel_crtc(intel_get_crtc_for_pipe(dev, pipe));
7418         struct intel_crtc_state pipe_config = {
7419                 .base.crtc = &crtc->base,
7420                 .pixel_multiplier = 1,
7421                 .dpll = *dpll,
7422         };
7423
7424         if (IS_CHERRYVIEW(dev)) {
7425                 chv_compute_dpll(crtc, &pipe_config);
7426                 chv_prepare_pll(crtc, &pipe_config);
7427                 chv_enable_pll(crtc, &pipe_config);
7428         } else {
7429                 vlv_compute_dpll(crtc, &pipe_config);
7430                 vlv_prepare_pll(crtc, &pipe_config);
7431                 vlv_enable_pll(crtc, &pipe_config);
7432         }
7433 }
7434
7435 /**
7436  * vlv_force_pll_off - forcibly disable just the PLL
7437  * @dev_priv: i915 private structure
7438  * @pipe: pipe PLL to disable
7439  *
7440  * Disable the PLL for @pipe. To be used in cases where we need
7441  * the PLL enabled even when @pipe is not going to be enabled.
7442  */
7443 void vlv_force_pll_off(struct drm_device *dev, enum pipe pipe)
7444 {
7445         if (IS_CHERRYVIEW(dev))
7446                 chv_disable_pll(to_i915(dev), pipe);
7447         else
7448                 vlv_disable_pll(to_i915(dev), pipe);
7449 }
7450
7451 static void i9xx_compute_dpll(struct intel_crtc *crtc,
7452                               struct intel_crtc_state *crtc_state,
7453                               intel_clock_t *reduced_clock,
7454                               int num_connectors)
7455 {
7456         struct drm_device *dev = crtc->base.dev;
7457         struct drm_i915_private *dev_priv = dev->dev_private;
7458         u32 dpll;
7459         bool is_sdvo;
7460         struct dpll *clock = &crtc_state->dpll;
7461
7462         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7463
7464         is_sdvo = intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7465                 intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_HDMI);
7466
7467         dpll = DPLL_VGA_MODE_DIS;
7468
7469         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
7470                 dpll |= DPLLB_MODE_LVDS;
7471         else
7472                 dpll |= DPLLB_MODE_DAC_SERIAL;
7473
7474         if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
7475                 dpll |= (crtc_state->pixel_multiplier - 1)
7476                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7477         }
7478
7479         if (is_sdvo)
7480                 dpll |= DPLL_SDVO_HIGH_SPEED;
7481
7482         if (crtc_state->has_dp_encoder)
7483                 dpll |= DPLL_SDVO_HIGH_SPEED;
7484
7485         /* compute bitmask from p1 value */
7486         if (IS_PINEVIEW(dev))
7487                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7488         else {
7489                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7490                 if (IS_G4X(dev) && reduced_clock)
7491                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7492         }
7493         switch (clock->p2) {
7494         case 5:
7495                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7496                 break;
7497         case 7:
7498                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7499                 break;
7500         case 10:
7501                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7502                 break;
7503         case 14:
7504                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7505                 break;
7506         }
7507         if (INTEL_INFO(dev)->gen >= 4)
7508                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7509
7510         if (crtc_state->sdvo_tv_clock)
7511                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7512         else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7513                  intel_panel_use_ssc(dev_priv) && num_connectors < 2)
7514                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7515         else
7516                 dpll |= PLL_REF_INPUT_DREFCLK;
7517
7518         dpll |= DPLL_VCO_ENABLE;
7519         crtc_state->dpll_hw_state.dpll = dpll;
7520
7521         if (INTEL_INFO(dev)->gen >= 4) {
7522                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7523                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7524                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7525         }
7526 }
7527
7528 static void i8xx_compute_dpll(struct intel_crtc *crtc,
7529                               struct intel_crtc_state *crtc_state,
7530                               intel_clock_t *reduced_clock,
7531                               int num_connectors)
7532 {
7533         struct drm_device *dev = crtc->base.dev;
7534         struct drm_i915_private *dev_priv = dev->dev_private;
7535         u32 dpll;
7536         struct dpll *clock = &crtc_state->dpll;
7537
7538         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7539
7540         dpll = DPLL_VGA_MODE_DIS;
7541
7542         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7543                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7544         } else {
7545                 if (clock->p1 == 2)
7546                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7547                 else
7548                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7549                 if (clock->p2 == 4)
7550                         dpll |= PLL_P2_DIVIDE_BY_4;
7551         }
7552
7553         if (!IS_I830(dev) && intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_DVO))
7554                 dpll |= DPLL_DVO_2X_MODE;
7555
7556         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7557                  intel_panel_use_ssc(dev_priv) && num_connectors < 2)
7558                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7559         else
7560                 dpll |= PLL_REF_INPUT_DREFCLK;
7561
7562         dpll |= DPLL_VCO_ENABLE;
7563         crtc_state->dpll_hw_state.dpll = dpll;
7564 }
7565
7566 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
7567 {
7568         struct drm_device *dev = intel_crtc->base.dev;
7569         struct drm_i915_private *dev_priv = dev->dev_private;
7570         enum pipe pipe = intel_crtc->pipe;
7571         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
7572         struct drm_display_mode *adjusted_mode =
7573                 &intel_crtc->config->base.adjusted_mode;
7574         uint32_t crtc_vtotal, crtc_vblank_end;
7575         int vsyncshift = 0;
7576
7577         /* We need to be careful not to changed the adjusted mode, for otherwise
7578          * the hw state checker will get angry at the mismatch. */
7579         crtc_vtotal = adjusted_mode->crtc_vtotal;
7580         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7581
7582         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7583                 /* the chip adds 2 halflines automatically */
7584                 crtc_vtotal -= 1;
7585                 crtc_vblank_end -= 1;
7586
7587                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
7588                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7589                 else
7590                         vsyncshift = adjusted_mode->crtc_hsync_start -
7591                                 adjusted_mode->crtc_htotal / 2;
7592                 if (vsyncshift < 0)
7593                         vsyncshift += adjusted_mode->crtc_htotal;
7594         }
7595
7596         if (INTEL_INFO(dev)->gen > 3)
7597                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7598
7599         I915_WRITE(HTOTAL(cpu_transcoder),
7600                    (adjusted_mode->crtc_hdisplay - 1) |
7601                    ((adjusted_mode->crtc_htotal - 1) << 16));
7602         I915_WRITE(HBLANK(cpu_transcoder),
7603                    (adjusted_mode->crtc_hblank_start - 1) |
7604                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7605         I915_WRITE(HSYNC(cpu_transcoder),
7606                    (adjusted_mode->crtc_hsync_start - 1) |
7607                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7608
7609         I915_WRITE(VTOTAL(cpu_transcoder),
7610                    (adjusted_mode->crtc_vdisplay - 1) |
7611                    ((crtc_vtotal - 1) << 16));
7612         I915_WRITE(VBLANK(cpu_transcoder),
7613                    (adjusted_mode->crtc_vblank_start - 1) |
7614                    ((crtc_vblank_end - 1) << 16));
7615         I915_WRITE(VSYNC(cpu_transcoder),
7616                    (adjusted_mode->crtc_vsync_start - 1) |
7617                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7618
7619         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7620          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7621          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7622          * bits. */
7623         if (IS_HASWELL(dev) && cpu_transcoder == TRANSCODER_EDP &&
7624             (pipe == PIPE_B || pipe == PIPE_C))
7625                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7626
7627         /* pipesrc controls the size that is scaled from, which should
7628          * always be the user's requested size.
7629          */
7630         I915_WRITE(PIPESRC(pipe),
7631                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
7632                    (intel_crtc->config->pipe_src_h - 1));
7633 }
7634
7635 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7636                                    struct intel_crtc_state *pipe_config)
7637 {
7638         struct drm_device *dev = crtc->base.dev;
7639         struct drm_i915_private *dev_priv = dev->dev_private;
7640         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7641         uint32_t tmp;
7642
7643         tmp = I915_READ(HTOTAL(cpu_transcoder));
7644         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7645         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7646         tmp = I915_READ(HBLANK(cpu_transcoder));
7647         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7648         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7649         tmp = I915_READ(HSYNC(cpu_transcoder));
7650         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7651         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7652
7653         tmp = I915_READ(VTOTAL(cpu_transcoder));
7654         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7655         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7656         tmp = I915_READ(VBLANK(cpu_transcoder));
7657         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7658         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7659         tmp = I915_READ(VSYNC(cpu_transcoder));
7660         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7661         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7662
7663         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7664                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7665                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7666                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7667         }
7668
7669         tmp = I915_READ(PIPESRC(crtc->pipe));
7670         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7671         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7672
7673         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7674         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7675 }
7676
7677 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7678                                  struct intel_crtc_state *pipe_config)
7679 {
7680         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7681         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7682         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7683         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7684
7685         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7686         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7687         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7688         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7689
7690         mode->flags = pipe_config->base.adjusted_mode.flags;
7691         mode->type = DRM_MODE_TYPE_DRIVER;
7692
7693         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7694         mode->flags |= pipe_config->base.adjusted_mode.flags;
7695
7696         mode->hsync = drm_mode_hsync(mode);
7697         mode->vrefresh = drm_mode_vrefresh(mode);
7698         drm_mode_set_name(mode);
7699 }
7700
7701 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
7702 {
7703         struct drm_device *dev = intel_crtc->base.dev;
7704         struct drm_i915_private *dev_priv = dev->dev_private;
7705         uint32_t pipeconf;
7706
7707         pipeconf = 0;
7708
7709         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
7710             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
7711                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
7712
7713         if (intel_crtc->config->double_wide)
7714                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7715
7716         /* only g4x and later have fancy bpc/dither controls */
7717         if (IS_G4X(dev) || IS_VALLEYVIEW(dev)) {
7718                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7719                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
7720                         pipeconf |= PIPECONF_DITHER_EN |
7721                                     PIPECONF_DITHER_TYPE_SP;
7722
7723                 switch (intel_crtc->config->pipe_bpp) {
7724                 case 18:
7725                         pipeconf |= PIPECONF_6BPC;
7726                         break;
7727                 case 24:
7728                         pipeconf |= PIPECONF_8BPC;
7729                         break;
7730                 case 30:
7731                         pipeconf |= PIPECONF_10BPC;
7732                         break;
7733                 default:
7734                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7735                         BUG();
7736                 }
7737         }
7738
7739         if (HAS_PIPE_CXSR(dev)) {
7740                 if (intel_crtc->lowfreq_avail) {
7741                         DRM_DEBUG_KMS("enabling CxSR downclocking\n");
7742                         pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
7743                 } else {
7744                         DRM_DEBUG_KMS("disabling CxSR downclocking\n");
7745                 }
7746         }
7747
7748         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7749                 if (INTEL_INFO(dev)->gen < 4 ||
7750                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
7751                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7752                 else
7753                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7754         } else
7755                 pipeconf |= PIPECONF_PROGRESSIVE;
7756
7757         if (IS_VALLEYVIEW(dev) && intel_crtc->config->limited_color_range)
7758                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7759
7760         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
7761         POSTING_READ(PIPECONF(intel_crtc->pipe));
7762 }
7763
7764 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7765                                    struct intel_crtc_state *crtc_state)
7766 {
7767         struct drm_device *dev = crtc->base.dev;
7768         struct drm_i915_private *dev_priv = dev->dev_private;
7769         int refclk, num_connectors = 0;
7770         intel_clock_t clock;
7771         bool ok;
7772         bool is_dsi = false;
7773         struct intel_encoder *encoder;
7774         const intel_limit_t *limit;
7775         struct drm_atomic_state *state = crtc_state->base.state;
7776         struct drm_connector *connector;
7777         struct drm_connector_state *connector_state;
7778         int i;
7779
7780         memset(&crtc_state->dpll_hw_state, 0,
7781                sizeof(crtc_state->dpll_hw_state));
7782
7783         for_each_connector_in_state(state, connector, connector_state, i) {
7784                 if (connector_state->crtc != &crtc->base)
7785                         continue;
7786
7787                 encoder = to_intel_encoder(connector_state->best_encoder);
7788
7789                 switch (encoder->type) {
7790                 case INTEL_OUTPUT_DSI:
7791                         is_dsi = true;
7792                         break;
7793                 default:
7794                         break;
7795                 }
7796
7797                 num_connectors++;
7798         }
7799
7800         if (is_dsi)
7801                 return 0;
7802
7803         if (!crtc_state->clock_set) {
7804                 refclk = i9xx_get_refclk(crtc_state, num_connectors);
7805
7806                 /*
7807                  * Returns a set of divisors for the desired target clock with
7808                  * the given refclk, or FALSE.  The returned values represent
7809                  * the clock equation: reflck * (5 * (m1 + 2) + (m2 + 2)) / (n +
7810                  * 2) / p1 / p2.
7811                  */
7812                 limit = intel_limit(crtc_state, refclk);
7813                 ok = dev_priv->display.find_dpll(limit, crtc_state,
7814                                                  crtc_state->port_clock,
7815                                                  refclk, NULL, &clock);
7816                 if (!ok) {
7817                         DRM_ERROR("Couldn't find PLL settings for mode!\n");
7818                         return -EINVAL;
7819                 }
7820
7821                 /* Compat-code for transition, will disappear. */
7822                 crtc_state->dpll.n = clock.n;
7823                 crtc_state->dpll.m1 = clock.m1;
7824                 crtc_state->dpll.m2 = clock.m2;
7825                 crtc_state->dpll.p1 = clock.p1;
7826                 crtc_state->dpll.p2 = clock.p2;
7827         }
7828
7829         if (IS_GEN2(dev)) {
7830                 i8xx_compute_dpll(crtc, crtc_state, NULL,
7831                                   num_connectors);
7832         } else if (IS_CHERRYVIEW(dev)) {
7833                 chv_compute_dpll(crtc, crtc_state);
7834         } else if (IS_VALLEYVIEW(dev)) {
7835                 vlv_compute_dpll(crtc, crtc_state);
7836         } else {
7837                 i9xx_compute_dpll(crtc, crtc_state, NULL,
7838                                   num_connectors);
7839         }
7840
7841         return 0;
7842 }
7843
7844 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
7845                                  struct intel_crtc_state *pipe_config)
7846 {
7847         struct drm_device *dev = crtc->base.dev;
7848         struct drm_i915_private *dev_priv = dev->dev_private;
7849         uint32_t tmp;
7850
7851         if (INTEL_INFO(dev)->gen <= 3 && (IS_I830(dev) || !IS_MOBILE(dev)))
7852                 return;
7853
7854         tmp = I915_READ(PFIT_CONTROL);
7855         if (!(tmp & PFIT_ENABLE))
7856                 return;
7857
7858         /* Check whether the pfit is attached to our pipe. */
7859         if (INTEL_INFO(dev)->gen < 4) {
7860                 if (crtc->pipe != PIPE_B)
7861                         return;
7862         } else {
7863                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
7864                         return;
7865         }
7866
7867         pipe_config->gmch_pfit.control = tmp;
7868         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
7869         if (INTEL_INFO(dev)->gen < 5)
7870                 pipe_config->gmch_pfit.lvds_border_bits =
7871                         I915_READ(LVDS) & LVDS_BORDER_ENABLE;
7872 }
7873
7874 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
7875                                struct intel_crtc_state *pipe_config)
7876 {
7877         struct drm_device *dev = crtc->base.dev;
7878         struct drm_i915_private *dev_priv = dev->dev_private;
7879         int pipe = pipe_config->cpu_transcoder;
7880         intel_clock_t clock;
7881         u32 mdiv;
7882         int refclk = 100000;
7883
7884         /* In case of MIPI DPLL will not even be used */
7885         if (!(pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE))
7886                 return;
7887
7888         mutex_lock(&dev_priv->sb_lock);
7889         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
7890         mutex_unlock(&dev_priv->sb_lock);
7891
7892         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
7893         clock.m2 = mdiv & DPIO_M2DIV_MASK;
7894         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
7895         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
7896         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
7897
7898         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
7899 }
7900
7901 static void
7902 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
7903                               struct intel_initial_plane_config *plane_config)
7904 {
7905         struct drm_device *dev = crtc->base.dev;
7906         struct drm_i915_private *dev_priv = dev->dev_private;
7907         u32 val, base, offset;
7908         int pipe = crtc->pipe, plane = crtc->plane;
7909         int fourcc, pixel_format;
7910         unsigned int aligned_height;
7911         struct drm_framebuffer *fb;
7912         struct intel_framebuffer *intel_fb;
7913
7914         val = I915_READ(DSPCNTR(plane));
7915         if (!(val & DISPLAY_PLANE_ENABLE))
7916                 return;
7917
7918         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
7919         if (!intel_fb) {
7920                 DRM_DEBUG_KMS("failed to alloc fb\n");
7921                 return;
7922         }
7923
7924         fb = &intel_fb->base;
7925
7926         if (INTEL_INFO(dev)->gen >= 4) {
7927                 if (val & DISPPLANE_TILED) {
7928                         plane_config->tiling = I915_TILING_X;
7929                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
7930                 }
7931         }
7932
7933         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
7934         fourcc = i9xx_format_to_fourcc(pixel_format);
7935         fb->pixel_format = fourcc;
7936         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
7937
7938         if (INTEL_INFO(dev)->gen >= 4) {
7939                 if (plane_config->tiling)
7940                         offset = I915_READ(DSPTILEOFF(plane));
7941                 else
7942                         offset = I915_READ(DSPLINOFF(plane));
7943                 base = I915_READ(DSPSURF(plane)) & 0xfffff000;
7944         } else {
7945                 base = I915_READ(DSPADDR(plane));
7946         }
7947         plane_config->base = base;
7948
7949         val = I915_READ(PIPESRC(pipe));
7950         fb->width = ((val >> 16) & 0xfff) + 1;
7951         fb->height = ((val >> 0) & 0xfff) + 1;
7952
7953         val = I915_READ(DSPSTRIDE(pipe));
7954         fb->pitches[0] = val & 0xffffffc0;
7955
7956         aligned_height = intel_fb_align_height(dev, fb->height,
7957                                                fb->pixel_format,
7958                                                fb->modifier[0]);
7959
7960         plane_config->size = fb->pitches[0] * aligned_height;
7961
7962         DRM_DEBUG_KMS("pipe/plane %c/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
7963                       pipe_name(pipe), plane, fb->width, fb->height,
7964                       fb->bits_per_pixel, base, fb->pitches[0],
7965                       plane_config->size);
7966
7967         plane_config->fb = intel_fb;
7968 }
7969
7970 static void chv_crtc_clock_get(struct intel_crtc *crtc,
7971                                struct intel_crtc_state *pipe_config)
7972 {
7973         struct drm_device *dev = crtc->base.dev;
7974         struct drm_i915_private *dev_priv = dev->dev_private;
7975         int pipe = pipe_config->cpu_transcoder;
7976         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7977         intel_clock_t clock;
7978         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
7979         int refclk = 100000;
7980
7981         mutex_lock(&dev_priv->sb_lock);
7982         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
7983         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
7984         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
7985         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
7986         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7987         mutex_unlock(&dev_priv->sb_lock);
7988
7989         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
7990         clock.m2 = (pll_dw0 & 0xff) << 22;
7991         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
7992                 clock.m2 |= pll_dw2 & 0x3fffff;
7993         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
7994         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
7995         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
7996
7997         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
7998 }
7999
8000 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
8001                                  struct intel_crtc_state *pipe_config)
8002 {
8003         struct drm_device *dev = crtc->base.dev;
8004         struct drm_i915_private *dev_priv = dev->dev_private;
8005         uint32_t tmp;
8006
8007         if (!intel_display_power_is_enabled(dev_priv,
8008                                             POWER_DOMAIN_PIPE(crtc->pipe)))
8009                 return false;
8010
8011         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8012         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
8013
8014         tmp = I915_READ(PIPECONF(crtc->pipe));
8015         if (!(tmp & PIPECONF_ENABLE))
8016                 return false;
8017
8018         if (IS_G4X(dev) || IS_VALLEYVIEW(dev)) {
8019                 switch (tmp & PIPECONF_BPC_MASK) {
8020                 case PIPECONF_6BPC:
8021                         pipe_config->pipe_bpp = 18;
8022                         break;
8023                 case PIPECONF_8BPC:
8024                         pipe_config->pipe_bpp = 24;
8025                         break;
8026                 case PIPECONF_10BPC:
8027                         pipe_config->pipe_bpp = 30;
8028                         break;
8029                 default:
8030                         break;
8031                 }
8032         }
8033
8034         if (IS_VALLEYVIEW(dev) && (tmp & PIPECONF_COLOR_RANGE_SELECT))
8035                 pipe_config->limited_color_range = true;
8036
8037         if (INTEL_INFO(dev)->gen < 4)
8038                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
8039
8040         intel_get_pipe_timings(crtc, pipe_config);
8041
8042         i9xx_get_pfit_config(crtc, pipe_config);
8043
8044         if (INTEL_INFO(dev)->gen >= 4) {
8045                 tmp = I915_READ(DPLL_MD(crtc->pipe));
8046                 pipe_config->pixel_multiplier =
8047                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
8048                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
8049                 pipe_config->dpll_hw_state.dpll_md = tmp;
8050         } else if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
8051                 tmp = I915_READ(DPLL(crtc->pipe));
8052                 pipe_config->pixel_multiplier =
8053                         ((tmp & SDVO_MULTIPLIER_MASK)
8054                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
8055         } else {
8056                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
8057                  * port and will be fixed up in the encoder->get_config
8058                  * function. */
8059                 pipe_config->pixel_multiplier = 1;
8060         }
8061         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
8062         if (!IS_VALLEYVIEW(dev)) {
8063                 /*
8064                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
8065                  * on 830. Filter it out here so that we don't
8066                  * report errors due to that.
8067                  */
8068                 if (IS_I830(dev))
8069                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
8070
8071                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
8072                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
8073         } else {
8074                 /* Mask out read-only status bits. */
8075                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
8076                                                      DPLL_PORTC_READY_MASK |
8077                                                      DPLL_PORTB_READY_MASK);
8078         }
8079
8080         if (IS_CHERRYVIEW(dev))
8081                 chv_crtc_clock_get(crtc, pipe_config);
8082         else if (IS_VALLEYVIEW(dev))
8083                 vlv_crtc_clock_get(crtc, pipe_config);
8084         else
8085                 i9xx_crtc_clock_get(crtc, pipe_config);
8086
8087         return true;
8088 }
8089
8090 static void ironlake_init_pch_refclk(struct drm_device *dev)
8091 {
8092         struct drm_i915_private *dev_priv = dev->dev_private;
8093         struct intel_encoder *encoder;
8094         u32 val, final;
8095         bool has_lvds = false;
8096         bool has_cpu_edp = false;
8097         bool has_panel = false;
8098         bool has_ck505 = false;
8099         bool can_ssc = false;
8100
8101         /* We need to take the global config into account */
8102         for_each_intel_encoder(dev, encoder) {
8103                 switch (encoder->type) {
8104                 case INTEL_OUTPUT_LVDS:
8105                         has_panel = true;
8106                         has_lvds = true;
8107                         break;
8108                 case INTEL_OUTPUT_EDP:
8109                         has_panel = true;
8110                         if (enc_to_dig_port(&encoder->base)->port == PORT_A)
8111                                 has_cpu_edp = true;
8112                         break;
8113                 default:
8114                         break;
8115                 }
8116         }
8117
8118         if (HAS_PCH_IBX(dev)) {
8119                 has_ck505 = dev_priv->vbt.display_clock_mode;
8120                 can_ssc = has_ck505;
8121         } else {
8122                 has_ck505 = false;
8123                 can_ssc = true;
8124         }
8125
8126         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d\n",
8127                       has_panel, has_lvds, has_ck505);
8128
8129         /* Ironlake: try to setup display ref clock before DPLL
8130          * enabling. This is only under driver's control after
8131          * PCH B stepping, previous chipset stepping should be
8132          * ignoring this setting.
8133          */
8134         val = I915_READ(PCH_DREF_CONTROL);
8135
8136         /* As we must carefully and slowly disable/enable each source in turn,
8137          * compute the final state we want first and check if we need to
8138          * make any changes at all.
8139          */
8140         final = val;
8141         final &= ~DREF_NONSPREAD_SOURCE_MASK;
8142         if (has_ck505)
8143                 final |= DREF_NONSPREAD_CK505_ENABLE;
8144         else
8145                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
8146
8147         final &= ~DREF_SSC_SOURCE_MASK;
8148         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8149         final &= ~DREF_SSC1_ENABLE;
8150
8151         if (has_panel) {
8152                 final |= DREF_SSC_SOURCE_ENABLE;
8153
8154                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
8155                         final |= DREF_SSC1_ENABLE;
8156
8157                 if (has_cpu_edp) {
8158                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
8159                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8160                         else
8161                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8162                 } else
8163                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8164         } else {
8165                 final |= DREF_SSC_SOURCE_DISABLE;
8166                 final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8167         }
8168
8169         if (final == val)
8170                 return;
8171
8172         /* Always enable nonspread source */
8173         val &= ~DREF_NONSPREAD_SOURCE_MASK;
8174
8175         if (has_ck505)
8176                 val |= DREF_NONSPREAD_CK505_ENABLE;
8177         else
8178                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
8179
8180         if (has_panel) {
8181                 val &= ~DREF_SSC_SOURCE_MASK;
8182                 val |= DREF_SSC_SOURCE_ENABLE;
8183
8184                 /* SSC must be turned on before enabling the CPU output  */
8185                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8186                         DRM_DEBUG_KMS("Using SSC on panel\n");
8187                         val |= DREF_SSC1_ENABLE;
8188                 } else
8189                         val &= ~DREF_SSC1_ENABLE;
8190
8191                 /* Get SSC going before enabling the outputs */
8192                 I915_WRITE(PCH_DREF_CONTROL, val);
8193                 POSTING_READ(PCH_DREF_CONTROL);
8194                 udelay(200);
8195
8196                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8197
8198                 /* Enable CPU source on CPU attached eDP */
8199                 if (has_cpu_edp) {
8200                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8201                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
8202                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8203                         } else
8204                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8205                 } else
8206                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8207
8208                 I915_WRITE(PCH_DREF_CONTROL, val);
8209                 POSTING_READ(PCH_DREF_CONTROL);
8210                 udelay(200);
8211         } else {
8212                 DRM_DEBUG_KMS("Disabling SSC entirely\n");
8213
8214                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8215
8216                 /* Turn off CPU output */
8217                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8218
8219                 I915_WRITE(PCH_DREF_CONTROL, val);
8220                 POSTING_READ(PCH_DREF_CONTROL);
8221                 udelay(200);
8222
8223                 /* Turn off the SSC source */
8224                 val &= ~DREF_SSC_SOURCE_MASK;
8225                 val |= DREF_SSC_SOURCE_DISABLE;
8226
8227                 /* Turn off SSC1 */
8228                 val &= ~DREF_SSC1_ENABLE;
8229
8230                 I915_WRITE(PCH_DREF_CONTROL, val);
8231                 POSTING_READ(PCH_DREF_CONTROL);
8232                 udelay(200);
8233         }
8234
8235         BUG_ON(val != final);
8236 }
8237
8238 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
8239 {
8240         uint32_t tmp;
8241
8242         tmp = I915_READ(SOUTH_CHICKEN2);
8243         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
8244         I915_WRITE(SOUTH_CHICKEN2, tmp);
8245
8246         if (wait_for_atomic_us(I915_READ(SOUTH_CHICKEN2) &
8247                                FDI_MPHY_IOSFSB_RESET_STATUS, 100))
8248                 DRM_ERROR("FDI mPHY reset assert timeout\n");
8249
8250         tmp = I915_READ(SOUTH_CHICKEN2);
8251         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
8252         I915_WRITE(SOUTH_CHICKEN2, tmp);
8253
8254         if (wait_for_atomic_us((I915_READ(SOUTH_CHICKEN2) &
8255                                 FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
8256                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
8257 }
8258
8259 /* WaMPhyProgramming:hsw */
8260 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
8261 {
8262         uint32_t tmp;
8263
8264         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
8265         tmp &= ~(0xFF << 24);
8266         tmp |= (0x12 << 24);
8267         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
8268
8269         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
8270         tmp |= (1 << 11);
8271         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
8272
8273         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
8274         tmp |= (1 << 11);
8275         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
8276
8277         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
8278         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8279         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
8280
8281         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
8282         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8283         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
8284
8285         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
8286         tmp &= ~(7 << 13);
8287         tmp |= (5 << 13);
8288         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
8289
8290         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
8291         tmp &= ~(7 << 13);
8292         tmp |= (5 << 13);
8293         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
8294
8295         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
8296         tmp &= ~0xFF;
8297         tmp |= 0x1C;
8298         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
8299
8300         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
8301         tmp &= ~0xFF;
8302         tmp |= 0x1C;
8303         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
8304
8305         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
8306         tmp &= ~(0xFF << 16);
8307         tmp |= (0x1C << 16);
8308         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
8309
8310         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
8311         tmp &= ~(0xFF << 16);
8312         tmp |= (0x1C << 16);
8313         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
8314
8315         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8316         tmp |= (1 << 27);
8317         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8318
8319         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8320         tmp |= (1 << 27);
8321         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8322
8323         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8324         tmp &= ~(0xF << 28);
8325         tmp |= (4 << 28);
8326         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8327
8328         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
8329         tmp &= ~(0xF << 28);
8330         tmp |= (4 << 28);
8331         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
8332 }
8333
8334 /* Implements 3 different sequences from BSpec chapter "Display iCLK
8335  * Programming" based on the parameters passed:
8336  * - Sequence to enable CLKOUT_DP
8337  * - Sequence to enable CLKOUT_DP without spread
8338  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
8339  */
8340 static void lpt_enable_clkout_dp(struct drm_device *dev, bool with_spread,
8341                                  bool with_fdi)
8342 {
8343         struct drm_i915_private *dev_priv = dev->dev_private;
8344         uint32_t reg, tmp;
8345
8346         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
8347                 with_spread = true;
8348         if (WARN(dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE &&
8349                  with_fdi, "LP PCH doesn't have FDI\n"))
8350                 with_fdi = false;
8351
8352         mutex_lock(&dev_priv->sb_lock);
8353
8354         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8355         tmp &= ~SBI_SSCCTL_DISABLE;
8356         tmp |= SBI_SSCCTL_PATHALT;
8357         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8358
8359         udelay(24);
8360
8361         if (with_spread) {
8362                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8363                 tmp &= ~SBI_SSCCTL_PATHALT;
8364                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8365
8366                 if (with_fdi) {
8367                         lpt_reset_fdi_mphy(dev_priv);
8368                         lpt_program_fdi_mphy(dev_priv);
8369                 }
8370         }
8371
8372         reg = (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) ?
8373                SBI_GEN0 : SBI_DBUFF0;
8374         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8375         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8376         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8377
8378         mutex_unlock(&dev_priv->sb_lock);
8379 }
8380
8381 /* Sequence to disable CLKOUT_DP */
8382 static void lpt_disable_clkout_dp(struct drm_device *dev)
8383 {
8384         struct drm_i915_private *dev_priv = dev->dev_private;
8385         uint32_t reg, tmp;
8386
8387         mutex_lock(&dev_priv->sb_lock);
8388
8389         reg = (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) ?
8390                SBI_GEN0 : SBI_DBUFF0;
8391         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8392         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8393         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8394
8395         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8396         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8397                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8398                         tmp |= SBI_SSCCTL_PATHALT;
8399                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8400                         udelay(32);
8401                 }
8402                 tmp |= SBI_SSCCTL_DISABLE;
8403                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8404         }
8405
8406         mutex_unlock(&dev_priv->sb_lock);
8407 }
8408
8409 static void lpt_init_pch_refclk(struct drm_device *dev)
8410 {
8411         struct intel_encoder *encoder;
8412         bool has_vga = false;
8413
8414         for_each_intel_encoder(dev, encoder) {
8415                 switch (encoder->type) {
8416                 case INTEL_OUTPUT_ANALOG:
8417                         has_vga = true;
8418                         break;
8419                 default:
8420                         break;
8421                 }
8422         }
8423
8424         if (has_vga)
8425                 lpt_enable_clkout_dp(dev, true, true);
8426         else
8427                 lpt_disable_clkout_dp(dev);
8428 }
8429
8430 /*
8431  * Initialize reference clocks when the driver loads
8432  */
8433 void intel_init_pch_refclk(struct drm_device *dev)
8434 {
8435         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
8436                 ironlake_init_pch_refclk(dev);
8437         else if (HAS_PCH_LPT(dev))
8438                 lpt_init_pch_refclk(dev);
8439 }
8440
8441 static int ironlake_get_refclk(struct intel_crtc_state *crtc_state)
8442 {
8443         struct drm_device *dev = crtc_state->base.crtc->dev;
8444         struct drm_i915_private *dev_priv = dev->dev_private;
8445         struct drm_atomic_state *state = crtc_state->base.state;
8446         struct drm_connector *connector;
8447         struct drm_connector_state *connector_state;
8448         struct intel_encoder *encoder;
8449         int num_connectors = 0, i;
8450         bool is_lvds = false;
8451
8452         for_each_connector_in_state(state, connector, connector_state, i) {
8453                 if (connector_state->crtc != crtc_state->base.crtc)
8454                         continue;
8455
8456                 encoder = to_intel_encoder(connector_state->best_encoder);
8457
8458                 switch (encoder->type) {
8459                 case INTEL_OUTPUT_LVDS:
8460                         is_lvds = true;
8461                         break;
8462                 default:
8463                         break;
8464                 }
8465                 num_connectors++;
8466         }
8467
8468         if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2) {
8469                 DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8470                               dev_priv->vbt.lvds_ssc_freq);
8471                 return dev_priv->vbt.lvds_ssc_freq;
8472         }
8473
8474         return 120000;
8475 }
8476
8477 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
8478 {
8479         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
8480         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8481         int pipe = intel_crtc->pipe;
8482         uint32_t val;
8483
8484         val = 0;
8485
8486         switch (intel_crtc->config->pipe_bpp) {
8487         case 18:
8488                 val |= PIPECONF_6BPC;
8489                 break;
8490         case 24:
8491                 val |= PIPECONF_8BPC;
8492                 break;
8493         case 30:
8494                 val |= PIPECONF_10BPC;
8495                 break;
8496         case 36:
8497                 val |= PIPECONF_12BPC;
8498                 break;
8499         default:
8500                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8501                 BUG();
8502         }
8503
8504         if (intel_crtc->config->dither)
8505                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8506
8507         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8508                 val |= PIPECONF_INTERLACED_ILK;
8509         else
8510                 val |= PIPECONF_PROGRESSIVE;
8511
8512         if (intel_crtc->config->limited_color_range)
8513                 val |= PIPECONF_COLOR_RANGE_SELECT;
8514
8515         I915_WRITE(PIPECONF(pipe), val);
8516         POSTING_READ(PIPECONF(pipe));
8517 }
8518
8519 /*
8520  * Set up the pipe CSC unit.
8521  *
8522  * Currently only full range RGB to limited range RGB conversion
8523  * is supported, but eventually this should handle various
8524  * RGB<->YCbCr scenarios as well.
8525  */
8526 static void intel_set_pipe_csc(struct drm_crtc *crtc)
8527 {
8528         struct drm_device *dev = crtc->dev;
8529         struct drm_i915_private *dev_priv = dev->dev_private;
8530         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8531         int pipe = intel_crtc->pipe;
8532         uint16_t coeff = 0x7800; /* 1.0 */
8533
8534         /*
8535          * TODO: Check what kind of values actually come out of the pipe
8536          * with these coeff/postoff values and adjust to get the best
8537          * accuracy. Perhaps we even need to take the bpc value into
8538          * consideration.
8539          */
8540
8541         if (intel_crtc->config->limited_color_range)
8542                 coeff = ((235 - 16) * (1 << 12) / 255) & 0xff8; /* 0.xxx... */
8543
8544         /*
8545          * GY/GU and RY/RU should be the other way around according
8546          * to BSpec, but reality doesn't agree. Just set them up in
8547          * a way that results in the correct picture.
8548          */
8549         I915_WRITE(PIPE_CSC_COEFF_RY_GY(pipe), coeff << 16);
8550         I915_WRITE(PIPE_CSC_COEFF_BY(pipe), 0);
8551
8552         I915_WRITE(PIPE_CSC_COEFF_RU_GU(pipe), coeff);
8553         I915_WRITE(PIPE_CSC_COEFF_BU(pipe), 0);
8554
8555         I915_WRITE(PIPE_CSC_COEFF_RV_GV(pipe), 0);
8556         I915_WRITE(PIPE_CSC_COEFF_BV(pipe), coeff << 16);
8557
8558         I915_WRITE(PIPE_CSC_PREOFF_HI(pipe), 0);
8559         I915_WRITE(PIPE_CSC_PREOFF_ME(pipe), 0);
8560         I915_WRITE(PIPE_CSC_PREOFF_LO(pipe), 0);
8561
8562         if (INTEL_INFO(dev)->gen > 6) {
8563                 uint16_t postoff = 0;
8564
8565                 if (intel_crtc->config->limited_color_range)
8566                         postoff = (16 * (1 << 12) / 255) & 0x1fff;
8567
8568                 I915_WRITE(PIPE_CSC_POSTOFF_HI(pipe), postoff);
8569                 I915_WRITE(PIPE_CSC_POSTOFF_ME(pipe), postoff);
8570                 I915_WRITE(PIPE_CSC_POSTOFF_LO(pipe), postoff);
8571
8572                 I915_WRITE(PIPE_CSC_MODE(pipe), 0);
8573         } else {
8574                 uint32_t mode = CSC_MODE_YUV_TO_RGB;
8575
8576                 if (intel_crtc->config->limited_color_range)
8577                         mode |= CSC_BLACK_SCREEN_OFFSET;
8578
8579                 I915_WRITE(PIPE_CSC_MODE(pipe), mode);
8580         }
8581 }
8582
8583 static void haswell_set_pipeconf(struct drm_crtc *crtc)
8584 {
8585         struct drm_device *dev = crtc->dev;
8586         struct drm_i915_private *dev_priv = dev->dev_private;
8587         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8588         enum pipe pipe = intel_crtc->pipe;
8589         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8590         uint32_t val;
8591
8592         val = 0;
8593
8594         if (IS_HASWELL(dev) && intel_crtc->config->dither)
8595                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8596
8597         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8598                 val |= PIPECONF_INTERLACED_ILK;
8599         else
8600                 val |= PIPECONF_PROGRESSIVE;
8601
8602         I915_WRITE(PIPECONF(cpu_transcoder), val);
8603         POSTING_READ(PIPECONF(cpu_transcoder));
8604
8605         I915_WRITE(GAMMA_MODE(intel_crtc->pipe), GAMMA_MODE_MODE_8BIT);
8606         POSTING_READ(GAMMA_MODE(intel_crtc->pipe));
8607
8608         if (IS_BROADWELL(dev) || INTEL_INFO(dev)->gen >= 9) {
8609                 val = 0;
8610
8611                 switch (intel_crtc->config->pipe_bpp) {
8612                 case 18:
8613                         val |= PIPEMISC_DITHER_6_BPC;
8614                         break;
8615                 case 24:
8616                         val |= PIPEMISC_DITHER_8_BPC;
8617                         break;
8618                 case 30:
8619                         val |= PIPEMISC_DITHER_10_BPC;
8620                         break;
8621                 case 36:
8622                         val |= PIPEMISC_DITHER_12_BPC;
8623                         break;
8624                 default:
8625                         /* Case prevented by pipe_config_set_bpp. */
8626                         BUG();
8627                 }
8628
8629                 if (intel_crtc->config->dither)
8630                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8631
8632                 I915_WRITE(PIPEMISC(pipe), val);
8633         }
8634 }
8635
8636 static bool ironlake_compute_clocks(struct drm_crtc *crtc,
8637                                     struct intel_crtc_state *crtc_state,
8638                                     intel_clock_t *clock,
8639                                     bool *has_reduced_clock,
8640                                     intel_clock_t *reduced_clock)
8641 {
8642         struct drm_device *dev = crtc->dev;
8643         struct drm_i915_private *dev_priv = dev->dev_private;
8644         int refclk;
8645         const intel_limit_t *limit;
8646         bool ret;
8647
8648         refclk = ironlake_get_refclk(crtc_state);
8649
8650         /*
8651          * Returns a set of divisors for the desired target clock with the given
8652          * refclk, or FALSE.  The returned values represent the clock equation:
8653          * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
8654          */
8655         limit = intel_limit(crtc_state, refclk);
8656         ret = dev_priv->display.find_dpll(limit, crtc_state,
8657                                           crtc_state->port_clock,
8658                                           refclk, NULL, clock);
8659         if (!ret)
8660                 return false;
8661
8662         return true;
8663 }
8664
8665 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8666 {
8667         /*
8668          * Account for spread spectrum to avoid
8669          * oversubscribing the link. Max center spread
8670          * is 2.5%; use 5% for safety's sake.
8671          */
8672         u32 bps = target_clock * bpp * 21 / 20;
8673         return DIV_ROUND_UP(bps, link_bw * 8);
8674 }
8675
8676 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8677 {
8678         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8679 }
8680
8681 static uint32_t ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8682                                       struct intel_crtc_state *crtc_state,
8683                                       u32 *fp,
8684                                       intel_clock_t *reduced_clock, u32 *fp2)
8685 {
8686         struct drm_crtc *crtc = &intel_crtc->base;
8687         struct drm_device *dev = crtc->dev;
8688         struct drm_i915_private *dev_priv = dev->dev_private;
8689         struct drm_atomic_state *state = crtc_state->base.state;
8690         struct drm_connector *connector;
8691         struct drm_connector_state *connector_state;
8692         struct intel_encoder *encoder;
8693         uint32_t dpll;
8694         int factor, num_connectors = 0, i;
8695         bool is_lvds = false, is_sdvo = false;
8696
8697         for_each_connector_in_state(state, connector, connector_state, i) {
8698                 if (connector_state->crtc != crtc_state->base.crtc)
8699                         continue;
8700
8701                 encoder = to_intel_encoder(connector_state->best_encoder);
8702
8703                 switch (encoder->type) {
8704                 case INTEL_OUTPUT_LVDS:
8705                         is_lvds = true;
8706                         break;
8707                 case INTEL_OUTPUT_SDVO:
8708                 case INTEL_OUTPUT_HDMI:
8709                         is_sdvo = true;
8710                         break;
8711                 default:
8712                         break;
8713                 }
8714
8715                 num_connectors++;
8716         }
8717
8718         /* Enable autotuning of the PLL clock (if permissible) */
8719         factor = 21;
8720         if (is_lvds) {
8721                 if ((intel_panel_use_ssc(dev_priv) &&
8722                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8723                     (HAS_PCH_IBX(dev) && intel_is_dual_link_lvds(dev)))
8724                         factor = 25;
8725         } else if (crtc_state->sdvo_tv_clock)
8726                 factor = 20;
8727
8728         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8729                 *fp |= FP_CB_TUNE;
8730
8731         if (fp2 && (reduced_clock->m < factor * reduced_clock->n))
8732                 *fp2 |= FP_CB_TUNE;
8733
8734         dpll = 0;
8735
8736         if (is_lvds)
8737                 dpll |= DPLLB_MODE_LVDS;
8738         else
8739                 dpll |= DPLLB_MODE_DAC_SERIAL;
8740
8741         dpll |= (crtc_state->pixel_multiplier - 1)
8742                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8743
8744         if (is_sdvo)
8745                 dpll |= DPLL_SDVO_HIGH_SPEED;
8746         if (crtc_state->has_dp_encoder)
8747                 dpll |= DPLL_SDVO_HIGH_SPEED;
8748
8749         /* compute bitmask from p1 value */
8750         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8751         /* also FPA1 */
8752         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8753
8754         switch (crtc_state->dpll.p2) {
8755         case 5:
8756                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8757                 break;
8758         case 7:
8759                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8760                 break;
8761         case 10:
8762                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8763                 break;
8764         case 14:
8765                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8766                 break;
8767         }
8768
8769         if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2)
8770                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8771         else
8772                 dpll |= PLL_REF_INPUT_DREFCLK;
8773
8774         return dpll | DPLL_VCO_ENABLE;
8775 }
8776
8777 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
8778                                        struct intel_crtc_state *crtc_state)
8779 {
8780         struct drm_device *dev = crtc->base.dev;
8781         intel_clock_t clock, reduced_clock;
8782         u32 dpll = 0, fp = 0, fp2 = 0;
8783         bool ok, has_reduced_clock = false;
8784         bool is_lvds = false;
8785         struct intel_shared_dpll *pll;
8786
8787         memset(&crtc_state->dpll_hw_state, 0,
8788                sizeof(crtc_state->dpll_hw_state));
8789
8790         is_lvds = intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS);
8791
8792         WARN(!(HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev)),
8793              "Unexpected PCH type %d\n", INTEL_PCH_TYPE(dev));
8794
8795         ok = ironlake_compute_clocks(&crtc->base, crtc_state, &clock,
8796                                      &has_reduced_clock, &reduced_clock);
8797         if (!ok && !crtc_state->clock_set) {
8798                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8799                 return -EINVAL;
8800         }
8801         /* Compat-code for transition, will disappear. */
8802         if (!crtc_state->clock_set) {
8803                 crtc_state->dpll.n = clock.n;
8804                 crtc_state->dpll.m1 = clock.m1;
8805                 crtc_state->dpll.m2 = clock.m2;
8806                 crtc_state->dpll.p1 = clock.p1;
8807                 crtc_state->dpll.p2 = clock.p2;
8808         }
8809
8810         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
8811         if (crtc_state->has_pch_encoder) {
8812                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8813                 if (has_reduced_clock)
8814                         fp2 = i9xx_dpll_compute_fp(&reduced_clock);
8815
8816                 dpll = ironlake_compute_dpll(crtc, crtc_state,
8817                                              &fp, &reduced_clock,
8818                                              has_reduced_clock ? &fp2 : NULL);
8819
8820                 crtc_state->dpll_hw_state.dpll = dpll;
8821                 crtc_state->dpll_hw_state.fp0 = fp;
8822                 if (has_reduced_clock)
8823                         crtc_state->dpll_hw_state.fp1 = fp2;
8824                 else
8825                         crtc_state->dpll_hw_state.fp1 = fp;
8826
8827                 pll = intel_get_shared_dpll(crtc, crtc_state);
8828                 if (pll == NULL) {
8829                         DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
8830                                          pipe_name(crtc->pipe));
8831                         return -EINVAL;
8832                 }
8833         }
8834
8835         if (is_lvds && has_reduced_clock)
8836                 crtc->lowfreq_avail = true;
8837         else
8838                 crtc->lowfreq_avail = false;
8839
8840         return 0;
8841 }
8842
8843 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
8844                                          struct intel_link_m_n *m_n)
8845 {
8846         struct drm_device *dev = crtc->base.dev;
8847         struct drm_i915_private *dev_priv = dev->dev_private;
8848         enum pipe pipe = crtc->pipe;
8849
8850         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
8851         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
8852         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
8853                 & ~TU_SIZE_MASK;
8854         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
8855         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
8856                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8857 }
8858
8859 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
8860                                          enum transcoder transcoder,
8861                                          struct intel_link_m_n *m_n,
8862                                          struct intel_link_m_n *m2_n2)
8863 {
8864         struct drm_device *dev = crtc->base.dev;
8865         struct drm_i915_private *dev_priv = dev->dev_private;
8866         enum pipe pipe = crtc->pipe;
8867
8868         if (INTEL_INFO(dev)->gen >= 5) {
8869                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
8870                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
8871                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
8872                         & ~TU_SIZE_MASK;
8873                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
8874                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
8875                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8876                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
8877                  * gen < 8) and if DRRS is supported (to make sure the
8878                  * registers are not unnecessarily read).
8879                  */
8880                 if (m2_n2 && INTEL_INFO(dev)->gen < 8 &&
8881                         crtc->config->has_drrs) {
8882                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
8883                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
8884                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
8885                                         & ~TU_SIZE_MASK;
8886                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
8887                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
8888                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8889                 }
8890         } else {
8891                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
8892                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
8893                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
8894                         & ~TU_SIZE_MASK;
8895                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
8896                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
8897                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8898         }
8899 }
8900
8901 void intel_dp_get_m_n(struct intel_crtc *crtc,
8902                       struct intel_crtc_state *pipe_config)
8903 {
8904         if (pipe_config->has_pch_encoder)
8905                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
8906         else
8907                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8908                                              &pipe_config->dp_m_n,
8909                                              &pipe_config->dp_m2_n2);
8910 }
8911
8912 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
8913                                         struct intel_crtc_state *pipe_config)
8914 {
8915         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8916                                      &pipe_config->fdi_m_n, NULL);
8917 }
8918
8919 static void skylake_get_pfit_config(struct intel_crtc *crtc,
8920                                     struct intel_crtc_state *pipe_config)
8921 {
8922         struct drm_device *dev = crtc->base.dev;
8923         struct drm_i915_private *dev_priv = dev->dev_private;
8924         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
8925         uint32_t ps_ctrl = 0;
8926         int id = -1;
8927         int i;
8928
8929         /* find scaler attached to this pipe */
8930         for (i = 0; i < crtc->num_scalers; i++) {
8931                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
8932                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
8933                         id = i;
8934                         pipe_config->pch_pfit.enabled = true;
8935                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
8936                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
8937                         break;
8938                 }
8939         }
8940
8941         scaler_state->scaler_id = id;
8942         if (id >= 0) {
8943                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
8944         } else {
8945                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
8946         }
8947 }
8948
8949 static void
8950 skylake_get_initial_plane_config(struct intel_crtc *crtc,
8951                                  struct intel_initial_plane_config *plane_config)
8952 {
8953         struct drm_device *dev = crtc->base.dev;
8954         struct drm_i915_private *dev_priv = dev->dev_private;
8955         u32 val, base, offset, stride_mult, tiling;
8956         int pipe = crtc->pipe;
8957         int fourcc, pixel_format;
8958         unsigned int aligned_height;
8959         struct drm_framebuffer *fb;
8960         struct intel_framebuffer *intel_fb;
8961
8962         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8963         if (!intel_fb) {
8964                 DRM_DEBUG_KMS("failed to alloc fb\n");
8965                 return;
8966         }
8967
8968         fb = &intel_fb->base;
8969
8970         val = I915_READ(PLANE_CTL(pipe, 0));
8971         if (!(val & PLANE_CTL_ENABLE))
8972                 goto error;
8973
8974         pixel_format = val & PLANE_CTL_FORMAT_MASK;
8975         fourcc = skl_format_to_fourcc(pixel_format,
8976                                       val & PLANE_CTL_ORDER_RGBX,
8977                                       val & PLANE_CTL_ALPHA_MASK);
8978         fb->pixel_format = fourcc;
8979         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
8980
8981         tiling = val & PLANE_CTL_TILED_MASK;
8982         switch (tiling) {
8983         case PLANE_CTL_TILED_LINEAR:
8984                 fb->modifier[0] = DRM_FORMAT_MOD_NONE;
8985                 break;
8986         case PLANE_CTL_TILED_X:
8987                 plane_config->tiling = I915_TILING_X;
8988                 fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
8989                 break;
8990         case PLANE_CTL_TILED_Y:
8991                 fb->modifier[0] = I915_FORMAT_MOD_Y_TILED;
8992                 break;
8993         case PLANE_CTL_TILED_YF:
8994                 fb->modifier[0] = I915_FORMAT_MOD_Yf_TILED;
8995                 break;
8996         default:
8997                 MISSING_CASE(tiling);
8998                 goto error;
8999         }
9000
9001         base = I915_READ(PLANE_SURF(pipe, 0)) & 0xfffff000;
9002         plane_config->base = base;
9003
9004         offset = I915_READ(PLANE_OFFSET(pipe, 0));
9005
9006         val = I915_READ(PLANE_SIZE(pipe, 0));
9007         fb->height = ((val >> 16) & 0xfff) + 1;
9008         fb->width = ((val >> 0) & 0x1fff) + 1;
9009
9010         val = I915_READ(PLANE_STRIDE(pipe, 0));
9011         stride_mult = intel_fb_stride_alignment(dev, fb->modifier[0],
9012                                                 fb->pixel_format);
9013         fb->pitches[0] = (val & 0x3ff) * stride_mult;
9014
9015         aligned_height = intel_fb_align_height(dev, fb->height,
9016                                                fb->pixel_format,
9017                                                fb->modifier[0]);
9018
9019         plane_config->size = fb->pitches[0] * aligned_height;
9020
9021         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9022                       pipe_name(pipe), fb->width, fb->height,
9023                       fb->bits_per_pixel, base, fb->pitches[0],
9024                       plane_config->size);
9025
9026         plane_config->fb = intel_fb;
9027         return;
9028
9029 error:
9030         kfree(fb);
9031 }
9032
9033 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
9034                                      struct intel_crtc_state *pipe_config)
9035 {
9036         struct drm_device *dev = crtc->base.dev;
9037         struct drm_i915_private *dev_priv = dev->dev_private;
9038         uint32_t tmp;
9039
9040         tmp = I915_READ(PF_CTL(crtc->pipe));
9041
9042         if (tmp & PF_ENABLE) {
9043                 pipe_config->pch_pfit.enabled = true;
9044                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
9045                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
9046
9047                 /* We currently do not free assignements of panel fitters on
9048                  * ivb/hsw (since we don't use the higher upscaling modes which
9049                  * differentiates them) so just WARN about this case for now. */
9050                 if (IS_GEN7(dev)) {
9051                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
9052                                 PF_PIPE_SEL_IVB(crtc->pipe));
9053                 }
9054         }
9055 }
9056
9057 static void
9058 ironlake_get_initial_plane_config(struct intel_crtc *crtc,
9059                                   struct intel_initial_plane_config *plane_config)
9060 {
9061         struct drm_device *dev = crtc->base.dev;
9062         struct drm_i915_private *dev_priv = dev->dev_private;
9063         u32 val, base, offset;
9064         int pipe = crtc->pipe;
9065         int fourcc, pixel_format;
9066         unsigned int aligned_height;
9067         struct drm_framebuffer *fb;
9068         struct intel_framebuffer *intel_fb;
9069
9070         val = I915_READ(DSPCNTR(pipe));
9071         if (!(val & DISPLAY_PLANE_ENABLE))
9072                 return;
9073
9074         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9075         if (!intel_fb) {
9076                 DRM_DEBUG_KMS("failed to alloc fb\n");
9077                 return;
9078         }
9079
9080         fb = &intel_fb->base;
9081
9082         if (INTEL_INFO(dev)->gen >= 4) {
9083                 if (val & DISPPLANE_TILED) {
9084                         plane_config->tiling = I915_TILING_X;
9085                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9086                 }
9087         }
9088
9089         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
9090         fourcc = i9xx_format_to_fourcc(pixel_format);
9091         fb->pixel_format = fourcc;
9092         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9093
9094         base = I915_READ(DSPSURF(pipe)) & 0xfffff000;
9095         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
9096                 offset = I915_READ(DSPOFFSET(pipe));
9097         } else {
9098                 if (plane_config->tiling)
9099                         offset = I915_READ(DSPTILEOFF(pipe));
9100                 else
9101                         offset = I915_READ(DSPLINOFF(pipe));
9102         }
9103         plane_config->base = base;
9104
9105         val = I915_READ(PIPESRC(pipe));
9106         fb->width = ((val >> 16) & 0xfff) + 1;
9107         fb->height = ((val >> 0) & 0xfff) + 1;
9108
9109         val = I915_READ(DSPSTRIDE(pipe));
9110         fb->pitches[0] = val & 0xffffffc0;
9111
9112         aligned_height = intel_fb_align_height(dev, fb->height,
9113                                                fb->pixel_format,
9114                                                fb->modifier[0]);
9115
9116         plane_config->size = fb->pitches[0] * aligned_height;
9117
9118         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9119                       pipe_name(pipe), fb->width, fb->height,
9120                       fb->bits_per_pixel, base, fb->pitches[0],
9121                       plane_config->size);
9122
9123         plane_config->fb = intel_fb;
9124 }
9125
9126 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
9127                                      struct intel_crtc_state *pipe_config)
9128 {
9129         struct drm_device *dev = crtc->base.dev;
9130         struct drm_i915_private *dev_priv = dev->dev_private;
9131         uint32_t tmp;
9132
9133         if (!intel_display_power_is_enabled(dev_priv,
9134                                             POWER_DOMAIN_PIPE(crtc->pipe)))
9135                 return false;
9136
9137         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9138         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
9139
9140         tmp = I915_READ(PIPECONF(crtc->pipe));
9141         if (!(tmp & PIPECONF_ENABLE))
9142                 return false;
9143
9144         switch (tmp & PIPECONF_BPC_MASK) {
9145         case PIPECONF_6BPC:
9146                 pipe_config->pipe_bpp = 18;
9147                 break;
9148         case PIPECONF_8BPC:
9149                 pipe_config->pipe_bpp = 24;
9150                 break;
9151         case PIPECONF_10BPC:
9152                 pipe_config->pipe_bpp = 30;
9153                 break;
9154         case PIPECONF_12BPC:
9155                 pipe_config->pipe_bpp = 36;
9156                 break;
9157         default:
9158                 break;
9159         }
9160
9161         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
9162                 pipe_config->limited_color_range = true;
9163
9164         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
9165                 struct intel_shared_dpll *pll;
9166
9167                 pipe_config->has_pch_encoder = true;
9168
9169                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
9170                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9171                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9172
9173                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9174
9175                 if (HAS_PCH_IBX(dev_priv->dev)) {
9176                         pipe_config->shared_dpll =
9177                                 (enum intel_dpll_id) crtc->pipe;
9178                 } else {
9179                         tmp = I915_READ(PCH_DPLL_SEL);
9180                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
9181                                 pipe_config->shared_dpll = DPLL_ID_PCH_PLL_B;
9182                         else
9183                                 pipe_config->shared_dpll = DPLL_ID_PCH_PLL_A;
9184                 }
9185
9186                 pll = &dev_priv->shared_dplls[pipe_config->shared_dpll];
9187
9188                 WARN_ON(!pll->get_hw_state(dev_priv, pll,
9189                                            &pipe_config->dpll_hw_state));
9190
9191                 tmp = pipe_config->dpll_hw_state.dpll;
9192                 pipe_config->pixel_multiplier =
9193                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
9194                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
9195
9196                 ironlake_pch_clock_get(crtc, pipe_config);
9197         } else {
9198                 pipe_config->pixel_multiplier = 1;
9199         }
9200
9201         intel_get_pipe_timings(crtc, pipe_config);
9202
9203         ironlake_get_pfit_config(crtc, pipe_config);
9204
9205         return true;
9206 }
9207
9208 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
9209 {
9210         struct drm_device *dev = dev_priv->dev;
9211         struct intel_crtc *crtc;
9212
9213         for_each_intel_crtc(dev, crtc)
9214                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
9215                      pipe_name(crtc->pipe));
9216
9217         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_DRIVER), "Power well on\n");
9218         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
9219         I915_STATE_WARN(I915_READ(WRPLL_CTL1) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
9220         I915_STATE_WARN(I915_READ(WRPLL_CTL2) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
9221         I915_STATE_WARN(I915_READ(PCH_PP_STATUS) & PP_ON, "Panel power on\n");
9222         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
9223              "CPU PWM1 enabled\n");
9224         if (IS_HASWELL(dev))
9225                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
9226                      "CPU PWM2 enabled\n");
9227         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
9228              "PCH PWM1 enabled\n");
9229         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
9230              "Utility pin enabled\n");
9231         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
9232
9233         /*
9234          * In theory we can still leave IRQs enabled, as long as only the HPD
9235          * interrupts remain enabled. We used to check for that, but since it's
9236          * gen-specific and since we only disable LCPLL after we fully disable
9237          * the interrupts, the check below should be enough.
9238          */
9239         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
9240 }
9241
9242 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
9243 {
9244         struct drm_device *dev = dev_priv->dev;
9245
9246         if (IS_HASWELL(dev))
9247                 return I915_READ(D_COMP_HSW);
9248         else
9249                 return I915_READ(D_COMP_BDW);
9250 }
9251
9252 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
9253 {
9254         struct drm_device *dev = dev_priv->dev;
9255
9256         if (IS_HASWELL(dev)) {
9257                 mutex_lock(&dev_priv->rps.hw_lock);
9258                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
9259                                             val))
9260                         DRM_ERROR("Failed to write to D_COMP\n");
9261                 mutex_unlock(&dev_priv->rps.hw_lock);
9262         } else {
9263                 I915_WRITE(D_COMP_BDW, val);
9264                 POSTING_READ(D_COMP_BDW);
9265         }
9266 }
9267
9268 /*
9269  * This function implements pieces of two sequences from BSpec:
9270  * - Sequence for display software to disable LCPLL
9271  * - Sequence for display software to allow package C8+
9272  * The steps implemented here are just the steps that actually touch the LCPLL
9273  * register. Callers should take care of disabling all the display engine
9274  * functions, doing the mode unset, fixing interrupts, etc.
9275  */
9276 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
9277                               bool switch_to_fclk, bool allow_power_down)
9278 {
9279         uint32_t val;
9280
9281         assert_can_disable_lcpll(dev_priv);
9282
9283         val = I915_READ(LCPLL_CTL);
9284
9285         if (switch_to_fclk) {
9286                 val |= LCPLL_CD_SOURCE_FCLK;
9287                 I915_WRITE(LCPLL_CTL, val);
9288
9289                 if (wait_for_atomic_us(I915_READ(LCPLL_CTL) &
9290                                        LCPLL_CD_SOURCE_FCLK_DONE, 1))
9291                         DRM_ERROR("Switching to FCLK failed\n");
9292
9293                 val = I915_READ(LCPLL_CTL);
9294         }
9295
9296         val |= LCPLL_PLL_DISABLE;
9297         I915_WRITE(LCPLL_CTL, val);
9298         POSTING_READ(LCPLL_CTL);
9299
9300         if (wait_for((I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK) == 0, 1))
9301                 DRM_ERROR("LCPLL still locked\n");
9302
9303         val = hsw_read_dcomp(dev_priv);
9304         val |= D_COMP_COMP_DISABLE;
9305         hsw_write_dcomp(dev_priv, val);
9306         ndelay(100);
9307
9308         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
9309                      1))
9310                 DRM_ERROR("D_COMP RCOMP still in progress\n");
9311
9312         if (allow_power_down) {
9313                 val = I915_READ(LCPLL_CTL);
9314                 val |= LCPLL_POWER_DOWN_ALLOW;
9315                 I915_WRITE(LCPLL_CTL, val);
9316                 POSTING_READ(LCPLL_CTL);
9317         }
9318 }
9319
9320 /*
9321  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
9322  * source.
9323  */
9324 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
9325 {
9326         uint32_t val;
9327
9328         val = I915_READ(LCPLL_CTL);
9329
9330         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
9331                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
9332                 return;
9333
9334         /*
9335          * Make sure we're not on PC8 state before disabling PC8, otherwise
9336          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
9337          */
9338         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
9339
9340         if (val & LCPLL_POWER_DOWN_ALLOW) {
9341                 val &= ~LCPLL_POWER_DOWN_ALLOW;
9342                 I915_WRITE(LCPLL_CTL, val);
9343                 POSTING_READ(LCPLL_CTL);
9344         }
9345
9346         val = hsw_read_dcomp(dev_priv);
9347         val |= D_COMP_COMP_FORCE;
9348         val &= ~D_COMP_COMP_DISABLE;
9349         hsw_write_dcomp(dev_priv, val);
9350
9351         val = I915_READ(LCPLL_CTL);
9352         val &= ~LCPLL_PLL_DISABLE;
9353         I915_WRITE(LCPLL_CTL, val);
9354
9355         if (wait_for(I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK, 5))
9356                 DRM_ERROR("LCPLL not locked yet\n");
9357
9358         if (val & LCPLL_CD_SOURCE_FCLK) {
9359                 val = I915_READ(LCPLL_CTL);
9360                 val &= ~LCPLL_CD_SOURCE_FCLK;
9361                 I915_WRITE(LCPLL_CTL, val);
9362
9363                 if (wait_for_atomic_us((I915_READ(LCPLL_CTL) &
9364                                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9365                         DRM_ERROR("Switching back to LCPLL failed\n");
9366         }
9367
9368         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
9369         intel_update_cdclk(dev_priv->dev);
9370 }
9371
9372 /*
9373  * Package states C8 and deeper are really deep PC states that can only be
9374  * reached when all the devices on the system allow it, so even if the graphics
9375  * device allows PC8+, it doesn't mean the system will actually get to these
9376  * states. Our driver only allows PC8+ when going into runtime PM.
9377  *
9378  * The requirements for PC8+ are that all the outputs are disabled, the power
9379  * well is disabled and most interrupts are disabled, and these are also
9380  * requirements for runtime PM. When these conditions are met, we manually do
9381  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
9382  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
9383  * hang the machine.
9384  *
9385  * When we really reach PC8 or deeper states (not just when we allow it) we lose
9386  * the state of some registers, so when we come back from PC8+ we need to
9387  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
9388  * need to take care of the registers kept by RC6. Notice that this happens even
9389  * if we don't put the device in PCI D3 state (which is what currently happens
9390  * because of the runtime PM support).
9391  *
9392  * For more, read "Display Sequences for Package C8" on the hardware
9393  * documentation.
9394  */
9395 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
9396 {
9397         struct drm_device *dev = dev_priv->dev;
9398         uint32_t val;
9399
9400         DRM_DEBUG_KMS("Enabling package C8+\n");
9401
9402         if (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) {
9403                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9404                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
9405                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9406         }
9407
9408         lpt_disable_clkout_dp(dev);
9409         hsw_disable_lcpll(dev_priv, true, true);
9410 }
9411
9412 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
9413 {
9414         struct drm_device *dev = dev_priv->dev;
9415         uint32_t val;
9416
9417         DRM_DEBUG_KMS("Disabling package C8+\n");
9418
9419         hsw_restore_lcpll(dev_priv);
9420         lpt_init_pch_refclk(dev);
9421
9422         if (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) {
9423                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9424                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
9425                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9426         }
9427
9428         intel_prepare_ddi(dev);
9429 }
9430
9431 static void broxton_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9432 {
9433         struct drm_device *dev = old_state->dev;
9434         unsigned int req_cdclk = to_intel_atomic_state(old_state)->cdclk;
9435
9436         broxton_set_cdclk(dev, req_cdclk);
9437 }
9438
9439 /* compute the max rate for new configuration */
9440 static int ilk_max_pixel_rate(struct drm_atomic_state *state)
9441 {
9442         struct intel_crtc *intel_crtc;
9443         struct intel_crtc_state *crtc_state;
9444         int max_pixel_rate = 0;
9445
9446         for_each_intel_crtc(state->dev, intel_crtc) {
9447                 int pixel_rate;
9448
9449                 crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
9450                 if (IS_ERR(crtc_state))
9451                         return PTR_ERR(crtc_state);
9452
9453                 if (!crtc_state->base.enable)
9454                         continue;
9455
9456                 pixel_rate = ilk_pipe_pixel_rate(crtc_state);
9457
9458                 /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
9459                 if (IS_BROADWELL(state->dev) && crtc_state->ips_enabled)
9460                         pixel_rate = DIV_ROUND_UP(pixel_rate * 100, 95);
9461
9462                 max_pixel_rate = max(max_pixel_rate, pixel_rate);
9463         }
9464
9465         return max_pixel_rate;
9466 }
9467
9468 static void broadwell_set_cdclk(struct drm_device *dev, int cdclk)
9469 {
9470         struct drm_i915_private *dev_priv = dev->dev_private;
9471         uint32_t val, data;
9472         int ret;
9473
9474         if (WARN((I915_READ(LCPLL_CTL) &
9475                   (LCPLL_PLL_DISABLE | LCPLL_PLL_LOCK |
9476                    LCPLL_CD_CLOCK_DISABLE | LCPLL_ROOT_CD_CLOCK_DISABLE |
9477                    LCPLL_CD2X_CLOCK_DISABLE | LCPLL_POWER_DOWN_ALLOW |
9478                    LCPLL_CD_SOURCE_FCLK)) != LCPLL_PLL_LOCK,
9479                  "trying to change cdclk frequency with cdclk not enabled\n"))
9480                 return;
9481
9482         mutex_lock(&dev_priv->rps.hw_lock);
9483         ret = sandybridge_pcode_write(dev_priv,
9484                                       BDW_PCODE_DISPLAY_FREQ_CHANGE_REQ, 0x0);
9485         mutex_unlock(&dev_priv->rps.hw_lock);
9486         if (ret) {
9487                 DRM_ERROR("failed to inform pcode about cdclk change\n");
9488                 return;
9489         }
9490
9491         val = I915_READ(LCPLL_CTL);
9492         val |= LCPLL_CD_SOURCE_FCLK;
9493         I915_WRITE(LCPLL_CTL, val);
9494
9495         if (wait_for_atomic_us(I915_READ(LCPLL_CTL) &
9496                                LCPLL_CD_SOURCE_FCLK_DONE, 1))
9497                 DRM_ERROR("Switching to FCLK failed\n");
9498
9499         val = I915_READ(LCPLL_CTL);
9500         val &= ~LCPLL_CLK_FREQ_MASK;
9501
9502         switch (cdclk) {
9503         case 450000:
9504                 val |= LCPLL_CLK_FREQ_450;
9505                 data = 0;
9506                 break;
9507         case 540000:
9508                 val |= LCPLL_CLK_FREQ_54O_BDW;
9509                 data = 1;
9510                 break;
9511         case 337500:
9512                 val |= LCPLL_CLK_FREQ_337_5_BDW;
9513                 data = 2;
9514                 break;
9515         case 675000:
9516                 val |= LCPLL_CLK_FREQ_675_BDW;
9517                 data = 3;
9518                 break;
9519         default:
9520                 WARN(1, "invalid cdclk frequency\n");
9521                 return;
9522         }
9523
9524         I915_WRITE(LCPLL_CTL, val);
9525
9526         val = I915_READ(LCPLL_CTL);
9527         val &= ~LCPLL_CD_SOURCE_FCLK;
9528         I915_WRITE(LCPLL_CTL, val);
9529
9530         if (wait_for_atomic_us((I915_READ(LCPLL_CTL) &
9531                                 LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9532                 DRM_ERROR("Switching back to LCPLL failed\n");
9533
9534         mutex_lock(&dev_priv->rps.hw_lock);
9535         sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ, data);
9536         mutex_unlock(&dev_priv->rps.hw_lock);
9537
9538         intel_update_cdclk(dev);
9539
9540         WARN(cdclk != dev_priv->cdclk_freq,
9541              "cdclk requested %d kHz but got %d kHz\n",
9542              cdclk, dev_priv->cdclk_freq);
9543 }
9544
9545 static int broadwell_modeset_calc_cdclk(struct drm_atomic_state *state)
9546 {
9547         struct drm_i915_private *dev_priv = to_i915(state->dev);
9548         int max_pixclk = ilk_max_pixel_rate(state);
9549         int cdclk;
9550
9551         /*
9552          * FIXME should also account for plane ratio
9553          * once 64bpp pixel formats are supported.
9554          */
9555         if (max_pixclk > 540000)
9556                 cdclk = 675000;
9557         else if (max_pixclk > 450000)
9558                 cdclk = 540000;
9559         else if (max_pixclk > 337500)
9560                 cdclk = 450000;
9561         else
9562                 cdclk = 337500;
9563
9564         /*
9565          * FIXME move the cdclk caclulation to
9566          * compute_config() so we can fail gracegully.
9567          */
9568         if (cdclk > dev_priv->max_cdclk_freq) {
9569                 DRM_ERROR("requested cdclk (%d kHz) exceeds max (%d kHz)\n",
9570                           cdclk, dev_priv->max_cdclk_freq);
9571                 cdclk = dev_priv->max_cdclk_freq;
9572         }
9573
9574         to_intel_atomic_state(state)->cdclk = cdclk;
9575
9576         return 0;
9577 }
9578
9579 static void broadwell_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9580 {
9581         struct drm_device *dev = old_state->dev;
9582         unsigned int req_cdclk = to_intel_atomic_state(old_state)->cdclk;
9583
9584         broadwell_set_cdclk(dev, req_cdclk);
9585 }
9586
9587 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9588                                       struct intel_crtc_state *crtc_state)
9589 {
9590         if (!intel_ddi_pll_select(crtc, crtc_state))
9591                 return -EINVAL;
9592
9593         crtc->lowfreq_avail = false;
9594
9595         return 0;
9596 }
9597
9598 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9599                                 enum port port,
9600                                 struct intel_crtc_state *pipe_config)
9601 {
9602         switch (port) {
9603         case PORT_A:
9604                 pipe_config->ddi_pll_sel = SKL_DPLL0;
9605                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL1;
9606                 break;
9607         case PORT_B:
9608                 pipe_config->ddi_pll_sel = SKL_DPLL1;
9609                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL2;
9610                 break;
9611         case PORT_C:
9612                 pipe_config->ddi_pll_sel = SKL_DPLL2;
9613                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL3;
9614                 break;
9615         default:
9616                 DRM_ERROR("Incorrect port type\n");
9617         }
9618 }
9619
9620 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9621                                 enum port port,
9622                                 struct intel_crtc_state *pipe_config)
9623 {
9624         u32 temp, dpll_ctl1;
9625
9626         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9627         pipe_config->ddi_pll_sel = temp >> (port * 3 + 1);
9628
9629         switch (pipe_config->ddi_pll_sel) {
9630         case SKL_DPLL0:
9631                 /*
9632                  * On SKL the eDP DPLL (DPLL0 as we don't use SSC) is not part
9633                  * of the shared DPLL framework and thus needs to be read out
9634                  * separately
9635                  */
9636                 dpll_ctl1 = I915_READ(DPLL_CTRL1);
9637                 pipe_config->dpll_hw_state.ctrl1 = dpll_ctl1 & 0x3f;
9638                 break;
9639         case SKL_DPLL1:
9640                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL1;
9641                 break;
9642         case SKL_DPLL2:
9643                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL2;
9644                 break;
9645         case SKL_DPLL3:
9646                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL3;
9647                 break;
9648         }
9649 }
9650
9651 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9652                                 enum port port,
9653                                 struct intel_crtc_state *pipe_config)
9654 {
9655         pipe_config->ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9656
9657         switch (pipe_config->ddi_pll_sel) {
9658         case PORT_CLK_SEL_WRPLL1:
9659                 pipe_config->shared_dpll = DPLL_ID_WRPLL1;
9660                 break;
9661         case PORT_CLK_SEL_WRPLL2:
9662                 pipe_config->shared_dpll = DPLL_ID_WRPLL2;
9663                 break;
9664         }
9665 }
9666
9667 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9668                                        struct intel_crtc_state *pipe_config)
9669 {
9670         struct drm_device *dev = crtc->base.dev;
9671         struct drm_i915_private *dev_priv = dev->dev_private;
9672         struct intel_shared_dpll *pll;
9673         enum port port;
9674         uint32_t tmp;
9675
9676         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9677
9678         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9679
9680         if (IS_SKYLAKE(dev))
9681                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
9682         else if (IS_BROXTON(dev))
9683                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
9684         else
9685                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
9686
9687         if (pipe_config->shared_dpll >= 0) {
9688                 pll = &dev_priv->shared_dplls[pipe_config->shared_dpll];
9689
9690                 WARN_ON(!pll->get_hw_state(dev_priv, pll,
9691                                            &pipe_config->dpll_hw_state));
9692         }
9693
9694         /*
9695          * Haswell has only FDI/PCH transcoder A. It is which is connected to
9696          * DDI E. So just check whether this pipe is wired to DDI E and whether
9697          * the PCH transcoder is on.
9698          */
9699         if (INTEL_INFO(dev)->gen < 9 &&
9700             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
9701                 pipe_config->has_pch_encoder = true;
9702
9703                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
9704                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9705                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9706
9707                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9708         }
9709 }
9710
9711 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
9712                                     struct intel_crtc_state *pipe_config)
9713 {
9714         struct drm_device *dev = crtc->base.dev;
9715         struct drm_i915_private *dev_priv = dev->dev_private;
9716         enum intel_display_power_domain pfit_domain;
9717         uint32_t tmp;
9718
9719         if (!intel_display_power_is_enabled(dev_priv,
9720                                          POWER_DOMAIN_PIPE(crtc->pipe)))
9721                 return false;
9722
9723         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9724         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
9725
9726         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
9727         if (tmp & TRANS_DDI_FUNC_ENABLE) {
9728                 enum pipe trans_edp_pipe;
9729                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9730                 default:
9731                         WARN(1, "unknown pipe linked to edp transcoder\n");
9732                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9733                 case TRANS_DDI_EDP_INPUT_A_ON:
9734                         trans_edp_pipe = PIPE_A;
9735                         break;
9736                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
9737                         trans_edp_pipe = PIPE_B;
9738                         break;
9739                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
9740                         trans_edp_pipe = PIPE_C;
9741                         break;
9742                 }
9743
9744                 if (trans_edp_pipe == crtc->pipe)
9745                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
9746         }
9747
9748         if (!intel_display_power_is_enabled(dev_priv,
9749                         POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder)))
9750                 return false;
9751
9752         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
9753         if (!(tmp & PIPECONF_ENABLE))
9754                 return false;
9755
9756         haswell_get_ddi_port_state(crtc, pipe_config);
9757
9758         intel_get_pipe_timings(crtc, pipe_config);
9759
9760         if (INTEL_INFO(dev)->gen >= 9) {
9761                 skl_init_scalers(dev, crtc, pipe_config);
9762         }
9763
9764         pfit_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
9765
9766         if (INTEL_INFO(dev)->gen >= 9) {
9767                 pipe_config->scaler_state.scaler_id = -1;
9768                 pipe_config->scaler_state.scaler_users &= ~(1 << SKL_CRTC_INDEX);
9769         }
9770
9771         if (intel_display_power_is_enabled(dev_priv, pfit_domain)) {
9772                 if (INTEL_INFO(dev)->gen == 9)
9773                         skylake_get_pfit_config(crtc, pipe_config);
9774                 else if (INTEL_INFO(dev)->gen < 9)
9775                         ironlake_get_pfit_config(crtc, pipe_config);
9776                 else
9777                         MISSING_CASE(INTEL_INFO(dev)->gen);
9778         }
9779
9780         if (IS_HASWELL(dev))
9781                 pipe_config->ips_enabled = hsw_crtc_supports_ips(crtc) &&
9782                         (I915_READ(IPS_CTL) & IPS_ENABLE);
9783
9784         if (pipe_config->cpu_transcoder != TRANSCODER_EDP) {
9785                 pipe_config->pixel_multiplier =
9786                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
9787         } else {
9788                 pipe_config->pixel_multiplier = 1;
9789         }
9790
9791         return true;
9792 }
9793
9794 static void i845_update_cursor(struct drm_crtc *crtc, u32 base)
9795 {
9796         struct drm_device *dev = crtc->dev;
9797         struct drm_i915_private *dev_priv = dev->dev_private;
9798         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9799         uint32_t cntl = 0, size = 0;
9800
9801         if (base) {
9802                 unsigned int width = intel_crtc->base.cursor->state->crtc_w;
9803                 unsigned int height = intel_crtc->base.cursor->state->crtc_h;
9804                 unsigned int stride = roundup_pow_of_two(width) * 4;
9805
9806                 switch (stride) {
9807                 default:
9808                         WARN_ONCE(1, "Invalid cursor width/stride, width=%u, stride=%u\n",
9809                                   width, stride);
9810                         stride = 256;
9811                         /* fallthrough */
9812                 case 256:
9813                 case 512:
9814                 case 1024:
9815                 case 2048:
9816                         break;
9817                 }
9818
9819                 cntl |= CURSOR_ENABLE |
9820                         CURSOR_GAMMA_ENABLE |
9821                         CURSOR_FORMAT_ARGB |
9822                         CURSOR_STRIDE(stride);
9823
9824                 size = (height << 12) | width;
9825         }
9826
9827         if (intel_crtc->cursor_cntl != 0 &&
9828             (intel_crtc->cursor_base != base ||
9829              intel_crtc->cursor_size != size ||
9830              intel_crtc->cursor_cntl != cntl)) {
9831                 /* On these chipsets we can only modify the base/size/stride
9832                  * whilst the cursor is disabled.
9833                  */
9834                 I915_WRITE(_CURACNTR, 0);
9835                 POSTING_READ(_CURACNTR);
9836                 intel_crtc->cursor_cntl = 0;
9837         }
9838
9839         if (intel_crtc->cursor_base != base) {
9840                 I915_WRITE(_CURABASE, base);
9841                 intel_crtc->cursor_base = base;
9842         }
9843
9844         if (intel_crtc->cursor_size != size) {
9845                 I915_WRITE(CURSIZE, size);
9846                 intel_crtc->cursor_size = size;
9847         }
9848
9849         if (intel_crtc->cursor_cntl != cntl) {
9850                 I915_WRITE(_CURACNTR, cntl);
9851                 POSTING_READ(_CURACNTR);
9852                 intel_crtc->cursor_cntl = cntl;
9853         }
9854 }
9855
9856 static void i9xx_update_cursor(struct drm_crtc *crtc, u32 base)
9857 {
9858         struct drm_device *dev = crtc->dev;
9859         struct drm_i915_private *dev_priv = dev->dev_private;
9860         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9861         int pipe = intel_crtc->pipe;
9862         uint32_t cntl;
9863
9864         cntl = 0;
9865         if (base) {
9866                 cntl = MCURSOR_GAMMA_ENABLE;
9867                 switch (intel_crtc->base.cursor->state->crtc_w) {
9868                         case 64:
9869                                 cntl |= CURSOR_MODE_64_ARGB_AX;
9870                                 break;
9871                         case 128:
9872                                 cntl |= CURSOR_MODE_128_ARGB_AX;
9873                                 break;
9874                         case 256:
9875                                 cntl |= CURSOR_MODE_256_ARGB_AX;
9876                                 break;
9877                         default:
9878                                 MISSING_CASE(intel_crtc->base.cursor->state->crtc_w);
9879                                 return;
9880                 }
9881                 cntl |= pipe << 28; /* Connect to correct pipe */
9882
9883                 if (IS_HASWELL(dev) || IS_BROADWELL(dev))
9884                         cntl |= CURSOR_PIPE_CSC_ENABLE;
9885         }
9886
9887         if (crtc->cursor->state->rotation == BIT(DRM_ROTATE_180))
9888                 cntl |= CURSOR_ROTATE_180;
9889
9890         if (intel_crtc->cursor_cntl != cntl) {
9891                 I915_WRITE(CURCNTR(pipe), cntl);
9892                 POSTING_READ(CURCNTR(pipe));
9893                 intel_crtc->cursor_cntl = cntl;
9894         }
9895
9896         /* and commit changes on next vblank */
9897         I915_WRITE(CURBASE(pipe), base);
9898         POSTING_READ(CURBASE(pipe));
9899
9900         intel_crtc->cursor_base = base;
9901 }
9902
9903 /* If no-part of the cursor is visible on the framebuffer, then the GPU may hang... */
9904 static void intel_crtc_update_cursor(struct drm_crtc *crtc,
9905                                      bool on)
9906 {
9907         struct drm_device *dev = crtc->dev;
9908         struct drm_i915_private *dev_priv = dev->dev_private;
9909         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9910         int pipe = intel_crtc->pipe;
9911         int x = crtc->cursor_x;
9912         int y = crtc->cursor_y;
9913         u32 base = 0, pos = 0;
9914
9915         if (on)
9916                 base = intel_crtc->cursor_addr;
9917
9918         if (x >= intel_crtc->config->pipe_src_w)
9919                 base = 0;
9920
9921         if (y >= intel_crtc->config->pipe_src_h)
9922                 base = 0;
9923
9924         if (x < 0) {
9925                 if (x + intel_crtc->base.cursor->state->crtc_w <= 0)
9926                         base = 0;
9927
9928                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
9929                 x = -x;
9930         }
9931         pos |= x << CURSOR_X_SHIFT;
9932
9933         if (y < 0) {
9934                 if (y + intel_crtc->base.cursor->state->crtc_h <= 0)
9935                         base = 0;
9936
9937                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
9938                 y = -y;
9939         }
9940         pos |= y << CURSOR_Y_SHIFT;
9941
9942         if (base == 0 && intel_crtc->cursor_base == 0)
9943                 return;
9944
9945         I915_WRITE(CURPOS(pipe), pos);
9946
9947         /* ILK+ do this automagically */
9948         if (HAS_GMCH_DISPLAY(dev) &&
9949             crtc->cursor->state->rotation == BIT(DRM_ROTATE_180)) {
9950                 base += (intel_crtc->base.cursor->state->crtc_h *
9951                         intel_crtc->base.cursor->state->crtc_w - 1) * 4;
9952         }
9953
9954         if (IS_845G(dev) || IS_I865G(dev))
9955                 i845_update_cursor(crtc, base);
9956         else
9957                 i9xx_update_cursor(crtc, base);
9958 }
9959
9960 static bool cursor_size_ok(struct drm_device *dev,
9961                            uint32_t width, uint32_t height)
9962 {
9963         if (width == 0 || height == 0)
9964                 return false;
9965
9966         /*
9967          * 845g/865g are special in that they are only limited by
9968          * the width of their cursors, the height is arbitrary up to
9969          * the precision of the register. Everything else requires
9970          * square cursors, limited to a few power-of-two sizes.
9971          */
9972         if (IS_845G(dev) || IS_I865G(dev)) {
9973                 if ((width & 63) != 0)
9974                         return false;
9975
9976                 if (width > (IS_845G(dev) ? 64 : 512))
9977                         return false;
9978
9979                 if (height > 1023)
9980                         return false;
9981         } else {
9982                 switch (width | height) {
9983                 case 256:
9984                 case 128:
9985                         if (IS_GEN2(dev))
9986                                 return false;
9987                 case 64:
9988                         break;
9989                 default:
9990                         return false;
9991                 }
9992         }
9993
9994         return true;
9995 }
9996
9997 static void intel_crtc_gamma_set(struct drm_crtc *crtc, u16 *red, u16 *green,
9998                                  u16 *blue, uint32_t start, uint32_t size)
9999 {
10000         int end = (start + size > 256) ? 256 : start + size, i;
10001         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10002
10003         for (i = start; i < end; i++) {
10004                 intel_crtc->lut_r[i] = red[i] >> 8;
10005                 intel_crtc->lut_g[i] = green[i] >> 8;
10006                 intel_crtc->lut_b[i] = blue[i] >> 8;
10007         }
10008
10009         intel_crtc_load_lut(crtc);
10010 }
10011
10012 /* VESA 640x480x72Hz mode to set on the pipe */
10013 static struct drm_display_mode load_detect_mode = {
10014         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10015                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10016 };
10017
10018 struct drm_framebuffer *
10019 __intel_framebuffer_create(struct drm_device *dev,
10020                            struct drm_mode_fb_cmd2 *mode_cmd,
10021                            struct drm_i915_gem_object *obj)
10022 {
10023         struct intel_framebuffer *intel_fb;
10024         int ret;
10025
10026         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10027         if (!intel_fb) {
10028                 drm_gem_object_unreference(&obj->base);
10029                 return ERR_PTR(-ENOMEM);
10030         }
10031
10032         ret = intel_framebuffer_init(dev, intel_fb, mode_cmd, obj);
10033         if (ret)
10034                 goto err;
10035
10036         return &intel_fb->base;
10037 err:
10038         drm_gem_object_unreference(&obj->base);
10039         kfree(intel_fb);
10040
10041         return ERR_PTR(ret);
10042 }
10043
10044 static struct drm_framebuffer *
10045 intel_framebuffer_create(struct drm_device *dev,
10046                          struct drm_mode_fb_cmd2 *mode_cmd,
10047                          struct drm_i915_gem_object *obj)
10048 {
10049         struct drm_framebuffer *fb;
10050         int ret;
10051
10052         ret = i915_mutex_lock_interruptible(dev);
10053         if (ret)
10054                 return ERR_PTR(ret);
10055         fb = __intel_framebuffer_create(dev, mode_cmd, obj);
10056         mutex_unlock(&dev->struct_mutex);
10057
10058         return fb;
10059 }
10060
10061 static u32
10062 intel_framebuffer_pitch_for_width(int width, int bpp)
10063 {
10064         u32 pitch = DIV_ROUND_UP(width * bpp, 8);
10065         return ALIGN(pitch, 64);
10066 }
10067
10068 static u32
10069 intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
10070 {
10071         u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
10072         return PAGE_ALIGN(pitch * mode->vdisplay);
10073 }
10074
10075 static struct drm_framebuffer *
10076 intel_framebuffer_create_for_mode(struct drm_device *dev,
10077                                   struct drm_display_mode *mode,
10078                                   int depth, int bpp)
10079 {
10080         struct drm_i915_gem_object *obj;
10081         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
10082
10083         obj = i915_gem_alloc_object(dev,
10084                                     intel_framebuffer_size_for_mode(mode, bpp));
10085         if (obj == NULL)
10086                 return ERR_PTR(-ENOMEM);
10087
10088         mode_cmd.width = mode->hdisplay;
10089         mode_cmd.height = mode->vdisplay;
10090         mode_cmd.pitches[0] = intel_framebuffer_pitch_for_width(mode_cmd.width,
10091                                                                 bpp);
10092         mode_cmd.pixel_format = drm_mode_legacy_fb_format(bpp, depth);
10093
10094         return intel_framebuffer_create(dev, &mode_cmd, obj);
10095 }
10096
10097 static struct drm_framebuffer *
10098 mode_fits_in_fbdev(struct drm_device *dev,
10099                    struct drm_display_mode *mode)
10100 {
10101 #ifdef CONFIG_DRM_I915_FBDEV
10102         struct drm_i915_private *dev_priv = dev->dev_private;
10103         struct drm_i915_gem_object *obj;
10104         struct drm_framebuffer *fb;
10105
10106         if (!dev_priv->fbdev)
10107                 return NULL;
10108
10109         if (!dev_priv->fbdev->fb)
10110                 return NULL;
10111
10112         obj = dev_priv->fbdev->fb->obj;
10113         BUG_ON(!obj);
10114
10115         fb = &dev_priv->fbdev->fb->base;
10116         if (fb->pitches[0] < intel_framebuffer_pitch_for_width(mode->hdisplay,
10117                                                                fb->bits_per_pixel))
10118                 return NULL;
10119
10120         if (obj->base.size < mode->vdisplay * fb->pitches[0])
10121                 return NULL;
10122
10123         return fb;
10124 #else
10125         return NULL;
10126 #endif
10127 }
10128
10129 static int intel_modeset_setup_plane_state(struct drm_atomic_state *state,
10130                                            struct drm_crtc *crtc,
10131                                            struct drm_display_mode *mode,
10132                                            struct drm_framebuffer *fb,
10133                                            int x, int y)
10134 {
10135         struct drm_plane_state *plane_state;
10136         int hdisplay, vdisplay;
10137         int ret;
10138
10139         plane_state = drm_atomic_get_plane_state(state, crtc->primary);
10140         if (IS_ERR(plane_state))
10141                 return PTR_ERR(plane_state);
10142
10143         if (mode)
10144                 drm_crtc_get_hv_timing(mode, &hdisplay, &vdisplay);
10145         else
10146                 hdisplay = vdisplay = 0;
10147
10148         ret = drm_atomic_set_crtc_for_plane(plane_state, fb ? crtc : NULL);
10149         if (ret)
10150                 return ret;
10151         drm_atomic_set_fb_for_plane(plane_state, fb);
10152         plane_state->crtc_x = 0;
10153         plane_state->crtc_y = 0;
10154         plane_state->crtc_w = hdisplay;
10155         plane_state->crtc_h = vdisplay;
10156         plane_state->src_x = x << 16;
10157         plane_state->src_y = y << 16;
10158         plane_state->src_w = hdisplay << 16;
10159         plane_state->src_h = vdisplay << 16;
10160
10161         return 0;
10162 }
10163
10164 bool intel_get_load_detect_pipe(struct drm_connector *connector,
10165                                 struct drm_display_mode *mode,
10166                                 struct intel_load_detect_pipe *old,
10167                                 struct drm_modeset_acquire_ctx *ctx)
10168 {
10169         struct intel_crtc *intel_crtc;
10170         struct intel_encoder *intel_encoder =
10171                 intel_attached_encoder(connector);
10172         struct drm_crtc *possible_crtc;
10173         struct drm_encoder *encoder = &intel_encoder->base;
10174         struct drm_crtc *crtc = NULL;
10175         struct drm_device *dev = encoder->dev;
10176         struct drm_framebuffer *fb;
10177         struct drm_mode_config *config = &dev->mode_config;
10178         struct drm_atomic_state *state = NULL;
10179         struct drm_connector_state *connector_state;
10180         struct intel_crtc_state *crtc_state;
10181         int ret, i = -1;
10182
10183         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10184                       connector->base.id, connector->name,
10185                       encoder->base.id, encoder->name);
10186
10187 retry:
10188         ret = drm_modeset_lock(&config->connection_mutex, ctx);
10189         if (ret)
10190                 goto fail;
10191
10192         /*
10193          * Algorithm gets a little messy:
10194          *
10195          *   - if the connector already has an assigned crtc, use it (but make
10196          *     sure it's on first)
10197          *
10198          *   - try to find the first unused crtc that can drive this connector,
10199          *     and use that if we find one
10200          */
10201
10202         /* See if we already have a CRTC for this connector */
10203         if (encoder->crtc) {
10204                 crtc = encoder->crtc;
10205
10206                 ret = drm_modeset_lock(&crtc->mutex, ctx);
10207                 if (ret)
10208                         goto fail;
10209                 ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
10210                 if (ret)
10211                         goto fail;
10212
10213                 old->dpms_mode = connector->dpms;
10214                 old->load_detect_temp = false;
10215
10216                 /* Make sure the crtc and connector are running */
10217                 if (connector->dpms != DRM_MODE_DPMS_ON)
10218                         connector->funcs->dpms(connector, DRM_MODE_DPMS_ON);
10219
10220                 return true;
10221         }
10222
10223         /* Find an unused one (if possible) */
10224         for_each_crtc(dev, possible_crtc) {
10225                 i++;
10226                 if (!(encoder->possible_crtcs & (1 << i)))
10227                         continue;
10228                 if (possible_crtc->state->enable)
10229                         continue;
10230
10231                 crtc = possible_crtc;
10232                 break;
10233         }
10234
10235         /*
10236          * If we didn't find an unused CRTC, don't use any.
10237          */
10238         if (!crtc) {
10239                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
10240                 goto fail;
10241         }
10242
10243         ret = drm_modeset_lock(&crtc->mutex, ctx);
10244         if (ret)
10245                 goto fail;
10246         ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
10247         if (ret)
10248                 goto fail;
10249
10250         intel_crtc = to_intel_crtc(crtc);
10251         old->dpms_mode = connector->dpms;
10252         old->load_detect_temp = true;
10253         old->release_fb = NULL;
10254
10255         state = drm_atomic_state_alloc(dev);
10256         if (!state)
10257                 return false;
10258
10259         state->acquire_ctx = ctx;
10260
10261         connector_state = drm_atomic_get_connector_state(state, connector);
10262         if (IS_ERR(connector_state)) {
10263                 ret = PTR_ERR(connector_state);
10264                 goto fail;
10265         }
10266
10267         connector_state->crtc = crtc;
10268         connector_state->best_encoder = &intel_encoder->base;
10269
10270         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10271         if (IS_ERR(crtc_state)) {
10272                 ret = PTR_ERR(crtc_state);
10273                 goto fail;
10274         }
10275
10276         crtc_state->base.active = crtc_state->base.enable = true;
10277
10278         if (!mode)
10279                 mode = &load_detect_mode;
10280
10281         /* We need a framebuffer large enough to accommodate all accesses
10282          * that the plane may generate whilst we perform load detection.
10283          * We can not rely on the fbcon either being present (we get called
10284          * during its initialisation to detect all boot displays, or it may
10285          * not even exist) or that it is large enough to satisfy the
10286          * requested mode.
10287          */
10288         fb = mode_fits_in_fbdev(dev, mode);
10289         if (fb == NULL) {
10290                 DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
10291                 fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
10292                 old->release_fb = fb;
10293         } else
10294                 DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
10295         if (IS_ERR(fb)) {
10296                 DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
10297                 goto fail;
10298         }
10299
10300         ret = intel_modeset_setup_plane_state(state, crtc, mode, fb, 0, 0);
10301         if (ret)
10302                 goto fail;
10303
10304         drm_mode_copy(&crtc_state->base.mode, mode);
10305
10306         if (drm_atomic_commit(state)) {
10307                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
10308                 if (old->release_fb)
10309                         old->release_fb->funcs->destroy(old->release_fb);
10310                 goto fail;
10311         }
10312         crtc->primary->crtc = crtc;
10313
10314         /* let the connector get through one full cycle before testing */
10315         intel_wait_for_vblank(dev, intel_crtc->pipe);
10316         return true;
10317
10318 fail:
10319         drm_atomic_state_free(state);
10320         state = NULL;
10321
10322         if (ret == -EDEADLK) {
10323                 drm_modeset_backoff(ctx);
10324                 goto retry;
10325         }
10326
10327         return false;
10328 }
10329
10330 void intel_release_load_detect_pipe(struct drm_connector *connector,
10331                                     struct intel_load_detect_pipe *old,
10332                                     struct drm_modeset_acquire_ctx *ctx)
10333 {
10334         struct drm_device *dev = connector->dev;
10335         struct intel_encoder *intel_encoder =
10336                 intel_attached_encoder(connector);
10337         struct drm_encoder *encoder = &intel_encoder->base;
10338         struct drm_crtc *crtc = encoder->crtc;
10339         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10340         struct drm_atomic_state *state;
10341         struct drm_connector_state *connector_state;
10342         struct intel_crtc_state *crtc_state;
10343         int ret;
10344
10345         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10346                       connector->base.id, connector->name,
10347                       encoder->base.id, encoder->name);
10348
10349         if (old->load_detect_temp) {
10350                 state = drm_atomic_state_alloc(dev);
10351                 if (!state)
10352                         goto fail;
10353
10354                 state->acquire_ctx = ctx;
10355
10356                 connector_state = drm_atomic_get_connector_state(state, connector);
10357                 if (IS_ERR(connector_state))
10358                         goto fail;
10359
10360                 crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10361                 if (IS_ERR(crtc_state))
10362                         goto fail;
10363
10364                 connector_state->best_encoder = NULL;
10365                 connector_state->crtc = NULL;
10366
10367                 crtc_state->base.enable = crtc_state->base.active = false;
10368
10369                 ret = intel_modeset_setup_plane_state(state, crtc, NULL, NULL,
10370                                                       0, 0);
10371                 if (ret)
10372                         goto fail;
10373
10374                 ret = drm_atomic_commit(state);
10375                 if (ret)
10376                         goto fail;
10377
10378                 if (old->release_fb) {
10379                         drm_framebuffer_unregister_private(old->release_fb);
10380                         drm_framebuffer_unreference(old->release_fb);
10381                 }
10382
10383                 return;
10384         }
10385
10386         /* Switch crtc and encoder back off if necessary */
10387         if (old->dpms_mode != DRM_MODE_DPMS_ON)
10388                 connector->funcs->dpms(connector, old->dpms_mode);
10389
10390         return;
10391 fail:
10392         DRM_DEBUG_KMS("Couldn't release load detect pipe.\n");
10393         drm_atomic_state_free(state);
10394 }
10395
10396 static int i9xx_pll_refclk(struct drm_device *dev,
10397                            const struct intel_crtc_state *pipe_config)
10398 {
10399         struct drm_i915_private *dev_priv = dev->dev_private;
10400         u32 dpll = pipe_config->dpll_hw_state.dpll;
10401
10402         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10403                 return dev_priv->vbt.lvds_ssc_freq;
10404         else if (HAS_PCH_SPLIT(dev))
10405                 return 120000;
10406         else if (!IS_GEN2(dev))
10407                 return 96000;
10408         else
10409                 return 48000;
10410 }
10411
10412 /* Returns the clock of the currently programmed mode of the given pipe. */
10413 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
10414                                 struct intel_crtc_state *pipe_config)
10415 {
10416         struct drm_device *dev = crtc->base.dev;
10417         struct drm_i915_private *dev_priv = dev->dev_private;
10418         int pipe = pipe_config->cpu_transcoder;
10419         u32 dpll = pipe_config->dpll_hw_state.dpll;
10420         u32 fp;
10421         intel_clock_t clock;
10422         int port_clock;
10423         int refclk = i9xx_pll_refclk(dev, pipe_config);
10424
10425         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10426                 fp = pipe_config->dpll_hw_state.fp0;
10427         else
10428                 fp = pipe_config->dpll_hw_state.fp1;
10429
10430         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10431         if (IS_PINEVIEW(dev)) {
10432                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10433                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10434         } else {
10435                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10436                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10437         }
10438
10439         if (!IS_GEN2(dev)) {
10440                 if (IS_PINEVIEW(dev))
10441                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10442                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10443                 else
10444                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10445                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10446
10447                 switch (dpll & DPLL_MODE_MASK) {
10448                 case DPLLB_MODE_DAC_SERIAL:
10449                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10450                                 5 : 10;
10451                         break;
10452                 case DPLLB_MODE_LVDS:
10453                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10454                                 7 : 14;
10455                         break;
10456                 default:
10457                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10458                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10459                         return;
10460                 }
10461
10462                 if (IS_PINEVIEW(dev))
10463                         port_clock = pnv_calc_dpll_params(refclk, &clock);
10464                 else
10465                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
10466         } else {
10467                 u32 lvds = IS_I830(dev) ? 0 : I915_READ(LVDS);
10468                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10469
10470                 if (is_lvds) {
10471                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10472                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10473
10474                         if (lvds & LVDS_CLKB_POWER_UP)
10475                                 clock.p2 = 7;
10476                         else
10477                                 clock.p2 = 14;
10478                 } else {
10479                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10480                                 clock.p1 = 2;
10481                         else {
10482                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10483                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10484                         }
10485                         if (dpll & PLL_P2_DIVIDE_BY_4)
10486                                 clock.p2 = 4;
10487                         else
10488                                 clock.p2 = 2;
10489                 }
10490
10491                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10492         }
10493
10494         /*
10495          * This value includes pixel_multiplier. We will use
10496          * port_clock to compute adjusted_mode.crtc_clock in the
10497          * encoder's get_config() function.
10498          */
10499         pipe_config->port_clock = port_clock;
10500 }
10501
10502 int intel_dotclock_calculate(int link_freq,
10503                              const struct intel_link_m_n *m_n)
10504 {
10505         /*
10506          * The calculation for the data clock is:
10507          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10508          * But we want to avoid losing precison if possible, so:
10509          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10510          *
10511          * and the link clock is simpler:
10512          * link_clock = (m * link_clock) / n
10513          */
10514
10515         if (!m_n->link_n)
10516                 return 0;
10517
10518         return div_u64((u64)m_n->link_m * link_freq, m_n->link_n);
10519 }
10520
10521 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10522                                    struct intel_crtc_state *pipe_config)
10523 {
10524         struct drm_device *dev = crtc->base.dev;
10525
10526         /* read out port_clock from the DPLL */
10527         i9xx_crtc_clock_get(crtc, pipe_config);
10528
10529         /*
10530          * This value does not include pixel_multiplier.
10531          * We will check that port_clock and adjusted_mode.crtc_clock
10532          * agree once we know their relationship in the encoder's
10533          * get_config() function.
10534          */
10535         pipe_config->base.adjusted_mode.crtc_clock =
10536                 intel_dotclock_calculate(intel_fdi_link_freq(dev) * 10000,
10537                                          &pipe_config->fdi_m_n);
10538 }
10539
10540 /** Returns the currently programmed mode of the given pipe. */
10541 struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
10542                                              struct drm_crtc *crtc)
10543 {
10544         struct drm_i915_private *dev_priv = dev->dev_private;
10545         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10546         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
10547         struct drm_display_mode *mode;
10548         struct intel_crtc_state pipe_config;
10549         int htot = I915_READ(HTOTAL(cpu_transcoder));
10550         int hsync = I915_READ(HSYNC(cpu_transcoder));
10551         int vtot = I915_READ(VTOTAL(cpu_transcoder));
10552         int vsync = I915_READ(VSYNC(cpu_transcoder));
10553         enum pipe pipe = intel_crtc->pipe;
10554
10555         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10556         if (!mode)
10557                 return NULL;
10558
10559         /*
10560          * Construct a pipe_config sufficient for getting the clock info
10561          * back out of crtc_clock_get.
10562          *
10563          * Note, if LVDS ever uses a non-1 pixel multiplier, we'll need
10564          * to use a real value here instead.
10565          */
10566         pipe_config.cpu_transcoder = (enum transcoder) pipe;
10567         pipe_config.pixel_multiplier = 1;
10568         pipe_config.dpll_hw_state.dpll = I915_READ(DPLL(pipe));
10569         pipe_config.dpll_hw_state.fp0 = I915_READ(FP0(pipe));
10570         pipe_config.dpll_hw_state.fp1 = I915_READ(FP1(pipe));
10571         i9xx_crtc_clock_get(intel_crtc, &pipe_config);
10572
10573         mode->clock = pipe_config.port_clock / pipe_config.pixel_multiplier;
10574         mode->hdisplay = (htot & 0xffff) + 1;
10575         mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
10576         mode->hsync_start = (hsync & 0xffff) + 1;
10577         mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
10578         mode->vdisplay = (vtot & 0xffff) + 1;
10579         mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
10580         mode->vsync_start = (vsync & 0xffff) + 1;
10581         mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
10582
10583         drm_mode_set_name(mode);
10584
10585         return mode;
10586 }
10587
10588 void intel_mark_busy(struct drm_device *dev)
10589 {
10590         struct drm_i915_private *dev_priv = dev->dev_private;
10591
10592         if (dev_priv->mm.busy)
10593                 return;
10594
10595         intel_runtime_pm_get(dev_priv);
10596         i915_update_gfx_val(dev_priv);
10597         if (INTEL_INFO(dev)->gen >= 6)
10598                 gen6_rps_busy(dev_priv);
10599         dev_priv->mm.busy = true;
10600 }
10601
10602 void intel_mark_idle(struct drm_device *dev)
10603 {
10604         struct drm_i915_private *dev_priv = dev->dev_private;
10605
10606         if (!dev_priv->mm.busy)
10607                 return;
10608
10609         dev_priv->mm.busy = false;
10610
10611         if (INTEL_INFO(dev)->gen >= 6)
10612                 gen6_rps_idle(dev->dev_private);
10613
10614         intel_runtime_pm_put(dev_priv);
10615 }
10616
10617 static void intel_crtc_destroy(struct drm_crtc *crtc)
10618 {
10619         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10620         struct drm_device *dev = crtc->dev;
10621         struct intel_unpin_work *work;
10622
10623         spin_lock_irq(&dev->event_lock);
10624         work = intel_crtc->unpin_work;
10625         intel_crtc->unpin_work = NULL;
10626         spin_unlock_irq(&dev->event_lock);
10627
10628         if (work) {
10629                 cancel_work_sync(&work->work);
10630                 kfree(work);
10631         }
10632
10633         drm_crtc_cleanup(crtc);
10634
10635         kfree(intel_crtc);
10636 }
10637
10638 static void intel_unpin_work_fn(struct work_struct *__work)
10639 {
10640         struct intel_unpin_work *work =
10641                 container_of(__work, struct intel_unpin_work, work);
10642         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
10643         struct drm_device *dev = crtc->base.dev;
10644         struct drm_plane *primary = crtc->base.primary;
10645
10646         mutex_lock(&dev->struct_mutex);
10647         intel_unpin_fb_obj(work->old_fb, primary->state);
10648         drm_gem_object_unreference(&work->pending_flip_obj->base);
10649
10650         if (work->flip_queued_req)
10651                 i915_gem_request_assign(&work->flip_queued_req, NULL);
10652         mutex_unlock(&dev->struct_mutex);
10653
10654         intel_frontbuffer_flip_complete(dev, to_intel_plane(primary)->frontbuffer_bit);
10655         drm_framebuffer_unreference(work->old_fb);
10656
10657         BUG_ON(atomic_read(&crtc->unpin_work_count) == 0);
10658         atomic_dec(&crtc->unpin_work_count);
10659
10660         kfree(work);
10661 }
10662
10663 static void do_intel_finish_page_flip(struct drm_device *dev,
10664                                       struct drm_crtc *crtc)
10665 {
10666         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10667         struct intel_unpin_work *work;
10668         unsigned long flags;
10669
10670         /* Ignore early vblank irqs */
10671         if (intel_crtc == NULL)
10672                 return;
10673
10674         /*
10675          * This is called both by irq handlers and the reset code (to complete
10676          * lost pageflips) so needs the full irqsave spinlocks.
10677          */
10678         spin_lock_irqsave(&dev->event_lock, flags);
10679         work = intel_crtc->unpin_work;
10680
10681         /* Ensure we don't miss a work->pending update ... */
10682         smp_rmb();
10683
10684         if (work == NULL || atomic_read(&work->pending) < INTEL_FLIP_COMPLETE) {
10685                 spin_unlock_irqrestore(&dev->event_lock, flags);
10686                 return;
10687         }
10688
10689         page_flip_completed(intel_crtc);
10690
10691         spin_unlock_irqrestore(&dev->event_lock, flags);
10692 }
10693
10694 void intel_finish_page_flip(struct drm_device *dev, int pipe)
10695 {
10696         struct drm_i915_private *dev_priv = dev->dev_private;
10697         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
10698
10699         do_intel_finish_page_flip(dev, crtc);
10700 }
10701
10702 void intel_finish_page_flip_plane(struct drm_device *dev, int plane)
10703 {
10704         struct drm_i915_private *dev_priv = dev->dev_private;
10705         struct drm_crtc *crtc = dev_priv->plane_to_crtc_mapping[plane];
10706
10707         do_intel_finish_page_flip(dev, crtc);
10708 }
10709
10710 /* Is 'a' after or equal to 'b'? */
10711 static bool g4x_flip_count_after_eq(u32 a, u32 b)
10712 {
10713         return !((a - b) & 0x80000000);
10714 }
10715
10716 static bool page_flip_finished(struct intel_crtc *crtc)
10717 {
10718         struct drm_device *dev = crtc->base.dev;
10719         struct drm_i915_private *dev_priv = dev->dev_private;
10720
10721         if (i915_reset_in_progress(&dev_priv->gpu_error) ||
10722             crtc->reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
10723                 return true;
10724
10725         /*
10726          * The relevant registers doen't exist on pre-ctg.
10727          * As the flip done interrupt doesn't trigger for mmio
10728          * flips on gmch platforms, a flip count check isn't
10729          * really needed there. But since ctg has the registers,
10730          * include it in the check anyway.
10731          */
10732         if (INTEL_INFO(dev)->gen < 5 && !IS_G4X(dev))
10733                 return true;
10734
10735         /*
10736          * A DSPSURFLIVE check isn't enough in case the mmio and CS flips
10737          * used the same base address. In that case the mmio flip might
10738          * have completed, but the CS hasn't even executed the flip yet.
10739          *
10740          * A flip count check isn't enough as the CS might have updated
10741          * the base address just after start of vblank, but before we
10742          * managed to process the interrupt. This means we'd complete the
10743          * CS flip too soon.
10744          *
10745          * Combining both checks should get us a good enough result. It may
10746          * still happen that the CS flip has been executed, but has not
10747          * yet actually completed. But in case the base address is the same
10748          * anyway, we don't really care.
10749          */
10750         return (I915_READ(DSPSURFLIVE(crtc->plane)) & ~0xfff) ==
10751                 crtc->unpin_work->gtt_offset &&
10752                 g4x_flip_count_after_eq(I915_READ(PIPE_FLIPCOUNT_GM45(crtc->pipe)),
10753                                     crtc->unpin_work->flip_count);
10754 }
10755
10756 void intel_prepare_page_flip(struct drm_device *dev, int plane)
10757 {
10758         struct drm_i915_private *dev_priv = dev->dev_private;
10759         struct intel_crtc *intel_crtc =
10760                 to_intel_crtc(dev_priv->plane_to_crtc_mapping[plane]);
10761         unsigned long flags;
10762
10763
10764         /*
10765          * This is called both by irq handlers and the reset code (to complete
10766          * lost pageflips) so needs the full irqsave spinlocks.
10767          *
10768          * NB: An MMIO update of the plane base pointer will also
10769          * generate a page-flip completion irq, i.e. every modeset
10770          * is also accompanied by a spurious intel_prepare_page_flip().
10771          */
10772         spin_lock_irqsave(&dev->event_lock, flags);
10773         if (intel_crtc->unpin_work && page_flip_finished(intel_crtc))
10774                 atomic_inc_not_zero(&intel_crtc->unpin_work->pending);
10775         spin_unlock_irqrestore(&dev->event_lock, flags);
10776 }
10777
10778 static inline void intel_mark_page_flip_active(struct intel_crtc *intel_crtc)
10779 {
10780         /* Ensure that the work item is consistent when activating it ... */
10781         smp_wmb();
10782         atomic_set(&intel_crtc->unpin_work->pending, INTEL_FLIP_PENDING);
10783         /* and that it is marked active as soon as the irq could fire. */
10784         smp_wmb();
10785 }
10786
10787 static int intel_gen2_queue_flip(struct drm_device *dev,
10788                                  struct drm_crtc *crtc,
10789                                  struct drm_framebuffer *fb,
10790                                  struct drm_i915_gem_object *obj,
10791                                  struct drm_i915_gem_request *req,
10792                                  uint32_t flags)
10793 {
10794         struct intel_engine_cs *ring = req->ring;
10795         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10796         u32 flip_mask;
10797         int ret;
10798
10799         ret = intel_ring_begin(req, 6);
10800         if (ret)
10801                 return ret;
10802
10803         /* Can't queue multiple flips, so wait for the previous
10804          * one to finish before executing the next.
10805          */
10806         if (intel_crtc->plane)
10807                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
10808         else
10809                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
10810         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
10811         intel_ring_emit(ring, MI_NOOP);
10812         intel_ring_emit(ring, MI_DISPLAY_FLIP |
10813                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
10814         intel_ring_emit(ring, fb->pitches[0]);
10815         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
10816         intel_ring_emit(ring, 0); /* aux display base address, unused */
10817
10818         intel_mark_page_flip_active(intel_crtc);
10819         return 0;
10820 }
10821
10822 static int intel_gen3_queue_flip(struct drm_device *dev,
10823                                  struct drm_crtc *crtc,
10824                                  struct drm_framebuffer *fb,
10825                                  struct drm_i915_gem_object *obj,
10826                                  struct drm_i915_gem_request *req,
10827                                  uint32_t flags)
10828 {
10829         struct intel_engine_cs *ring = req->ring;
10830         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10831         u32 flip_mask;
10832         int ret;
10833
10834         ret = intel_ring_begin(req, 6);
10835         if (ret)
10836                 return ret;
10837
10838         if (intel_crtc->plane)
10839                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
10840         else
10841                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
10842         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
10843         intel_ring_emit(ring, MI_NOOP);
10844         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 |
10845                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
10846         intel_ring_emit(ring, fb->pitches[0]);
10847         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
10848         intel_ring_emit(ring, MI_NOOP);
10849
10850         intel_mark_page_flip_active(intel_crtc);
10851         return 0;
10852 }
10853
10854 static int intel_gen4_queue_flip(struct drm_device *dev,
10855                                  struct drm_crtc *crtc,
10856                                  struct drm_framebuffer *fb,
10857                                  struct drm_i915_gem_object *obj,
10858                                  struct drm_i915_gem_request *req,
10859                                  uint32_t flags)
10860 {
10861         struct intel_engine_cs *ring = req->ring;
10862         struct drm_i915_private *dev_priv = dev->dev_private;
10863         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10864         uint32_t pf, pipesrc;
10865         int ret;
10866
10867         ret = intel_ring_begin(req, 4);
10868         if (ret)
10869                 return ret;
10870
10871         /* i965+ uses the linear or tiled offsets from the
10872          * Display Registers (which do not change across a page-flip)
10873          * so we need only reprogram the base address.
10874          */
10875         intel_ring_emit(ring, MI_DISPLAY_FLIP |
10876                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
10877         intel_ring_emit(ring, fb->pitches[0]);
10878         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset |
10879                         obj->tiling_mode);
10880
10881         /* XXX Enabling the panel-fitter across page-flip is so far
10882          * untested on non-native modes, so ignore it for now.
10883          * pf = I915_READ(pipe == 0 ? PFA_CTL_1 : PFB_CTL_1) & PF_ENABLE;
10884          */
10885         pf = 0;
10886         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
10887         intel_ring_emit(ring, pf | pipesrc);
10888
10889         intel_mark_page_flip_active(intel_crtc);
10890         return 0;
10891 }
10892
10893 static int intel_gen6_queue_flip(struct drm_device *dev,
10894                                  struct drm_crtc *crtc,
10895                                  struct drm_framebuffer *fb,
10896                                  struct drm_i915_gem_object *obj,
10897                                  struct drm_i915_gem_request *req,
10898                                  uint32_t flags)
10899 {
10900         struct intel_engine_cs *ring = req->ring;
10901         struct drm_i915_private *dev_priv = dev->dev_private;
10902         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10903         uint32_t pf, pipesrc;
10904         int ret;
10905
10906         ret = intel_ring_begin(req, 4);
10907         if (ret)
10908                 return ret;
10909
10910         intel_ring_emit(ring, MI_DISPLAY_FLIP |
10911                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
10912         intel_ring_emit(ring, fb->pitches[0] | obj->tiling_mode);
10913         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
10914
10915         /* Contrary to the suggestions in the documentation,
10916          * "Enable Panel Fitter" does not seem to be required when page
10917          * flipping with a non-native mode, and worse causes a normal
10918          * modeset to fail.
10919          * pf = I915_READ(PF_CTL(intel_crtc->pipe)) & PF_ENABLE;
10920          */
10921         pf = 0;
10922         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
10923         intel_ring_emit(ring, pf | pipesrc);
10924
10925         intel_mark_page_flip_active(intel_crtc);
10926         return 0;
10927 }
10928
10929 static int intel_gen7_queue_flip(struct drm_device *dev,
10930                                  struct drm_crtc *crtc,
10931                                  struct drm_framebuffer *fb,
10932                                  struct drm_i915_gem_object *obj,
10933                                  struct drm_i915_gem_request *req,
10934                                  uint32_t flags)
10935 {
10936         struct intel_engine_cs *ring = req->ring;
10937         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10938         uint32_t plane_bit = 0;
10939         int len, ret;
10940
10941         switch (intel_crtc->plane) {
10942         case PLANE_A:
10943                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_A;
10944                 break;
10945         case PLANE_B:
10946                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_B;
10947                 break;
10948         case PLANE_C:
10949                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_C;
10950                 break;
10951         default:
10952                 WARN_ONCE(1, "unknown plane in flip command\n");
10953                 return -ENODEV;
10954         }
10955
10956         len = 4;
10957         if (ring->id == RCS) {
10958                 len += 6;
10959                 /*
10960                  * On Gen 8, SRM is now taking an extra dword to accommodate
10961                  * 48bits addresses, and we need a NOOP for the batch size to
10962                  * stay even.
10963                  */
10964                 if (IS_GEN8(dev))
10965                         len += 2;
10966         }
10967
10968         /*
10969          * BSpec MI_DISPLAY_FLIP for IVB:
10970          * "The full packet must be contained within the same cache line."
10971          *
10972          * Currently the LRI+SRM+MI_DISPLAY_FLIP all fit within the same
10973          * cacheline, if we ever start emitting more commands before
10974          * the MI_DISPLAY_FLIP we may need to first emit everything else,
10975          * then do the cacheline alignment, and finally emit the
10976          * MI_DISPLAY_FLIP.
10977          */
10978         ret = intel_ring_cacheline_align(req);
10979         if (ret)
10980                 return ret;
10981
10982         ret = intel_ring_begin(req, len);
10983         if (ret)
10984                 return ret;
10985
10986         /* Unmask the flip-done completion message. Note that the bspec says that
10987          * we should do this for both the BCS and RCS, and that we must not unmask
10988          * more than one flip event at any time (or ensure that one flip message
10989          * can be sent by waiting for flip-done prior to queueing new flips).
10990          * Experimentation says that BCS works despite DERRMR masking all
10991          * flip-done completion events and that unmasking all planes at once
10992          * for the RCS also doesn't appear to drop events. Setting the DERRMR
10993          * to zero does lead to lockups within MI_DISPLAY_FLIP.
10994          */
10995         if (ring->id == RCS) {
10996                 intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
10997                 intel_ring_emit(ring, DERRMR);
10998                 intel_ring_emit(ring, ~(DERRMR_PIPEA_PRI_FLIP_DONE |
10999                                         DERRMR_PIPEB_PRI_FLIP_DONE |
11000                                         DERRMR_PIPEC_PRI_FLIP_DONE));
11001                 if (IS_GEN8(dev))
11002                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM_GEN8 |
11003                                               MI_SRM_LRM_GLOBAL_GTT);
11004                 else
11005                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM |
11006                                               MI_SRM_LRM_GLOBAL_GTT);
11007                 intel_ring_emit(ring, DERRMR);
11008                 intel_ring_emit(ring, ring->scratch.gtt_offset + 256);
11009                 if (IS_GEN8(dev)) {
11010                         intel_ring_emit(ring, 0);
11011                         intel_ring_emit(ring, MI_NOOP);
11012                 }
11013         }
11014
11015         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 | plane_bit);
11016         intel_ring_emit(ring, (fb->pitches[0] | obj->tiling_mode));
11017         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
11018         intel_ring_emit(ring, (MI_NOOP));
11019
11020         intel_mark_page_flip_active(intel_crtc);
11021         return 0;
11022 }
11023
11024 static bool use_mmio_flip(struct intel_engine_cs *ring,
11025                           struct drm_i915_gem_object *obj)
11026 {
11027         /*
11028          * This is not being used for older platforms, because
11029          * non-availability of flip done interrupt forces us to use
11030          * CS flips. Older platforms derive flip done using some clever
11031          * tricks involving the flip_pending status bits and vblank irqs.
11032          * So using MMIO flips there would disrupt this mechanism.
11033          */
11034
11035         if (ring == NULL)
11036                 return true;
11037
11038         if (INTEL_INFO(ring->dev)->gen < 5)
11039                 return false;
11040
11041         if (i915.use_mmio_flip < 0)
11042                 return false;
11043         else if (i915.use_mmio_flip > 0)
11044                 return true;
11045         else if (i915.enable_execlists)
11046                 return true;
11047         else
11048                 return ring != i915_gem_request_get_ring(obj->last_write_req);
11049 }
11050
11051 static void skl_do_mmio_flip(struct intel_crtc *intel_crtc)
11052 {
11053         struct drm_device *dev = intel_crtc->base.dev;
11054         struct drm_i915_private *dev_priv = dev->dev_private;
11055         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
11056         const enum pipe pipe = intel_crtc->pipe;
11057         u32 ctl, stride;
11058
11059         ctl = I915_READ(PLANE_CTL(pipe, 0));
11060         ctl &= ~PLANE_CTL_TILED_MASK;
11061         switch (fb->modifier[0]) {
11062         case DRM_FORMAT_MOD_NONE:
11063                 break;
11064         case I915_FORMAT_MOD_X_TILED:
11065                 ctl |= PLANE_CTL_TILED_X;
11066                 break;
11067         case I915_FORMAT_MOD_Y_TILED:
11068                 ctl |= PLANE_CTL_TILED_Y;
11069                 break;
11070         case I915_FORMAT_MOD_Yf_TILED:
11071                 ctl |= PLANE_CTL_TILED_YF;
11072                 break;
11073         default:
11074                 MISSING_CASE(fb->modifier[0]);
11075         }
11076
11077         /*
11078          * The stride is either expressed as a multiple of 64 bytes chunks for
11079          * linear buffers or in number of tiles for tiled buffers.
11080          */
11081         stride = fb->pitches[0] /
11082                  intel_fb_stride_alignment(dev, fb->modifier[0],
11083                                            fb->pixel_format);
11084
11085         /*
11086          * Both PLANE_CTL and PLANE_STRIDE are not updated on vblank but on
11087          * PLANE_SURF updates, the update is then guaranteed to be atomic.
11088          */
11089         I915_WRITE(PLANE_CTL(pipe, 0), ctl);
11090         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
11091
11092         I915_WRITE(PLANE_SURF(pipe, 0), intel_crtc->unpin_work->gtt_offset);
11093         POSTING_READ(PLANE_SURF(pipe, 0));
11094 }
11095
11096 static void ilk_do_mmio_flip(struct intel_crtc *intel_crtc)
11097 {
11098         struct drm_device *dev = intel_crtc->base.dev;
11099         struct drm_i915_private *dev_priv = dev->dev_private;
11100         struct intel_framebuffer *intel_fb =
11101                 to_intel_framebuffer(intel_crtc->base.primary->fb);
11102         struct drm_i915_gem_object *obj = intel_fb->obj;
11103         u32 dspcntr;
11104         u32 reg;
11105
11106         reg = DSPCNTR(intel_crtc->plane);
11107         dspcntr = I915_READ(reg);
11108
11109         if (obj->tiling_mode != I915_TILING_NONE)
11110                 dspcntr |= DISPPLANE_TILED;
11111         else
11112                 dspcntr &= ~DISPPLANE_TILED;
11113
11114         I915_WRITE(reg, dspcntr);
11115
11116         I915_WRITE(DSPSURF(intel_crtc->plane),
11117                    intel_crtc->unpin_work->gtt_offset);
11118         POSTING_READ(DSPSURF(intel_crtc->plane));
11119
11120 }
11121
11122 /*
11123  * XXX: This is the temporary way to update the plane registers until we get
11124  * around to using the usual plane update functions for MMIO flips
11125  */
11126 static void intel_do_mmio_flip(struct intel_crtc *intel_crtc)
11127 {
11128         struct drm_device *dev = intel_crtc->base.dev;
11129         u32 start_vbl_count;
11130
11131         intel_mark_page_flip_active(intel_crtc);
11132
11133         intel_pipe_update_start(intel_crtc, &start_vbl_count);
11134
11135         if (INTEL_INFO(dev)->gen >= 9)
11136                 skl_do_mmio_flip(intel_crtc);
11137         else
11138                 /* use_mmio_flip() retricts MMIO flips to ilk+ */
11139                 ilk_do_mmio_flip(intel_crtc);
11140
11141         intel_pipe_update_end(intel_crtc, start_vbl_count);
11142 }
11143
11144 static void intel_mmio_flip_work_func(struct work_struct *work)
11145 {
11146         struct intel_mmio_flip *mmio_flip =
11147                 container_of(work, struct intel_mmio_flip, work);
11148
11149         if (mmio_flip->req)
11150                 WARN_ON(__i915_wait_request(mmio_flip->req,
11151                                             mmio_flip->crtc->reset_counter,
11152                                             false, NULL,
11153                                             &mmio_flip->i915->rps.mmioflips));
11154
11155         intel_do_mmio_flip(mmio_flip->crtc);
11156
11157         i915_gem_request_unreference__unlocked(mmio_flip->req);
11158         kfree(mmio_flip);
11159 }
11160
11161 static int intel_queue_mmio_flip(struct drm_device *dev,
11162                                  struct drm_crtc *crtc,
11163                                  struct drm_framebuffer *fb,
11164                                  struct drm_i915_gem_object *obj,
11165                                  struct intel_engine_cs *ring,
11166                                  uint32_t flags)
11167 {
11168         struct intel_mmio_flip *mmio_flip;
11169
11170         mmio_flip = kmalloc(sizeof(*mmio_flip), GFP_KERNEL);
11171         if (mmio_flip == NULL)
11172                 return -ENOMEM;
11173
11174         mmio_flip->i915 = to_i915(dev);
11175         mmio_flip->req = i915_gem_request_reference(obj->last_write_req);
11176         mmio_flip->crtc = to_intel_crtc(crtc);
11177
11178         INIT_WORK(&mmio_flip->work, intel_mmio_flip_work_func);
11179         schedule_work(&mmio_flip->work);
11180
11181         return 0;
11182 }
11183
11184 static int intel_default_queue_flip(struct drm_device *dev,
11185                                     struct drm_crtc *crtc,
11186                                     struct drm_framebuffer *fb,
11187                                     struct drm_i915_gem_object *obj,
11188                                     struct drm_i915_gem_request *req,
11189                                     uint32_t flags)
11190 {
11191         return -ENODEV;
11192 }
11193
11194 static bool __intel_pageflip_stall_check(struct drm_device *dev,
11195                                          struct drm_crtc *crtc)
11196 {
11197         struct drm_i915_private *dev_priv = dev->dev_private;
11198         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11199         struct intel_unpin_work *work = intel_crtc->unpin_work;
11200         u32 addr;
11201
11202         if (atomic_read(&work->pending) >= INTEL_FLIP_COMPLETE)
11203                 return true;
11204
11205         if (atomic_read(&work->pending) < INTEL_FLIP_PENDING)
11206                 return false;
11207
11208         if (!work->enable_stall_check)
11209                 return false;
11210
11211         if (work->flip_ready_vblank == 0) {
11212                 if (work->flip_queued_req &&
11213                     !i915_gem_request_completed(work->flip_queued_req, true))
11214                         return false;
11215
11216                 work->flip_ready_vblank = drm_crtc_vblank_count(crtc);
11217         }
11218
11219         if (drm_crtc_vblank_count(crtc) - work->flip_ready_vblank < 3)
11220                 return false;
11221
11222         /* Potential stall - if we see that the flip has happened,
11223          * assume a missed interrupt. */
11224         if (INTEL_INFO(dev)->gen >= 4)
11225                 addr = I915_HI_DISPBASE(I915_READ(DSPSURF(intel_crtc->plane)));
11226         else
11227                 addr = I915_READ(DSPADDR(intel_crtc->plane));
11228
11229         /* There is a potential issue here with a false positive after a flip
11230          * to the same address. We could address this by checking for a
11231          * non-incrementing frame counter.
11232          */
11233         return addr == work->gtt_offset;
11234 }
11235
11236 void intel_check_page_flip(struct drm_device *dev, int pipe)
11237 {
11238         struct drm_i915_private *dev_priv = dev->dev_private;
11239         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11240         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11241         struct intel_unpin_work *work;
11242
11243         WARN_ON(!in_interrupt());
11244
11245         if (crtc == NULL)
11246                 return;
11247
11248         spin_lock(&dev->event_lock);
11249         work = intel_crtc->unpin_work;
11250         if (work != NULL && __intel_pageflip_stall_check(dev, crtc)) {
11251                 WARN_ONCE(1, "Kicking stuck page flip: queued at %d, now %d\n",
11252                          work->flip_queued_vblank, drm_vblank_count(dev, pipe));
11253                 page_flip_completed(intel_crtc);
11254                 work = NULL;
11255         }
11256         if (work != NULL &&
11257             drm_vblank_count(dev, pipe) - work->flip_queued_vblank > 1)
11258                 intel_queue_rps_boost_for_request(dev, work->flip_queued_req);
11259         spin_unlock(&dev->event_lock);
11260 }
11261
11262 static int intel_crtc_page_flip(struct drm_crtc *crtc,
11263                                 struct drm_framebuffer *fb,
11264                                 struct drm_pending_vblank_event *event,
11265                                 uint32_t page_flip_flags)
11266 {
11267         struct drm_device *dev = crtc->dev;
11268         struct drm_i915_private *dev_priv = dev->dev_private;
11269         struct drm_framebuffer *old_fb = crtc->primary->fb;
11270         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
11271         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11272         struct drm_plane *primary = crtc->primary;
11273         enum pipe pipe = intel_crtc->pipe;
11274         struct intel_unpin_work *work;
11275         struct intel_engine_cs *ring;
11276         bool mmio_flip;
11277         struct drm_i915_gem_request *request = NULL;
11278         int ret;
11279
11280         /*
11281          * drm_mode_page_flip_ioctl() should already catch this, but double
11282          * check to be safe.  In the future we may enable pageflipping from
11283          * a disabled primary plane.
11284          */
11285         if (WARN_ON(intel_fb_obj(old_fb) == NULL))
11286                 return -EBUSY;
11287
11288         /* Can't change pixel format via MI display flips. */
11289         if (fb->pixel_format != crtc->primary->fb->pixel_format)
11290                 return -EINVAL;
11291
11292         /*
11293          * TILEOFF/LINOFF registers can't be changed via MI display flips.
11294          * Note that pitch changes could also affect these register.
11295          */
11296         if (INTEL_INFO(dev)->gen > 3 &&
11297             (fb->offsets[0] != crtc->primary->fb->offsets[0] ||
11298              fb->pitches[0] != crtc->primary->fb->pitches[0]))
11299                 return -EINVAL;
11300
11301         if (i915_terminally_wedged(&dev_priv->gpu_error))
11302                 goto out_hang;
11303
11304         work = kzalloc(sizeof(*work), GFP_KERNEL);
11305         if (work == NULL)
11306                 return -ENOMEM;
11307
11308         work->event = event;
11309         work->crtc = crtc;
11310         work->old_fb = old_fb;
11311         INIT_WORK(&work->work, intel_unpin_work_fn);
11312
11313         ret = drm_crtc_vblank_get(crtc);
11314         if (ret)
11315                 goto free_work;
11316
11317         /* We borrow the event spin lock for protecting unpin_work */
11318         spin_lock_irq(&dev->event_lock);
11319         if (intel_crtc->unpin_work) {
11320                 /* Before declaring the flip queue wedged, check if
11321                  * the hardware completed the operation behind our backs.
11322                  */
11323                 if (__intel_pageflip_stall_check(dev, crtc)) {
11324                         DRM_DEBUG_DRIVER("flip queue: previous flip completed, continuing\n");
11325                         page_flip_completed(intel_crtc);
11326                 } else {
11327                         DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
11328                         spin_unlock_irq(&dev->event_lock);
11329
11330                         drm_crtc_vblank_put(crtc);
11331                         kfree(work);
11332                         return -EBUSY;
11333                 }
11334         }
11335         intel_crtc->unpin_work = work;
11336         spin_unlock_irq(&dev->event_lock);
11337
11338         if (atomic_read(&intel_crtc->unpin_work_count) >= 2)
11339                 flush_workqueue(dev_priv->wq);
11340
11341         /* Reference the objects for the scheduled work. */
11342         drm_framebuffer_reference(work->old_fb);
11343         drm_gem_object_reference(&obj->base);
11344
11345         crtc->primary->fb = fb;
11346         update_state_fb(crtc->primary);
11347
11348         work->pending_flip_obj = obj;
11349
11350         ret = i915_mutex_lock_interruptible(dev);
11351         if (ret)
11352                 goto cleanup;
11353
11354         atomic_inc(&intel_crtc->unpin_work_count);
11355         intel_crtc->reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
11356
11357         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
11358                 work->flip_count = I915_READ(PIPE_FLIPCOUNT_GM45(pipe)) + 1;
11359
11360         if (IS_VALLEYVIEW(dev)) {
11361                 ring = &dev_priv->ring[BCS];
11362                 if (obj->tiling_mode != intel_fb_obj(work->old_fb)->tiling_mode)
11363                         /* vlv: DISPLAY_FLIP fails to change tiling */
11364                         ring = NULL;
11365         } else if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev)) {
11366                 ring = &dev_priv->ring[BCS];
11367         } else if (INTEL_INFO(dev)->gen >= 7) {
11368                 ring = i915_gem_request_get_ring(obj->last_write_req);
11369                 if (ring == NULL || ring->id != RCS)
11370                         ring = &dev_priv->ring[BCS];
11371         } else {
11372                 ring = &dev_priv->ring[RCS];
11373         }
11374
11375         mmio_flip = use_mmio_flip(ring, obj);
11376
11377         /* When using CS flips, we want to emit semaphores between rings.
11378          * However, when using mmio flips we will create a task to do the
11379          * synchronisation, so all we want here is to pin the framebuffer
11380          * into the display plane and skip any waits.
11381          */
11382         ret = intel_pin_and_fence_fb_obj(crtc->primary, fb,
11383                                          crtc->primary->state,
11384                                          mmio_flip ? i915_gem_request_get_ring(obj->last_write_req) : ring, &request);
11385         if (ret)
11386                 goto cleanup_pending;
11387
11388         work->gtt_offset = intel_plane_obj_offset(to_intel_plane(primary), obj)
11389                                                   + intel_crtc->dspaddr_offset;
11390
11391         if (mmio_flip) {
11392                 ret = intel_queue_mmio_flip(dev, crtc, fb, obj, ring,
11393                                             page_flip_flags);
11394                 if (ret)
11395                         goto cleanup_unpin;
11396
11397                 i915_gem_request_assign(&work->flip_queued_req,
11398                                         obj->last_write_req);
11399         } else {
11400                 if (!request) {
11401                         ret = i915_gem_request_alloc(ring, ring->default_context, &request);
11402                         if (ret)
11403                                 goto cleanup_unpin;
11404                 }
11405
11406                 ret = dev_priv->display.queue_flip(dev, crtc, fb, obj, request,
11407                                                    page_flip_flags);
11408                 if (ret)
11409                         goto cleanup_unpin;
11410
11411                 i915_gem_request_assign(&work->flip_queued_req, request);
11412         }
11413
11414         if (request)
11415                 i915_add_request_no_flush(request);
11416
11417         work->flip_queued_vblank = drm_crtc_vblank_count(crtc);
11418         work->enable_stall_check = true;
11419
11420         i915_gem_track_fb(intel_fb_obj(work->old_fb), obj,
11421                           to_intel_plane(primary)->frontbuffer_bit);
11422         mutex_unlock(&dev->struct_mutex);
11423
11424         intel_fbc_disable_crtc(intel_crtc);
11425         intel_frontbuffer_flip_prepare(dev,
11426                                        to_intel_plane(primary)->frontbuffer_bit);
11427
11428         trace_i915_flip_request(intel_crtc->plane, obj);
11429
11430         return 0;
11431
11432 cleanup_unpin:
11433         intel_unpin_fb_obj(fb, crtc->primary->state);
11434 cleanup_pending:
11435         if (request)
11436                 i915_gem_request_cancel(request);
11437         atomic_dec(&intel_crtc->unpin_work_count);
11438         mutex_unlock(&dev->struct_mutex);
11439 cleanup:
11440         crtc->primary->fb = old_fb;
11441         update_state_fb(crtc->primary);
11442
11443         drm_gem_object_unreference_unlocked(&obj->base);
11444         drm_framebuffer_unreference(work->old_fb);
11445
11446         spin_lock_irq(&dev->event_lock);
11447         intel_crtc->unpin_work = NULL;
11448         spin_unlock_irq(&dev->event_lock);
11449
11450         drm_crtc_vblank_put(crtc);
11451 free_work:
11452         kfree(work);
11453
11454         if (ret == -EIO) {
11455                 struct drm_atomic_state *state;
11456                 struct drm_plane_state *plane_state;
11457
11458 out_hang:
11459                 state = drm_atomic_state_alloc(dev);
11460                 if (!state)
11461                         return -ENOMEM;
11462                 state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
11463
11464 retry:
11465                 plane_state = drm_atomic_get_plane_state(state, primary);
11466                 ret = PTR_ERR_OR_ZERO(plane_state);
11467                 if (!ret) {
11468                         drm_atomic_set_fb_for_plane(plane_state, fb);
11469
11470                         ret = drm_atomic_set_crtc_for_plane(plane_state, crtc);
11471                         if (!ret)
11472                                 ret = drm_atomic_commit(state);
11473                 }
11474
11475                 if (ret == -EDEADLK) {
11476                         drm_modeset_backoff(state->acquire_ctx);
11477                         drm_atomic_state_clear(state);
11478                         goto retry;
11479                 }
11480
11481                 if (ret)
11482                         drm_atomic_state_free(state);
11483
11484                 if (ret == 0 && event) {
11485                         spin_lock_irq(&dev->event_lock);
11486                         drm_send_vblank_event(dev, pipe, event);
11487                         spin_unlock_irq(&dev->event_lock);
11488                 }
11489         }
11490         return ret;
11491 }
11492
11493
11494 /**
11495  * intel_wm_need_update - Check whether watermarks need updating
11496  * @plane: drm plane
11497  * @state: new plane state
11498  *
11499  * Check current plane state versus the new one to determine whether
11500  * watermarks need to be recalculated.
11501  *
11502  * Returns true or false.
11503  */
11504 static bool intel_wm_need_update(struct drm_plane *plane,
11505                                  struct drm_plane_state *state)
11506 {
11507         /* Update watermarks on tiling changes. */
11508         if (!plane->state->fb || !state->fb ||
11509             plane->state->fb->modifier[0] != state->fb->modifier[0] ||
11510             plane->state->rotation != state->rotation)
11511                 return true;
11512
11513         if (plane->state->crtc_w != state->crtc_w)
11514                 return true;
11515
11516         return false;
11517 }
11518
11519 int intel_plane_atomic_calc_changes(struct drm_crtc_state *crtc_state,
11520                                     struct drm_plane_state *plane_state)
11521 {
11522         struct drm_crtc *crtc = crtc_state->crtc;
11523         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11524         struct drm_plane *plane = plane_state->plane;
11525         struct drm_device *dev = crtc->dev;
11526         struct drm_i915_private *dev_priv = dev->dev_private;
11527         struct intel_plane_state *old_plane_state =
11528                 to_intel_plane_state(plane->state);
11529         int idx = intel_crtc->base.base.id, ret;
11530         int i = drm_plane_index(plane);
11531         bool mode_changed = needs_modeset(crtc_state);
11532         bool was_crtc_enabled = crtc->state->active;
11533         bool is_crtc_enabled = crtc_state->active;
11534
11535         bool turn_off, turn_on, visible, was_visible;
11536         struct drm_framebuffer *fb = plane_state->fb;
11537
11538         if (crtc_state && INTEL_INFO(dev)->gen >= 9 &&
11539             plane->type != DRM_PLANE_TYPE_CURSOR) {
11540                 ret = skl_update_scaler_plane(
11541                         to_intel_crtc_state(crtc_state),
11542                         to_intel_plane_state(plane_state));
11543                 if (ret)
11544                         return ret;
11545         }
11546
11547         /*
11548          * Disabling a plane is always okay; we just need to update
11549          * fb tracking in a special way since cleanup_fb() won't
11550          * get called by the plane helpers.
11551          */
11552         if (old_plane_state->base.fb && !fb)
11553                 intel_crtc->atomic.disabled_planes |= 1 << i;
11554
11555         was_visible = old_plane_state->visible;
11556         visible = to_intel_plane_state(plane_state)->visible;
11557
11558         if (!was_crtc_enabled && WARN_ON(was_visible))
11559                 was_visible = false;
11560
11561         if (!is_crtc_enabled && WARN_ON(visible))
11562                 visible = false;
11563
11564         if (!was_visible && !visible)
11565                 return 0;
11566
11567         turn_off = was_visible && (!visible || mode_changed);
11568         turn_on = visible && (!was_visible || mode_changed);
11569
11570         DRM_DEBUG_ATOMIC("[CRTC:%i] has [PLANE:%i] with fb %i\n", idx,
11571                          plane->base.id, fb ? fb->base.id : -1);
11572
11573         DRM_DEBUG_ATOMIC("[PLANE:%i] visible %i -> %i, off %i, on %i, ms %i\n",
11574                          plane->base.id, was_visible, visible,
11575                          turn_off, turn_on, mode_changed);
11576
11577         if (turn_on) {
11578                 intel_crtc->atomic.update_wm_pre = true;
11579                 /* must disable cxsr around plane enable/disable */
11580                 if (plane->type != DRM_PLANE_TYPE_CURSOR) {
11581                         intel_crtc->atomic.disable_cxsr = true;
11582                         /* to potentially re-enable cxsr */
11583                         intel_crtc->atomic.wait_vblank = true;
11584                         intel_crtc->atomic.update_wm_post = true;
11585                 }
11586         } else if (turn_off) {
11587                 intel_crtc->atomic.update_wm_post = true;
11588                 /* must disable cxsr around plane enable/disable */
11589                 if (plane->type != DRM_PLANE_TYPE_CURSOR) {
11590                         if (is_crtc_enabled)
11591                                 intel_crtc->atomic.wait_vblank = true;
11592                         intel_crtc->atomic.disable_cxsr = true;
11593                 }
11594         } else if (intel_wm_need_update(plane, plane_state)) {
11595                 intel_crtc->atomic.update_wm_pre = true;
11596         }
11597
11598         if (visible || was_visible)
11599                 intel_crtc->atomic.fb_bits |=
11600                         to_intel_plane(plane)->frontbuffer_bit;
11601
11602         switch (plane->type) {
11603         case DRM_PLANE_TYPE_PRIMARY:
11604                 intel_crtc->atomic.wait_for_flips = true;
11605                 intel_crtc->atomic.pre_disable_primary = turn_off;
11606                 intel_crtc->atomic.post_enable_primary = turn_on;
11607
11608                 if (turn_off) {
11609                         /*
11610                          * FIXME: Actually if we will still have any other
11611                          * plane enabled on the pipe we could let IPS enabled
11612                          * still, but for now lets consider that when we make
11613                          * primary invisible by setting DSPCNTR to 0 on
11614                          * update_primary_plane function IPS needs to be
11615                          * disable.
11616                          */
11617                         intel_crtc->atomic.disable_ips = true;
11618
11619                         intel_crtc->atomic.disable_fbc = true;
11620                 }
11621
11622                 /*
11623                  * FBC does not work on some platforms for rotated
11624                  * planes, so disable it when rotation is not 0 and
11625                  * update it when rotation is set back to 0.
11626                  *
11627                  * FIXME: This is redundant with the fbc update done in
11628                  * the primary plane enable function except that that
11629                  * one is done too late. We eventually need to unify
11630                  * this.
11631                  */
11632
11633                 if (visible &&
11634                     INTEL_INFO(dev)->gen <= 4 && !IS_G4X(dev) &&
11635                     dev_priv->fbc.crtc == intel_crtc &&
11636                     plane_state->rotation != BIT(DRM_ROTATE_0))
11637                         intel_crtc->atomic.disable_fbc = true;
11638
11639                 /*
11640                  * BDW signals flip done immediately if the plane
11641                  * is disabled, even if the plane enable is already
11642                  * armed to occur at the next vblank :(
11643                  */
11644                 if (turn_on && IS_BROADWELL(dev))
11645                         intel_crtc->atomic.wait_vblank = true;
11646
11647                 intel_crtc->atomic.update_fbc |= visible || mode_changed;
11648                 break;
11649         case DRM_PLANE_TYPE_CURSOR:
11650                 break;
11651         case DRM_PLANE_TYPE_OVERLAY:
11652                 if (turn_off && !mode_changed) {
11653                         intel_crtc->atomic.wait_vblank = true;
11654                         intel_crtc->atomic.update_sprite_watermarks |=
11655                                 1 << i;
11656                 }
11657         }
11658         return 0;
11659 }
11660
11661 static bool encoders_cloneable(const struct intel_encoder *a,
11662                                const struct intel_encoder *b)
11663 {
11664         /* masks could be asymmetric, so check both ways */
11665         return a == b || (a->cloneable & (1 << b->type) &&
11666                           b->cloneable & (1 << a->type));
11667 }
11668
11669 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
11670                                          struct intel_crtc *crtc,
11671                                          struct intel_encoder *encoder)
11672 {
11673         struct intel_encoder *source_encoder;
11674         struct drm_connector *connector;
11675         struct drm_connector_state *connector_state;
11676         int i;
11677
11678         for_each_connector_in_state(state, connector, connector_state, i) {
11679                 if (connector_state->crtc != &crtc->base)
11680                         continue;
11681
11682                 source_encoder =
11683                         to_intel_encoder(connector_state->best_encoder);
11684                 if (!encoders_cloneable(encoder, source_encoder))
11685                         return false;
11686         }
11687
11688         return true;
11689 }
11690
11691 static bool check_encoder_cloning(struct drm_atomic_state *state,
11692                                   struct intel_crtc *crtc)
11693 {
11694         struct intel_encoder *encoder;
11695         struct drm_connector *connector;
11696         struct drm_connector_state *connector_state;
11697         int i;
11698
11699         for_each_connector_in_state(state, connector, connector_state, i) {
11700                 if (connector_state->crtc != &crtc->base)
11701                         continue;
11702
11703                 encoder = to_intel_encoder(connector_state->best_encoder);
11704                 if (!check_single_encoder_cloning(state, crtc, encoder))
11705                         return false;
11706         }
11707
11708         return true;
11709 }
11710
11711 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
11712                                    struct drm_crtc_state *crtc_state)
11713 {
11714         struct drm_device *dev = crtc->dev;
11715         struct drm_i915_private *dev_priv = dev->dev_private;
11716         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11717         struct intel_crtc_state *pipe_config =
11718                 to_intel_crtc_state(crtc_state);
11719         struct drm_atomic_state *state = crtc_state->state;
11720         int ret;
11721         bool mode_changed = needs_modeset(crtc_state);
11722
11723         if (mode_changed && !check_encoder_cloning(state, intel_crtc)) {
11724                 DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
11725                 return -EINVAL;
11726         }
11727
11728         if (mode_changed && !crtc_state->active)
11729                 intel_crtc->atomic.update_wm_post = true;
11730
11731         if (mode_changed && crtc_state->enable &&
11732             dev_priv->display.crtc_compute_clock &&
11733             !WARN_ON(pipe_config->shared_dpll != DPLL_ID_PRIVATE)) {
11734                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
11735                                                            pipe_config);
11736                 if (ret)
11737                         return ret;
11738         }
11739
11740         ret = 0;
11741         if (INTEL_INFO(dev)->gen >= 9) {
11742                 if (mode_changed)
11743                         ret = skl_update_scaler_crtc(pipe_config);
11744
11745                 if (!ret)
11746                         ret = intel_atomic_setup_scalers(dev, intel_crtc,
11747                                                          pipe_config);
11748         }
11749
11750         return ret;
11751 }
11752
11753 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
11754         .mode_set_base_atomic = intel_pipe_set_base_atomic,
11755         .load_lut = intel_crtc_load_lut,
11756         .atomic_begin = intel_begin_crtc_commit,
11757         .atomic_flush = intel_finish_crtc_commit,
11758         .atomic_check = intel_crtc_atomic_check,
11759 };
11760
11761 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
11762 {
11763         struct intel_connector *connector;
11764
11765         for_each_intel_connector(dev, connector) {
11766                 if (connector->base.encoder) {
11767                         connector->base.state->best_encoder =
11768                                 connector->base.encoder;
11769                         connector->base.state->crtc =
11770                                 connector->base.encoder->crtc;
11771                 } else {
11772                         connector->base.state->best_encoder = NULL;
11773                         connector->base.state->crtc = NULL;
11774                 }
11775         }
11776 }
11777
11778 static void
11779 connected_sink_compute_bpp(struct intel_connector *connector,
11780                            struct intel_crtc_state *pipe_config)
11781 {
11782         int bpp = pipe_config->pipe_bpp;
11783
11784         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
11785                 connector->base.base.id,
11786                 connector->base.name);
11787
11788         /* Don't use an invalid EDID bpc value */
11789         if (connector->base.display_info.bpc &&
11790             connector->base.display_info.bpc * 3 < bpp) {
11791                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
11792                               bpp, connector->base.display_info.bpc*3);
11793                 pipe_config->pipe_bpp = connector->base.display_info.bpc*3;
11794         }
11795
11796         /* Clamp bpp to 8 on screens without EDID 1.4 */
11797         if (connector->base.display_info.bpc == 0 && bpp > 24) {
11798                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
11799                               bpp);
11800                 pipe_config->pipe_bpp = 24;
11801         }
11802 }
11803
11804 static int
11805 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
11806                           struct intel_crtc_state *pipe_config)
11807 {
11808         struct drm_device *dev = crtc->base.dev;
11809         struct drm_atomic_state *state;
11810         struct drm_connector *connector;
11811         struct drm_connector_state *connector_state;
11812         int bpp, i;
11813
11814         if ((IS_G4X(dev) || IS_VALLEYVIEW(dev)))
11815                 bpp = 10*3;
11816         else if (INTEL_INFO(dev)->gen >= 5)
11817                 bpp = 12*3;
11818         else
11819                 bpp = 8*3;
11820
11821
11822         pipe_config->pipe_bpp = bpp;
11823
11824         state = pipe_config->base.state;
11825
11826         /* Clamp display bpp to EDID value */
11827         for_each_connector_in_state(state, connector, connector_state, i) {
11828                 if (connector_state->crtc != &crtc->base)
11829                         continue;
11830
11831                 connected_sink_compute_bpp(to_intel_connector(connector),
11832                                            pipe_config);
11833         }
11834
11835         return bpp;
11836 }
11837
11838 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
11839 {
11840         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
11841                         "type: 0x%x flags: 0x%x\n",
11842                 mode->crtc_clock,
11843                 mode->crtc_hdisplay, mode->crtc_hsync_start,
11844                 mode->crtc_hsync_end, mode->crtc_htotal,
11845                 mode->crtc_vdisplay, mode->crtc_vsync_start,
11846                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
11847 }
11848
11849 static void intel_dump_pipe_config(struct intel_crtc *crtc,
11850                                    struct intel_crtc_state *pipe_config,
11851                                    const char *context)
11852 {
11853         struct drm_device *dev = crtc->base.dev;
11854         struct drm_plane *plane;
11855         struct intel_plane *intel_plane;
11856         struct intel_plane_state *state;
11857         struct drm_framebuffer *fb;
11858
11859         DRM_DEBUG_KMS("[CRTC:%d]%s config %p for pipe %c\n", crtc->base.base.id,
11860                       context, pipe_config, pipe_name(crtc->pipe));
11861
11862         DRM_DEBUG_KMS("cpu_transcoder: %c\n", transcoder_name(pipe_config->cpu_transcoder));
11863         DRM_DEBUG_KMS("pipe bpp: %i, dithering: %i\n",
11864                       pipe_config->pipe_bpp, pipe_config->dither);
11865         DRM_DEBUG_KMS("fdi/pch: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
11866                       pipe_config->has_pch_encoder,
11867                       pipe_config->fdi_lanes,
11868                       pipe_config->fdi_m_n.gmch_m, pipe_config->fdi_m_n.gmch_n,
11869                       pipe_config->fdi_m_n.link_m, pipe_config->fdi_m_n.link_n,
11870                       pipe_config->fdi_m_n.tu);
11871         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
11872                       pipe_config->has_dp_encoder,
11873                       pipe_config->lane_count,
11874                       pipe_config->dp_m_n.gmch_m, pipe_config->dp_m_n.gmch_n,
11875                       pipe_config->dp_m_n.link_m, pipe_config->dp_m_n.link_n,
11876                       pipe_config->dp_m_n.tu);
11877
11878         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m2: %u, gmch_n2: %u, link_m2: %u, link_n2: %u, tu2: %u\n",
11879                       pipe_config->has_dp_encoder,
11880                       pipe_config->lane_count,
11881                       pipe_config->dp_m2_n2.gmch_m,
11882                       pipe_config->dp_m2_n2.gmch_n,
11883                       pipe_config->dp_m2_n2.link_m,
11884                       pipe_config->dp_m2_n2.link_n,
11885                       pipe_config->dp_m2_n2.tu);
11886
11887         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
11888                       pipe_config->has_audio,
11889                       pipe_config->has_infoframe);
11890
11891         DRM_DEBUG_KMS("requested mode:\n");
11892         drm_mode_debug_printmodeline(&pipe_config->base.mode);
11893         DRM_DEBUG_KMS("adjusted mode:\n");
11894         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
11895         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
11896         DRM_DEBUG_KMS("port clock: %d\n", pipe_config->port_clock);
11897         DRM_DEBUG_KMS("pipe src size: %dx%d\n",
11898                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
11899         DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
11900                       crtc->num_scalers,
11901                       pipe_config->scaler_state.scaler_users,
11902                       pipe_config->scaler_state.scaler_id);
11903         DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
11904                       pipe_config->gmch_pfit.control,
11905                       pipe_config->gmch_pfit.pgm_ratios,
11906                       pipe_config->gmch_pfit.lvds_border_bits);
11907         DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
11908                       pipe_config->pch_pfit.pos,
11909                       pipe_config->pch_pfit.size,
11910                       pipe_config->pch_pfit.enabled ? "enabled" : "disabled");
11911         DRM_DEBUG_KMS("ips: %i\n", pipe_config->ips_enabled);
11912         DRM_DEBUG_KMS("double wide: %i\n", pipe_config->double_wide);
11913
11914         if (IS_BROXTON(dev)) {
11915                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: ebb0: 0x%x, ebb4: 0x%x,"
11916                               "pll0: 0x%x, pll1: 0x%x, pll2: 0x%x, pll3: 0x%x, "
11917                               "pll6: 0x%x, pll8: 0x%x, pll9: 0x%x, pll10: 0x%x, pcsdw12: 0x%x\n",
11918                               pipe_config->ddi_pll_sel,
11919                               pipe_config->dpll_hw_state.ebb0,
11920                               pipe_config->dpll_hw_state.ebb4,
11921                               pipe_config->dpll_hw_state.pll0,
11922                               pipe_config->dpll_hw_state.pll1,
11923                               pipe_config->dpll_hw_state.pll2,
11924                               pipe_config->dpll_hw_state.pll3,
11925                               pipe_config->dpll_hw_state.pll6,
11926                               pipe_config->dpll_hw_state.pll8,
11927                               pipe_config->dpll_hw_state.pll9,
11928                               pipe_config->dpll_hw_state.pll10,
11929                               pipe_config->dpll_hw_state.pcsdw12);
11930         } else if (IS_SKYLAKE(dev)) {
11931                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: "
11932                               "ctrl1: 0x%x, cfgcr1: 0x%x, cfgcr2: 0x%x\n",
11933                               pipe_config->ddi_pll_sel,
11934                               pipe_config->dpll_hw_state.ctrl1,
11935                               pipe_config->dpll_hw_state.cfgcr1,
11936                               pipe_config->dpll_hw_state.cfgcr2);
11937         } else if (HAS_DDI(dev)) {
11938                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: wrpll: 0x%x\n",
11939                               pipe_config->ddi_pll_sel,
11940                               pipe_config->dpll_hw_state.wrpll);
11941         } else {
11942                 DRM_DEBUG_KMS("dpll_hw_state: dpll: 0x%x, dpll_md: 0x%x, "
11943                               "fp0: 0x%x, fp1: 0x%x\n",
11944                               pipe_config->dpll_hw_state.dpll,
11945                               pipe_config->dpll_hw_state.dpll_md,
11946                               pipe_config->dpll_hw_state.fp0,
11947                               pipe_config->dpll_hw_state.fp1);
11948         }
11949
11950         DRM_DEBUG_KMS("planes on this crtc\n");
11951         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
11952                 intel_plane = to_intel_plane(plane);
11953                 if (intel_plane->pipe != crtc->pipe)
11954                         continue;
11955
11956                 state = to_intel_plane_state(plane->state);
11957                 fb = state->base.fb;
11958                 if (!fb) {
11959                         DRM_DEBUG_KMS("%s PLANE:%d plane: %u.%u idx: %d "
11960                                 "disabled, scaler_id = %d\n",
11961                                 plane->type == DRM_PLANE_TYPE_CURSOR ? "CURSOR" : "STANDARD",
11962                                 plane->base.id, intel_plane->pipe,
11963                                 (crtc->base.primary == plane) ? 0 : intel_plane->plane + 1,
11964                                 drm_plane_index(plane), state->scaler_id);
11965                         continue;
11966                 }
11967
11968                 DRM_DEBUG_KMS("%s PLANE:%d plane: %u.%u idx: %d enabled",
11969                         plane->type == DRM_PLANE_TYPE_CURSOR ? "CURSOR" : "STANDARD",
11970                         plane->base.id, intel_plane->pipe,
11971                         crtc->base.primary == plane ? 0 : intel_plane->plane + 1,
11972                         drm_plane_index(plane));
11973                 DRM_DEBUG_KMS("\tFB:%d, fb = %ux%u format = 0x%x",
11974                         fb->base.id, fb->width, fb->height, fb->pixel_format);
11975                 DRM_DEBUG_KMS("\tscaler:%d src (%u, %u) %ux%u dst (%u, %u) %ux%u\n",
11976                         state->scaler_id,
11977                         state->src.x1 >> 16, state->src.y1 >> 16,
11978                         drm_rect_width(&state->src) >> 16,
11979                         drm_rect_height(&state->src) >> 16,
11980                         state->dst.x1, state->dst.y1,
11981                         drm_rect_width(&state->dst), drm_rect_height(&state->dst));
11982         }
11983 }
11984
11985 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
11986 {
11987         struct drm_device *dev = state->dev;
11988         struct intel_encoder *encoder;
11989         struct drm_connector *connector;
11990         struct drm_connector_state *connector_state;
11991         unsigned int used_ports = 0;
11992         int i;
11993
11994         /*
11995          * Walk the connector list instead of the encoder
11996          * list to detect the problem on ddi platforms
11997          * where there's just one encoder per digital port.
11998          */
11999         for_each_connector_in_state(state, connector, connector_state, i) {
12000                 if (!connector_state->best_encoder)
12001                         continue;
12002
12003                 encoder = to_intel_encoder(connector_state->best_encoder);
12004
12005                 WARN_ON(!connector_state->crtc);
12006
12007                 switch (encoder->type) {
12008                         unsigned int port_mask;
12009                 case INTEL_OUTPUT_UNKNOWN:
12010                         if (WARN_ON(!HAS_DDI(dev)))
12011                                 break;
12012                 case INTEL_OUTPUT_DISPLAYPORT:
12013                 case INTEL_OUTPUT_HDMI:
12014                 case INTEL_OUTPUT_EDP:
12015                         port_mask = 1 << enc_to_dig_port(&encoder->base)->port;
12016
12017                         /* the same port mustn't appear more than once */
12018                         if (used_ports & port_mask)
12019                                 return false;
12020
12021                         used_ports |= port_mask;
12022                 default:
12023                         break;
12024                 }
12025         }
12026
12027         return true;
12028 }
12029
12030 static void
12031 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
12032 {
12033         struct drm_crtc_state tmp_state;
12034         struct intel_crtc_scaler_state scaler_state;
12035         struct intel_dpll_hw_state dpll_hw_state;
12036         enum intel_dpll_id shared_dpll;
12037         uint32_t ddi_pll_sel;
12038         bool force_thru;
12039
12040         /* FIXME: before the switch to atomic started, a new pipe_config was
12041          * kzalloc'd. Code that depends on any field being zero should be
12042          * fixed, so that the crtc_state can be safely duplicated. For now,
12043          * only fields that are know to not cause problems are preserved. */
12044
12045         tmp_state = crtc_state->base;
12046         scaler_state = crtc_state->scaler_state;
12047         shared_dpll = crtc_state->shared_dpll;
12048         dpll_hw_state = crtc_state->dpll_hw_state;
12049         ddi_pll_sel = crtc_state->ddi_pll_sel;
12050         force_thru = crtc_state->pch_pfit.force_thru;
12051
12052         memset(crtc_state, 0, sizeof *crtc_state);
12053
12054         crtc_state->base = tmp_state;
12055         crtc_state->scaler_state = scaler_state;
12056         crtc_state->shared_dpll = shared_dpll;
12057         crtc_state->dpll_hw_state = dpll_hw_state;
12058         crtc_state->ddi_pll_sel = ddi_pll_sel;
12059         crtc_state->pch_pfit.force_thru = force_thru;
12060 }
12061
12062 static int
12063 intel_modeset_pipe_config(struct drm_crtc *crtc,
12064                           struct intel_crtc_state *pipe_config)
12065 {
12066         struct drm_atomic_state *state = pipe_config->base.state;
12067         struct intel_encoder *encoder;
12068         struct drm_connector *connector;
12069         struct drm_connector_state *connector_state;
12070         int base_bpp, ret = -EINVAL;
12071         int i;
12072         bool retry = true;
12073
12074         clear_intel_crtc_state(pipe_config);
12075
12076         pipe_config->cpu_transcoder =
12077                 (enum transcoder) to_intel_crtc(crtc)->pipe;
12078
12079         /*
12080          * Sanitize sync polarity flags based on requested ones. If neither
12081          * positive or negative polarity is requested, treat this as meaning
12082          * negative polarity.
12083          */
12084         if (!(pipe_config->base.adjusted_mode.flags &
12085               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
12086                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
12087
12088         if (!(pipe_config->base.adjusted_mode.flags &
12089               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
12090                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
12091
12092         /* Compute a starting value for pipe_config->pipe_bpp taking the source
12093          * plane pixel format and any sink constraints into account. Returns the
12094          * source plane bpp so that dithering can be selected on mismatches
12095          * after encoders and crtc also have had their say. */
12096         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
12097                                              pipe_config);
12098         if (base_bpp < 0)
12099                 goto fail;
12100
12101         /*
12102          * Determine the real pipe dimensions. Note that stereo modes can
12103          * increase the actual pipe size due to the frame doubling and
12104          * insertion of additional space for blanks between the frame. This
12105          * is stored in the crtc timings. We use the requested mode to do this
12106          * computation to clearly distinguish it from the adjusted mode, which
12107          * can be changed by the connectors in the below retry loop.
12108          */
12109         drm_crtc_get_hv_timing(&pipe_config->base.mode,
12110                                &pipe_config->pipe_src_w,
12111                                &pipe_config->pipe_src_h);
12112
12113 encoder_retry:
12114         /* Ensure the port clock defaults are reset when retrying. */
12115         pipe_config->port_clock = 0;
12116         pipe_config->pixel_multiplier = 1;
12117
12118         /* Fill in default crtc timings, allow encoders to overwrite them. */
12119         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
12120                               CRTC_STEREO_DOUBLE);
12121
12122         /* Pass our mode to the connectors and the CRTC to give them a chance to
12123          * adjust it according to limitations or connector properties, and also
12124          * a chance to reject the mode entirely.
12125          */
12126         for_each_connector_in_state(state, connector, connector_state, i) {
12127                 if (connector_state->crtc != crtc)
12128                         continue;
12129
12130                 encoder = to_intel_encoder(connector_state->best_encoder);
12131
12132                 if (!(encoder->compute_config(encoder, pipe_config))) {
12133                         DRM_DEBUG_KMS("Encoder config failure\n");
12134                         goto fail;
12135                 }
12136         }
12137
12138         /* Set default port clock if not overwritten by the encoder. Needs to be
12139          * done afterwards in case the encoder adjusts the mode. */
12140         if (!pipe_config->port_clock)
12141                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
12142                         * pipe_config->pixel_multiplier;
12143
12144         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
12145         if (ret < 0) {
12146                 DRM_DEBUG_KMS("CRTC fixup failed\n");
12147                 goto fail;
12148         }
12149
12150         if (ret == RETRY) {
12151                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
12152                         ret = -EINVAL;
12153                         goto fail;
12154                 }
12155
12156                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
12157                 retry = false;
12158                 goto encoder_retry;
12159         }
12160
12161         /* Dithering seems to not pass-through bits correctly when it should, so
12162          * only enable it on 6bpc panels. */
12163         pipe_config->dither = pipe_config->pipe_bpp == 6*3;
12164         DRM_DEBUG_KMS("plane bpp: %i, pipe bpp: %i, dithering: %i\n",
12165                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
12166
12167 fail:
12168         return ret;
12169 }
12170
12171 static void
12172 intel_modeset_update_crtc_state(struct drm_atomic_state *state)
12173 {
12174         struct drm_crtc *crtc;
12175         struct drm_crtc_state *crtc_state;
12176         int i;
12177
12178         /* Double check state. */
12179         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12180                 to_intel_crtc(crtc)->config = to_intel_crtc_state(crtc->state);
12181
12182                 /* Update hwmode for vblank functions */
12183                 if (crtc->state->active)
12184                         crtc->hwmode = crtc->state->adjusted_mode;
12185                 else
12186                         crtc->hwmode.crtc_clock = 0;
12187         }
12188 }
12189
12190 static bool intel_fuzzy_clock_check(int clock1, int clock2)
12191 {
12192         int diff;
12193
12194         if (clock1 == clock2)
12195                 return true;
12196
12197         if (!clock1 || !clock2)
12198                 return false;
12199
12200         diff = abs(clock1 - clock2);
12201
12202         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
12203                 return true;
12204
12205         return false;
12206 }
12207
12208 #define for_each_intel_crtc_masked(dev, mask, intel_crtc) \
12209         list_for_each_entry((intel_crtc), \
12210                             &(dev)->mode_config.crtc_list, \
12211                             base.head) \
12212                 if (mask & (1 <<(intel_crtc)->pipe))
12213
12214
12215 static bool
12216 intel_compare_m_n(unsigned int m, unsigned int n,
12217                   unsigned int m2, unsigned int n2,
12218                   bool exact)
12219 {
12220         if (m == m2 && n == n2)
12221                 return true;
12222
12223         if (exact || !m || !n || !m2 || !n2)
12224                 return false;
12225
12226         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
12227
12228         if (m > m2) {
12229                 while (m > m2) {
12230                         m2 <<= 1;
12231                         n2 <<= 1;
12232                 }
12233         } else if (m < m2) {
12234                 while (m < m2) {
12235                         m <<= 1;
12236                         n <<= 1;
12237                 }
12238         }
12239
12240         return m == m2 && n == n2;
12241 }
12242
12243 static bool
12244 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
12245                        struct intel_link_m_n *m2_n2,
12246                        bool adjust)
12247 {
12248         if (m_n->tu == m2_n2->tu &&
12249             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
12250                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
12251             intel_compare_m_n(m_n->link_m, m_n->link_n,
12252                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
12253                 if (adjust)
12254                         *m2_n2 = *m_n;
12255
12256                 return true;
12257         }
12258
12259         return false;
12260 }
12261
12262 static bool
12263 intel_pipe_config_compare(struct drm_device *dev,
12264                           struct intel_crtc_state *current_config,
12265                           struct intel_crtc_state *pipe_config,
12266                           bool adjust)
12267 {
12268         bool ret = true;
12269
12270 #define INTEL_ERR_OR_DBG_KMS(fmt, ...) \
12271         do { \
12272                 if (!adjust) \
12273                         DRM_ERROR(fmt, ##__VA_ARGS__); \
12274                 else \
12275                         DRM_DEBUG_KMS(fmt, ##__VA_ARGS__); \
12276         } while (0)
12277
12278 #define PIPE_CONF_CHECK_X(name) \
12279         if (current_config->name != pipe_config->name) { \
12280                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12281                           "(expected 0x%08x, found 0x%08x)\n", \
12282                           current_config->name, \
12283                           pipe_config->name); \
12284                 ret = false; \
12285         }
12286
12287 #define PIPE_CONF_CHECK_I(name) \
12288         if (current_config->name != pipe_config->name) { \
12289                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12290                           "(expected %i, found %i)\n", \
12291                           current_config->name, \
12292                           pipe_config->name); \
12293                 ret = false; \
12294         }
12295
12296 #define PIPE_CONF_CHECK_M_N(name) \
12297         if (!intel_compare_link_m_n(&current_config->name, \
12298                                     &pipe_config->name,\
12299                                     adjust)) { \
12300                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12301                           "(expected tu %i gmch %i/%i link %i/%i, " \
12302                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12303                           current_config->name.tu, \
12304                           current_config->name.gmch_m, \
12305                           current_config->name.gmch_n, \
12306                           current_config->name.link_m, \
12307                           current_config->name.link_n, \
12308                           pipe_config->name.tu, \
12309                           pipe_config->name.gmch_m, \
12310                           pipe_config->name.gmch_n, \
12311                           pipe_config->name.link_m, \
12312                           pipe_config->name.link_n); \
12313                 ret = false; \
12314         }
12315
12316 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) \
12317         if (!intel_compare_link_m_n(&current_config->name, \
12318                                     &pipe_config->name, adjust) && \
12319             !intel_compare_link_m_n(&current_config->alt_name, \
12320                                     &pipe_config->name, adjust)) { \
12321                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12322                           "(expected tu %i gmch %i/%i link %i/%i, " \
12323                           "or tu %i gmch %i/%i link %i/%i, " \
12324                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12325                           current_config->name.tu, \
12326                           current_config->name.gmch_m, \
12327                           current_config->name.gmch_n, \
12328                           current_config->name.link_m, \
12329                           current_config->name.link_n, \
12330                           current_config->alt_name.tu, \
12331                           current_config->alt_name.gmch_m, \
12332                           current_config->alt_name.gmch_n, \
12333                           current_config->alt_name.link_m, \
12334                           current_config->alt_name.link_n, \
12335                           pipe_config->name.tu, \
12336                           pipe_config->name.gmch_m, \
12337                           pipe_config->name.gmch_n, \
12338                           pipe_config->name.link_m, \
12339                           pipe_config->name.link_n); \
12340                 ret = false; \
12341         }
12342
12343 /* This is required for BDW+ where there is only one set of registers for
12344  * switching between high and low RR.
12345  * This macro can be used whenever a comparison has to be made between one
12346  * hw state and multiple sw state variables.
12347  */
12348 #define PIPE_CONF_CHECK_I_ALT(name, alt_name) \
12349         if ((current_config->name != pipe_config->name) && \
12350                 (current_config->alt_name != pipe_config->name)) { \
12351                         INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12352                                   "(expected %i or %i, found %i)\n", \
12353                                   current_config->name, \
12354                                   current_config->alt_name, \
12355                                   pipe_config->name); \
12356                         ret = false; \
12357         }
12358
12359 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
12360         if ((current_config->name ^ pipe_config->name) & (mask)) { \
12361                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name "(" #mask ") " \
12362                           "(expected %i, found %i)\n", \
12363                           current_config->name & (mask), \
12364                           pipe_config->name & (mask)); \
12365                 ret = false; \
12366         }
12367
12368 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
12369         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
12370                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12371                           "(expected %i, found %i)\n", \
12372                           current_config->name, \
12373                           pipe_config->name); \
12374                 ret = false; \
12375         }
12376
12377 #define PIPE_CONF_QUIRK(quirk)  \
12378         ((current_config->quirks | pipe_config->quirks) & (quirk))
12379
12380         PIPE_CONF_CHECK_I(cpu_transcoder);
12381
12382         PIPE_CONF_CHECK_I(has_pch_encoder);
12383         PIPE_CONF_CHECK_I(fdi_lanes);
12384         PIPE_CONF_CHECK_M_N(fdi_m_n);
12385
12386         PIPE_CONF_CHECK_I(has_dp_encoder);
12387         PIPE_CONF_CHECK_I(lane_count);
12388
12389         if (INTEL_INFO(dev)->gen < 8) {
12390                 PIPE_CONF_CHECK_M_N(dp_m_n);
12391
12392                 PIPE_CONF_CHECK_I(has_drrs);
12393                 if (current_config->has_drrs)
12394                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
12395         } else
12396                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
12397
12398         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
12399         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
12400         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
12401         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
12402         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
12403         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
12404
12405         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
12406         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
12407         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
12408         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
12409         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
12410         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
12411
12412         PIPE_CONF_CHECK_I(pixel_multiplier);
12413         PIPE_CONF_CHECK_I(has_hdmi_sink);
12414         if ((INTEL_INFO(dev)->gen < 8 && !IS_HASWELL(dev)) ||
12415             IS_VALLEYVIEW(dev))
12416                 PIPE_CONF_CHECK_I(limited_color_range);
12417         PIPE_CONF_CHECK_I(has_infoframe);
12418
12419         PIPE_CONF_CHECK_I(has_audio);
12420
12421         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12422                               DRM_MODE_FLAG_INTERLACE);
12423
12424         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
12425                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12426                                       DRM_MODE_FLAG_PHSYNC);
12427                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12428                                       DRM_MODE_FLAG_NHSYNC);
12429                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12430                                       DRM_MODE_FLAG_PVSYNC);
12431                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12432                                       DRM_MODE_FLAG_NVSYNC);
12433         }
12434
12435         PIPE_CONF_CHECK_I(pipe_src_w);
12436         PIPE_CONF_CHECK_I(pipe_src_h);
12437
12438         PIPE_CONF_CHECK_I(gmch_pfit.control);
12439         /* pfit ratios are autocomputed by the hw on gen4+ */
12440         if (INTEL_INFO(dev)->gen < 4)
12441                 PIPE_CONF_CHECK_I(gmch_pfit.pgm_ratios);
12442         PIPE_CONF_CHECK_I(gmch_pfit.lvds_border_bits);
12443
12444         PIPE_CONF_CHECK_I(pch_pfit.enabled);
12445         if (current_config->pch_pfit.enabled) {
12446                 PIPE_CONF_CHECK_I(pch_pfit.pos);
12447                 PIPE_CONF_CHECK_I(pch_pfit.size);
12448         }
12449
12450         PIPE_CONF_CHECK_I(scaler_state.scaler_id);
12451
12452         /* BDW+ don't expose a synchronous way to read the state */
12453         if (IS_HASWELL(dev))
12454                 PIPE_CONF_CHECK_I(ips_enabled);
12455
12456         PIPE_CONF_CHECK_I(double_wide);
12457
12458         PIPE_CONF_CHECK_X(ddi_pll_sel);
12459
12460         PIPE_CONF_CHECK_I(shared_dpll);
12461         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
12462         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
12463         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
12464         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
12465         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
12466         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
12467         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
12468         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
12469
12470         if (IS_G4X(dev) || INTEL_INFO(dev)->gen >= 5)
12471                 PIPE_CONF_CHECK_I(pipe_bpp);
12472
12473         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
12474         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
12475
12476 #undef PIPE_CONF_CHECK_X
12477 #undef PIPE_CONF_CHECK_I
12478 #undef PIPE_CONF_CHECK_I_ALT
12479 #undef PIPE_CONF_CHECK_FLAGS
12480 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
12481 #undef PIPE_CONF_QUIRK
12482 #undef INTEL_ERR_OR_DBG_KMS
12483
12484         return ret;
12485 }
12486
12487 static void check_wm_state(struct drm_device *dev)
12488 {
12489         struct drm_i915_private *dev_priv = dev->dev_private;
12490         struct skl_ddb_allocation hw_ddb, *sw_ddb;
12491         struct intel_crtc *intel_crtc;
12492         int plane;
12493
12494         if (INTEL_INFO(dev)->gen < 9)
12495                 return;
12496
12497         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
12498         sw_ddb = &dev_priv->wm.skl_hw.ddb;
12499
12500         for_each_intel_crtc(dev, intel_crtc) {
12501                 struct skl_ddb_entry *hw_entry, *sw_entry;
12502                 const enum pipe pipe = intel_crtc->pipe;
12503
12504                 if (!intel_crtc->active)
12505                         continue;
12506
12507                 /* planes */
12508                 for_each_plane(dev_priv, pipe, plane) {
12509                         hw_entry = &hw_ddb.plane[pipe][plane];
12510                         sw_entry = &sw_ddb->plane[pipe][plane];
12511
12512                         if (skl_ddb_entry_equal(hw_entry, sw_entry))
12513                                 continue;
12514
12515                         DRM_ERROR("mismatch in DDB state pipe %c plane %d "
12516                                   "(expected (%u,%u), found (%u,%u))\n",
12517                                   pipe_name(pipe), plane + 1,
12518                                   sw_entry->start, sw_entry->end,
12519                                   hw_entry->start, hw_entry->end);
12520                 }
12521
12522                 /* cursor */
12523                 hw_entry = &hw_ddb.cursor[pipe];
12524                 sw_entry = &sw_ddb->cursor[pipe];
12525
12526                 if (skl_ddb_entry_equal(hw_entry, sw_entry))
12527                         continue;
12528
12529                 DRM_ERROR("mismatch in DDB state pipe %c cursor "
12530                           "(expected (%u,%u), found (%u,%u))\n",
12531                           pipe_name(pipe),
12532                           sw_entry->start, sw_entry->end,
12533                           hw_entry->start, hw_entry->end);
12534         }
12535 }
12536
12537 static void
12538 check_connector_state(struct drm_device *dev,
12539                       struct drm_atomic_state *old_state)
12540 {
12541         struct drm_connector_state *old_conn_state;
12542         struct drm_connector *connector;
12543         int i;
12544
12545         for_each_connector_in_state(old_state, connector, old_conn_state, i) {
12546                 struct drm_encoder *encoder = connector->encoder;
12547                 struct drm_connector_state *state = connector->state;
12548
12549                 /* This also checks the encoder/connector hw state with the
12550                  * ->get_hw_state callbacks. */
12551                 intel_connector_check_state(to_intel_connector(connector));
12552
12553                 I915_STATE_WARN(state->best_encoder != encoder,
12554                      "connector's atomic encoder doesn't match legacy encoder\n");
12555         }
12556 }
12557
12558 static void
12559 check_encoder_state(struct drm_device *dev)
12560 {
12561         struct intel_encoder *encoder;
12562         struct intel_connector *connector;
12563
12564         for_each_intel_encoder(dev, encoder) {
12565                 bool enabled = false;
12566                 enum pipe pipe;
12567
12568                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
12569                               encoder->base.base.id,
12570                               encoder->base.name);
12571
12572                 for_each_intel_connector(dev, connector) {
12573                         if (connector->base.state->best_encoder != &encoder->base)
12574                                 continue;
12575                         enabled = true;
12576
12577                         I915_STATE_WARN(connector->base.state->crtc !=
12578                                         encoder->base.crtc,
12579                              "connector's crtc doesn't match encoder crtc\n");
12580                 }
12581
12582                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
12583                      "encoder's enabled state mismatch "
12584                      "(expected %i, found %i)\n",
12585                      !!encoder->base.crtc, enabled);
12586
12587                 if (!encoder->base.crtc) {
12588                         bool active;
12589
12590                         active = encoder->get_hw_state(encoder, &pipe);
12591                         I915_STATE_WARN(active,
12592                              "encoder detached but still enabled on pipe %c.\n",
12593                              pipe_name(pipe));
12594                 }
12595         }
12596 }
12597
12598 static void
12599 check_crtc_state(struct drm_device *dev, struct drm_atomic_state *old_state)
12600 {
12601         struct drm_i915_private *dev_priv = dev->dev_private;
12602         struct intel_encoder *encoder;
12603         struct drm_crtc_state *old_crtc_state;
12604         struct drm_crtc *crtc;
12605         int i;
12606
12607         for_each_crtc_in_state(old_state, crtc, old_crtc_state, i) {
12608                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12609                 struct intel_crtc_state *pipe_config, *sw_config;
12610                 bool active;
12611
12612                 if (!needs_modeset(crtc->state))
12613                         continue;
12614
12615                 __drm_atomic_helper_crtc_destroy_state(crtc, old_crtc_state);
12616                 pipe_config = to_intel_crtc_state(old_crtc_state);
12617                 memset(pipe_config, 0, sizeof(*pipe_config));
12618                 pipe_config->base.crtc = crtc;
12619                 pipe_config->base.state = old_state;
12620
12621                 DRM_DEBUG_KMS("[CRTC:%d]\n",
12622                               crtc->base.id);
12623
12624                 active = dev_priv->display.get_pipe_config(intel_crtc,
12625                                                            pipe_config);
12626
12627                 /* hw state is inconsistent with the pipe quirk */
12628                 if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
12629                     (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
12630                         active = crtc->state->active;
12631
12632                 I915_STATE_WARN(crtc->state->active != active,
12633                      "crtc active state doesn't match with hw state "
12634                      "(expected %i, found %i)\n", crtc->state->active, active);
12635
12636                 I915_STATE_WARN(intel_crtc->active != crtc->state->active,
12637                      "transitional active state does not match atomic hw state "
12638                      "(expected %i, found %i)\n", crtc->state->active, intel_crtc->active);
12639
12640                 for_each_encoder_on_crtc(dev, crtc, encoder) {
12641                         enum pipe pipe;
12642
12643                         active = encoder->get_hw_state(encoder, &pipe);
12644                         I915_STATE_WARN(active != crtc->state->active,
12645                                 "[ENCODER:%i] active %i with crtc active %i\n",
12646                                 encoder->base.base.id, active, crtc->state->active);
12647
12648                         I915_STATE_WARN(active && intel_crtc->pipe != pipe,
12649                                         "Encoder connected to wrong pipe %c\n",
12650                                         pipe_name(pipe));
12651
12652                         if (active)
12653                                 encoder->get_config(encoder, pipe_config);
12654                 }
12655
12656                 if (!crtc->state->active)
12657                         continue;
12658
12659                 sw_config = to_intel_crtc_state(crtc->state);
12660                 if (!intel_pipe_config_compare(dev, sw_config,
12661                                                pipe_config, false)) {
12662                         I915_STATE_WARN(1, "pipe state doesn't match!\n");
12663                         intel_dump_pipe_config(intel_crtc, pipe_config,
12664                                                "[hw state]");
12665                         intel_dump_pipe_config(intel_crtc, sw_config,
12666                                                "[sw state]");
12667                 }
12668         }
12669 }
12670
12671 static void
12672 check_shared_dpll_state(struct drm_device *dev)
12673 {
12674         struct drm_i915_private *dev_priv = dev->dev_private;
12675         struct intel_crtc *crtc;
12676         struct intel_dpll_hw_state dpll_hw_state;
12677         int i;
12678
12679         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
12680                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
12681                 int enabled_crtcs = 0, active_crtcs = 0;
12682                 bool active;
12683
12684                 memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
12685
12686                 DRM_DEBUG_KMS("%s\n", pll->name);
12687
12688                 active = pll->get_hw_state(dev_priv, pll, &dpll_hw_state);
12689
12690                 I915_STATE_WARN(pll->active > hweight32(pll->config.crtc_mask),
12691                      "more active pll users than references: %i vs %i\n",
12692                      pll->active, hweight32(pll->config.crtc_mask));
12693                 I915_STATE_WARN(pll->active && !pll->on,
12694                      "pll in active use but not on in sw tracking\n");
12695                 I915_STATE_WARN(pll->on && !pll->active,
12696                      "pll in on but not on in use in sw tracking\n");
12697                 I915_STATE_WARN(pll->on != active,
12698                      "pll on state mismatch (expected %i, found %i)\n",
12699                      pll->on, active);
12700
12701                 for_each_intel_crtc(dev, crtc) {
12702                         if (crtc->base.state->enable && intel_crtc_to_shared_dpll(crtc) == pll)
12703                                 enabled_crtcs++;
12704                         if (crtc->active && intel_crtc_to_shared_dpll(crtc) == pll)
12705                                 active_crtcs++;
12706                 }
12707                 I915_STATE_WARN(pll->active != active_crtcs,
12708                      "pll active crtcs mismatch (expected %i, found %i)\n",
12709                      pll->active, active_crtcs);
12710                 I915_STATE_WARN(hweight32(pll->config.crtc_mask) != enabled_crtcs,
12711                      "pll enabled crtcs mismatch (expected %i, found %i)\n",
12712                      hweight32(pll->config.crtc_mask), enabled_crtcs);
12713
12714                 I915_STATE_WARN(pll->on && memcmp(&pll->config.hw_state, &dpll_hw_state,
12715                                        sizeof(dpll_hw_state)),
12716                      "pll hw state mismatch\n");
12717         }
12718 }
12719
12720 static void
12721 intel_modeset_check_state(struct drm_device *dev,
12722                           struct drm_atomic_state *old_state)
12723 {
12724         check_wm_state(dev);
12725         check_connector_state(dev, old_state);
12726         check_encoder_state(dev);
12727         check_crtc_state(dev, old_state);
12728         check_shared_dpll_state(dev);
12729 }
12730
12731 void ironlake_check_encoder_dotclock(const struct intel_crtc_state *pipe_config,
12732                                      int dotclock)
12733 {
12734         /*
12735          * FDI already provided one idea for the dotclock.
12736          * Yell if the encoder disagrees.
12737          */
12738         WARN(!intel_fuzzy_clock_check(pipe_config->base.adjusted_mode.crtc_clock, dotclock),
12739              "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
12740              pipe_config->base.adjusted_mode.crtc_clock, dotclock);
12741 }
12742
12743 static void update_scanline_offset(struct intel_crtc *crtc)
12744 {
12745         struct drm_device *dev = crtc->base.dev;
12746
12747         /*
12748          * The scanline counter increments at the leading edge of hsync.
12749          *
12750          * On most platforms it starts counting from vtotal-1 on the
12751          * first active line. That means the scanline counter value is
12752          * always one less than what we would expect. Ie. just after
12753          * start of vblank, which also occurs at start of hsync (on the
12754          * last active line), the scanline counter will read vblank_start-1.
12755          *
12756          * On gen2 the scanline counter starts counting from 1 instead
12757          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
12758          * to keep the value positive), instead of adding one.
12759          *
12760          * On HSW+ the behaviour of the scanline counter depends on the output
12761          * type. For DP ports it behaves like most other platforms, but on HDMI
12762          * there's an extra 1 line difference. So we need to add two instead of
12763          * one to the value.
12764          */
12765         if (IS_GEN2(dev)) {
12766                 const struct drm_display_mode *mode = &crtc->config->base.adjusted_mode;
12767                 int vtotal;
12768
12769                 vtotal = mode->crtc_vtotal;
12770                 if (mode->flags & DRM_MODE_FLAG_INTERLACE)
12771                         vtotal /= 2;
12772
12773                 crtc->scanline_offset = vtotal - 1;
12774         } else if (HAS_DDI(dev) &&
12775                    intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI)) {
12776                 crtc->scanline_offset = 2;
12777         } else
12778                 crtc->scanline_offset = 1;
12779 }
12780
12781 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
12782 {
12783         struct drm_device *dev = state->dev;
12784         struct drm_i915_private *dev_priv = to_i915(dev);
12785         struct intel_shared_dpll_config *shared_dpll = NULL;
12786         struct intel_crtc *intel_crtc;
12787         struct intel_crtc_state *intel_crtc_state;
12788         struct drm_crtc *crtc;
12789         struct drm_crtc_state *crtc_state;
12790         int i;
12791
12792         if (!dev_priv->display.crtc_compute_clock)
12793                 return;
12794
12795         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12796                 int dpll;
12797
12798                 intel_crtc = to_intel_crtc(crtc);
12799                 intel_crtc_state = to_intel_crtc_state(crtc_state);
12800                 dpll = intel_crtc_state->shared_dpll;
12801
12802                 if (!needs_modeset(crtc_state) || dpll == DPLL_ID_PRIVATE)
12803                         continue;
12804
12805                 intel_crtc_state->shared_dpll = DPLL_ID_PRIVATE;
12806
12807                 if (!shared_dpll)
12808                         shared_dpll = intel_atomic_get_shared_dpll_state(state);
12809
12810                 shared_dpll[dpll].crtc_mask &= ~(1 << intel_crtc->pipe);
12811         }
12812 }
12813
12814 /*
12815  * This implements the workaround described in the "notes" section of the mode
12816  * set sequence documentation. When going from no pipes or single pipe to
12817  * multiple pipes, and planes are enabled after the pipe, we need to wait at
12818  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
12819  */
12820 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
12821 {
12822         struct drm_crtc_state *crtc_state;
12823         struct intel_crtc *intel_crtc;
12824         struct drm_crtc *crtc;
12825         struct intel_crtc_state *first_crtc_state = NULL;
12826         struct intel_crtc_state *other_crtc_state = NULL;
12827         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
12828         int i;
12829
12830         /* look at all crtc's that are going to be enabled in during modeset */
12831         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12832                 intel_crtc = to_intel_crtc(crtc);
12833
12834                 if (!crtc_state->active || !needs_modeset(crtc_state))
12835                         continue;
12836
12837                 if (first_crtc_state) {
12838                         other_crtc_state = to_intel_crtc_state(crtc_state);
12839                         break;
12840                 } else {
12841                         first_crtc_state = to_intel_crtc_state(crtc_state);
12842                         first_pipe = intel_crtc->pipe;
12843                 }
12844         }
12845
12846         /* No workaround needed? */
12847         if (!first_crtc_state)
12848                 return 0;
12849
12850         /* w/a possibly needed, check how many crtc's are already enabled. */
12851         for_each_intel_crtc(state->dev, intel_crtc) {
12852                 struct intel_crtc_state *pipe_config;
12853
12854                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
12855                 if (IS_ERR(pipe_config))
12856                         return PTR_ERR(pipe_config);
12857
12858                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
12859
12860                 if (!pipe_config->base.active ||
12861                     needs_modeset(&pipe_config->base))
12862                         continue;
12863
12864                 /* 2 or more enabled crtcs means no need for w/a */
12865                 if (enabled_pipe != INVALID_PIPE)
12866                         return 0;
12867
12868                 enabled_pipe = intel_crtc->pipe;
12869         }
12870
12871         if (enabled_pipe != INVALID_PIPE)
12872                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
12873         else if (other_crtc_state)
12874                 other_crtc_state->hsw_workaround_pipe = first_pipe;
12875
12876         return 0;
12877 }
12878
12879 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
12880 {
12881         struct drm_crtc *crtc;
12882         struct drm_crtc_state *crtc_state;
12883         int ret = 0;
12884
12885         /* add all active pipes to the state */
12886         for_each_crtc(state->dev, crtc) {
12887                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
12888                 if (IS_ERR(crtc_state))
12889                         return PTR_ERR(crtc_state);
12890
12891                 if (!crtc_state->active || needs_modeset(crtc_state))
12892                         continue;
12893
12894                 crtc_state->mode_changed = true;
12895
12896                 ret = drm_atomic_add_affected_connectors(state, crtc);
12897                 if (ret)
12898                         break;
12899
12900                 ret = drm_atomic_add_affected_planes(state, crtc);
12901                 if (ret)
12902                         break;
12903         }
12904
12905         return ret;
12906 }
12907
12908
12909 static int intel_modeset_checks(struct drm_atomic_state *state)
12910 {
12911         struct drm_device *dev = state->dev;
12912         struct drm_i915_private *dev_priv = dev->dev_private;
12913         int ret;
12914
12915         if (!check_digital_port_conflicts(state)) {
12916                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
12917                 return -EINVAL;
12918         }
12919
12920         /*
12921          * See if the config requires any additional preparation, e.g.
12922          * to adjust global state with pipes off.  We need to do this
12923          * here so we can get the modeset_pipe updated config for the new
12924          * mode set on this crtc.  For other crtcs we need to use the
12925          * adjusted_mode bits in the crtc directly.
12926          */
12927         if (dev_priv->display.modeset_calc_cdclk) {
12928                 unsigned int cdclk;
12929
12930                 ret = dev_priv->display.modeset_calc_cdclk(state);
12931
12932                 cdclk = to_intel_atomic_state(state)->cdclk;
12933                 if (!ret && cdclk != dev_priv->cdclk_freq)
12934                         ret = intel_modeset_all_pipes(state);
12935
12936                 if (ret < 0)
12937                         return ret;
12938         } else
12939                 to_intel_atomic_state(state)->cdclk = dev_priv->cdclk_freq;
12940
12941         intel_modeset_clear_plls(state);
12942
12943         if (IS_HASWELL(dev))
12944                 return haswell_mode_set_planes_workaround(state);
12945
12946         return 0;
12947 }
12948
12949 /**
12950  * intel_atomic_check - validate state object
12951  * @dev: drm device
12952  * @state: state to validate
12953  */
12954 static int intel_atomic_check(struct drm_device *dev,
12955                               struct drm_atomic_state *state)
12956 {
12957         struct drm_crtc *crtc;
12958         struct drm_crtc_state *crtc_state;
12959         int ret, i;
12960         bool any_ms = false;
12961
12962         ret = drm_atomic_helper_check_modeset(dev, state);
12963         if (ret)
12964                 return ret;
12965
12966         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12967                 struct intel_crtc_state *pipe_config =
12968                         to_intel_crtc_state(crtc_state);
12969
12970                 /* Catch I915_MODE_FLAG_INHERITED */
12971                 if (crtc_state->mode.private_flags != crtc->state->mode.private_flags)
12972                         crtc_state->mode_changed = true;
12973
12974                 if (!crtc_state->enable) {
12975                         if (needs_modeset(crtc_state))
12976                                 any_ms = true;
12977                         continue;
12978                 }
12979
12980                 if (!needs_modeset(crtc_state))
12981                         continue;
12982
12983                 /* FIXME: For only active_changed we shouldn't need to do any
12984                  * state recomputation at all. */
12985
12986                 ret = drm_atomic_add_affected_connectors(state, crtc);
12987                 if (ret)
12988                         return ret;
12989
12990                 ret = intel_modeset_pipe_config(crtc, pipe_config);
12991                 if (ret)
12992                         return ret;
12993
12994                 if (i915.fastboot &&
12995                     intel_pipe_config_compare(state->dev,
12996                                         to_intel_crtc_state(crtc->state),
12997                                         pipe_config, true)) {
12998                         crtc_state->mode_changed = false;
12999                 }
13000
13001                 if (needs_modeset(crtc_state)) {
13002                         any_ms = true;
13003
13004                         ret = drm_atomic_add_affected_planes(state, crtc);
13005                         if (ret)
13006                                 return ret;
13007                 }
13008
13009                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
13010                                        needs_modeset(crtc_state) ?
13011                                        "[modeset]" : "[fastset]");
13012         }
13013
13014         if (any_ms) {
13015                 ret = intel_modeset_checks(state);
13016
13017                 if (ret)
13018                         return ret;
13019         } else
13020                 to_intel_atomic_state(state)->cdclk =
13021                         to_i915(state->dev)->cdclk_freq;
13022
13023         return drm_atomic_helper_check_planes(state->dev, state);
13024 }
13025
13026 /**
13027  * intel_atomic_commit - commit validated state object
13028  * @dev: DRM device
13029  * @state: the top-level driver state object
13030  * @async: asynchronous commit
13031  *
13032  * This function commits a top-level state object that has been validated
13033  * with drm_atomic_helper_check().
13034  *
13035  * FIXME:  Atomic modeset support for i915 is not yet complete.  At the moment
13036  * we can only handle plane-related operations and do not yet support
13037  * asynchronous commit.
13038  *
13039  * RETURNS
13040  * Zero for success or -errno.
13041  */
13042 static int intel_atomic_commit(struct drm_device *dev,
13043                                struct drm_atomic_state *state,
13044                                bool async)
13045 {
13046         struct drm_i915_private *dev_priv = dev->dev_private;
13047         struct drm_crtc *crtc;
13048         struct drm_crtc_state *crtc_state;
13049         int ret = 0;
13050         int i;
13051         bool any_ms = false;
13052
13053         if (async) {
13054                 DRM_DEBUG_KMS("i915 does not yet support async commit\n");
13055                 return -EINVAL;
13056         }
13057
13058         ret = drm_atomic_helper_prepare_planes(dev, state);
13059         if (ret)
13060                 return ret;
13061
13062         drm_atomic_helper_swap_state(dev, state);
13063
13064         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13065                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13066
13067                 if (!needs_modeset(crtc->state))
13068                         continue;
13069
13070                 any_ms = true;
13071                 intel_pre_plane_update(intel_crtc);
13072
13073                 if (crtc_state->active) {
13074                         intel_crtc_disable_planes(crtc, crtc_state->plane_mask);
13075                         dev_priv->display.crtc_disable(crtc);
13076                         intel_crtc->active = false;
13077                         intel_disable_shared_dpll(intel_crtc);
13078                 }
13079         }
13080
13081         /* Only after disabling all output pipelines that will be changed can we
13082          * update the the output configuration. */
13083         intel_modeset_update_crtc_state(state);
13084
13085         if (any_ms) {
13086                 intel_shared_dpll_commit(state);
13087
13088                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
13089                 modeset_update_crtc_power_domains(state);
13090         }
13091
13092         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
13093         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13094                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13095                 bool modeset = needs_modeset(crtc->state);
13096
13097                 if (modeset && crtc->state->active) {
13098                         update_scanline_offset(to_intel_crtc(crtc));
13099                         dev_priv->display.crtc_enable(crtc);
13100                 }
13101
13102                 if (!modeset)
13103                         intel_pre_plane_update(intel_crtc);
13104
13105                 drm_atomic_helper_commit_planes_on_crtc(crtc_state);
13106                 intel_post_plane_update(intel_crtc);
13107         }
13108
13109         /* FIXME: add subpixel order */
13110
13111         drm_atomic_helper_wait_for_vblanks(dev, state);
13112         drm_atomic_helper_cleanup_planes(dev, state);
13113
13114         if (any_ms)
13115                 intel_modeset_check_state(dev, state);
13116
13117         drm_atomic_state_free(state);
13118
13119         return 0;
13120 }
13121
13122 void intel_crtc_restore_mode(struct drm_crtc *crtc)
13123 {
13124         struct drm_device *dev = crtc->dev;
13125         struct drm_atomic_state *state;
13126         struct drm_crtc_state *crtc_state;
13127         int ret;
13128
13129         state = drm_atomic_state_alloc(dev);
13130         if (!state) {
13131                 DRM_DEBUG_KMS("[CRTC:%d] crtc restore failed, out of memory",
13132                               crtc->base.id);
13133                 return;
13134         }
13135
13136         state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
13137
13138 retry:
13139         crtc_state = drm_atomic_get_crtc_state(state, crtc);
13140         ret = PTR_ERR_OR_ZERO(crtc_state);
13141         if (!ret) {
13142                 if (!crtc_state->active)
13143                         goto out;
13144
13145                 crtc_state->mode_changed = true;
13146                 ret = drm_atomic_commit(state);
13147         }
13148
13149         if (ret == -EDEADLK) {
13150                 drm_atomic_state_clear(state);
13151                 drm_modeset_backoff(state->acquire_ctx);
13152                 goto retry;
13153         }
13154
13155         if (ret)
13156 out:
13157                 drm_atomic_state_free(state);
13158 }
13159
13160 #undef for_each_intel_crtc_masked
13161
13162 static const struct drm_crtc_funcs intel_crtc_funcs = {
13163         .gamma_set = intel_crtc_gamma_set,
13164         .set_config = drm_atomic_helper_set_config,
13165         .destroy = intel_crtc_destroy,
13166         .page_flip = intel_crtc_page_flip,
13167         .atomic_duplicate_state = intel_crtc_duplicate_state,
13168         .atomic_destroy_state = intel_crtc_destroy_state,
13169 };
13170
13171 static bool ibx_pch_dpll_get_hw_state(struct drm_i915_private *dev_priv,
13172                                       struct intel_shared_dpll *pll,
13173                                       struct intel_dpll_hw_state *hw_state)
13174 {
13175         uint32_t val;
13176
13177         if (!intel_display_power_is_enabled(dev_priv, POWER_DOMAIN_PLLS))
13178                 return false;
13179
13180         val = I915_READ(PCH_DPLL(pll->id));
13181         hw_state->dpll = val;
13182         hw_state->fp0 = I915_READ(PCH_FP0(pll->id));
13183         hw_state->fp1 = I915_READ(PCH_FP1(pll->id));
13184
13185         return val & DPLL_VCO_ENABLE;
13186 }
13187
13188 static void ibx_pch_dpll_mode_set(struct drm_i915_private *dev_priv,
13189                                   struct intel_shared_dpll *pll)
13190 {
13191         I915_WRITE(PCH_FP0(pll->id), pll->config.hw_state.fp0);
13192         I915_WRITE(PCH_FP1(pll->id), pll->config.hw_state.fp1);
13193 }
13194
13195 static void ibx_pch_dpll_enable(struct drm_i915_private *dev_priv,
13196                                 struct intel_shared_dpll *pll)
13197 {
13198         /* PCH refclock must be enabled first */
13199         ibx_assert_pch_refclk_enabled(dev_priv);
13200
13201         I915_WRITE(PCH_DPLL(pll->id), pll->config.hw_state.dpll);
13202
13203         /* Wait for the clocks to stabilize. */
13204         POSTING_READ(PCH_DPLL(pll->id));
13205         udelay(150);
13206
13207         /* The pixel multiplier can only be updated once the
13208          * DPLL is enabled and the clocks are stable.
13209          *
13210          * So write it again.
13211          */
13212         I915_WRITE(PCH_DPLL(pll->id), pll->config.hw_state.dpll);
13213         POSTING_READ(PCH_DPLL(pll->id));
13214         udelay(200);
13215 }
13216
13217 static void ibx_pch_dpll_disable(struct drm_i915_private *dev_priv,
13218                                  struct intel_shared_dpll *pll)
13219 {
13220         struct drm_device *dev = dev_priv->dev;
13221         struct intel_crtc *crtc;
13222
13223         /* Make sure no transcoder isn't still depending on us. */
13224         for_each_intel_crtc(dev, crtc) {
13225                 if (intel_crtc_to_shared_dpll(crtc) == pll)
13226                         assert_pch_transcoder_disabled(dev_priv, crtc->pipe);
13227         }
13228
13229         I915_WRITE(PCH_DPLL(pll->id), 0);
13230         POSTING_READ(PCH_DPLL(pll->id));
13231         udelay(200);
13232 }
13233
13234 static char *ibx_pch_dpll_names[] = {
13235         "PCH DPLL A",
13236         "PCH DPLL B",
13237 };
13238
13239 static void ibx_pch_dpll_init(struct drm_device *dev)
13240 {
13241         struct drm_i915_private *dev_priv = dev->dev_private;
13242         int i;
13243
13244         dev_priv->num_shared_dpll = 2;
13245
13246         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
13247                 dev_priv->shared_dplls[i].id = i;
13248                 dev_priv->shared_dplls[i].name = ibx_pch_dpll_names[i];
13249                 dev_priv->shared_dplls[i].mode_set = ibx_pch_dpll_mode_set;
13250                 dev_priv->shared_dplls[i].enable = ibx_pch_dpll_enable;
13251                 dev_priv->shared_dplls[i].disable = ibx_pch_dpll_disable;
13252                 dev_priv->shared_dplls[i].get_hw_state =
13253                         ibx_pch_dpll_get_hw_state;
13254         }
13255 }
13256
13257 static void intel_shared_dpll_init(struct drm_device *dev)
13258 {
13259         struct drm_i915_private *dev_priv = dev->dev_private;
13260
13261         intel_update_cdclk(dev);
13262
13263         if (HAS_DDI(dev))
13264                 intel_ddi_pll_init(dev);
13265         else if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
13266                 ibx_pch_dpll_init(dev);
13267         else
13268                 dev_priv->num_shared_dpll = 0;
13269
13270         BUG_ON(dev_priv->num_shared_dpll > I915_NUM_PLLS);
13271 }
13272
13273 /**
13274  * intel_prepare_plane_fb - Prepare fb for usage on plane
13275  * @plane: drm plane to prepare for
13276  * @fb: framebuffer to prepare for presentation
13277  *
13278  * Prepares a framebuffer for usage on a display plane.  Generally this
13279  * involves pinning the underlying object and updating the frontbuffer tracking
13280  * bits.  Some older platforms need special physical address handling for
13281  * cursor planes.
13282  *
13283  * Returns 0 on success, negative error code on failure.
13284  */
13285 int
13286 intel_prepare_plane_fb(struct drm_plane *plane,
13287                        struct drm_framebuffer *fb,
13288                        const struct drm_plane_state *new_state)
13289 {
13290         struct drm_device *dev = plane->dev;
13291         struct intel_plane *intel_plane = to_intel_plane(plane);
13292         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13293         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->fb);
13294         int ret = 0;
13295
13296         if (!obj)
13297                 return 0;
13298
13299         mutex_lock(&dev->struct_mutex);
13300
13301         if (plane->type == DRM_PLANE_TYPE_CURSOR &&
13302             INTEL_INFO(dev)->cursor_needs_physical) {
13303                 int align = IS_I830(dev) ? 16 * 1024 : 256;
13304                 ret = i915_gem_object_attach_phys(obj, align);
13305                 if (ret)
13306                         DRM_DEBUG_KMS("failed to attach phys object\n");
13307         } else {
13308                 ret = intel_pin_and_fence_fb_obj(plane, fb, new_state, NULL, NULL);
13309         }
13310
13311         if (ret == 0)
13312                 i915_gem_track_fb(old_obj, obj, intel_plane->frontbuffer_bit);
13313
13314         mutex_unlock(&dev->struct_mutex);
13315
13316         return ret;
13317 }
13318
13319 /**
13320  * intel_cleanup_plane_fb - Cleans up an fb after plane use
13321  * @plane: drm plane to clean up for
13322  * @fb: old framebuffer that was on plane
13323  *
13324  * Cleans up a framebuffer that has just been removed from a plane.
13325  */
13326 void
13327 intel_cleanup_plane_fb(struct drm_plane *plane,
13328                        struct drm_framebuffer *fb,
13329                        const struct drm_plane_state *old_state)
13330 {
13331         struct drm_device *dev = plane->dev;
13332         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13333
13334         if (WARN_ON(!obj))
13335                 return;
13336
13337         if (plane->type != DRM_PLANE_TYPE_CURSOR ||
13338             !INTEL_INFO(dev)->cursor_needs_physical) {
13339                 mutex_lock(&dev->struct_mutex);
13340                 intel_unpin_fb_obj(fb, old_state);
13341                 mutex_unlock(&dev->struct_mutex);
13342         }
13343 }
13344
13345 int
13346 skl_max_scale(struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state)
13347 {
13348         int max_scale;
13349         struct drm_device *dev;
13350         struct drm_i915_private *dev_priv;
13351         int crtc_clock, cdclk;
13352
13353         if (!intel_crtc || !crtc_state)
13354                 return DRM_PLANE_HELPER_NO_SCALING;
13355
13356         dev = intel_crtc->base.dev;
13357         dev_priv = dev->dev_private;
13358         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
13359         cdclk = to_intel_atomic_state(crtc_state->base.state)->cdclk;
13360
13361         if (!crtc_clock || !cdclk)
13362                 return DRM_PLANE_HELPER_NO_SCALING;
13363
13364         /*
13365          * skl max scale is lower of:
13366          *    close to 3 but not 3, -1 is for that purpose
13367          *            or
13368          *    cdclk/crtc_clock
13369          */
13370         max_scale = min((1 << 16) * 3 - 1, (1 << 8) * ((cdclk << 8) / crtc_clock));
13371
13372         return max_scale;
13373 }
13374
13375 static int
13376 intel_check_primary_plane(struct drm_plane *plane,
13377                           struct intel_crtc_state *crtc_state,
13378                           struct intel_plane_state *state)
13379 {
13380         struct drm_crtc *crtc = state->base.crtc;
13381         struct drm_framebuffer *fb = state->base.fb;
13382         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
13383         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
13384         bool can_position = false;
13385
13386         /* use scaler when colorkey is not required */
13387         if (INTEL_INFO(plane->dev)->gen >= 9 &&
13388             state->ckey.flags == I915_SET_COLORKEY_NONE) {
13389                 min_scale = 1;
13390                 max_scale = skl_max_scale(to_intel_crtc(crtc), crtc_state);
13391                 can_position = true;
13392         }
13393
13394         return drm_plane_helper_check_update(plane, crtc, fb, &state->src,
13395                                              &state->dst, &state->clip,
13396                                              min_scale, max_scale,
13397                                              can_position, true,
13398                                              &state->visible);
13399 }
13400
13401 static void
13402 intel_commit_primary_plane(struct drm_plane *plane,
13403                            struct intel_plane_state *state)
13404 {
13405         struct drm_crtc *crtc = state->base.crtc;
13406         struct drm_framebuffer *fb = state->base.fb;
13407         struct drm_device *dev = plane->dev;
13408         struct drm_i915_private *dev_priv = dev->dev_private;
13409         struct intel_crtc *intel_crtc;
13410         struct drm_rect *src = &state->src;
13411
13412         crtc = crtc ? crtc : plane->crtc;
13413         intel_crtc = to_intel_crtc(crtc);
13414
13415         plane->fb = fb;
13416         crtc->x = src->x1 >> 16;
13417         crtc->y = src->y1 >> 16;
13418
13419         if (!crtc->state->active)
13420                 return;
13421
13422         if (state->visible)
13423                 /* FIXME: kill this fastboot hack */
13424                 intel_update_pipe_size(intel_crtc);
13425
13426         dev_priv->display.update_primary_plane(crtc, fb, crtc->x, crtc->y);
13427 }
13428
13429 static void
13430 intel_disable_primary_plane(struct drm_plane *plane,
13431                             struct drm_crtc *crtc)
13432 {
13433         struct drm_device *dev = plane->dev;
13434         struct drm_i915_private *dev_priv = dev->dev_private;
13435
13436         dev_priv->display.update_primary_plane(crtc, NULL, 0, 0);
13437 }
13438
13439 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
13440                                     struct drm_crtc_state *old_crtc_state)
13441 {
13442         struct drm_device *dev = crtc->dev;
13443         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13444
13445         if (intel_crtc->atomic.update_wm_pre)
13446                 intel_update_watermarks(crtc);
13447
13448         /* Perform vblank evasion around commit operation */
13449         if (crtc->state->active)
13450                 intel_pipe_update_start(intel_crtc, &intel_crtc->start_vbl_count);
13451
13452         if (!needs_modeset(crtc->state) && INTEL_INFO(dev)->gen >= 9)
13453                 skl_detach_scalers(intel_crtc);
13454 }
13455
13456 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
13457                                      struct drm_crtc_state *old_crtc_state)
13458 {
13459         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13460
13461         if (crtc->state->active)
13462                 intel_pipe_update_end(intel_crtc, intel_crtc->start_vbl_count);
13463 }
13464
13465 /**
13466  * intel_plane_destroy - destroy a plane
13467  * @plane: plane to destroy
13468  *
13469  * Common destruction function for all types of planes (primary, cursor,
13470  * sprite).
13471  */
13472 void intel_plane_destroy(struct drm_plane *plane)
13473 {
13474         struct intel_plane *intel_plane = to_intel_plane(plane);
13475         drm_plane_cleanup(plane);
13476         kfree(intel_plane);
13477 }
13478
13479 const struct drm_plane_funcs intel_plane_funcs = {
13480         .update_plane = drm_atomic_helper_update_plane,
13481         .disable_plane = drm_atomic_helper_disable_plane,
13482         .destroy = intel_plane_destroy,
13483         .set_property = drm_atomic_helper_plane_set_property,
13484         .atomic_get_property = intel_plane_atomic_get_property,
13485         .atomic_set_property = intel_plane_atomic_set_property,
13486         .atomic_duplicate_state = intel_plane_duplicate_state,
13487         .atomic_destroy_state = intel_plane_destroy_state,
13488
13489 };
13490
13491 static struct drm_plane *intel_primary_plane_create(struct drm_device *dev,
13492                                                     int pipe)
13493 {
13494         struct intel_plane *primary;
13495         struct intel_plane_state *state;
13496         const uint32_t *intel_primary_formats;
13497         int num_formats;
13498
13499         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
13500         if (primary == NULL)
13501                 return NULL;
13502
13503         state = intel_create_plane_state(&primary->base);
13504         if (!state) {
13505                 kfree(primary);
13506                 return NULL;
13507         }
13508         primary->base.state = &state->base;
13509
13510         primary->can_scale = false;
13511         primary->max_downscale = 1;
13512         if (INTEL_INFO(dev)->gen >= 9) {
13513                 primary->can_scale = true;
13514                 state->scaler_id = -1;
13515         }
13516         primary->pipe = pipe;
13517         primary->plane = pipe;
13518         primary->frontbuffer_bit = INTEL_FRONTBUFFER_PRIMARY(pipe);
13519         primary->check_plane = intel_check_primary_plane;
13520         primary->commit_plane = intel_commit_primary_plane;
13521         primary->disable_plane = intel_disable_primary_plane;
13522         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4)
13523                 primary->plane = !pipe;
13524
13525         if (INTEL_INFO(dev)->gen >= 9) {
13526                 intel_primary_formats = skl_primary_formats;
13527                 num_formats = ARRAY_SIZE(skl_primary_formats);
13528         } else if (INTEL_INFO(dev)->gen >= 4) {
13529                 intel_primary_formats = i965_primary_formats;
13530                 num_formats = ARRAY_SIZE(i965_primary_formats);
13531         } else {
13532                 intel_primary_formats = i8xx_primary_formats;
13533                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
13534         }
13535
13536         drm_universal_plane_init(dev, &primary->base, 0,
13537                                  &intel_plane_funcs,
13538                                  intel_primary_formats, num_formats,
13539                                  DRM_PLANE_TYPE_PRIMARY);
13540
13541         if (INTEL_INFO(dev)->gen >= 4)
13542                 intel_create_rotation_property(dev, primary);
13543
13544         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
13545
13546         return &primary->base;
13547 }
13548
13549 void intel_create_rotation_property(struct drm_device *dev, struct intel_plane *plane)
13550 {
13551         if (!dev->mode_config.rotation_property) {
13552                 unsigned long flags = BIT(DRM_ROTATE_0) |
13553                         BIT(DRM_ROTATE_180);
13554
13555                 if (INTEL_INFO(dev)->gen >= 9)
13556                         flags |= BIT(DRM_ROTATE_90) | BIT(DRM_ROTATE_270);
13557
13558                 dev->mode_config.rotation_property =
13559                         drm_mode_create_rotation_property(dev, flags);
13560         }
13561         if (dev->mode_config.rotation_property)
13562                 drm_object_attach_property(&plane->base.base,
13563                                 dev->mode_config.rotation_property,
13564                                 plane->base.state->rotation);
13565 }
13566
13567 static int
13568 intel_check_cursor_plane(struct drm_plane *plane,
13569                          struct intel_crtc_state *crtc_state,
13570                          struct intel_plane_state *state)
13571 {
13572         struct drm_crtc *crtc = crtc_state->base.crtc;
13573         struct drm_framebuffer *fb = state->base.fb;
13574         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13575         unsigned stride;
13576         int ret;
13577
13578         ret = drm_plane_helper_check_update(plane, crtc, fb, &state->src,
13579                                             &state->dst, &state->clip,
13580                                             DRM_PLANE_HELPER_NO_SCALING,
13581                                             DRM_PLANE_HELPER_NO_SCALING,
13582                                             true, true, &state->visible);
13583         if (ret)
13584                 return ret;
13585
13586         /* if we want to turn off the cursor ignore width and height */
13587         if (!obj)
13588                 return 0;
13589
13590         /* Check for which cursor types we support */
13591         if (!cursor_size_ok(plane->dev, state->base.crtc_w, state->base.crtc_h)) {
13592                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
13593                           state->base.crtc_w, state->base.crtc_h);
13594                 return -EINVAL;
13595         }
13596
13597         stride = roundup_pow_of_two(state->base.crtc_w) * 4;
13598         if (obj->base.size < stride * state->base.crtc_h) {
13599                 DRM_DEBUG_KMS("buffer is too small\n");
13600                 return -ENOMEM;
13601         }
13602
13603         if (fb->modifier[0] != DRM_FORMAT_MOD_NONE) {
13604                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
13605                 return -EINVAL;
13606         }
13607
13608         return 0;
13609 }
13610
13611 static void
13612 intel_disable_cursor_plane(struct drm_plane *plane,
13613                            struct drm_crtc *crtc)
13614 {
13615         intel_crtc_update_cursor(crtc, false);
13616 }
13617
13618 static void
13619 intel_commit_cursor_plane(struct drm_plane *plane,
13620                           struct intel_plane_state *state)
13621 {
13622         struct drm_crtc *crtc = state->base.crtc;
13623         struct drm_device *dev = plane->dev;
13624         struct intel_crtc *intel_crtc;
13625         struct drm_i915_gem_object *obj = intel_fb_obj(state->base.fb);
13626         uint32_t addr;
13627
13628         crtc = crtc ? crtc : plane->crtc;
13629         intel_crtc = to_intel_crtc(crtc);
13630
13631         plane->fb = state->base.fb;
13632         crtc->cursor_x = state->base.crtc_x;
13633         crtc->cursor_y = state->base.crtc_y;
13634
13635         if (intel_crtc->cursor_bo == obj)
13636                 goto update;
13637
13638         if (!obj)
13639                 addr = 0;
13640         else if (!INTEL_INFO(dev)->cursor_needs_physical)
13641                 addr = i915_gem_obj_ggtt_offset(obj);
13642         else
13643                 addr = obj->phys_handle->busaddr;
13644
13645         intel_crtc->cursor_addr = addr;
13646         intel_crtc->cursor_bo = obj;
13647
13648 update:
13649         if (crtc->state->active)
13650                 intel_crtc_update_cursor(crtc, state->visible);
13651 }
13652
13653 static struct drm_plane *intel_cursor_plane_create(struct drm_device *dev,
13654                                                    int pipe)
13655 {
13656         struct intel_plane *cursor;
13657         struct intel_plane_state *state;
13658
13659         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
13660         if (cursor == NULL)
13661                 return NULL;
13662
13663         state = intel_create_plane_state(&cursor->base);
13664         if (!state) {
13665                 kfree(cursor);
13666                 return NULL;
13667         }
13668         cursor->base.state = &state->base;
13669
13670         cursor->can_scale = false;
13671         cursor->max_downscale = 1;
13672         cursor->pipe = pipe;
13673         cursor->plane = pipe;
13674         cursor->frontbuffer_bit = INTEL_FRONTBUFFER_CURSOR(pipe);
13675         cursor->check_plane = intel_check_cursor_plane;
13676         cursor->commit_plane = intel_commit_cursor_plane;
13677         cursor->disable_plane = intel_disable_cursor_plane;
13678
13679         drm_universal_plane_init(dev, &cursor->base, 0,
13680                                  &intel_plane_funcs,
13681                                  intel_cursor_formats,
13682                                  ARRAY_SIZE(intel_cursor_formats),
13683                                  DRM_PLANE_TYPE_CURSOR);
13684
13685         if (INTEL_INFO(dev)->gen >= 4) {
13686                 if (!dev->mode_config.rotation_property)
13687                         dev->mode_config.rotation_property =
13688                                 drm_mode_create_rotation_property(dev,
13689                                                         BIT(DRM_ROTATE_0) |
13690                                                         BIT(DRM_ROTATE_180));
13691                 if (dev->mode_config.rotation_property)
13692                         drm_object_attach_property(&cursor->base.base,
13693                                 dev->mode_config.rotation_property,
13694                                 state->base.rotation);
13695         }
13696
13697         if (INTEL_INFO(dev)->gen >=9)
13698                 state->scaler_id = -1;
13699
13700         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
13701
13702         return &cursor->base;
13703 }
13704
13705 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
13706         struct intel_crtc_state *crtc_state)
13707 {
13708         int i;
13709         struct intel_scaler *intel_scaler;
13710         struct intel_crtc_scaler_state *scaler_state = &crtc_state->scaler_state;
13711
13712         for (i = 0; i < intel_crtc->num_scalers; i++) {
13713                 intel_scaler = &scaler_state->scalers[i];
13714                 intel_scaler->in_use = 0;
13715                 intel_scaler->mode = PS_SCALER_MODE_DYN;
13716         }
13717
13718         scaler_state->scaler_id = -1;
13719 }
13720
13721 static void intel_crtc_init(struct drm_device *dev, int pipe)
13722 {
13723         struct drm_i915_private *dev_priv = dev->dev_private;
13724         struct intel_crtc *intel_crtc;
13725         struct intel_crtc_state *crtc_state = NULL;
13726         struct drm_plane *primary = NULL;
13727         struct drm_plane *cursor = NULL;
13728         int i, ret;
13729
13730         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
13731         if (intel_crtc == NULL)
13732                 return;
13733
13734         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
13735         if (!crtc_state)
13736                 goto fail;
13737         intel_crtc->config = crtc_state;
13738         intel_crtc->base.state = &crtc_state->base;
13739         crtc_state->base.crtc = &intel_crtc->base;
13740
13741         /* initialize shared scalers */
13742         if (INTEL_INFO(dev)->gen >= 9) {
13743                 if (pipe == PIPE_C)
13744                         intel_crtc->num_scalers = 1;
13745                 else
13746                         intel_crtc->num_scalers = SKL_NUM_SCALERS;
13747
13748                 skl_init_scalers(dev, intel_crtc, crtc_state);
13749         }
13750
13751         primary = intel_primary_plane_create(dev, pipe);
13752         if (!primary)
13753                 goto fail;
13754
13755         cursor = intel_cursor_plane_create(dev, pipe);
13756         if (!cursor)
13757                 goto fail;
13758
13759         ret = drm_crtc_init_with_planes(dev, &intel_crtc->base, primary,
13760                                         cursor, &intel_crtc_funcs);
13761         if (ret)
13762                 goto fail;
13763
13764         drm_mode_crtc_set_gamma_size(&intel_crtc->base, 256);
13765         for (i = 0; i < 256; i++) {
13766                 intel_crtc->lut_r[i] = i;
13767                 intel_crtc->lut_g[i] = i;
13768                 intel_crtc->lut_b[i] = i;
13769         }
13770
13771         /*
13772          * On gen2/3 only plane A can do fbc, but the panel fitter and lvds port
13773          * is hooked to pipe B. Hence we want plane A feeding pipe B.
13774          */
13775         intel_crtc->pipe = pipe;
13776         intel_crtc->plane = pipe;
13777         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4) {
13778                 DRM_DEBUG_KMS("swapping pipes & planes for FBC\n");
13779                 intel_crtc->plane = !pipe;
13780         }
13781
13782         intel_crtc->cursor_base = ~0;
13783         intel_crtc->cursor_cntl = ~0;
13784         intel_crtc->cursor_size = ~0;
13785
13786         intel_crtc->wm.cxsr_allowed = true;
13787
13788         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
13789                dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
13790         dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = &intel_crtc->base;
13791         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = &intel_crtc->base;
13792
13793         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
13794
13795         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
13796         return;
13797
13798 fail:
13799         if (primary)
13800                 drm_plane_cleanup(primary);
13801         if (cursor)
13802                 drm_plane_cleanup(cursor);
13803         kfree(crtc_state);
13804         kfree(intel_crtc);
13805 }
13806
13807 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
13808 {
13809         struct drm_encoder *encoder = connector->base.encoder;
13810         struct drm_device *dev = connector->base.dev;
13811
13812         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
13813
13814         if (!encoder || WARN_ON(!encoder->crtc))
13815                 return INVALID_PIPE;
13816
13817         return to_intel_crtc(encoder->crtc)->pipe;
13818 }
13819
13820 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
13821                                 struct drm_file *file)
13822 {
13823         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
13824         struct drm_crtc *drmmode_crtc;
13825         struct intel_crtc *crtc;
13826
13827         drmmode_crtc = drm_crtc_find(dev, pipe_from_crtc_id->crtc_id);
13828
13829         if (!drmmode_crtc) {
13830                 DRM_ERROR("no such CRTC id\n");
13831                 return -ENOENT;
13832         }
13833
13834         crtc = to_intel_crtc(drmmode_crtc);
13835         pipe_from_crtc_id->pipe = crtc->pipe;
13836
13837         return 0;
13838 }
13839
13840 static int intel_encoder_clones(struct intel_encoder *encoder)
13841 {
13842         struct drm_device *dev = encoder->base.dev;
13843         struct intel_encoder *source_encoder;
13844         int index_mask = 0;
13845         int entry = 0;
13846
13847         for_each_intel_encoder(dev, source_encoder) {
13848                 if (encoders_cloneable(encoder, source_encoder))
13849                         index_mask |= (1 << entry);
13850
13851                 entry++;
13852         }
13853
13854         return index_mask;
13855 }
13856
13857 static bool has_edp_a(struct drm_device *dev)
13858 {
13859         struct drm_i915_private *dev_priv = dev->dev_private;
13860
13861         if (!IS_MOBILE(dev))
13862                 return false;
13863
13864         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
13865                 return false;
13866
13867         if (IS_GEN5(dev) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
13868                 return false;
13869
13870         return true;
13871 }
13872
13873 static bool intel_crt_present(struct drm_device *dev)
13874 {
13875         struct drm_i915_private *dev_priv = dev->dev_private;
13876
13877         if (INTEL_INFO(dev)->gen >= 9)
13878                 return false;
13879
13880         if (IS_HSW_ULT(dev) || IS_BDW_ULT(dev))
13881                 return false;
13882
13883         if (IS_CHERRYVIEW(dev))
13884                 return false;
13885
13886         if (IS_VALLEYVIEW(dev) && !dev_priv->vbt.int_crt_support)
13887                 return false;
13888
13889         return true;
13890 }
13891
13892 static void intel_setup_outputs(struct drm_device *dev)
13893 {
13894         struct drm_i915_private *dev_priv = dev->dev_private;
13895         struct intel_encoder *encoder;
13896         bool dpd_is_edp = false;
13897
13898         intel_lvds_init(dev);
13899
13900         if (intel_crt_present(dev))
13901                 intel_crt_init(dev);
13902
13903         if (IS_BROXTON(dev)) {
13904                 /*
13905                  * FIXME: Broxton doesn't support port detection via the
13906                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
13907                  * detect the ports.
13908                  */
13909                 intel_ddi_init(dev, PORT_A);
13910                 intel_ddi_init(dev, PORT_B);
13911                 intel_ddi_init(dev, PORT_C);
13912         } else if (HAS_DDI(dev)) {
13913                 int found;
13914
13915                 /*
13916                  * Haswell uses DDI functions to detect digital outputs.
13917                  * On SKL pre-D0 the strap isn't connected, so we assume
13918                  * it's there.
13919                  */
13920                 found = I915_READ(DDI_BUF_CTL_A) & DDI_INIT_DISPLAY_DETECTED;
13921                 /* WaIgnoreDDIAStrap: skl */
13922                 if (found || IS_SKYLAKE(dev))
13923                         intel_ddi_init(dev, PORT_A);
13924
13925                 /* DDI B, C and D detection is indicated by the SFUSE_STRAP
13926                  * register */
13927                 found = I915_READ(SFUSE_STRAP);
13928
13929                 if (found & SFUSE_STRAP_DDIB_DETECTED)
13930                         intel_ddi_init(dev, PORT_B);
13931                 if (found & SFUSE_STRAP_DDIC_DETECTED)
13932                         intel_ddi_init(dev, PORT_C);
13933                 if (found & SFUSE_STRAP_DDID_DETECTED)
13934                         intel_ddi_init(dev, PORT_D);
13935         } else if (HAS_PCH_SPLIT(dev)) {
13936                 int found;
13937                 dpd_is_edp = intel_dp_is_edp(dev, PORT_D);
13938
13939                 if (has_edp_a(dev))
13940                         intel_dp_init(dev, DP_A, PORT_A);
13941
13942                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
13943                         /* PCH SDVOB multiplex with HDMIB */
13944                         found = intel_sdvo_init(dev, PCH_SDVOB, true);
13945                         if (!found)
13946                                 intel_hdmi_init(dev, PCH_HDMIB, PORT_B);
13947                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
13948                                 intel_dp_init(dev, PCH_DP_B, PORT_B);
13949                 }
13950
13951                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
13952                         intel_hdmi_init(dev, PCH_HDMIC, PORT_C);
13953
13954                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
13955                         intel_hdmi_init(dev, PCH_HDMID, PORT_D);
13956
13957                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
13958                         intel_dp_init(dev, PCH_DP_C, PORT_C);
13959
13960                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
13961                         intel_dp_init(dev, PCH_DP_D, PORT_D);
13962         } else if (IS_VALLEYVIEW(dev)) {
13963                 /*
13964                  * The DP_DETECTED bit is the latched state of the DDC
13965                  * SDA pin at boot. However since eDP doesn't require DDC
13966                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
13967                  * eDP ports may have been muxed to an alternate function.
13968                  * Thus we can't rely on the DP_DETECTED bit alone to detect
13969                  * eDP ports. Consult the VBT as well as DP_DETECTED to
13970                  * detect eDP ports.
13971                  */
13972                 if (I915_READ(VLV_DISPLAY_BASE + GEN4_HDMIB) & SDVO_DETECTED &&
13973                     !intel_dp_is_edp(dev, PORT_B))
13974                         intel_hdmi_init(dev, VLV_DISPLAY_BASE + GEN4_HDMIB,
13975                                         PORT_B);
13976                 if (I915_READ(VLV_DISPLAY_BASE + DP_B) & DP_DETECTED ||
13977                     intel_dp_is_edp(dev, PORT_B))
13978                         intel_dp_init(dev, VLV_DISPLAY_BASE + DP_B, PORT_B);
13979
13980                 if (I915_READ(VLV_DISPLAY_BASE + GEN4_HDMIC) & SDVO_DETECTED &&
13981                     !intel_dp_is_edp(dev, PORT_C))
13982                         intel_hdmi_init(dev, VLV_DISPLAY_BASE + GEN4_HDMIC,
13983                                         PORT_C);
13984                 if (I915_READ(VLV_DISPLAY_BASE + DP_C) & DP_DETECTED ||
13985                     intel_dp_is_edp(dev, PORT_C))
13986                         intel_dp_init(dev, VLV_DISPLAY_BASE + DP_C, PORT_C);
13987
13988                 if (IS_CHERRYVIEW(dev)) {
13989                         if (I915_READ(VLV_DISPLAY_BASE + CHV_HDMID) & SDVO_DETECTED)
13990                                 intel_hdmi_init(dev, VLV_DISPLAY_BASE + CHV_HDMID,
13991                                                 PORT_D);
13992                         /* eDP not supported on port D, so don't check VBT */
13993                         if (I915_READ(VLV_DISPLAY_BASE + DP_D) & DP_DETECTED)
13994                                 intel_dp_init(dev, VLV_DISPLAY_BASE + DP_D, PORT_D);
13995                 }
13996
13997                 intel_dsi_init(dev);
13998         } else if (!IS_GEN2(dev) && !IS_PINEVIEW(dev)) {
13999                 bool found = false;
14000
14001                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14002                         DRM_DEBUG_KMS("probing SDVOB\n");
14003                         found = intel_sdvo_init(dev, GEN3_SDVOB, true);
14004                         if (!found && IS_G4X(dev)) {
14005                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
14006                                 intel_hdmi_init(dev, GEN4_HDMIB, PORT_B);
14007                         }
14008
14009                         if (!found && IS_G4X(dev))
14010                                 intel_dp_init(dev, DP_B, PORT_B);
14011                 }
14012
14013                 /* Before G4X SDVOC doesn't have its own detect register */
14014
14015                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14016                         DRM_DEBUG_KMS("probing SDVOC\n");
14017                         found = intel_sdvo_init(dev, GEN3_SDVOC, false);
14018                 }
14019
14020                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
14021
14022                         if (IS_G4X(dev)) {
14023                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
14024                                 intel_hdmi_init(dev, GEN4_HDMIC, PORT_C);
14025                         }
14026                         if (IS_G4X(dev))
14027                                 intel_dp_init(dev, DP_C, PORT_C);
14028                 }
14029
14030                 if (IS_G4X(dev) &&
14031                     (I915_READ(DP_D) & DP_DETECTED))
14032                         intel_dp_init(dev, DP_D, PORT_D);
14033         } else if (IS_GEN2(dev))
14034                 intel_dvo_init(dev);
14035
14036         if (SUPPORTS_TV(dev))
14037                 intel_tv_init(dev);
14038
14039         intel_psr_init(dev);
14040
14041         for_each_intel_encoder(dev, encoder) {
14042                 encoder->base.possible_crtcs = encoder->crtc_mask;
14043                 encoder->base.possible_clones =
14044                         intel_encoder_clones(encoder);
14045         }
14046
14047         intel_init_pch_refclk(dev);
14048
14049         drm_helper_move_panel_connectors_to_head(dev);
14050 }
14051
14052 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
14053 {
14054         struct drm_device *dev = fb->dev;
14055         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14056
14057         drm_framebuffer_cleanup(fb);
14058         mutex_lock(&dev->struct_mutex);
14059         WARN_ON(!intel_fb->obj->framebuffer_references--);
14060         drm_gem_object_unreference(&intel_fb->obj->base);
14061         mutex_unlock(&dev->struct_mutex);
14062         kfree(intel_fb);
14063 }
14064
14065 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
14066                                                 struct drm_file *file,
14067                                                 unsigned int *handle)
14068 {
14069         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14070         struct drm_i915_gem_object *obj = intel_fb->obj;
14071
14072         return drm_gem_handle_create(file, &obj->base, handle);
14073 }
14074
14075 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
14076                                         struct drm_file *file,
14077                                         unsigned flags, unsigned color,
14078                                         struct drm_clip_rect *clips,
14079                                         unsigned num_clips)
14080 {
14081         struct drm_device *dev = fb->dev;
14082         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14083         struct drm_i915_gem_object *obj = intel_fb->obj;
14084
14085         mutex_lock(&dev->struct_mutex);
14086         intel_fb_obj_flush(obj, false, ORIGIN_DIRTYFB);
14087         mutex_unlock(&dev->struct_mutex);
14088
14089         return 0;
14090 }
14091
14092 static const struct drm_framebuffer_funcs intel_fb_funcs = {
14093         .destroy = intel_user_framebuffer_destroy,
14094         .create_handle = intel_user_framebuffer_create_handle,
14095         .dirty = intel_user_framebuffer_dirty,
14096 };
14097
14098 static
14099 u32 intel_fb_pitch_limit(struct drm_device *dev, uint64_t fb_modifier,
14100                          uint32_t pixel_format)
14101 {
14102         u32 gen = INTEL_INFO(dev)->gen;
14103
14104         if (gen >= 9) {
14105                 /* "The stride in bytes must not exceed the of the size of 8K
14106                  *  pixels and 32K bytes."
14107                  */
14108                  return min(8192*drm_format_plane_cpp(pixel_format, 0), 32768);
14109         } else if (gen >= 5 && !IS_VALLEYVIEW(dev)) {
14110                 return 32*1024;
14111         } else if (gen >= 4) {
14112                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14113                         return 16*1024;
14114                 else
14115                         return 32*1024;
14116         } else if (gen >= 3) {
14117                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14118                         return 8*1024;
14119                 else
14120                         return 16*1024;
14121         } else {
14122                 /* XXX DSPC is limited to 4k tiled */
14123                 return 8*1024;
14124         }
14125 }
14126
14127 static int intel_framebuffer_init(struct drm_device *dev,
14128                                   struct intel_framebuffer *intel_fb,
14129                                   struct drm_mode_fb_cmd2 *mode_cmd,
14130                                   struct drm_i915_gem_object *obj)
14131 {
14132         unsigned int aligned_height;
14133         int ret;
14134         u32 pitch_limit, stride_alignment;
14135
14136         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
14137
14138         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
14139                 /* Enforce that fb modifier and tiling mode match, but only for
14140                  * X-tiled. This is needed for FBC. */
14141                 if (!!(obj->tiling_mode == I915_TILING_X) !=
14142                     !!(mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED)) {
14143                         DRM_DEBUG("tiling_mode doesn't match fb modifier\n");
14144                         return -EINVAL;
14145                 }
14146         } else {
14147                 if (obj->tiling_mode == I915_TILING_X)
14148                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
14149                 else if (obj->tiling_mode == I915_TILING_Y) {
14150                         DRM_DEBUG("No Y tiling for legacy addfb\n");
14151                         return -EINVAL;
14152                 }
14153         }
14154
14155         /* Passed in modifier sanity checking. */
14156         switch (mode_cmd->modifier[0]) {
14157         case I915_FORMAT_MOD_Y_TILED:
14158         case I915_FORMAT_MOD_Yf_TILED:
14159                 if (INTEL_INFO(dev)->gen < 9) {
14160                         DRM_DEBUG("Unsupported tiling 0x%llx!\n",
14161                                   mode_cmd->modifier[0]);
14162                         return -EINVAL;
14163                 }
14164         case DRM_FORMAT_MOD_NONE:
14165         case I915_FORMAT_MOD_X_TILED:
14166                 break;
14167         default:
14168                 DRM_DEBUG("Unsupported fb modifier 0x%llx!\n",
14169                           mode_cmd->modifier[0]);
14170                 return -EINVAL;
14171         }
14172
14173         stride_alignment = intel_fb_stride_alignment(dev, mode_cmd->modifier[0],
14174                                                      mode_cmd->pixel_format);
14175         if (mode_cmd->pitches[0] & (stride_alignment - 1)) {
14176                 DRM_DEBUG("pitch (%d) must be at least %u byte aligned\n",
14177                           mode_cmd->pitches[0], stride_alignment);
14178                 return -EINVAL;
14179         }
14180
14181         pitch_limit = intel_fb_pitch_limit(dev, mode_cmd->modifier[0],
14182                                            mode_cmd->pixel_format);
14183         if (mode_cmd->pitches[0] > pitch_limit) {
14184                 DRM_DEBUG("%s pitch (%u) must be at less than %d\n",
14185                           mode_cmd->modifier[0] != DRM_FORMAT_MOD_NONE ?
14186                           "tiled" : "linear",
14187                           mode_cmd->pitches[0], pitch_limit);
14188                 return -EINVAL;
14189         }
14190
14191         if (mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED &&
14192             mode_cmd->pitches[0] != obj->stride) {
14193                 DRM_DEBUG("pitch (%d) must match tiling stride (%d)\n",
14194                           mode_cmd->pitches[0], obj->stride);
14195                 return -EINVAL;
14196         }
14197
14198         /* Reject formats not supported by any plane early. */
14199         switch (mode_cmd->pixel_format) {
14200         case DRM_FORMAT_C8:
14201         case DRM_FORMAT_RGB565:
14202         case DRM_FORMAT_XRGB8888:
14203         case DRM_FORMAT_ARGB8888:
14204                 break;
14205         case DRM_FORMAT_XRGB1555:
14206                 if (INTEL_INFO(dev)->gen > 3) {
14207                         DRM_DEBUG("unsupported pixel format: %s\n",
14208                                   drm_get_format_name(mode_cmd->pixel_format));
14209                         return -EINVAL;
14210                 }
14211                 break;
14212         case DRM_FORMAT_ABGR8888:
14213                 if (!IS_VALLEYVIEW(dev) && INTEL_INFO(dev)->gen < 9) {
14214                         DRM_DEBUG("unsupported pixel format: %s\n",
14215                                   drm_get_format_name(mode_cmd->pixel_format));
14216                         return -EINVAL;
14217                 }
14218                 break;
14219         case DRM_FORMAT_XBGR8888:
14220         case DRM_FORMAT_XRGB2101010:
14221         case DRM_FORMAT_XBGR2101010:
14222                 if (INTEL_INFO(dev)->gen < 4) {
14223                         DRM_DEBUG("unsupported pixel format: %s\n",
14224                                   drm_get_format_name(mode_cmd->pixel_format));
14225                         return -EINVAL;
14226                 }
14227                 break;
14228         case DRM_FORMAT_ABGR2101010:
14229                 if (!IS_VALLEYVIEW(dev)) {
14230                         DRM_DEBUG("unsupported pixel format: %s\n",
14231                                   drm_get_format_name(mode_cmd->pixel_format));
14232                         return -EINVAL;
14233                 }
14234                 break;
14235         case DRM_FORMAT_YUYV:
14236         case DRM_FORMAT_UYVY:
14237         case DRM_FORMAT_YVYU:
14238         case DRM_FORMAT_VYUY:
14239                 if (INTEL_INFO(dev)->gen < 5) {
14240                         DRM_DEBUG("unsupported pixel format: %s\n",
14241                                   drm_get_format_name(mode_cmd->pixel_format));
14242                         return -EINVAL;
14243                 }
14244                 break;
14245         default:
14246                 DRM_DEBUG("unsupported pixel format: %s\n",
14247                           drm_get_format_name(mode_cmd->pixel_format));
14248                 return -EINVAL;
14249         }
14250
14251         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14252         if (mode_cmd->offsets[0] != 0)
14253                 return -EINVAL;
14254
14255         aligned_height = intel_fb_align_height(dev, mode_cmd->height,
14256                                                mode_cmd->pixel_format,
14257                                                mode_cmd->modifier[0]);
14258         /* FIXME drm helper for size checks (especially planar formats)? */
14259         if (obj->base.size < aligned_height * mode_cmd->pitches[0])
14260                 return -EINVAL;
14261
14262         drm_helper_mode_fill_fb_struct(&intel_fb->base, mode_cmd);
14263         intel_fb->obj = obj;
14264         intel_fb->obj->framebuffer_references++;
14265
14266         ret = drm_framebuffer_init(dev, &intel_fb->base, &intel_fb_funcs);
14267         if (ret) {
14268                 DRM_ERROR("framebuffer init failed %d\n", ret);
14269                 return ret;
14270         }
14271
14272         return 0;
14273 }
14274
14275 static struct drm_framebuffer *
14276 intel_user_framebuffer_create(struct drm_device *dev,
14277                               struct drm_file *filp,
14278                               struct drm_mode_fb_cmd2 *mode_cmd)
14279 {
14280         struct drm_i915_gem_object *obj;
14281
14282         obj = to_intel_bo(drm_gem_object_lookup(dev, filp,
14283                                                 mode_cmd->handles[0]));
14284         if (&obj->base == NULL)
14285                 return ERR_PTR(-ENOENT);
14286
14287         return intel_framebuffer_create(dev, mode_cmd, obj);
14288 }
14289
14290 #ifndef CONFIG_DRM_I915_FBDEV
14291 static inline void intel_fbdev_output_poll_changed(struct drm_device *dev)
14292 {
14293 }
14294 #endif
14295
14296 static const struct drm_mode_config_funcs intel_mode_funcs = {
14297         .fb_create = intel_user_framebuffer_create,
14298         .output_poll_changed = intel_fbdev_output_poll_changed,
14299         .atomic_check = intel_atomic_check,
14300         .atomic_commit = intel_atomic_commit,
14301         .atomic_state_alloc = intel_atomic_state_alloc,
14302         .atomic_state_clear = intel_atomic_state_clear,
14303 };
14304
14305 /* Set up chip specific display functions */
14306 static void intel_init_display(struct drm_device *dev)
14307 {
14308         struct drm_i915_private *dev_priv = dev->dev_private;
14309
14310         if (HAS_PCH_SPLIT(dev) || IS_G4X(dev))
14311                 dev_priv->display.find_dpll = g4x_find_best_dpll;
14312         else if (IS_CHERRYVIEW(dev))
14313                 dev_priv->display.find_dpll = chv_find_best_dpll;
14314         else if (IS_VALLEYVIEW(dev))
14315                 dev_priv->display.find_dpll = vlv_find_best_dpll;
14316         else if (IS_PINEVIEW(dev))
14317                 dev_priv->display.find_dpll = pnv_find_best_dpll;
14318         else
14319                 dev_priv->display.find_dpll = i9xx_find_best_dpll;
14320
14321         if (INTEL_INFO(dev)->gen >= 9) {
14322                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14323                 dev_priv->display.get_initial_plane_config =
14324                         skylake_get_initial_plane_config;
14325                 dev_priv->display.crtc_compute_clock =
14326                         haswell_crtc_compute_clock;
14327                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14328                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14329                 dev_priv->display.update_primary_plane =
14330                         skylake_update_primary_plane;
14331         } else if (HAS_DDI(dev)) {
14332                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14333                 dev_priv->display.get_initial_plane_config =
14334                         ironlake_get_initial_plane_config;
14335                 dev_priv->display.crtc_compute_clock =
14336                         haswell_crtc_compute_clock;
14337                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14338                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14339                 dev_priv->display.update_primary_plane =
14340                         ironlake_update_primary_plane;
14341         } else if (HAS_PCH_SPLIT(dev)) {
14342                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
14343                 dev_priv->display.get_initial_plane_config =
14344                         ironlake_get_initial_plane_config;
14345                 dev_priv->display.crtc_compute_clock =
14346                         ironlake_crtc_compute_clock;
14347                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
14348                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
14349                 dev_priv->display.update_primary_plane =
14350                         ironlake_update_primary_plane;
14351         } else if (IS_VALLEYVIEW(dev)) {
14352                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14353                 dev_priv->display.get_initial_plane_config =
14354                         i9xx_get_initial_plane_config;
14355                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14356                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14357                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14358                 dev_priv->display.update_primary_plane =
14359                         i9xx_update_primary_plane;
14360         } else {
14361                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14362                 dev_priv->display.get_initial_plane_config =
14363                         i9xx_get_initial_plane_config;
14364                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14365                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14366                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14367                 dev_priv->display.update_primary_plane =
14368                         i9xx_update_primary_plane;
14369         }
14370
14371         /* Returns the core display clock speed */
14372         if (IS_SKYLAKE(dev))
14373                 dev_priv->display.get_display_clock_speed =
14374                         skylake_get_display_clock_speed;
14375         else if (IS_BROXTON(dev))
14376                 dev_priv->display.get_display_clock_speed =
14377                         broxton_get_display_clock_speed;
14378         else if (IS_BROADWELL(dev))
14379                 dev_priv->display.get_display_clock_speed =
14380                         broadwell_get_display_clock_speed;
14381         else if (IS_HASWELL(dev))
14382                 dev_priv->display.get_display_clock_speed =
14383                         haswell_get_display_clock_speed;
14384         else if (IS_VALLEYVIEW(dev))
14385                 dev_priv->display.get_display_clock_speed =
14386                         valleyview_get_display_clock_speed;
14387         else if (IS_GEN5(dev))
14388                 dev_priv->display.get_display_clock_speed =
14389                         ilk_get_display_clock_speed;
14390         else if (IS_I945G(dev) || IS_BROADWATER(dev) ||
14391                  IS_GEN6(dev) || IS_IVYBRIDGE(dev))
14392                 dev_priv->display.get_display_clock_speed =
14393                         i945_get_display_clock_speed;
14394         else if (IS_GM45(dev))
14395                 dev_priv->display.get_display_clock_speed =
14396                         gm45_get_display_clock_speed;
14397         else if (IS_CRESTLINE(dev))
14398                 dev_priv->display.get_display_clock_speed =
14399                         i965gm_get_display_clock_speed;
14400         else if (IS_PINEVIEW(dev))
14401                 dev_priv->display.get_display_clock_speed =
14402                         pnv_get_display_clock_speed;
14403         else if (IS_G33(dev) || IS_G4X(dev))
14404                 dev_priv->display.get_display_clock_speed =
14405                         g33_get_display_clock_speed;
14406         else if (IS_I915G(dev))
14407                 dev_priv->display.get_display_clock_speed =
14408                         i915_get_display_clock_speed;
14409         else if (IS_I945GM(dev) || IS_845G(dev))
14410                 dev_priv->display.get_display_clock_speed =
14411                         i9xx_misc_get_display_clock_speed;
14412         else if (IS_PINEVIEW(dev))
14413                 dev_priv->display.get_display_clock_speed =
14414                         pnv_get_display_clock_speed;
14415         else if (IS_I915GM(dev))
14416                 dev_priv->display.get_display_clock_speed =
14417                         i915gm_get_display_clock_speed;
14418         else if (IS_I865G(dev))
14419                 dev_priv->display.get_display_clock_speed =
14420                         i865_get_display_clock_speed;
14421         else if (IS_I85X(dev))
14422                 dev_priv->display.get_display_clock_speed =
14423                         i85x_get_display_clock_speed;
14424         else { /* 830 */
14425                 WARN(!IS_I830(dev), "Unknown platform. Assuming 133 MHz CDCLK\n");
14426                 dev_priv->display.get_display_clock_speed =
14427                         i830_get_display_clock_speed;
14428         }
14429
14430         if (IS_GEN5(dev)) {
14431                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
14432         } else if (IS_GEN6(dev)) {
14433                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
14434         } else if (IS_IVYBRIDGE(dev)) {
14435                 /* FIXME: detect B0+ stepping and use auto training */
14436                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
14437         } else if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
14438                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
14439                 if (IS_BROADWELL(dev)) {
14440                         dev_priv->display.modeset_commit_cdclk =
14441                                 broadwell_modeset_commit_cdclk;
14442                         dev_priv->display.modeset_calc_cdclk =
14443                                 broadwell_modeset_calc_cdclk;
14444                 }
14445         } else if (IS_VALLEYVIEW(dev)) {
14446                 dev_priv->display.modeset_commit_cdclk =
14447                         valleyview_modeset_commit_cdclk;
14448                 dev_priv->display.modeset_calc_cdclk =
14449                         valleyview_modeset_calc_cdclk;
14450         } else if (IS_BROXTON(dev)) {
14451                 dev_priv->display.modeset_commit_cdclk =
14452                         broxton_modeset_commit_cdclk;
14453                 dev_priv->display.modeset_calc_cdclk =
14454                         broxton_modeset_calc_cdclk;
14455         }
14456
14457         switch (INTEL_INFO(dev)->gen) {
14458         case 2:
14459                 dev_priv->display.queue_flip = intel_gen2_queue_flip;
14460                 break;
14461
14462         case 3:
14463                 dev_priv->display.queue_flip = intel_gen3_queue_flip;
14464                 break;
14465
14466         case 4:
14467         case 5:
14468                 dev_priv->display.queue_flip = intel_gen4_queue_flip;
14469                 break;
14470
14471         case 6:
14472                 dev_priv->display.queue_flip = intel_gen6_queue_flip;
14473                 break;
14474         case 7:
14475         case 8: /* FIXME(BDW): Check that the gen8 RCS flip works. */
14476                 dev_priv->display.queue_flip = intel_gen7_queue_flip;
14477                 break;
14478         case 9:
14479                 /* Drop through - unsupported since execlist only. */
14480         default:
14481                 /* Default just returns -ENODEV to indicate unsupported */
14482                 dev_priv->display.queue_flip = intel_default_queue_flip;
14483         }
14484
14485         intel_panel_init_backlight_funcs(dev);
14486
14487         mutex_init(&dev_priv->pps_mutex);
14488 }
14489
14490 /*
14491  * Some BIOSes insist on assuming the GPU's pipe A is enabled at suspend,
14492  * resume, or other times.  This quirk makes sure that's the case for
14493  * affected systems.
14494  */
14495 static void quirk_pipea_force(struct drm_device *dev)
14496 {
14497         struct drm_i915_private *dev_priv = dev->dev_private;
14498
14499         dev_priv->quirks |= QUIRK_PIPEA_FORCE;
14500         DRM_INFO("applying pipe a force quirk\n");
14501 }
14502
14503 static void quirk_pipeb_force(struct drm_device *dev)
14504 {
14505         struct drm_i915_private *dev_priv = dev->dev_private;
14506
14507         dev_priv->quirks |= QUIRK_PIPEB_FORCE;
14508         DRM_INFO("applying pipe b force quirk\n");
14509 }
14510
14511 /*
14512  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
14513  */
14514 static void quirk_ssc_force_disable(struct drm_device *dev)
14515 {
14516         struct drm_i915_private *dev_priv = dev->dev_private;
14517         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
14518         DRM_INFO("applying lvds SSC disable quirk\n");
14519 }
14520
14521 /*
14522  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
14523  * brightness value
14524  */
14525 static void quirk_invert_brightness(struct drm_device *dev)
14526 {
14527         struct drm_i915_private *dev_priv = dev->dev_private;
14528         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
14529         DRM_INFO("applying inverted panel brightness quirk\n");
14530 }
14531
14532 /* Some VBT's incorrectly indicate no backlight is present */
14533 static void quirk_backlight_present(struct drm_device *dev)
14534 {
14535         struct drm_i915_private *dev_priv = dev->dev_private;
14536         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
14537         DRM_INFO("applying backlight present quirk\n");
14538 }
14539
14540 struct intel_quirk {
14541         int device;
14542         int subsystem_vendor;
14543         int subsystem_device;
14544         void (*hook)(struct drm_device *dev);
14545 };
14546
14547 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
14548 struct intel_dmi_quirk {
14549         void (*hook)(struct drm_device *dev);
14550         const struct dmi_system_id (*dmi_id_list)[];
14551 };
14552
14553 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
14554 {
14555         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
14556         return 1;
14557 }
14558
14559 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
14560         {
14561                 .dmi_id_list = &(const struct dmi_system_id[]) {
14562                         {
14563                                 .callback = intel_dmi_reverse_brightness,
14564                                 .ident = "NCR Corporation",
14565                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
14566                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
14567                                 },
14568                         },
14569                         { }  /* terminating entry */
14570                 },
14571                 .hook = quirk_invert_brightness,
14572         },
14573 };
14574
14575 static struct intel_quirk intel_quirks[] = {
14576         /* Toshiba Protege R-205, S-209 needs pipe A force quirk */
14577         { 0x2592, 0x1179, 0x0001, quirk_pipea_force },
14578
14579         /* ThinkPad T60 needs pipe A force quirk (bug #16494) */
14580         { 0x2782, 0x17aa, 0x201a, quirk_pipea_force },
14581
14582         /* 830 needs to leave pipe A & dpll A up */
14583         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipea_force },
14584
14585         /* 830 needs to leave pipe B & dpll B up */
14586         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipeb_force },
14587
14588         /* Lenovo U160 cannot use SSC on LVDS */
14589         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
14590
14591         /* Sony Vaio Y cannot use SSC on LVDS */
14592         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
14593
14594         /* Acer Aspire 5734Z must invert backlight brightness */
14595         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
14596
14597         /* Acer/eMachines G725 */
14598         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
14599
14600         /* Acer/eMachines e725 */
14601         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
14602
14603         /* Acer/Packard Bell NCL20 */
14604         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
14605
14606         /* Acer Aspire 4736Z */
14607         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
14608
14609         /* Acer Aspire 5336 */
14610         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
14611
14612         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
14613         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
14614
14615         /* Acer C720 Chromebook (Core i3 4005U) */
14616         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
14617
14618         /* Apple Macbook 2,1 (Core 2 T7400) */
14619         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
14620
14621         /* Toshiba CB35 Chromebook (Celeron 2955U) */
14622         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
14623
14624         /* HP Chromebook 14 (Celeron 2955U) */
14625         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
14626
14627         /* Dell Chromebook 11 */
14628         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
14629 };
14630
14631 static void intel_init_quirks(struct drm_device *dev)
14632 {
14633         struct pci_dev *d = dev->pdev;
14634         int i;
14635
14636         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
14637                 struct intel_quirk *q = &intel_quirks[i];
14638
14639                 if (d->device == q->device &&
14640                     (d->subsystem_vendor == q->subsystem_vendor ||
14641                      q->subsystem_vendor == PCI_ANY_ID) &&
14642                     (d->subsystem_device == q->subsystem_device ||
14643                      q->subsystem_device == PCI_ANY_ID))
14644                         q->hook(dev);
14645         }
14646         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
14647                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
14648                         intel_dmi_quirks[i].hook(dev);
14649         }
14650 }
14651
14652 /* Disable the VGA plane that we never use */
14653 static void i915_disable_vga(struct drm_device *dev)
14654 {
14655         struct drm_i915_private *dev_priv = dev->dev_private;
14656         u8 sr1;
14657         u32 vga_reg = i915_vgacntrl_reg(dev);
14658
14659         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
14660         vga_get_uninterruptible(dev->pdev, VGA_RSRC_LEGACY_IO);
14661         outb(SR01, VGA_SR_INDEX);
14662         sr1 = inb(VGA_SR_DATA);
14663         outb(sr1 | 1<<5, VGA_SR_DATA);
14664         vga_put(dev->pdev, VGA_RSRC_LEGACY_IO);
14665         udelay(300);
14666
14667         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
14668         POSTING_READ(vga_reg);
14669 }
14670
14671 void intel_modeset_init_hw(struct drm_device *dev)
14672 {
14673         intel_update_cdclk(dev);
14674         intel_prepare_ddi(dev);
14675         intel_init_clock_gating(dev);
14676         intel_enable_gt_powersave(dev);
14677 }
14678
14679 void intel_modeset_init(struct drm_device *dev)
14680 {
14681         struct drm_i915_private *dev_priv = dev->dev_private;
14682         int sprite, ret;
14683         enum pipe pipe;
14684         struct intel_crtc *crtc;
14685
14686         drm_mode_config_init(dev);
14687
14688         dev->mode_config.min_width = 0;
14689         dev->mode_config.min_height = 0;
14690
14691         dev->mode_config.preferred_depth = 24;
14692         dev->mode_config.prefer_shadow = 1;
14693
14694         dev->mode_config.allow_fb_modifiers = true;
14695
14696         dev->mode_config.funcs = &intel_mode_funcs;
14697
14698         intel_init_quirks(dev);
14699
14700         intel_init_pm(dev);
14701
14702         if (INTEL_INFO(dev)->num_pipes == 0)
14703                 return;
14704
14705         intel_init_display(dev);
14706         intel_init_audio(dev);
14707
14708         if (IS_GEN2(dev)) {
14709                 dev->mode_config.max_width = 2048;
14710                 dev->mode_config.max_height = 2048;
14711         } else if (IS_GEN3(dev)) {
14712                 dev->mode_config.max_width = 4096;
14713                 dev->mode_config.max_height = 4096;
14714         } else {
14715                 dev->mode_config.max_width = 8192;
14716                 dev->mode_config.max_height = 8192;
14717         }
14718
14719         if (IS_845G(dev) || IS_I865G(dev)) {
14720                 dev->mode_config.cursor_width = IS_845G(dev) ? 64 : 512;
14721                 dev->mode_config.cursor_height = 1023;
14722         } else if (IS_GEN2(dev)) {
14723                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
14724                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
14725         } else {
14726                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
14727                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
14728         }
14729
14730         dev->mode_config.fb_base = dev_priv->gtt.mappable_base;
14731
14732         DRM_DEBUG_KMS("%d display pipe%s available.\n",
14733                       INTEL_INFO(dev)->num_pipes,
14734                       INTEL_INFO(dev)->num_pipes > 1 ? "s" : "");
14735
14736         for_each_pipe(dev_priv, pipe) {
14737                 intel_crtc_init(dev, pipe);
14738                 for_each_sprite(dev_priv, pipe, sprite) {
14739                         ret = intel_plane_init(dev, pipe, sprite);
14740                         if (ret)
14741                                 DRM_DEBUG_KMS("pipe %c sprite %c init failed: %d\n",
14742                                               pipe_name(pipe), sprite_name(pipe, sprite), ret);
14743                 }
14744         }
14745
14746         intel_shared_dpll_init(dev);
14747
14748         /* Just disable it once at startup */
14749         i915_disable_vga(dev);
14750         intel_setup_outputs(dev);
14751
14752         /* Just in case the BIOS is doing something questionable. */
14753         intel_fbc_disable(dev_priv);
14754
14755         drm_modeset_lock_all(dev);
14756         intel_modeset_setup_hw_state(dev);
14757         drm_modeset_unlock_all(dev);
14758
14759         for_each_intel_crtc(dev, crtc) {
14760                 struct intel_initial_plane_config plane_config = {};
14761
14762                 if (!crtc->active)
14763                         continue;
14764
14765                 /*
14766                  * Note that reserving the BIOS fb up front prevents us
14767                  * from stuffing other stolen allocations like the ring
14768                  * on top.  This prevents some ugliness at boot time, and
14769                  * can even allow for smooth boot transitions if the BIOS
14770                  * fb is large enough for the active pipe configuration.
14771                  */
14772                 dev_priv->display.get_initial_plane_config(crtc,
14773                                                            &plane_config);
14774
14775                 /*
14776                  * If the fb is shared between multiple heads, we'll
14777                  * just get the first one.
14778                  */
14779                 intel_find_initial_plane_obj(crtc, &plane_config);
14780         }
14781 }
14782
14783 static void intel_enable_pipe_a(struct drm_device *dev)
14784 {
14785         struct intel_connector *connector;
14786         struct drm_connector *crt = NULL;
14787         struct intel_load_detect_pipe load_detect_temp;
14788         struct drm_modeset_acquire_ctx *ctx = dev->mode_config.acquire_ctx;
14789
14790         /* We can't just switch on the pipe A, we need to set things up with a
14791          * proper mode and output configuration. As a gross hack, enable pipe A
14792          * by enabling the load detect pipe once. */
14793         for_each_intel_connector(dev, connector) {
14794                 if (connector->encoder->type == INTEL_OUTPUT_ANALOG) {
14795                         crt = &connector->base;
14796                         break;
14797                 }
14798         }
14799
14800         if (!crt)
14801                 return;
14802
14803         if (intel_get_load_detect_pipe(crt, NULL, &load_detect_temp, ctx))
14804                 intel_release_load_detect_pipe(crt, &load_detect_temp, ctx);
14805 }
14806
14807 static bool
14808 intel_check_plane_mapping(struct intel_crtc *crtc)
14809 {
14810         struct drm_device *dev = crtc->base.dev;
14811         struct drm_i915_private *dev_priv = dev->dev_private;
14812         u32 reg, val;
14813
14814         if (INTEL_INFO(dev)->num_pipes == 1)
14815                 return true;
14816
14817         reg = DSPCNTR(!crtc->plane);
14818         val = I915_READ(reg);
14819
14820         if ((val & DISPLAY_PLANE_ENABLE) &&
14821             (!!(val & DISPPLANE_SEL_PIPE_MASK) == crtc->pipe))
14822                 return false;
14823
14824         return true;
14825 }
14826
14827 static void intel_sanitize_crtc(struct intel_crtc *crtc)
14828 {
14829         struct drm_device *dev = crtc->base.dev;
14830         struct drm_i915_private *dev_priv = dev->dev_private;
14831         struct intel_encoder *encoder;
14832         u32 reg;
14833         bool enable;
14834
14835         /* Clear any frame start delays used for debugging left by the BIOS */
14836         reg = PIPECONF(crtc->config->cpu_transcoder);
14837         I915_WRITE(reg, I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
14838
14839         /* restore vblank interrupts to correct state */
14840         drm_crtc_vblank_reset(&crtc->base);
14841         if (crtc->active) {
14842                 drm_calc_timestamping_constants(&crtc->base, &crtc->base.hwmode);
14843                 update_scanline_offset(crtc);
14844                 drm_crtc_vblank_on(&crtc->base);
14845         }
14846
14847         /* We need to sanitize the plane -> pipe mapping first because this will
14848          * disable the crtc (and hence change the state) if it is wrong. Note
14849          * that gen4+ has a fixed plane -> pipe mapping.  */
14850         if (INTEL_INFO(dev)->gen < 4 && !intel_check_plane_mapping(crtc)) {
14851                 bool plane;
14852
14853                 DRM_DEBUG_KMS("[CRTC:%d] wrong plane connection detected!\n",
14854                               crtc->base.base.id);
14855
14856                 /* Pipe has the wrong plane attached and the plane is active.
14857                  * Temporarily change the plane mapping and disable everything
14858                  * ...  */
14859                 plane = crtc->plane;
14860                 to_intel_plane_state(crtc->base.primary->state)->visible = true;
14861                 crtc->plane = !plane;
14862                 intel_crtc_disable_noatomic(&crtc->base);
14863                 crtc->plane = plane;
14864         }
14865
14866         if (dev_priv->quirks & QUIRK_PIPEA_FORCE &&
14867             crtc->pipe == PIPE_A && !crtc->active) {
14868                 /* BIOS forgot to enable pipe A, this mostly happens after
14869                  * resume. Force-enable the pipe to fix this, the update_dpms
14870                  * call below we restore the pipe to the right state, but leave
14871                  * the required bits on. */
14872                 intel_enable_pipe_a(dev);
14873         }
14874
14875         /* Adjust the state of the output pipe according to whether we
14876          * have active connectors/encoders. */
14877         enable = false;
14878         for_each_encoder_on_crtc(dev, &crtc->base, encoder) {
14879                 enable = true;
14880                 break;
14881         }
14882
14883         if (!enable)
14884                 intel_crtc_disable_noatomic(&crtc->base);
14885
14886         if (crtc->active != crtc->base.state->active) {
14887
14888                 /* This can happen either due to bugs in the get_hw_state
14889                  * functions or because of calls to intel_crtc_disable_noatomic,
14890                  * or because the pipe is force-enabled due to the
14891                  * pipe A quirk. */
14892                 DRM_DEBUG_KMS("[CRTC:%d] hw state adjusted, was %s, now %s\n",
14893                               crtc->base.base.id,
14894                               crtc->base.state->enable ? "enabled" : "disabled",
14895                               crtc->active ? "enabled" : "disabled");
14896
14897                 WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, NULL) < 0);
14898                 crtc->base.state->active = crtc->active;
14899                 crtc->base.enabled = crtc->active;
14900
14901                 /* Because we only establish the connector -> encoder ->
14902                  * crtc links if something is active, this means the
14903                  * crtc is now deactivated. Break the links. connector
14904                  * -> encoder links are only establish when things are
14905                  *  actually up, hence no need to break them. */
14906                 WARN_ON(crtc->active);
14907
14908                 for_each_encoder_on_crtc(dev, &crtc->base, encoder)
14909                         encoder->base.crtc = NULL;
14910         }
14911
14912         if (crtc->active || HAS_GMCH_DISPLAY(dev)) {
14913                 /*
14914                  * We start out with underrun reporting disabled to avoid races.
14915                  * For correct bookkeeping mark this on active crtcs.
14916                  *
14917                  * Also on gmch platforms we dont have any hardware bits to
14918                  * disable the underrun reporting. Which means we need to start
14919                  * out with underrun reporting disabled also on inactive pipes,
14920                  * since otherwise we'll complain about the garbage we read when
14921                  * e.g. coming up after runtime pm.
14922                  *
14923                  * No protection against concurrent access is required - at
14924                  * worst a fifo underrun happens which also sets this to false.
14925                  */
14926                 crtc->cpu_fifo_underrun_disabled = true;
14927                 crtc->pch_fifo_underrun_disabled = true;
14928         }
14929 }
14930
14931 static void intel_sanitize_encoder(struct intel_encoder *encoder)
14932 {
14933         struct intel_connector *connector;
14934         struct drm_device *dev = encoder->base.dev;
14935         bool active = false;
14936
14937         /* We need to check both for a crtc link (meaning that the
14938          * encoder is active and trying to read from a pipe) and the
14939          * pipe itself being active. */
14940         bool has_active_crtc = encoder->base.crtc &&
14941                 to_intel_crtc(encoder->base.crtc)->active;
14942
14943         for_each_intel_connector(dev, connector) {
14944                 if (connector->base.encoder != &encoder->base)
14945                         continue;
14946
14947                 active = true;
14948                 break;
14949         }
14950
14951         if (active && !has_active_crtc) {
14952                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
14953                               encoder->base.base.id,
14954                               encoder->base.name);
14955
14956                 /* Connector is active, but has no active pipe. This is
14957                  * fallout from our resume register restoring. Disable
14958                  * the encoder manually again. */
14959                 if (encoder->base.crtc) {
14960                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
14961                                       encoder->base.base.id,
14962                                       encoder->base.name);
14963                         encoder->disable(encoder);
14964                         if (encoder->post_disable)
14965                                 encoder->post_disable(encoder);
14966                 }
14967                 encoder->base.crtc = NULL;
14968
14969                 /* Inconsistent output/port/pipe state happens presumably due to
14970                  * a bug in one of the get_hw_state functions. Or someplace else
14971                  * in our code, like the register restore mess on resume. Clamp
14972                  * things to off as a safer default. */
14973                 for_each_intel_connector(dev, connector) {
14974                         if (connector->encoder != encoder)
14975                                 continue;
14976                         connector->base.dpms = DRM_MODE_DPMS_OFF;
14977                         connector->base.encoder = NULL;
14978                 }
14979         }
14980         /* Enabled encoders without active connectors will be fixed in
14981          * the crtc fixup. */
14982 }
14983
14984 void i915_redisable_vga_power_on(struct drm_device *dev)
14985 {
14986         struct drm_i915_private *dev_priv = dev->dev_private;
14987         u32 vga_reg = i915_vgacntrl_reg(dev);
14988
14989         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
14990                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
14991                 i915_disable_vga(dev);
14992         }
14993 }
14994
14995 void i915_redisable_vga(struct drm_device *dev)
14996 {
14997         struct drm_i915_private *dev_priv = dev->dev_private;
14998
14999         /* This function can be called both from intel_modeset_setup_hw_state or
15000          * at a very early point in our resume sequence, where the power well
15001          * structures are not yet restored. Since this function is at a very
15002          * paranoid "someone might have enabled VGA while we were not looking"
15003          * level, just check if the power well is enabled instead of trying to
15004          * follow the "don't touch the power well if we don't need it" policy
15005          * the rest of the driver uses. */
15006         if (!intel_display_power_is_enabled(dev_priv, POWER_DOMAIN_VGA))
15007                 return;
15008
15009         i915_redisable_vga_power_on(dev);
15010 }
15011
15012 static bool primary_get_hw_state(struct intel_crtc *crtc)
15013 {
15014         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
15015
15016         return !!(I915_READ(DSPCNTR(crtc->plane)) & DISPLAY_PLANE_ENABLE);
15017 }
15018
15019 static void readout_plane_state(struct intel_crtc *crtc,
15020                                 struct intel_crtc_state *crtc_state)
15021 {
15022         struct intel_plane *p;
15023         struct intel_plane_state *plane_state;
15024         bool active = crtc_state->base.active;
15025
15026         for_each_intel_plane(crtc->base.dev, p) {
15027                 if (crtc->pipe != p->pipe)
15028                         continue;
15029
15030                 plane_state = to_intel_plane_state(p->base.state);
15031
15032                 if (p->base.type == DRM_PLANE_TYPE_PRIMARY)
15033                         plane_state->visible = primary_get_hw_state(crtc);
15034                 else {
15035                         if (active)
15036                                 p->disable_plane(&p->base, &crtc->base);
15037
15038                         plane_state->visible = false;
15039                 }
15040         }
15041 }
15042
15043 static void intel_modeset_readout_hw_state(struct drm_device *dev)
15044 {
15045         struct drm_i915_private *dev_priv = dev->dev_private;
15046         enum pipe pipe;
15047         struct intel_crtc *crtc;
15048         struct intel_encoder *encoder;
15049         struct intel_connector *connector;
15050         int i;
15051
15052         for_each_intel_crtc(dev, crtc) {
15053                 __drm_atomic_helper_crtc_destroy_state(&crtc->base, crtc->base.state);
15054                 memset(crtc->config, 0, sizeof(*crtc->config));
15055                 crtc->config->base.crtc = &crtc->base;
15056
15057                 crtc->active = dev_priv->display.get_pipe_config(crtc,
15058                                                                  crtc->config);
15059
15060                 crtc->base.state->active = crtc->active;
15061                 crtc->base.enabled = crtc->active;
15062
15063                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
15064                 if (crtc->base.state->active) {
15065                         intel_mode_from_pipe_config(&crtc->base.mode, crtc->config);
15066                         intel_mode_from_pipe_config(&crtc->base.state->adjusted_mode, crtc->config);
15067                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
15068
15069                         /*
15070                          * The initial mode needs to be set in order to keep
15071                          * the atomic core happy. It wants a valid mode if the
15072                          * crtc's enabled, so we do the above call.
15073                          *
15074                          * At this point some state updated by the connectors
15075                          * in their ->detect() callback has not run yet, so
15076                          * no recalculation can be done yet.
15077                          *
15078                          * Even if we could do a recalculation and modeset
15079                          * right now it would cause a double modeset if
15080                          * fbdev or userspace chooses a different initial mode.
15081                          *
15082                          * If that happens, someone indicated they wanted a
15083                          * mode change, which means it's safe to do a full
15084                          * recalculation.
15085                          */
15086                         crtc->base.state->mode.private_flags = I915_MODE_FLAG_INHERITED;
15087                 }
15088
15089                 crtc->base.hwmode = crtc->config->base.adjusted_mode;
15090                 readout_plane_state(crtc, to_intel_crtc_state(crtc->base.state));
15091
15092                 DRM_DEBUG_KMS("[CRTC:%d] hw state readout: %s\n",
15093                               crtc->base.base.id,
15094                               crtc->active ? "enabled" : "disabled");
15095         }
15096
15097         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15098                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15099
15100                 pll->on = pll->get_hw_state(dev_priv, pll,
15101                                             &pll->config.hw_state);
15102                 pll->active = 0;
15103                 pll->config.crtc_mask = 0;
15104                 for_each_intel_crtc(dev, crtc) {
15105                         if (crtc->active && intel_crtc_to_shared_dpll(crtc) == pll) {
15106                                 pll->active++;
15107                                 pll->config.crtc_mask |= 1 << crtc->pipe;
15108                         }
15109                 }
15110
15111                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15112                               pll->name, pll->config.crtc_mask, pll->on);
15113
15114                 if (pll->config.crtc_mask)
15115                         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
15116         }
15117
15118         for_each_intel_encoder(dev, encoder) {
15119                 pipe = 0;
15120
15121                 if (encoder->get_hw_state(encoder, &pipe)) {
15122                         crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
15123                         encoder->base.crtc = &crtc->base;
15124                         encoder->get_config(encoder, crtc->config);
15125                 } else {
15126                         encoder->base.crtc = NULL;
15127                 }
15128
15129                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
15130                               encoder->base.base.id,
15131                               encoder->base.name,
15132                               encoder->base.crtc ? "enabled" : "disabled",
15133                               pipe_name(pipe));
15134         }
15135
15136         for_each_intel_connector(dev, connector) {
15137                 if (connector->get_hw_state(connector)) {
15138                         connector->base.dpms = DRM_MODE_DPMS_ON;
15139                         connector->base.encoder = &connector->encoder->base;
15140                 } else {
15141                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15142                         connector->base.encoder = NULL;
15143                 }
15144                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
15145                               connector->base.base.id,
15146                               connector->base.name,
15147                               connector->base.encoder ? "enabled" : "disabled");
15148         }
15149 }
15150
15151 /* Scan out the current hw modeset state,
15152  * and sanitizes it to the current state
15153  */
15154 static void
15155 intel_modeset_setup_hw_state(struct drm_device *dev)
15156 {
15157         struct drm_i915_private *dev_priv = dev->dev_private;
15158         enum pipe pipe;
15159         struct intel_crtc *crtc;
15160         struct intel_encoder *encoder;
15161         int i;
15162
15163         intel_modeset_readout_hw_state(dev);
15164
15165         /* HW state is read out, now we need to sanitize this mess. */
15166         for_each_intel_encoder(dev, encoder) {
15167                 intel_sanitize_encoder(encoder);
15168         }
15169
15170         for_each_pipe(dev_priv, pipe) {
15171                 crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
15172                 intel_sanitize_crtc(crtc);
15173                 intel_dump_pipe_config(crtc, crtc->config,
15174                                        "[setup_hw_state]");
15175         }
15176
15177         intel_modeset_update_connector_atomic_state(dev);
15178
15179         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15180                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15181
15182                 if (!pll->on || pll->active)
15183                         continue;
15184
15185                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
15186
15187                 pll->disable(dev_priv, pll);
15188                 pll->on = false;
15189         }
15190
15191         if (IS_VALLEYVIEW(dev))
15192                 vlv_wm_get_hw_state(dev);
15193         else if (IS_GEN9(dev))
15194                 skl_wm_get_hw_state(dev);
15195         else if (HAS_PCH_SPLIT(dev))
15196                 ilk_wm_get_hw_state(dev);
15197
15198         for_each_intel_crtc(dev, crtc) {
15199                 unsigned long put_domains;
15200
15201                 put_domains = modeset_get_crtc_power_domains(&crtc->base);
15202                 if (WARN_ON(put_domains))
15203                         modeset_put_power_domains(dev_priv, put_domains);
15204         }
15205         intel_display_set_init_power(dev_priv, false);
15206 }
15207
15208 void intel_display_resume(struct drm_device *dev)
15209 {
15210         struct drm_atomic_state *state = drm_atomic_state_alloc(dev);
15211         struct intel_connector *conn;
15212         struct intel_plane *plane;
15213         struct drm_crtc *crtc;
15214         int ret;
15215
15216         if (!state)
15217                 return;
15218
15219         state->acquire_ctx = dev->mode_config.acquire_ctx;
15220
15221         /* preserve complete old state, including dpll */
15222         intel_atomic_get_shared_dpll_state(state);
15223
15224         for_each_crtc(dev, crtc) {
15225                 struct drm_crtc_state *crtc_state =
15226                         drm_atomic_get_crtc_state(state, crtc);
15227
15228                 ret = PTR_ERR_OR_ZERO(crtc_state);
15229                 if (ret)
15230                         goto err;
15231
15232                 /* force a restore */
15233                 crtc_state->mode_changed = true;
15234         }
15235
15236         for_each_intel_plane(dev, plane) {
15237                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_plane_state(state, &plane->base));
15238                 if (ret)
15239                         goto err;
15240         }
15241
15242         for_each_intel_connector(dev, conn) {
15243                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(state, &conn->base));
15244                 if (ret)
15245                         goto err;
15246         }
15247
15248         intel_modeset_setup_hw_state(dev);
15249
15250         i915_redisable_vga(dev);
15251         ret = drm_atomic_commit(state);
15252         if (!ret)
15253                 return;
15254
15255 err:
15256         DRM_ERROR("Restoring old state failed with %i\n", ret);
15257         drm_atomic_state_free(state);
15258 }
15259
15260 void intel_modeset_gem_init(struct drm_device *dev)
15261 {
15262         struct drm_i915_private *dev_priv = dev->dev_private;
15263         struct drm_crtc *c;
15264         struct drm_i915_gem_object *obj;
15265         int ret;
15266
15267         mutex_lock(&dev->struct_mutex);
15268         intel_init_gt_powersave(dev);
15269         mutex_unlock(&dev->struct_mutex);
15270
15271         /*
15272          * There may be no VBT; and if the BIOS enabled SSC we can
15273          * just keep using it to avoid unnecessary flicker.  Whereas if the
15274          * BIOS isn't using it, don't assume it will work even if the VBT
15275          * indicates as much.
15276          */
15277         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
15278                 dev_priv->vbt.lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
15279                                                 DREF_SSC1_ENABLE);
15280
15281         intel_modeset_init_hw(dev);
15282
15283         intel_setup_overlay(dev);
15284
15285         /*
15286          * Make sure any fbs we allocated at startup are properly
15287          * pinned & fenced.  When we do the allocation it's too early
15288          * for this.
15289          */
15290         for_each_crtc(dev, c) {
15291                 obj = intel_fb_obj(c->primary->fb);
15292                 if (obj == NULL)
15293                         continue;
15294
15295                 mutex_lock(&dev->struct_mutex);
15296                 ret = intel_pin_and_fence_fb_obj(c->primary,
15297                                                  c->primary->fb,
15298                                                  c->primary->state,
15299                                                  NULL, NULL);
15300                 mutex_unlock(&dev->struct_mutex);
15301                 if (ret) {
15302                         DRM_ERROR("failed to pin boot fb on pipe %d\n",
15303                                   to_intel_crtc(c)->pipe);
15304                         drm_framebuffer_unreference(c->primary->fb);
15305                         c->primary->fb = NULL;
15306                         c->primary->crtc = c->primary->state->crtc = NULL;
15307                         update_state_fb(c->primary);
15308                         c->state->plane_mask &= ~(1 << drm_plane_index(c->primary));
15309                 }
15310         }
15311
15312         intel_backlight_register(dev);
15313 }
15314
15315 void intel_connector_unregister(struct intel_connector *intel_connector)
15316 {
15317         struct drm_connector *connector = &intel_connector->base;
15318
15319         intel_panel_destroy_backlight(connector);
15320         drm_connector_unregister(connector);
15321 }
15322
15323 void intel_modeset_cleanup(struct drm_device *dev)
15324 {
15325         struct drm_i915_private *dev_priv = dev->dev_private;
15326         struct drm_connector *connector;
15327
15328         intel_disable_gt_powersave(dev);
15329
15330         intel_backlight_unregister(dev);
15331
15332         /*
15333          * Interrupts and polling as the first thing to avoid creating havoc.
15334          * Too much stuff here (turning of connectors, ...) would
15335          * experience fancy races otherwise.
15336          */
15337         intel_irq_uninstall(dev_priv);
15338
15339         /*
15340          * Due to the hpd irq storm handling the hotplug work can re-arm the
15341          * poll handlers. Hence disable polling after hpd handling is shut down.
15342          */
15343         drm_kms_helper_poll_fini(dev);
15344
15345         intel_unregister_dsm_handler();
15346
15347         intel_fbc_disable(dev_priv);
15348
15349         /* flush any delayed tasks or pending work */
15350         flush_scheduled_work();
15351
15352         /* destroy the backlight and sysfs files before encoders/connectors */
15353         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
15354                 struct intel_connector *intel_connector;
15355
15356                 intel_connector = to_intel_connector(connector);
15357                 intel_connector->unregister(intel_connector);
15358         }
15359
15360         drm_mode_config_cleanup(dev);
15361
15362         intel_cleanup_overlay(dev);
15363
15364         mutex_lock(&dev->struct_mutex);
15365         intel_cleanup_gt_powersave(dev);
15366         mutex_unlock(&dev->struct_mutex);
15367 }
15368
15369 /*
15370  * Return which encoder is currently attached for connector.
15371  */
15372 struct drm_encoder *intel_best_encoder(struct drm_connector *connector)
15373 {
15374         return &intel_attached_encoder(connector)->base;
15375 }
15376
15377 void intel_connector_attach_encoder(struct intel_connector *connector,
15378                                     struct intel_encoder *encoder)
15379 {
15380         connector->encoder = encoder;
15381         drm_mode_connector_attach_encoder(&connector->base,
15382                                           &encoder->base);
15383 }
15384
15385 /*
15386  * set vga decode state - true == enable VGA decode
15387  */
15388 int intel_modeset_vga_set_state(struct drm_device *dev, bool state)
15389 {
15390         struct drm_i915_private *dev_priv = dev->dev_private;
15391         unsigned reg = INTEL_INFO(dev)->gen >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
15392         u16 gmch_ctrl;
15393
15394         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
15395                 DRM_ERROR("failed to read control word\n");
15396                 return -EIO;
15397         }
15398
15399         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
15400                 return 0;
15401
15402         if (state)
15403                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
15404         else
15405                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
15406
15407         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
15408                 DRM_ERROR("failed to write control word\n");
15409                 return -EIO;
15410         }
15411
15412         return 0;
15413 }
15414
15415 struct intel_display_error_state {
15416
15417         u32 power_well_driver;
15418
15419         int num_transcoders;
15420
15421         struct intel_cursor_error_state {
15422                 u32 control;
15423                 u32 position;
15424                 u32 base;
15425                 u32 size;
15426         } cursor[I915_MAX_PIPES];
15427
15428         struct intel_pipe_error_state {
15429                 bool power_domain_on;
15430                 u32 source;
15431                 u32 stat;
15432         } pipe[I915_MAX_PIPES];
15433
15434         struct intel_plane_error_state {
15435                 u32 control;
15436                 u32 stride;
15437                 u32 size;
15438                 u32 pos;
15439                 u32 addr;
15440                 u32 surface;
15441                 u32 tile_offset;
15442         } plane[I915_MAX_PIPES];
15443
15444         struct intel_transcoder_error_state {
15445                 bool power_domain_on;
15446                 enum transcoder cpu_transcoder;
15447
15448                 u32 conf;
15449
15450                 u32 htotal;
15451                 u32 hblank;
15452                 u32 hsync;
15453                 u32 vtotal;
15454                 u32 vblank;
15455                 u32 vsync;
15456         } transcoder[4];
15457 };
15458
15459 struct intel_display_error_state *
15460 intel_display_capture_error_state(struct drm_device *dev)
15461 {
15462         struct drm_i915_private *dev_priv = dev->dev_private;
15463         struct intel_display_error_state *error;
15464         int transcoders[] = {
15465                 TRANSCODER_A,
15466                 TRANSCODER_B,
15467                 TRANSCODER_C,
15468                 TRANSCODER_EDP,
15469         };
15470         int i;
15471
15472         if (INTEL_INFO(dev)->num_pipes == 0)
15473                 return NULL;
15474
15475         error = kzalloc(sizeof(*error), GFP_ATOMIC);
15476         if (error == NULL)
15477                 return NULL;
15478
15479         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
15480                 error->power_well_driver = I915_READ(HSW_PWR_WELL_DRIVER);
15481
15482         for_each_pipe(dev_priv, i) {
15483                 error->pipe[i].power_domain_on =
15484                         __intel_display_power_is_enabled(dev_priv,
15485                                                          POWER_DOMAIN_PIPE(i));
15486                 if (!error->pipe[i].power_domain_on)
15487                         continue;
15488
15489                 error->cursor[i].control = I915_READ(CURCNTR(i));
15490                 error->cursor[i].position = I915_READ(CURPOS(i));
15491                 error->cursor[i].base = I915_READ(CURBASE(i));
15492
15493                 error->plane[i].control = I915_READ(DSPCNTR(i));
15494                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
15495                 if (INTEL_INFO(dev)->gen <= 3) {
15496                         error->plane[i].size = I915_READ(DSPSIZE(i));
15497                         error->plane[i].pos = I915_READ(DSPPOS(i));
15498                 }
15499                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
15500                         error->plane[i].addr = I915_READ(DSPADDR(i));
15501                 if (INTEL_INFO(dev)->gen >= 4) {
15502                         error->plane[i].surface = I915_READ(DSPSURF(i));
15503                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
15504                 }
15505
15506                 error->pipe[i].source = I915_READ(PIPESRC(i));
15507
15508                 if (HAS_GMCH_DISPLAY(dev))
15509                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
15510         }
15511
15512         error->num_transcoders = INTEL_INFO(dev)->num_pipes;
15513         if (HAS_DDI(dev_priv->dev))
15514                 error->num_transcoders++; /* Account for eDP. */
15515
15516         for (i = 0; i < error->num_transcoders; i++) {
15517                 enum transcoder cpu_transcoder = transcoders[i];
15518
15519                 error->transcoder[i].power_domain_on =
15520                         __intel_display_power_is_enabled(dev_priv,
15521                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
15522                 if (!error->transcoder[i].power_domain_on)
15523                         continue;
15524
15525                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
15526
15527                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
15528                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
15529                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
15530                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
15531                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
15532                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
15533                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
15534         }
15535
15536         return error;
15537 }
15538
15539 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
15540
15541 void
15542 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
15543                                 struct drm_device *dev,
15544                                 struct intel_display_error_state *error)
15545 {
15546         struct drm_i915_private *dev_priv = dev->dev_private;
15547         int i;
15548
15549         if (!error)
15550                 return;
15551
15552         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev)->num_pipes);
15553         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
15554                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
15555                            error->power_well_driver);
15556         for_each_pipe(dev_priv, i) {
15557                 err_printf(m, "Pipe [%d]:\n", i);
15558                 err_printf(m, "  Power: %s\n",
15559                            error->pipe[i].power_domain_on ? "on" : "off");
15560                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
15561                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
15562
15563                 err_printf(m, "Plane [%d]:\n", i);
15564                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
15565                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
15566                 if (INTEL_INFO(dev)->gen <= 3) {
15567                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
15568                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
15569                 }
15570                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
15571                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
15572                 if (INTEL_INFO(dev)->gen >= 4) {
15573                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
15574                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
15575                 }
15576
15577                 err_printf(m, "Cursor [%d]:\n", i);
15578                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
15579                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
15580                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
15581         }
15582
15583         for (i = 0; i < error->num_transcoders; i++) {
15584                 err_printf(m, "CPU transcoder: %c\n",
15585                            transcoder_name(error->transcoder[i].cpu_transcoder));
15586                 err_printf(m, "  Power: %s\n",
15587                            error->transcoder[i].power_domain_on ? "on" : "off");
15588                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
15589                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
15590                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
15591                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
15592                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
15593                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
15594                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
15595         }
15596 }
15597
15598 void intel_modeset_preclose(struct drm_device *dev, struct drm_file *file)
15599 {
15600         struct intel_crtc *crtc;
15601
15602         for_each_intel_crtc(dev, crtc) {
15603                 struct intel_unpin_work *work;
15604
15605                 spin_lock_irq(&dev->event_lock);
15606
15607                 work = crtc->unpin_work;
15608
15609                 if (work && work->event &&
15610                     work->event->base.file_priv == file) {
15611                         kfree(work->event);
15612                         work->event = NULL;
15613                 }
15614
15615                 spin_unlock_irq(&dev->event_lock);
15616         }
15617 }