OSDN Git Service

Merge tag 'drm-intel-next-2015-04-23-fixed' of git://anongit.freedesktop.org/drm...
[uclinux-h8/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 supported by all gen */
49 #define COMMON_PRIMARY_FORMATS \
50         DRM_FORMAT_C8, \
51         DRM_FORMAT_RGB565, \
52         DRM_FORMAT_XRGB8888, \
53         DRM_FORMAT_ARGB8888
54
55 /* Primary plane formats for gen <= 3 */
56 static const uint32_t intel_primary_formats_gen2[] = {
57         COMMON_PRIMARY_FORMATS,
58         DRM_FORMAT_XRGB1555,
59         DRM_FORMAT_ARGB1555,
60 };
61
62 /* Primary plane formats for gen >= 4 */
63 static const uint32_t intel_primary_formats_gen4[] = {
64         COMMON_PRIMARY_FORMATS, \
65         DRM_FORMAT_XBGR8888,
66         DRM_FORMAT_ABGR8888,
67         DRM_FORMAT_XRGB2101010,
68         DRM_FORMAT_ARGB2101010,
69         DRM_FORMAT_XBGR2101010,
70         DRM_FORMAT_ABGR2101010,
71 };
72
73 /* Cursor formats */
74 static const uint32_t intel_cursor_formats[] = {
75         DRM_FORMAT_ARGB8888,
76 };
77
78 static void intel_crtc_update_cursor(struct drm_crtc *crtc, bool on);
79
80 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
81                                 struct intel_crtc_state *pipe_config);
82 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
83                                    struct intel_crtc_state *pipe_config);
84
85 static int intel_set_mode(struct drm_crtc *crtc, struct drm_display_mode *mode,
86                           int x, int y, struct drm_framebuffer *old_fb,
87                           struct drm_atomic_state *state);
88 static int intel_framebuffer_init(struct drm_device *dev,
89                                   struct intel_framebuffer *ifb,
90                                   struct drm_mode_fb_cmd2 *mode_cmd,
91                                   struct drm_i915_gem_object *obj);
92 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc);
93 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc);
94 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
95                                          struct intel_link_m_n *m_n,
96                                          struct intel_link_m_n *m2_n2);
97 static void ironlake_set_pipeconf(struct drm_crtc *crtc);
98 static void haswell_set_pipeconf(struct drm_crtc *crtc);
99 static void intel_set_pipe_csc(struct drm_crtc *crtc);
100 static void vlv_prepare_pll(struct intel_crtc *crtc,
101                             const struct intel_crtc_state *pipe_config);
102 static void chv_prepare_pll(struct intel_crtc *crtc,
103                             const struct intel_crtc_state *pipe_config);
104 static void intel_begin_crtc_commit(struct drm_crtc *crtc);
105 static void intel_finish_crtc_commit(struct drm_crtc *crtc);
106 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
107         struct intel_crtc_state *crtc_state);
108 static int i9xx_get_refclk(const struct intel_crtc_state *crtc_state,
109                            int num_connectors);
110
111 static struct intel_encoder *intel_find_encoder(struct intel_connector *connector, int pipe)
112 {
113         if (!connector->mst_port)
114                 return connector->encoder;
115         else
116                 return &connector->mst_port->mst_encoders[pipe]->base;
117 }
118
119 typedef struct {
120         int     min, max;
121 } intel_range_t;
122
123 typedef struct {
124         int     dot_limit;
125         int     p2_slow, p2_fast;
126 } intel_p2_t;
127
128 typedef struct intel_limit intel_limit_t;
129 struct intel_limit {
130         intel_range_t   dot, vco, n, m, m1, m2, p, p1;
131         intel_p2_t          p2;
132 };
133
134 int
135 intel_pch_rawclk(struct drm_device *dev)
136 {
137         struct drm_i915_private *dev_priv = dev->dev_private;
138
139         WARN_ON(!HAS_PCH_SPLIT(dev));
140
141         return I915_READ(PCH_RAWCLK_FREQ) & RAWCLK_FREQ_MASK;
142 }
143
144 static inline u32 /* units of 100MHz */
145 intel_fdi_link_freq(struct drm_device *dev)
146 {
147         if (IS_GEN5(dev)) {
148                 struct drm_i915_private *dev_priv = dev->dev_private;
149                 return (I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK) + 2;
150         } else
151                 return 27;
152 }
153
154 static const intel_limit_t intel_limits_i8xx_dac = {
155         .dot = { .min = 25000, .max = 350000 },
156         .vco = { .min = 908000, .max = 1512000 },
157         .n = { .min = 2, .max = 16 },
158         .m = { .min = 96, .max = 140 },
159         .m1 = { .min = 18, .max = 26 },
160         .m2 = { .min = 6, .max = 16 },
161         .p = { .min = 4, .max = 128 },
162         .p1 = { .min = 2, .max = 33 },
163         .p2 = { .dot_limit = 165000,
164                 .p2_slow = 4, .p2_fast = 2 },
165 };
166
167 static const intel_limit_t intel_limits_i8xx_dvo = {
168         .dot = { .min = 25000, .max = 350000 },
169         .vco = { .min = 908000, .max = 1512000 },
170         .n = { .min = 2, .max = 16 },
171         .m = { .min = 96, .max = 140 },
172         .m1 = { .min = 18, .max = 26 },
173         .m2 = { .min = 6, .max = 16 },
174         .p = { .min = 4, .max = 128 },
175         .p1 = { .min = 2, .max = 33 },
176         .p2 = { .dot_limit = 165000,
177                 .p2_slow = 4, .p2_fast = 4 },
178 };
179
180 static const intel_limit_t intel_limits_i8xx_lvds = {
181         .dot = { .min = 25000, .max = 350000 },
182         .vco = { .min = 908000, .max = 1512000 },
183         .n = { .min = 2, .max = 16 },
184         .m = { .min = 96, .max = 140 },
185         .m1 = { .min = 18, .max = 26 },
186         .m2 = { .min = 6, .max = 16 },
187         .p = { .min = 4, .max = 128 },
188         .p1 = { .min = 1, .max = 6 },
189         .p2 = { .dot_limit = 165000,
190                 .p2_slow = 14, .p2_fast = 7 },
191 };
192
193 static const intel_limit_t intel_limits_i9xx_sdvo = {
194         .dot = { .min = 20000, .max = 400000 },
195         .vco = { .min = 1400000, .max = 2800000 },
196         .n = { .min = 1, .max = 6 },
197         .m = { .min = 70, .max = 120 },
198         .m1 = { .min = 8, .max = 18 },
199         .m2 = { .min = 3, .max = 7 },
200         .p = { .min = 5, .max = 80 },
201         .p1 = { .min = 1, .max = 8 },
202         .p2 = { .dot_limit = 200000,
203                 .p2_slow = 10, .p2_fast = 5 },
204 };
205
206 static const intel_limit_t intel_limits_i9xx_lvds = {
207         .dot = { .min = 20000, .max = 400000 },
208         .vco = { .min = 1400000, .max = 2800000 },
209         .n = { .min = 1, .max = 6 },
210         .m = { .min = 70, .max = 120 },
211         .m1 = { .min = 8, .max = 18 },
212         .m2 = { .min = 3, .max = 7 },
213         .p = { .min = 7, .max = 98 },
214         .p1 = { .min = 1, .max = 8 },
215         .p2 = { .dot_limit = 112000,
216                 .p2_slow = 14, .p2_fast = 7 },
217 };
218
219
220 static const intel_limit_t intel_limits_g4x_sdvo = {
221         .dot = { .min = 25000, .max = 270000 },
222         .vco = { .min = 1750000, .max = 3500000},
223         .n = { .min = 1, .max = 4 },
224         .m = { .min = 104, .max = 138 },
225         .m1 = { .min = 17, .max = 23 },
226         .m2 = { .min = 5, .max = 11 },
227         .p = { .min = 10, .max = 30 },
228         .p1 = { .min = 1, .max = 3},
229         .p2 = { .dot_limit = 270000,
230                 .p2_slow = 10,
231                 .p2_fast = 10
232         },
233 };
234
235 static const intel_limit_t intel_limits_g4x_hdmi = {
236         .dot = { .min = 22000, .max = 400000 },
237         .vco = { .min = 1750000, .max = 3500000},
238         .n = { .min = 1, .max = 4 },
239         .m = { .min = 104, .max = 138 },
240         .m1 = { .min = 16, .max = 23 },
241         .m2 = { .min = 5, .max = 11 },
242         .p = { .min = 5, .max = 80 },
243         .p1 = { .min = 1, .max = 8},
244         .p2 = { .dot_limit = 165000,
245                 .p2_slow = 10, .p2_fast = 5 },
246 };
247
248 static const intel_limit_t intel_limits_g4x_single_channel_lvds = {
249         .dot = { .min = 20000, .max = 115000 },
250         .vco = { .min = 1750000, .max = 3500000 },
251         .n = { .min = 1, .max = 3 },
252         .m = { .min = 104, .max = 138 },
253         .m1 = { .min = 17, .max = 23 },
254         .m2 = { .min = 5, .max = 11 },
255         .p = { .min = 28, .max = 112 },
256         .p1 = { .min = 2, .max = 8 },
257         .p2 = { .dot_limit = 0,
258                 .p2_slow = 14, .p2_fast = 14
259         },
260 };
261
262 static const intel_limit_t intel_limits_g4x_dual_channel_lvds = {
263         .dot = { .min = 80000, .max = 224000 },
264         .vco = { .min = 1750000, .max = 3500000 },
265         .n = { .min = 1, .max = 3 },
266         .m = { .min = 104, .max = 138 },
267         .m1 = { .min = 17, .max = 23 },
268         .m2 = { .min = 5, .max = 11 },
269         .p = { .min = 14, .max = 42 },
270         .p1 = { .min = 2, .max = 6 },
271         .p2 = { .dot_limit = 0,
272                 .p2_slow = 7, .p2_fast = 7
273         },
274 };
275
276 static const intel_limit_t intel_limits_pineview_sdvo = {
277         .dot = { .min = 20000, .max = 400000},
278         .vco = { .min = 1700000, .max = 3500000 },
279         /* Pineview's Ncounter is a ring counter */
280         .n = { .min = 3, .max = 6 },
281         .m = { .min = 2, .max = 256 },
282         /* Pineview only has one combined m divider, which we treat as m2. */
283         .m1 = { .min = 0, .max = 0 },
284         .m2 = { .min = 0, .max = 254 },
285         .p = { .min = 5, .max = 80 },
286         .p1 = { .min = 1, .max = 8 },
287         .p2 = { .dot_limit = 200000,
288                 .p2_slow = 10, .p2_fast = 5 },
289 };
290
291 static const intel_limit_t intel_limits_pineview_lvds = {
292         .dot = { .min = 20000, .max = 400000 },
293         .vco = { .min = 1700000, .max = 3500000 },
294         .n = { .min = 3, .max = 6 },
295         .m = { .min = 2, .max = 256 },
296         .m1 = { .min = 0, .max = 0 },
297         .m2 = { .min = 0, .max = 254 },
298         .p = { .min = 7, .max = 112 },
299         .p1 = { .min = 1, .max = 8 },
300         .p2 = { .dot_limit = 112000,
301                 .p2_slow = 14, .p2_fast = 14 },
302 };
303
304 /* Ironlake / Sandybridge
305  *
306  * We calculate clock using (register_value + 2) for N/M1/M2, so here
307  * the range value for them is (actual_value - 2).
308  */
309 static const intel_limit_t intel_limits_ironlake_dac = {
310         .dot = { .min = 25000, .max = 350000 },
311         .vco = { .min = 1760000, .max = 3510000 },
312         .n = { .min = 1, .max = 5 },
313         .m = { .min = 79, .max = 127 },
314         .m1 = { .min = 12, .max = 22 },
315         .m2 = { .min = 5, .max = 9 },
316         .p = { .min = 5, .max = 80 },
317         .p1 = { .min = 1, .max = 8 },
318         .p2 = { .dot_limit = 225000,
319                 .p2_slow = 10, .p2_fast = 5 },
320 };
321
322 static const intel_limit_t intel_limits_ironlake_single_lvds = {
323         .dot = { .min = 25000, .max = 350000 },
324         .vco = { .min = 1760000, .max = 3510000 },
325         .n = { .min = 1, .max = 3 },
326         .m = { .min = 79, .max = 118 },
327         .m1 = { .min = 12, .max = 22 },
328         .m2 = { .min = 5, .max = 9 },
329         .p = { .min = 28, .max = 112 },
330         .p1 = { .min = 2, .max = 8 },
331         .p2 = { .dot_limit = 225000,
332                 .p2_slow = 14, .p2_fast = 14 },
333 };
334
335 static const intel_limit_t intel_limits_ironlake_dual_lvds = {
336         .dot = { .min = 25000, .max = 350000 },
337         .vco = { .min = 1760000, .max = 3510000 },
338         .n = { .min = 1, .max = 3 },
339         .m = { .min = 79, .max = 127 },
340         .m1 = { .min = 12, .max = 22 },
341         .m2 = { .min = 5, .max = 9 },
342         .p = { .min = 14, .max = 56 },
343         .p1 = { .min = 2, .max = 8 },
344         .p2 = { .dot_limit = 225000,
345                 .p2_slow = 7, .p2_fast = 7 },
346 };
347
348 /* LVDS 100mhz refclk limits. */
349 static const intel_limit_t intel_limits_ironlake_single_lvds_100m = {
350         .dot = { .min = 25000, .max = 350000 },
351         .vco = { .min = 1760000, .max = 3510000 },
352         .n = { .min = 1, .max = 2 },
353         .m = { .min = 79, .max = 126 },
354         .m1 = { .min = 12, .max = 22 },
355         .m2 = { .min = 5, .max = 9 },
356         .p = { .min = 28, .max = 112 },
357         .p1 = { .min = 2, .max = 8 },
358         .p2 = { .dot_limit = 225000,
359                 .p2_slow = 14, .p2_fast = 14 },
360 };
361
362 static const intel_limit_t intel_limits_ironlake_dual_lvds_100m = {
363         .dot = { .min = 25000, .max = 350000 },
364         .vco = { .min = 1760000, .max = 3510000 },
365         .n = { .min = 1, .max = 3 },
366         .m = { .min = 79, .max = 126 },
367         .m1 = { .min = 12, .max = 22 },
368         .m2 = { .min = 5, .max = 9 },
369         .p = { .min = 14, .max = 42 },
370         .p1 = { .min = 2, .max = 6 },
371         .p2 = { .dot_limit = 225000,
372                 .p2_slow = 7, .p2_fast = 7 },
373 };
374
375 static const intel_limit_t intel_limits_vlv = {
376          /*
377           * These are the data rate limits (measured in fast clocks)
378           * since those are the strictest limits we have. The fast
379           * clock and actual rate limits are more relaxed, so checking
380           * them would make no difference.
381           */
382         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
383         .vco = { .min = 4000000, .max = 6000000 },
384         .n = { .min = 1, .max = 7 },
385         .m1 = { .min = 2, .max = 3 },
386         .m2 = { .min = 11, .max = 156 },
387         .p1 = { .min = 2, .max = 3 },
388         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
389 };
390
391 static const intel_limit_t intel_limits_chv = {
392         /*
393          * These are the data rate limits (measured in fast clocks)
394          * since those are the strictest limits we have.  The fast
395          * clock and actual rate limits are more relaxed, so checking
396          * them would make no difference.
397          */
398         .dot = { .min = 25000 * 5, .max = 540000 * 5},
399         .vco = { .min = 4800000, .max = 6480000 },
400         .n = { .min = 1, .max = 1 },
401         .m1 = { .min = 2, .max = 2 },
402         .m2 = { .min = 24 << 22, .max = 175 << 22 },
403         .p1 = { .min = 2, .max = 4 },
404         .p2 = { .p2_slow = 1, .p2_fast = 14 },
405 };
406
407 static const intel_limit_t intel_limits_bxt = {
408         /* FIXME: find real dot limits */
409         .dot = { .min = 0, .max = INT_MAX },
410         .vco = { .min = 4800000, .max = 6480000 },
411         .n = { .min = 1, .max = 1 },
412         .m1 = { .min = 2, .max = 2 },
413         /* FIXME: find real m2 limits */
414         .m2 = { .min = 2 << 22, .max = 255 << 22 },
415         .p1 = { .min = 2, .max = 4 },
416         .p2 = { .p2_slow = 1, .p2_fast = 20 },
417 };
418
419 static void vlv_clock(int refclk, intel_clock_t *clock)
420 {
421         clock->m = clock->m1 * clock->m2;
422         clock->p = clock->p1 * clock->p2;
423         if (WARN_ON(clock->n == 0 || clock->p == 0))
424                 return;
425         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
426         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
427 }
428
429 /**
430  * Returns whether any output on the specified pipe is of the specified type
431  */
432 bool intel_pipe_has_type(struct intel_crtc *crtc, enum intel_output_type type)
433 {
434         struct drm_device *dev = crtc->base.dev;
435         struct intel_encoder *encoder;
436
437         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
438                 if (encoder->type == type)
439                         return true;
440
441         return false;
442 }
443
444 /**
445  * Returns whether any output on the specified pipe will have the specified
446  * type after a staged modeset is complete, i.e., the same as
447  * intel_pipe_has_type() but looking at encoder->new_crtc instead of
448  * encoder->crtc.
449  */
450 static bool intel_pipe_will_have_type(const struct intel_crtc_state *crtc_state,
451                                       int type)
452 {
453         struct drm_atomic_state *state = crtc_state->base.state;
454         struct drm_connector_state *connector_state;
455         struct intel_encoder *encoder;
456         int i, num_connectors = 0;
457
458         for (i = 0; i < state->num_connector; i++) {
459                 if (!state->connectors[i])
460                         continue;
461
462                 connector_state = state->connector_states[i];
463                 if (connector_state->crtc != crtc_state->base.crtc)
464                         continue;
465
466                 num_connectors++;
467
468                 encoder = to_intel_encoder(connector_state->best_encoder);
469                 if (encoder->type == type)
470                         return true;
471         }
472
473         WARN_ON(num_connectors == 0);
474
475         return false;
476 }
477
478 static const intel_limit_t *
479 intel_ironlake_limit(struct intel_crtc_state *crtc_state, int refclk)
480 {
481         struct drm_device *dev = crtc_state->base.crtc->dev;
482         const intel_limit_t *limit;
483
484         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
485                 if (intel_is_dual_link_lvds(dev)) {
486                         if (refclk == 100000)
487                                 limit = &intel_limits_ironlake_dual_lvds_100m;
488                         else
489                                 limit = &intel_limits_ironlake_dual_lvds;
490                 } else {
491                         if (refclk == 100000)
492                                 limit = &intel_limits_ironlake_single_lvds_100m;
493                         else
494                                 limit = &intel_limits_ironlake_single_lvds;
495                 }
496         } else
497                 limit = &intel_limits_ironlake_dac;
498
499         return limit;
500 }
501
502 static const intel_limit_t *
503 intel_g4x_limit(struct intel_crtc_state *crtc_state)
504 {
505         struct drm_device *dev = crtc_state->base.crtc->dev;
506         const intel_limit_t *limit;
507
508         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
509                 if (intel_is_dual_link_lvds(dev))
510                         limit = &intel_limits_g4x_dual_channel_lvds;
511                 else
512                         limit = &intel_limits_g4x_single_channel_lvds;
513         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_HDMI) ||
514                    intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
515                 limit = &intel_limits_g4x_hdmi;
516         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_SDVO)) {
517                 limit = &intel_limits_g4x_sdvo;
518         } else /* The option is for other outputs */
519                 limit = &intel_limits_i9xx_sdvo;
520
521         return limit;
522 }
523
524 static const intel_limit_t *
525 intel_limit(struct intel_crtc_state *crtc_state, int refclk)
526 {
527         struct drm_device *dev = crtc_state->base.crtc->dev;
528         const intel_limit_t *limit;
529
530         if (IS_BROXTON(dev))
531                 limit = &intel_limits_bxt;
532         else if (HAS_PCH_SPLIT(dev))
533                 limit = intel_ironlake_limit(crtc_state, refclk);
534         else if (IS_G4X(dev)) {
535                 limit = intel_g4x_limit(crtc_state);
536         } else if (IS_PINEVIEW(dev)) {
537                 if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
538                         limit = &intel_limits_pineview_lvds;
539                 else
540                         limit = &intel_limits_pineview_sdvo;
541         } else if (IS_CHERRYVIEW(dev)) {
542                 limit = &intel_limits_chv;
543         } else if (IS_VALLEYVIEW(dev)) {
544                 limit = &intel_limits_vlv;
545         } else if (!IS_GEN2(dev)) {
546                 if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
547                         limit = &intel_limits_i9xx_lvds;
548                 else
549                         limit = &intel_limits_i9xx_sdvo;
550         } else {
551                 if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
552                         limit = &intel_limits_i8xx_lvds;
553                 else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_DVO))
554                         limit = &intel_limits_i8xx_dvo;
555                 else
556                         limit = &intel_limits_i8xx_dac;
557         }
558         return limit;
559 }
560
561 /* m1 is reserved as 0 in Pineview, n is a ring counter */
562 static void pineview_clock(int refclk, intel_clock_t *clock)
563 {
564         clock->m = clock->m2 + 2;
565         clock->p = clock->p1 * clock->p2;
566         if (WARN_ON(clock->n == 0 || clock->p == 0))
567                 return;
568         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
569         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
570 }
571
572 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
573 {
574         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
575 }
576
577 static void i9xx_clock(int refclk, intel_clock_t *clock)
578 {
579         clock->m = i9xx_dpll_compute_m(clock);
580         clock->p = clock->p1 * clock->p2;
581         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
582                 return;
583         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
584         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
585 }
586
587 static void chv_clock(int refclk, intel_clock_t *clock)
588 {
589         clock->m = clock->m1 * clock->m2;
590         clock->p = clock->p1 * clock->p2;
591         if (WARN_ON(clock->n == 0 || clock->p == 0))
592                 return;
593         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
594                         clock->n << 22);
595         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
596 }
597
598 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
599 /**
600  * Returns whether the given set of divisors are valid for a given refclk with
601  * the given connectors.
602  */
603
604 static bool intel_PLL_is_valid(struct drm_device *dev,
605                                const intel_limit_t *limit,
606                                const intel_clock_t *clock)
607 {
608         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
609                 INTELPllInvalid("n out of range\n");
610         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
611                 INTELPllInvalid("p1 out of range\n");
612         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
613                 INTELPllInvalid("m2 out of range\n");
614         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
615                 INTELPllInvalid("m1 out of range\n");
616
617         if (!IS_PINEVIEW(dev) && !IS_VALLEYVIEW(dev) && !IS_BROXTON(dev))
618                 if (clock->m1 <= clock->m2)
619                         INTELPllInvalid("m1 <= m2\n");
620
621         if (!IS_VALLEYVIEW(dev) && !IS_BROXTON(dev)) {
622                 if (clock->p < limit->p.min || limit->p.max < clock->p)
623                         INTELPllInvalid("p out of range\n");
624                 if (clock->m < limit->m.min || limit->m.max < clock->m)
625                         INTELPllInvalid("m out of range\n");
626         }
627
628         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
629                 INTELPllInvalid("vco out of range\n");
630         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
631          * connector, etc., rather than just a single range.
632          */
633         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
634                 INTELPllInvalid("dot out of range\n");
635
636         return true;
637 }
638
639 static bool
640 i9xx_find_best_dpll(const intel_limit_t *limit,
641                     struct intel_crtc_state *crtc_state,
642                     int target, int refclk, intel_clock_t *match_clock,
643                     intel_clock_t *best_clock)
644 {
645         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
646         struct drm_device *dev = crtc->base.dev;
647         intel_clock_t clock;
648         int err = target;
649
650         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
651                 /*
652                  * For LVDS just rely on its current settings for dual-channel.
653                  * We haven't figured out how to reliably set up different
654                  * single/dual channel state, if we even can.
655                  */
656                 if (intel_is_dual_link_lvds(dev))
657                         clock.p2 = limit->p2.p2_fast;
658                 else
659                         clock.p2 = limit->p2.p2_slow;
660         } else {
661                 if (target < limit->p2.dot_limit)
662                         clock.p2 = limit->p2.p2_slow;
663                 else
664                         clock.p2 = limit->p2.p2_fast;
665         }
666
667         memset(best_clock, 0, sizeof(*best_clock));
668
669         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
670              clock.m1++) {
671                 for (clock.m2 = limit->m2.min;
672                      clock.m2 <= limit->m2.max; clock.m2++) {
673                         if (clock.m2 >= clock.m1)
674                                 break;
675                         for (clock.n = limit->n.min;
676                              clock.n <= limit->n.max; clock.n++) {
677                                 for (clock.p1 = limit->p1.min;
678                                         clock.p1 <= limit->p1.max; clock.p1++) {
679                                         int this_err;
680
681                                         i9xx_clock(refclk, &clock);
682                                         if (!intel_PLL_is_valid(dev, limit,
683                                                                 &clock))
684                                                 continue;
685                                         if (match_clock &&
686                                             clock.p != match_clock->p)
687                                                 continue;
688
689                                         this_err = abs(clock.dot - target);
690                                         if (this_err < err) {
691                                                 *best_clock = clock;
692                                                 err = this_err;
693                                         }
694                                 }
695                         }
696                 }
697         }
698
699         return (err != target);
700 }
701
702 static bool
703 pnv_find_best_dpll(const intel_limit_t *limit,
704                    struct intel_crtc_state *crtc_state,
705                    int target, int refclk, intel_clock_t *match_clock,
706                    intel_clock_t *best_clock)
707 {
708         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
709         struct drm_device *dev = crtc->base.dev;
710         intel_clock_t clock;
711         int err = target;
712
713         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
714                 /*
715                  * For LVDS just rely on its current settings for dual-channel.
716                  * We haven't figured out how to reliably set up different
717                  * single/dual channel state, if we even can.
718                  */
719                 if (intel_is_dual_link_lvds(dev))
720                         clock.p2 = limit->p2.p2_fast;
721                 else
722                         clock.p2 = limit->p2.p2_slow;
723         } else {
724                 if (target < limit->p2.dot_limit)
725                         clock.p2 = limit->p2.p2_slow;
726                 else
727                         clock.p2 = limit->p2.p2_fast;
728         }
729
730         memset(best_clock, 0, sizeof(*best_clock));
731
732         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
733              clock.m1++) {
734                 for (clock.m2 = limit->m2.min;
735                      clock.m2 <= limit->m2.max; clock.m2++) {
736                         for (clock.n = limit->n.min;
737                              clock.n <= limit->n.max; clock.n++) {
738                                 for (clock.p1 = limit->p1.min;
739                                         clock.p1 <= limit->p1.max; clock.p1++) {
740                                         int this_err;
741
742                                         pineview_clock(refclk, &clock);
743                                         if (!intel_PLL_is_valid(dev, limit,
744                                                                 &clock))
745                                                 continue;
746                                         if (match_clock &&
747                                             clock.p != match_clock->p)
748                                                 continue;
749
750                                         this_err = abs(clock.dot - target);
751                                         if (this_err < err) {
752                                                 *best_clock = clock;
753                                                 err = this_err;
754                                         }
755                                 }
756                         }
757                 }
758         }
759
760         return (err != target);
761 }
762
763 static bool
764 g4x_find_best_dpll(const intel_limit_t *limit,
765                    struct intel_crtc_state *crtc_state,
766                    int target, int refclk, intel_clock_t *match_clock,
767                    intel_clock_t *best_clock)
768 {
769         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
770         struct drm_device *dev = crtc->base.dev;
771         intel_clock_t clock;
772         int max_n;
773         bool found;
774         /* approximately equals target * 0.00585 */
775         int err_most = (target >> 8) + (target >> 9);
776         found = false;
777
778         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
779                 if (intel_is_dual_link_lvds(dev))
780                         clock.p2 = limit->p2.p2_fast;
781                 else
782                         clock.p2 = limit->p2.p2_slow;
783         } else {
784                 if (target < limit->p2.dot_limit)
785                         clock.p2 = limit->p2.p2_slow;
786                 else
787                         clock.p2 = limit->p2.p2_fast;
788         }
789
790         memset(best_clock, 0, sizeof(*best_clock));
791         max_n = limit->n.max;
792         /* based on hardware requirement, prefer smaller n to precision */
793         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
794                 /* based on hardware requirement, prefere larger m1,m2 */
795                 for (clock.m1 = limit->m1.max;
796                      clock.m1 >= limit->m1.min; clock.m1--) {
797                         for (clock.m2 = limit->m2.max;
798                              clock.m2 >= limit->m2.min; clock.m2--) {
799                                 for (clock.p1 = limit->p1.max;
800                                      clock.p1 >= limit->p1.min; clock.p1--) {
801                                         int this_err;
802
803                                         i9xx_clock(refclk, &clock);
804                                         if (!intel_PLL_is_valid(dev, limit,
805                                                                 &clock))
806                                                 continue;
807
808                                         this_err = abs(clock.dot - target);
809                                         if (this_err < err_most) {
810                                                 *best_clock = clock;
811                                                 err_most = this_err;
812                                                 max_n = clock.n;
813                                                 found = true;
814                                         }
815                                 }
816                         }
817                 }
818         }
819         return found;
820 }
821
822 /*
823  * Check if the calculated PLL configuration is more optimal compared to the
824  * best configuration and error found so far. Return the calculated error.
825  */
826 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
827                                const intel_clock_t *calculated_clock,
828                                const intel_clock_t *best_clock,
829                                unsigned int best_error_ppm,
830                                unsigned int *error_ppm)
831 {
832         /*
833          * For CHV ignore the error and consider only the P value.
834          * Prefer a bigger P value based on HW requirements.
835          */
836         if (IS_CHERRYVIEW(dev)) {
837                 *error_ppm = 0;
838
839                 return calculated_clock->p > best_clock->p;
840         }
841
842         if (WARN_ON_ONCE(!target_freq))
843                 return false;
844
845         *error_ppm = div_u64(1000000ULL *
846                                 abs(target_freq - calculated_clock->dot),
847                              target_freq);
848         /*
849          * Prefer a better P value over a better (smaller) error if the error
850          * is small. Ensure this preference for future configurations too by
851          * setting the error to 0.
852          */
853         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
854                 *error_ppm = 0;
855
856                 return true;
857         }
858
859         return *error_ppm + 10 < best_error_ppm;
860 }
861
862 static bool
863 vlv_find_best_dpll(const intel_limit_t *limit,
864                    struct intel_crtc_state *crtc_state,
865                    int target, int refclk, intel_clock_t *match_clock,
866                    intel_clock_t *best_clock)
867 {
868         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
869         struct drm_device *dev = crtc->base.dev;
870         intel_clock_t clock;
871         unsigned int bestppm = 1000000;
872         /* min update 19.2 MHz */
873         int max_n = min(limit->n.max, refclk / 19200);
874         bool found = false;
875
876         target *= 5; /* fast clock */
877
878         memset(best_clock, 0, sizeof(*best_clock));
879
880         /* based on hardware requirement, prefer smaller n to precision */
881         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
882                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
883                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
884                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
885                                 clock.p = clock.p1 * clock.p2;
886                                 /* based on hardware requirement, prefer bigger m1,m2 values */
887                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
888                                         unsigned int ppm;
889
890                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
891                                                                      refclk * clock.m1);
892
893                                         vlv_clock(refclk, &clock);
894
895                                         if (!intel_PLL_is_valid(dev, limit,
896                                                                 &clock))
897                                                 continue;
898
899                                         if (!vlv_PLL_is_optimal(dev, target,
900                                                                 &clock,
901                                                                 best_clock,
902                                                                 bestppm, &ppm))
903                                                 continue;
904
905                                         *best_clock = clock;
906                                         bestppm = ppm;
907                                         found = true;
908                                 }
909                         }
910                 }
911         }
912
913         return found;
914 }
915
916 static bool
917 chv_find_best_dpll(const intel_limit_t *limit,
918                    struct intel_crtc_state *crtc_state,
919                    int target, int refclk, intel_clock_t *match_clock,
920                    intel_clock_t *best_clock)
921 {
922         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
923         struct drm_device *dev = crtc->base.dev;
924         unsigned int best_error_ppm;
925         intel_clock_t clock;
926         uint64_t m2;
927         int found = false;
928
929         memset(best_clock, 0, sizeof(*best_clock));
930         best_error_ppm = 1000000;
931
932         /*
933          * Based on hardware doc, the n always set to 1, and m1 always
934          * set to 2.  If requires to support 200Mhz refclk, we need to
935          * revisit this because n may not 1 anymore.
936          */
937         clock.n = 1, clock.m1 = 2;
938         target *= 5;    /* fast clock */
939
940         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
941                 for (clock.p2 = limit->p2.p2_fast;
942                                 clock.p2 >= limit->p2.p2_slow;
943                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
944                         unsigned int error_ppm;
945
946                         clock.p = clock.p1 * clock.p2;
947
948                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
949                                         clock.n) << 22, refclk * clock.m1);
950
951                         if (m2 > INT_MAX/clock.m1)
952                                 continue;
953
954                         clock.m2 = m2;
955
956                         chv_clock(refclk, &clock);
957
958                         if (!intel_PLL_is_valid(dev, limit, &clock))
959                                 continue;
960
961                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
962                                                 best_error_ppm, &error_ppm))
963                                 continue;
964
965                         *best_clock = clock;
966                         best_error_ppm = error_ppm;
967                         found = true;
968                 }
969         }
970
971         return found;
972 }
973
974 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state, int target_clock,
975                         intel_clock_t *best_clock)
976 {
977         int refclk = i9xx_get_refclk(crtc_state, 0);
978
979         return chv_find_best_dpll(intel_limit(crtc_state, refclk), crtc_state,
980                                   target_clock, refclk, NULL, best_clock);
981 }
982
983 bool intel_crtc_active(struct drm_crtc *crtc)
984 {
985         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
986
987         /* Be paranoid as we can arrive here with only partial
988          * state retrieved from the hardware during setup.
989          *
990          * We can ditch the adjusted_mode.crtc_clock check as soon
991          * as Haswell has gained clock readout/fastboot support.
992          *
993          * We can ditch the crtc->primary->fb check as soon as we can
994          * properly reconstruct framebuffers.
995          *
996          * FIXME: The intel_crtc->active here should be switched to
997          * crtc->state->active once we have proper CRTC states wired up
998          * for atomic.
999          */
1000         return intel_crtc->active && crtc->primary->state->fb &&
1001                 intel_crtc->config->base.adjusted_mode.crtc_clock;
1002 }
1003
1004 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
1005                                              enum pipe pipe)
1006 {
1007         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1008         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1009
1010         return intel_crtc->config->cpu_transcoder;
1011 }
1012
1013 static bool pipe_dsl_stopped(struct drm_device *dev, enum pipe pipe)
1014 {
1015         struct drm_i915_private *dev_priv = dev->dev_private;
1016         u32 reg = PIPEDSL(pipe);
1017         u32 line1, line2;
1018         u32 line_mask;
1019
1020         if (IS_GEN2(dev))
1021                 line_mask = DSL_LINEMASK_GEN2;
1022         else
1023                 line_mask = DSL_LINEMASK_GEN3;
1024
1025         line1 = I915_READ(reg) & line_mask;
1026         mdelay(5);
1027         line2 = I915_READ(reg) & line_mask;
1028
1029         return line1 == line2;
1030 }
1031
1032 /*
1033  * intel_wait_for_pipe_off - wait for pipe to turn off
1034  * @crtc: crtc whose pipe to wait for
1035  *
1036  * After disabling a pipe, we can't wait for vblank in the usual way,
1037  * spinning on the vblank interrupt status bit, since we won't actually
1038  * see an interrupt when the pipe is disabled.
1039  *
1040  * On Gen4 and above:
1041  *   wait for the pipe register state bit to turn off
1042  *
1043  * Otherwise:
1044  *   wait for the display line value to settle (it usually
1045  *   ends up stopping at the start of the next frame).
1046  *
1047  */
1048 static void intel_wait_for_pipe_off(struct intel_crtc *crtc)
1049 {
1050         struct drm_device *dev = crtc->base.dev;
1051         struct drm_i915_private *dev_priv = dev->dev_private;
1052         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1053         enum pipe pipe = crtc->pipe;
1054
1055         if (INTEL_INFO(dev)->gen >= 4) {
1056                 int reg = PIPECONF(cpu_transcoder);
1057
1058                 /* Wait for the Pipe State to go off */
1059                 if (wait_for((I915_READ(reg) & I965_PIPECONF_ACTIVE) == 0,
1060                              100))
1061                         WARN(1, "pipe_off wait timed out\n");
1062         } else {
1063                 /* Wait for the display line to settle */
1064                 if (wait_for(pipe_dsl_stopped(dev, pipe), 100))
1065                         WARN(1, "pipe_off wait timed out\n");
1066         }
1067 }
1068
1069 /*
1070  * ibx_digital_port_connected - is the specified port connected?
1071  * @dev_priv: i915 private structure
1072  * @port: the port to test
1073  *
1074  * Returns true if @port is connected, false otherwise.
1075  */
1076 bool ibx_digital_port_connected(struct drm_i915_private *dev_priv,
1077                                 struct intel_digital_port *port)
1078 {
1079         u32 bit;
1080
1081         if (HAS_PCH_IBX(dev_priv->dev)) {
1082                 switch (port->port) {
1083                 case PORT_B:
1084                         bit = SDE_PORTB_HOTPLUG;
1085                         break;
1086                 case PORT_C:
1087                         bit = SDE_PORTC_HOTPLUG;
1088                         break;
1089                 case PORT_D:
1090                         bit = SDE_PORTD_HOTPLUG;
1091                         break;
1092                 default:
1093                         return true;
1094                 }
1095         } else {
1096                 switch (port->port) {
1097                 case PORT_B:
1098                         bit = SDE_PORTB_HOTPLUG_CPT;
1099                         break;
1100                 case PORT_C:
1101                         bit = SDE_PORTC_HOTPLUG_CPT;
1102                         break;
1103                 case PORT_D:
1104                         bit = SDE_PORTD_HOTPLUG_CPT;
1105                         break;
1106                 default:
1107                         return true;
1108                 }
1109         }
1110
1111         return I915_READ(SDEISR) & bit;
1112 }
1113
1114 static const char *state_string(bool enabled)
1115 {
1116         return enabled ? "on" : "off";
1117 }
1118
1119 /* Only for pre-ILK configs */
1120 void assert_pll(struct drm_i915_private *dev_priv,
1121                 enum pipe pipe, bool state)
1122 {
1123         int reg;
1124         u32 val;
1125         bool cur_state;
1126
1127         reg = DPLL(pipe);
1128         val = I915_READ(reg);
1129         cur_state = !!(val & DPLL_VCO_ENABLE);
1130         I915_STATE_WARN(cur_state != state,
1131              "PLL state assertion failure (expected %s, current %s)\n",
1132              state_string(state), state_string(cur_state));
1133 }
1134
1135 /* XXX: the dsi pll is shared between MIPI DSI ports */
1136 static void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1137 {
1138         u32 val;
1139         bool cur_state;
1140
1141         mutex_lock(&dev_priv->dpio_lock);
1142         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1143         mutex_unlock(&dev_priv->dpio_lock);
1144
1145         cur_state = val & DSI_PLL_VCO_EN;
1146         I915_STATE_WARN(cur_state != state,
1147              "DSI PLL state assertion failure (expected %s, current %s)\n",
1148              state_string(state), state_string(cur_state));
1149 }
1150 #define assert_dsi_pll_enabled(d) assert_dsi_pll(d, true)
1151 #define assert_dsi_pll_disabled(d) assert_dsi_pll(d, false)
1152
1153 struct intel_shared_dpll *
1154 intel_crtc_to_shared_dpll(struct intel_crtc *crtc)
1155 {
1156         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
1157
1158         if (crtc->config->shared_dpll < 0)
1159                 return NULL;
1160
1161         return &dev_priv->shared_dplls[crtc->config->shared_dpll];
1162 }
1163
1164 /* For ILK+ */
1165 void assert_shared_dpll(struct drm_i915_private *dev_priv,
1166                         struct intel_shared_dpll *pll,
1167                         bool state)
1168 {
1169         bool cur_state;
1170         struct intel_dpll_hw_state hw_state;
1171
1172         if (WARN (!pll,
1173                   "asserting DPLL %s with no DPLL\n", state_string(state)))
1174                 return;
1175
1176         cur_state = pll->get_hw_state(dev_priv, pll, &hw_state);
1177         I915_STATE_WARN(cur_state != state,
1178              "%s assertion failure (expected %s, current %s)\n",
1179              pll->name, state_string(state), state_string(cur_state));
1180 }
1181
1182 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1183                           enum pipe pipe, bool state)
1184 {
1185         int reg;
1186         u32 val;
1187         bool cur_state;
1188         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1189                                                                       pipe);
1190
1191         if (HAS_DDI(dev_priv->dev)) {
1192                 /* DDI does not have a specific FDI_TX register */
1193                 reg = TRANS_DDI_FUNC_CTL(cpu_transcoder);
1194                 val = I915_READ(reg);
1195                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1196         } else {
1197                 reg = FDI_TX_CTL(pipe);
1198                 val = I915_READ(reg);
1199                 cur_state = !!(val & FDI_TX_ENABLE);
1200         }
1201         I915_STATE_WARN(cur_state != state,
1202              "FDI TX state assertion failure (expected %s, current %s)\n",
1203              state_string(state), state_string(cur_state));
1204 }
1205 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1206 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1207
1208 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1209                           enum pipe pipe, bool state)
1210 {
1211         int reg;
1212         u32 val;
1213         bool cur_state;
1214
1215         reg = FDI_RX_CTL(pipe);
1216         val = I915_READ(reg);
1217         cur_state = !!(val & FDI_RX_ENABLE);
1218         I915_STATE_WARN(cur_state != state,
1219              "FDI RX state assertion failure (expected %s, current %s)\n",
1220              state_string(state), state_string(cur_state));
1221 }
1222 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1223 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1224
1225 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1226                                       enum pipe pipe)
1227 {
1228         int reg;
1229         u32 val;
1230
1231         /* ILK FDI PLL is always enabled */
1232         if (INTEL_INFO(dev_priv->dev)->gen == 5)
1233                 return;
1234
1235         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1236         if (HAS_DDI(dev_priv->dev))
1237                 return;
1238
1239         reg = FDI_TX_CTL(pipe);
1240         val = I915_READ(reg);
1241         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1242 }
1243
1244 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1245                        enum pipe pipe, bool state)
1246 {
1247         int reg;
1248         u32 val;
1249         bool cur_state;
1250
1251         reg = FDI_RX_CTL(pipe);
1252         val = I915_READ(reg);
1253         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1254         I915_STATE_WARN(cur_state != state,
1255              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1256              state_string(state), state_string(cur_state));
1257 }
1258
1259 void assert_panel_unlocked(struct drm_i915_private *dev_priv,
1260                            enum pipe pipe)
1261 {
1262         struct drm_device *dev = dev_priv->dev;
1263         int pp_reg;
1264         u32 val;
1265         enum pipe panel_pipe = PIPE_A;
1266         bool locked = true;
1267
1268         if (WARN_ON(HAS_DDI(dev)))
1269                 return;
1270
1271         if (HAS_PCH_SPLIT(dev)) {
1272                 u32 port_sel;
1273
1274                 pp_reg = PCH_PP_CONTROL;
1275                 port_sel = I915_READ(PCH_PP_ON_DELAYS) & PANEL_PORT_SELECT_MASK;
1276
1277                 if (port_sel == PANEL_PORT_SELECT_LVDS &&
1278                     I915_READ(PCH_LVDS) & LVDS_PIPEB_SELECT)
1279                         panel_pipe = PIPE_B;
1280                 /* XXX: else fix for eDP */
1281         } else if (IS_VALLEYVIEW(dev)) {
1282                 /* presumably write lock depends on pipe, not port select */
1283                 pp_reg = VLV_PIPE_PP_CONTROL(pipe);
1284                 panel_pipe = pipe;
1285         } else {
1286                 pp_reg = PP_CONTROL;
1287                 if (I915_READ(LVDS) & LVDS_PIPEB_SELECT)
1288                         panel_pipe = PIPE_B;
1289         }
1290
1291         val = I915_READ(pp_reg);
1292         if (!(val & PANEL_POWER_ON) ||
1293             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1294                 locked = false;
1295
1296         I915_STATE_WARN(panel_pipe == pipe && locked,
1297              "panel assertion failure, pipe %c regs locked\n",
1298              pipe_name(pipe));
1299 }
1300
1301 static void assert_cursor(struct drm_i915_private *dev_priv,
1302                           enum pipe pipe, bool state)
1303 {
1304         struct drm_device *dev = dev_priv->dev;
1305         bool cur_state;
1306
1307         if (IS_845G(dev) || IS_I865G(dev))
1308                 cur_state = I915_READ(_CURACNTR) & CURSOR_ENABLE;
1309         else
1310                 cur_state = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
1311
1312         I915_STATE_WARN(cur_state != state,
1313              "cursor on pipe %c assertion failure (expected %s, current %s)\n",
1314              pipe_name(pipe), state_string(state), state_string(cur_state));
1315 }
1316 #define assert_cursor_enabled(d, p) assert_cursor(d, p, true)
1317 #define assert_cursor_disabled(d, p) assert_cursor(d, p, false)
1318
1319 void assert_pipe(struct drm_i915_private *dev_priv,
1320                  enum pipe pipe, bool state)
1321 {
1322         int reg;
1323         u32 val;
1324         bool cur_state;
1325         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1326                                                                       pipe);
1327
1328         /* if we need the pipe quirk it must be always on */
1329         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1330             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1331                 state = true;
1332
1333         if (!intel_display_power_is_enabled(dev_priv,
1334                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder))) {
1335                 cur_state = false;
1336         } else {
1337                 reg = PIPECONF(cpu_transcoder);
1338                 val = I915_READ(reg);
1339                 cur_state = !!(val & PIPECONF_ENABLE);
1340         }
1341
1342         I915_STATE_WARN(cur_state != state,
1343              "pipe %c assertion failure (expected %s, current %s)\n",
1344              pipe_name(pipe), state_string(state), state_string(cur_state));
1345 }
1346
1347 static void assert_plane(struct drm_i915_private *dev_priv,
1348                          enum plane plane, bool state)
1349 {
1350         int reg;
1351         u32 val;
1352         bool cur_state;
1353
1354         reg = DSPCNTR(plane);
1355         val = I915_READ(reg);
1356         cur_state = !!(val & DISPLAY_PLANE_ENABLE);
1357         I915_STATE_WARN(cur_state != state,
1358              "plane %c assertion failure (expected %s, current %s)\n",
1359              plane_name(plane), state_string(state), state_string(cur_state));
1360 }
1361
1362 #define assert_plane_enabled(d, p) assert_plane(d, p, true)
1363 #define assert_plane_disabled(d, p) assert_plane(d, p, false)
1364
1365 static void assert_planes_disabled(struct drm_i915_private *dev_priv,
1366                                    enum pipe pipe)
1367 {
1368         struct drm_device *dev = dev_priv->dev;
1369         int reg, i;
1370         u32 val;
1371         int cur_pipe;
1372
1373         /* Primary planes are fixed to pipes on gen4+ */
1374         if (INTEL_INFO(dev)->gen >= 4) {
1375                 reg = DSPCNTR(pipe);
1376                 val = I915_READ(reg);
1377                 I915_STATE_WARN(val & DISPLAY_PLANE_ENABLE,
1378                      "plane %c assertion failure, should be disabled but not\n",
1379                      plane_name(pipe));
1380                 return;
1381         }
1382
1383         /* Need to check both planes against the pipe */
1384         for_each_pipe(dev_priv, i) {
1385                 reg = DSPCNTR(i);
1386                 val = I915_READ(reg);
1387                 cur_pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
1388                         DISPPLANE_SEL_PIPE_SHIFT;
1389                 I915_STATE_WARN((val & DISPLAY_PLANE_ENABLE) && pipe == cur_pipe,
1390                      "plane %c assertion failure, should be off on pipe %c but is still active\n",
1391                      plane_name(i), pipe_name(pipe));
1392         }
1393 }
1394
1395 static void assert_sprites_disabled(struct drm_i915_private *dev_priv,
1396                                     enum pipe pipe)
1397 {
1398         struct drm_device *dev = dev_priv->dev;
1399         int reg, sprite;
1400         u32 val;
1401
1402         if (INTEL_INFO(dev)->gen >= 9) {
1403                 for_each_sprite(dev_priv, pipe, sprite) {
1404                         val = I915_READ(PLANE_CTL(pipe, sprite));
1405                         I915_STATE_WARN(val & PLANE_CTL_ENABLE,
1406                              "plane %d assertion failure, should be off on pipe %c but is still active\n",
1407                              sprite, pipe_name(pipe));
1408                 }
1409         } else if (IS_VALLEYVIEW(dev)) {
1410                 for_each_sprite(dev_priv, pipe, sprite) {
1411                         reg = SPCNTR(pipe, sprite);
1412                         val = I915_READ(reg);
1413                         I915_STATE_WARN(val & SP_ENABLE,
1414                              "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1415                              sprite_name(pipe, sprite), pipe_name(pipe));
1416                 }
1417         } else if (INTEL_INFO(dev)->gen >= 7) {
1418                 reg = SPRCTL(pipe);
1419                 val = I915_READ(reg);
1420                 I915_STATE_WARN(val & SPRITE_ENABLE,
1421                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1422                      plane_name(pipe), pipe_name(pipe));
1423         } else if (INTEL_INFO(dev)->gen >= 5) {
1424                 reg = DVSCNTR(pipe);
1425                 val = I915_READ(reg);
1426                 I915_STATE_WARN(val & DVS_ENABLE,
1427                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1428                      plane_name(pipe), pipe_name(pipe));
1429         }
1430 }
1431
1432 static void assert_vblank_disabled(struct drm_crtc *crtc)
1433 {
1434         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1435                 drm_crtc_vblank_put(crtc);
1436 }
1437
1438 static void ibx_assert_pch_refclk_enabled(struct drm_i915_private *dev_priv)
1439 {
1440         u32 val;
1441         bool enabled;
1442
1443         I915_STATE_WARN_ON(!(HAS_PCH_IBX(dev_priv->dev) || HAS_PCH_CPT(dev_priv->dev)));
1444
1445         val = I915_READ(PCH_DREF_CONTROL);
1446         enabled = !!(val & (DREF_SSC_SOURCE_MASK | DREF_NONSPREAD_SOURCE_MASK |
1447                             DREF_SUPERSPREAD_SOURCE_MASK));
1448         I915_STATE_WARN(!enabled, "PCH refclk assertion failure, should be active but is disabled\n");
1449 }
1450
1451 static void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1452                                            enum pipe pipe)
1453 {
1454         int reg;
1455         u32 val;
1456         bool enabled;
1457
1458         reg = PCH_TRANSCONF(pipe);
1459         val = I915_READ(reg);
1460         enabled = !!(val & TRANS_ENABLE);
1461         I915_STATE_WARN(enabled,
1462              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1463              pipe_name(pipe));
1464 }
1465
1466 static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1467                             enum pipe pipe, u32 port_sel, u32 val)
1468 {
1469         if ((val & DP_PORT_EN) == 0)
1470                 return false;
1471
1472         if (HAS_PCH_CPT(dev_priv->dev)) {
1473                 u32     trans_dp_ctl_reg = TRANS_DP_CTL(pipe);
1474                 u32     trans_dp_ctl = I915_READ(trans_dp_ctl_reg);
1475                 if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1476                         return false;
1477         } else if (IS_CHERRYVIEW(dev_priv->dev)) {
1478                 if ((val & DP_PIPE_MASK_CHV) != DP_PIPE_SELECT_CHV(pipe))
1479                         return false;
1480         } else {
1481                 if ((val & DP_PIPE_MASK) != (pipe << 30))
1482                         return false;
1483         }
1484         return true;
1485 }
1486
1487 static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1488                               enum pipe pipe, u32 val)
1489 {
1490         if ((val & SDVO_ENABLE) == 0)
1491                 return false;
1492
1493         if (HAS_PCH_CPT(dev_priv->dev)) {
1494                 if ((val & SDVO_PIPE_SEL_MASK_CPT) != SDVO_PIPE_SEL_CPT(pipe))
1495                         return false;
1496         } else if (IS_CHERRYVIEW(dev_priv->dev)) {
1497                 if ((val & SDVO_PIPE_SEL_MASK_CHV) != SDVO_PIPE_SEL_CHV(pipe))
1498                         return false;
1499         } else {
1500                 if ((val & SDVO_PIPE_SEL_MASK) != SDVO_PIPE_SEL(pipe))
1501                         return false;
1502         }
1503         return true;
1504 }
1505
1506 static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1507                               enum pipe pipe, u32 val)
1508 {
1509         if ((val & LVDS_PORT_EN) == 0)
1510                 return false;
1511
1512         if (HAS_PCH_CPT(dev_priv->dev)) {
1513                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1514                         return false;
1515         } else {
1516                 if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1517                         return false;
1518         }
1519         return true;
1520 }
1521
1522 static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1523                               enum pipe pipe, u32 val)
1524 {
1525         if ((val & ADPA_DAC_ENABLE) == 0)
1526                 return false;
1527         if (HAS_PCH_CPT(dev_priv->dev)) {
1528                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1529                         return false;
1530         } else {
1531                 if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1532                         return false;
1533         }
1534         return true;
1535 }
1536
1537 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1538                                    enum pipe pipe, int reg, u32 port_sel)
1539 {
1540         u32 val = I915_READ(reg);
1541         I915_STATE_WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1542              "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1543              reg, pipe_name(pipe));
1544
1545         I915_STATE_WARN(HAS_PCH_IBX(dev_priv->dev) && (val & DP_PORT_EN) == 0
1546              && (val & DP_PIPEB_SELECT),
1547              "IBX PCH dp port still using transcoder B\n");
1548 }
1549
1550 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1551                                      enum pipe pipe, int reg)
1552 {
1553         u32 val = I915_READ(reg);
1554         I915_STATE_WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1555              "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1556              reg, pipe_name(pipe));
1557
1558         I915_STATE_WARN(HAS_PCH_IBX(dev_priv->dev) && (val & SDVO_ENABLE) == 0
1559              && (val & SDVO_PIPE_B_SELECT),
1560              "IBX PCH hdmi port still using transcoder B\n");
1561 }
1562
1563 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1564                                       enum pipe pipe)
1565 {
1566         int reg;
1567         u32 val;
1568
1569         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1570         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1571         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1572
1573         reg = PCH_ADPA;
1574         val = I915_READ(reg);
1575         I915_STATE_WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1576              "PCH VGA enabled on transcoder %c, should be disabled\n",
1577              pipe_name(pipe));
1578
1579         reg = PCH_LVDS;
1580         val = I915_READ(reg);
1581         I915_STATE_WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1582              "PCH LVDS enabled on transcoder %c, should be disabled\n",
1583              pipe_name(pipe));
1584
1585         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIB);
1586         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIC);
1587         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMID);
1588 }
1589
1590 static void intel_init_dpio(struct drm_device *dev)
1591 {
1592         struct drm_i915_private *dev_priv = dev->dev_private;
1593
1594         if (!IS_VALLEYVIEW(dev))
1595                 return;
1596
1597         /*
1598          * IOSF_PORT_DPIO is used for VLV x2 PHY (DP/HDMI B and C),
1599          * CHV x1 PHY (DP/HDMI D)
1600          * IOSF_PORT_DPIO_2 is used for CHV x2 PHY (DP/HDMI B and C)
1601          */
1602         if (IS_CHERRYVIEW(dev)) {
1603                 DPIO_PHY_IOSF_PORT(DPIO_PHY0) = IOSF_PORT_DPIO_2;
1604                 DPIO_PHY_IOSF_PORT(DPIO_PHY1) = IOSF_PORT_DPIO;
1605         } else {
1606                 DPIO_PHY_IOSF_PORT(DPIO_PHY0) = IOSF_PORT_DPIO;
1607         }
1608 }
1609
1610 static void vlv_enable_pll(struct intel_crtc *crtc,
1611                            const struct intel_crtc_state *pipe_config)
1612 {
1613         struct drm_device *dev = crtc->base.dev;
1614         struct drm_i915_private *dev_priv = dev->dev_private;
1615         int reg = DPLL(crtc->pipe);
1616         u32 dpll = pipe_config->dpll_hw_state.dpll;
1617
1618         assert_pipe_disabled(dev_priv, crtc->pipe);
1619
1620         /* No really, not for ILK+ */
1621         BUG_ON(!IS_VALLEYVIEW(dev_priv->dev));
1622
1623         /* PLL is protected by panel, make sure we can write it */
1624         if (IS_MOBILE(dev_priv->dev))
1625                 assert_panel_unlocked(dev_priv, crtc->pipe);
1626
1627         I915_WRITE(reg, dpll);
1628         POSTING_READ(reg);
1629         udelay(150);
1630
1631         if (wait_for(((I915_READ(reg) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1632                 DRM_ERROR("DPLL %d failed to lock\n", crtc->pipe);
1633
1634         I915_WRITE(DPLL_MD(crtc->pipe), pipe_config->dpll_hw_state.dpll_md);
1635         POSTING_READ(DPLL_MD(crtc->pipe));
1636
1637         /* We do this three times for luck */
1638         I915_WRITE(reg, dpll);
1639         POSTING_READ(reg);
1640         udelay(150); /* wait for warmup */
1641         I915_WRITE(reg, dpll);
1642         POSTING_READ(reg);
1643         udelay(150); /* wait for warmup */
1644         I915_WRITE(reg, dpll);
1645         POSTING_READ(reg);
1646         udelay(150); /* wait for warmup */
1647 }
1648
1649 static void chv_enable_pll(struct intel_crtc *crtc,
1650                            const struct intel_crtc_state *pipe_config)
1651 {
1652         struct drm_device *dev = crtc->base.dev;
1653         struct drm_i915_private *dev_priv = dev->dev_private;
1654         int pipe = crtc->pipe;
1655         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1656         u32 tmp;
1657
1658         assert_pipe_disabled(dev_priv, crtc->pipe);
1659
1660         BUG_ON(!IS_CHERRYVIEW(dev_priv->dev));
1661
1662         mutex_lock(&dev_priv->dpio_lock);
1663
1664         /* Enable back the 10bit clock to display controller */
1665         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1666         tmp |= DPIO_DCLKP_EN;
1667         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1668
1669         /*
1670          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1671          */
1672         udelay(1);
1673
1674         /* Enable PLL */
1675         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1676
1677         /* Check PLL is locked */
1678         if (wait_for(((I915_READ(DPLL(pipe)) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1679                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1680
1681         /* not sure when this should be written */
1682         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1683         POSTING_READ(DPLL_MD(pipe));
1684
1685         mutex_unlock(&dev_priv->dpio_lock);
1686 }
1687
1688 static int intel_num_dvo_pipes(struct drm_device *dev)
1689 {
1690         struct intel_crtc *crtc;
1691         int count = 0;
1692
1693         for_each_intel_crtc(dev, crtc)
1694                 count += crtc->active &&
1695                         intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO);
1696
1697         return count;
1698 }
1699
1700 static void i9xx_enable_pll(struct intel_crtc *crtc)
1701 {
1702         struct drm_device *dev = crtc->base.dev;
1703         struct drm_i915_private *dev_priv = dev->dev_private;
1704         int reg = DPLL(crtc->pipe);
1705         u32 dpll = crtc->config->dpll_hw_state.dpll;
1706
1707         assert_pipe_disabled(dev_priv, crtc->pipe);
1708
1709         /* No really, not for ILK+ */
1710         BUG_ON(INTEL_INFO(dev)->gen >= 5);
1711
1712         /* PLL is protected by panel, make sure we can write it */
1713         if (IS_MOBILE(dev) && !IS_I830(dev))
1714                 assert_panel_unlocked(dev_priv, crtc->pipe);
1715
1716         /* Enable DVO 2x clock on both PLLs if necessary */
1717         if (IS_I830(dev) && intel_num_dvo_pipes(dev) > 0) {
1718                 /*
1719                  * It appears to be important that we don't enable this
1720                  * for the current pipe before otherwise configuring the
1721                  * PLL. No idea how this should be handled if multiple
1722                  * DVO outputs are enabled simultaneosly.
1723                  */
1724                 dpll |= DPLL_DVO_2X_MODE;
1725                 I915_WRITE(DPLL(!crtc->pipe),
1726                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1727         }
1728
1729         /* Wait for the clocks to stabilize. */
1730         POSTING_READ(reg);
1731         udelay(150);
1732
1733         if (INTEL_INFO(dev)->gen >= 4) {
1734                 I915_WRITE(DPLL_MD(crtc->pipe),
1735                            crtc->config->dpll_hw_state.dpll_md);
1736         } else {
1737                 /* The pixel multiplier can only be updated once the
1738                  * DPLL is enabled and the clocks are stable.
1739                  *
1740                  * So write it again.
1741                  */
1742                 I915_WRITE(reg, dpll);
1743         }
1744
1745         /* We do this three times for luck */
1746         I915_WRITE(reg, dpll);
1747         POSTING_READ(reg);
1748         udelay(150); /* wait for warmup */
1749         I915_WRITE(reg, dpll);
1750         POSTING_READ(reg);
1751         udelay(150); /* wait for warmup */
1752         I915_WRITE(reg, dpll);
1753         POSTING_READ(reg);
1754         udelay(150); /* wait for warmup */
1755 }
1756
1757 /**
1758  * i9xx_disable_pll - disable a PLL
1759  * @dev_priv: i915 private structure
1760  * @pipe: pipe PLL to disable
1761  *
1762  * Disable the PLL for @pipe, making sure the pipe is off first.
1763  *
1764  * Note!  This is for pre-ILK only.
1765  */
1766 static void i9xx_disable_pll(struct intel_crtc *crtc)
1767 {
1768         struct drm_device *dev = crtc->base.dev;
1769         struct drm_i915_private *dev_priv = dev->dev_private;
1770         enum pipe pipe = crtc->pipe;
1771
1772         /* Disable DVO 2x clock on both PLLs if necessary */
1773         if (IS_I830(dev) &&
1774             intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO) &&
1775             intel_num_dvo_pipes(dev) == 1) {
1776                 I915_WRITE(DPLL(PIPE_B),
1777                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1778                 I915_WRITE(DPLL(PIPE_A),
1779                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1780         }
1781
1782         /* Don't disable pipe or pipe PLLs if needed */
1783         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1784             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1785                 return;
1786
1787         /* Make sure the pipe isn't still relying on us */
1788         assert_pipe_disabled(dev_priv, pipe);
1789
1790         I915_WRITE(DPLL(pipe), 0);
1791         POSTING_READ(DPLL(pipe));
1792 }
1793
1794 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1795 {
1796         u32 val = 0;
1797
1798         /* Make sure the pipe isn't still relying on us */
1799         assert_pipe_disabled(dev_priv, pipe);
1800
1801         /*
1802          * Leave integrated clock source and reference clock enabled for pipe B.
1803          * The latter is needed for VGA hotplug / manual detection.
1804          */
1805         if (pipe == PIPE_B)
1806                 val = DPLL_INTEGRATED_CRI_CLK_VLV | DPLL_REFA_CLK_ENABLE_VLV;
1807         I915_WRITE(DPLL(pipe), val);
1808         POSTING_READ(DPLL(pipe));
1809
1810 }
1811
1812 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1813 {
1814         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1815         u32 val;
1816
1817         /* Make sure the pipe isn't still relying on us */
1818         assert_pipe_disabled(dev_priv, pipe);
1819
1820         /* Set PLL en = 0 */
1821         val = DPLL_SSC_REF_CLOCK_CHV | DPLL_REFA_CLK_ENABLE_VLV;
1822         if (pipe != PIPE_A)
1823                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1824         I915_WRITE(DPLL(pipe), val);
1825         POSTING_READ(DPLL(pipe));
1826
1827         mutex_lock(&dev_priv->dpio_lock);
1828
1829         /* Disable 10bit clock to display controller */
1830         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1831         val &= ~DPIO_DCLKP_EN;
1832         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1833
1834         /* disable left/right clock distribution */
1835         if (pipe != PIPE_B) {
1836                 val = vlv_dpio_read(dev_priv, pipe, _CHV_CMN_DW5_CH0);
1837                 val &= ~(CHV_BUFLEFTENA1_MASK | CHV_BUFRIGHTENA1_MASK);
1838                 vlv_dpio_write(dev_priv, pipe, _CHV_CMN_DW5_CH0, val);
1839         } else {
1840                 val = vlv_dpio_read(dev_priv, pipe, _CHV_CMN_DW1_CH1);
1841                 val &= ~(CHV_BUFLEFTENA2_MASK | CHV_BUFRIGHTENA2_MASK);
1842                 vlv_dpio_write(dev_priv, pipe, _CHV_CMN_DW1_CH1, val);
1843         }
1844
1845         mutex_unlock(&dev_priv->dpio_lock);
1846 }
1847
1848 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1849                 struct intel_digital_port *dport)
1850 {
1851         u32 port_mask;
1852         int dpll_reg;
1853
1854         switch (dport->port) {
1855         case PORT_B:
1856                 port_mask = DPLL_PORTB_READY_MASK;
1857                 dpll_reg = DPLL(0);
1858                 break;
1859         case PORT_C:
1860                 port_mask = DPLL_PORTC_READY_MASK;
1861                 dpll_reg = DPLL(0);
1862                 break;
1863         case PORT_D:
1864                 port_mask = DPLL_PORTD_READY_MASK;
1865                 dpll_reg = DPIO_PHY_STATUS;
1866                 break;
1867         default:
1868                 BUG();
1869         }
1870
1871         if (wait_for((I915_READ(dpll_reg) & port_mask) == 0, 1000))
1872                 WARN(1, "timed out waiting for port %c ready: 0x%08x\n",
1873                      port_name(dport->port), I915_READ(dpll_reg));
1874 }
1875
1876 static void intel_prepare_shared_dpll(struct intel_crtc *crtc)
1877 {
1878         struct drm_device *dev = crtc->base.dev;
1879         struct drm_i915_private *dev_priv = dev->dev_private;
1880         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1881
1882         if (WARN_ON(pll == NULL))
1883                 return;
1884
1885         WARN_ON(!pll->config.crtc_mask);
1886         if (pll->active == 0) {
1887                 DRM_DEBUG_DRIVER("setting up %s\n", pll->name);
1888                 WARN_ON(pll->on);
1889                 assert_shared_dpll_disabled(dev_priv, pll);
1890
1891                 pll->mode_set(dev_priv, pll);
1892         }
1893 }
1894
1895 /**
1896  * intel_enable_shared_dpll - enable PCH PLL
1897  * @dev_priv: i915 private structure
1898  * @pipe: pipe PLL to enable
1899  *
1900  * The PCH PLL needs to be enabled before the PCH transcoder, since it
1901  * drives the transcoder clock.
1902  */
1903 static void intel_enable_shared_dpll(struct intel_crtc *crtc)
1904 {
1905         struct drm_device *dev = crtc->base.dev;
1906         struct drm_i915_private *dev_priv = dev->dev_private;
1907         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1908
1909         if (WARN_ON(pll == NULL))
1910                 return;
1911
1912         if (WARN_ON(pll->config.crtc_mask == 0))
1913                 return;
1914
1915         DRM_DEBUG_KMS("enable %s (active %d, on? %d) for crtc %d\n",
1916                       pll->name, pll->active, pll->on,
1917                       crtc->base.base.id);
1918
1919         if (pll->active++) {
1920                 WARN_ON(!pll->on);
1921                 assert_shared_dpll_enabled(dev_priv, pll);
1922                 return;
1923         }
1924         WARN_ON(pll->on);
1925
1926         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
1927
1928         DRM_DEBUG_KMS("enabling %s\n", pll->name);
1929         pll->enable(dev_priv, pll);
1930         pll->on = true;
1931 }
1932
1933 static void intel_disable_shared_dpll(struct intel_crtc *crtc)
1934 {
1935         struct drm_device *dev = crtc->base.dev;
1936         struct drm_i915_private *dev_priv = dev->dev_private;
1937         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1938
1939         /* PCH only available on ILK+ */
1940         BUG_ON(INTEL_INFO(dev)->gen < 5);
1941         if (WARN_ON(pll == NULL))
1942                return;
1943
1944         if (WARN_ON(pll->config.crtc_mask == 0))
1945                 return;
1946
1947         DRM_DEBUG_KMS("disable %s (active %d, on? %d) for crtc %d\n",
1948                       pll->name, pll->active, pll->on,
1949                       crtc->base.base.id);
1950
1951         if (WARN_ON(pll->active == 0)) {
1952                 assert_shared_dpll_disabled(dev_priv, pll);
1953                 return;
1954         }
1955
1956         assert_shared_dpll_enabled(dev_priv, pll);
1957         WARN_ON(!pll->on);
1958         if (--pll->active)
1959                 return;
1960
1961         DRM_DEBUG_KMS("disabling %s\n", pll->name);
1962         pll->disable(dev_priv, pll);
1963         pll->on = false;
1964
1965         intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS);
1966 }
1967
1968 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1969                                            enum pipe pipe)
1970 {
1971         struct drm_device *dev = dev_priv->dev;
1972         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1973         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1974         uint32_t reg, val, pipeconf_val;
1975
1976         /* PCH only available on ILK+ */
1977         BUG_ON(!HAS_PCH_SPLIT(dev));
1978
1979         /* Make sure PCH DPLL is enabled */
1980         assert_shared_dpll_enabled(dev_priv,
1981                                    intel_crtc_to_shared_dpll(intel_crtc));
1982
1983         /* FDI must be feeding us bits for PCH ports */
1984         assert_fdi_tx_enabled(dev_priv, pipe);
1985         assert_fdi_rx_enabled(dev_priv, pipe);
1986
1987         if (HAS_PCH_CPT(dev)) {
1988                 /* Workaround: Set the timing override bit before enabling the
1989                  * pch transcoder. */
1990                 reg = TRANS_CHICKEN2(pipe);
1991                 val = I915_READ(reg);
1992                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1993                 I915_WRITE(reg, val);
1994         }
1995
1996         reg = PCH_TRANSCONF(pipe);
1997         val = I915_READ(reg);
1998         pipeconf_val = I915_READ(PIPECONF(pipe));
1999
2000         if (HAS_PCH_IBX(dev_priv->dev)) {
2001                 /*
2002                  * make the BPC in transcoder be consistent with
2003                  * that in pipeconf reg.
2004                  */
2005                 val &= ~PIPECONF_BPC_MASK;
2006                 val |= pipeconf_val & PIPECONF_BPC_MASK;
2007         }
2008
2009         val &= ~TRANS_INTERLACE_MASK;
2010         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
2011                 if (HAS_PCH_IBX(dev_priv->dev) &&
2012                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
2013                         val |= TRANS_LEGACY_INTERLACED_ILK;
2014                 else
2015                         val |= TRANS_INTERLACED;
2016         else
2017                 val |= TRANS_PROGRESSIVE;
2018
2019         I915_WRITE(reg, val | TRANS_ENABLE);
2020         if (wait_for(I915_READ(reg) & TRANS_STATE_ENABLE, 100))
2021                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
2022 }
2023
2024 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
2025                                       enum transcoder cpu_transcoder)
2026 {
2027         u32 val, pipeconf_val;
2028
2029         /* PCH only available on ILK+ */
2030         BUG_ON(!HAS_PCH_SPLIT(dev_priv->dev));
2031
2032         /* FDI must be feeding us bits for PCH ports */
2033         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
2034         assert_fdi_rx_enabled(dev_priv, TRANSCODER_A);
2035
2036         /* Workaround: set timing override bit. */
2037         val = I915_READ(_TRANSA_CHICKEN2);
2038         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
2039         I915_WRITE(_TRANSA_CHICKEN2, val);
2040
2041         val = TRANS_ENABLE;
2042         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
2043
2044         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
2045             PIPECONF_INTERLACED_ILK)
2046                 val |= TRANS_INTERLACED;
2047         else
2048                 val |= TRANS_PROGRESSIVE;
2049
2050         I915_WRITE(LPT_TRANSCONF, val);
2051         if (wait_for(I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE, 100))
2052                 DRM_ERROR("Failed to enable PCH transcoder\n");
2053 }
2054
2055 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
2056                                             enum pipe pipe)
2057 {
2058         struct drm_device *dev = dev_priv->dev;
2059         uint32_t reg, val;
2060
2061         /* FDI relies on the transcoder */
2062         assert_fdi_tx_disabled(dev_priv, pipe);
2063         assert_fdi_rx_disabled(dev_priv, pipe);
2064
2065         /* Ports must be off as well */
2066         assert_pch_ports_disabled(dev_priv, pipe);
2067
2068         reg = PCH_TRANSCONF(pipe);
2069         val = I915_READ(reg);
2070         val &= ~TRANS_ENABLE;
2071         I915_WRITE(reg, val);
2072         /* wait for PCH transcoder off, transcoder state */
2073         if (wait_for((I915_READ(reg) & TRANS_STATE_ENABLE) == 0, 50))
2074                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
2075
2076         if (!HAS_PCH_IBX(dev)) {
2077                 /* Workaround: Clear the timing override chicken bit again. */
2078                 reg = TRANS_CHICKEN2(pipe);
2079                 val = I915_READ(reg);
2080                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
2081                 I915_WRITE(reg, val);
2082         }
2083 }
2084
2085 static void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
2086 {
2087         u32 val;
2088
2089         val = I915_READ(LPT_TRANSCONF);
2090         val &= ~TRANS_ENABLE;
2091         I915_WRITE(LPT_TRANSCONF, val);
2092         /* wait for PCH transcoder off, transcoder state */
2093         if (wait_for((I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE) == 0, 50))
2094                 DRM_ERROR("Failed to disable PCH transcoder\n");
2095
2096         /* Workaround: clear timing override bit. */
2097         val = I915_READ(_TRANSA_CHICKEN2);
2098         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
2099         I915_WRITE(_TRANSA_CHICKEN2, val);
2100 }
2101
2102 /**
2103  * intel_enable_pipe - enable a pipe, asserting requirements
2104  * @crtc: crtc responsible for the pipe
2105  *
2106  * Enable @crtc's pipe, making sure that various hardware specific requirements
2107  * are met, if applicable, e.g. PLL enabled, LVDS pairs enabled, etc.
2108  */
2109 static void intel_enable_pipe(struct intel_crtc *crtc)
2110 {
2111         struct drm_device *dev = crtc->base.dev;
2112         struct drm_i915_private *dev_priv = dev->dev_private;
2113         enum pipe pipe = crtc->pipe;
2114         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
2115                                                                       pipe);
2116         enum pipe pch_transcoder;
2117         int reg;
2118         u32 val;
2119
2120         assert_planes_disabled(dev_priv, pipe);
2121         assert_cursor_disabled(dev_priv, pipe);
2122         assert_sprites_disabled(dev_priv, pipe);
2123
2124         if (HAS_PCH_LPT(dev_priv->dev))
2125                 pch_transcoder = TRANSCODER_A;
2126         else
2127                 pch_transcoder = pipe;
2128
2129         /*
2130          * A pipe without a PLL won't actually be able to drive bits from
2131          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
2132          * need the check.
2133          */
2134         if (HAS_GMCH_DISPLAY(dev_priv->dev))
2135                 if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DSI))
2136                         assert_dsi_pll_enabled(dev_priv);
2137                 else
2138                         assert_pll_enabled(dev_priv, pipe);
2139         else {
2140                 if (crtc->config->has_pch_encoder) {
2141                         /* if driving the PCH, we need FDI enabled */
2142                         assert_fdi_rx_pll_enabled(dev_priv, pch_transcoder);
2143                         assert_fdi_tx_pll_enabled(dev_priv,
2144                                                   (enum pipe) cpu_transcoder);
2145                 }
2146                 /* FIXME: assert CPU port conditions for SNB+ */
2147         }
2148
2149         reg = PIPECONF(cpu_transcoder);
2150         val = I915_READ(reg);
2151         if (val & PIPECONF_ENABLE) {
2152                 WARN_ON(!((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
2153                           (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE)));
2154                 return;
2155         }
2156
2157         I915_WRITE(reg, val | PIPECONF_ENABLE);
2158         POSTING_READ(reg);
2159 }
2160
2161 /**
2162  * intel_disable_pipe - disable a pipe, asserting requirements
2163  * @crtc: crtc whose pipes is to be disabled
2164  *
2165  * Disable the pipe of @crtc, making sure that various hardware
2166  * specific requirements are met, if applicable, e.g. plane
2167  * disabled, panel fitter off, etc.
2168  *
2169  * Will wait until the pipe has shut down before returning.
2170  */
2171 static void intel_disable_pipe(struct intel_crtc *crtc)
2172 {
2173         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
2174         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
2175         enum pipe pipe = crtc->pipe;
2176         int reg;
2177         u32 val;
2178
2179         /*
2180          * Make sure planes won't keep trying to pump pixels to us,
2181          * or we might hang the display.
2182          */
2183         assert_planes_disabled(dev_priv, pipe);
2184         assert_cursor_disabled(dev_priv, pipe);
2185         assert_sprites_disabled(dev_priv, pipe);
2186
2187         reg = PIPECONF(cpu_transcoder);
2188         val = I915_READ(reg);
2189         if ((val & PIPECONF_ENABLE) == 0)
2190                 return;
2191
2192         /*
2193          * Double wide has implications for planes
2194          * so best keep it disabled when not needed.
2195          */
2196         if (crtc->config->double_wide)
2197                 val &= ~PIPECONF_DOUBLE_WIDE;
2198
2199         /* Don't disable pipe or pipe PLLs if needed */
2200         if (!(pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) &&
2201             !(pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
2202                 val &= ~PIPECONF_ENABLE;
2203
2204         I915_WRITE(reg, val);
2205         if ((val & PIPECONF_ENABLE) == 0)
2206                 intel_wait_for_pipe_off(crtc);
2207 }
2208
2209 /*
2210  * Plane regs are double buffered, going from enabled->disabled needs a
2211  * trigger in order to latch.  The display address reg provides this.
2212  */
2213 void intel_flush_primary_plane(struct drm_i915_private *dev_priv,
2214                                enum plane plane)
2215 {
2216         struct drm_device *dev = dev_priv->dev;
2217         u32 reg = INTEL_INFO(dev)->gen >= 4 ? DSPSURF(plane) : DSPADDR(plane);
2218
2219         I915_WRITE(reg, I915_READ(reg));
2220         POSTING_READ(reg);
2221 }
2222
2223 /**
2224  * intel_enable_primary_hw_plane - enable the primary plane on a given pipe
2225  * @plane:  plane to be enabled
2226  * @crtc: crtc for the plane
2227  *
2228  * Enable @plane on @crtc, making sure that the pipe is running first.
2229  */
2230 static void intel_enable_primary_hw_plane(struct drm_plane *plane,
2231                                           struct drm_crtc *crtc)
2232 {
2233         struct drm_device *dev = plane->dev;
2234         struct drm_i915_private *dev_priv = dev->dev_private;
2235         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2236
2237         /* If the pipe isn't enabled, we can't pump pixels and may hang */
2238         assert_pipe_enabled(dev_priv, intel_crtc->pipe);
2239
2240         if (intel_crtc->primary_enabled)
2241                 return;
2242
2243         intel_crtc->primary_enabled = true;
2244
2245         dev_priv->display.update_primary_plane(crtc, plane->fb,
2246                                                crtc->x, crtc->y);
2247
2248         /*
2249          * BDW signals flip done immediately if the plane
2250          * is disabled, even if the plane enable is already
2251          * armed to occur at the next vblank :(
2252          */
2253         if (IS_BROADWELL(dev))
2254                 intel_wait_for_vblank(dev, intel_crtc->pipe);
2255 }
2256
2257 /**
2258  * intel_disable_primary_hw_plane - disable the primary hardware plane
2259  * @plane: plane to be disabled
2260  * @crtc: crtc for the plane
2261  *
2262  * Disable @plane on @crtc, making sure that the pipe is running first.
2263  */
2264 static void intel_disable_primary_hw_plane(struct drm_plane *plane,
2265                                            struct drm_crtc *crtc)
2266 {
2267         struct drm_device *dev = plane->dev;
2268         struct drm_i915_private *dev_priv = dev->dev_private;
2269         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2270
2271         if (WARN_ON(!intel_crtc->active))
2272                 return;
2273
2274         if (!intel_crtc->primary_enabled)
2275                 return;
2276
2277         intel_crtc->primary_enabled = false;
2278
2279         dev_priv->display.update_primary_plane(crtc, plane->fb,
2280                                                crtc->x, crtc->y);
2281 }
2282
2283 static bool need_vtd_wa(struct drm_device *dev)
2284 {
2285 #ifdef CONFIG_INTEL_IOMMU
2286         if (INTEL_INFO(dev)->gen >= 6 && intel_iommu_gfx_mapped)
2287                 return true;
2288 #endif
2289         return false;
2290 }
2291
2292 unsigned int
2293 intel_tile_height(struct drm_device *dev, uint32_t pixel_format,
2294                   uint64_t fb_format_modifier)
2295 {
2296         unsigned int tile_height;
2297         uint32_t pixel_bytes;
2298
2299         switch (fb_format_modifier) {
2300         case DRM_FORMAT_MOD_NONE:
2301                 tile_height = 1;
2302                 break;
2303         case I915_FORMAT_MOD_X_TILED:
2304                 tile_height = IS_GEN2(dev) ? 16 : 8;
2305                 break;
2306         case I915_FORMAT_MOD_Y_TILED:
2307                 tile_height = 32;
2308                 break;
2309         case I915_FORMAT_MOD_Yf_TILED:
2310                 pixel_bytes = drm_format_plane_cpp(pixel_format, 0);
2311                 switch (pixel_bytes) {
2312                 default:
2313                 case 1:
2314                         tile_height = 64;
2315                         break;
2316                 case 2:
2317                 case 4:
2318                         tile_height = 32;
2319                         break;
2320                 case 8:
2321                         tile_height = 16;
2322                         break;
2323                 case 16:
2324                         WARN_ONCE(1,
2325                                   "128-bit pixels are not supported for display!");
2326                         tile_height = 16;
2327                         break;
2328                 }
2329                 break;
2330         default:
2331                 MISSING_CASE(fb_format_modifier);
2332                 tile_height = 1;
2333                 break;
2334         }
2335
2336         return tile_height;
2337 }
2338
2339 unsigned int
2340 intel_fb_align_height(struct drm_device *dev, unsigned int height,
2341                       uint32_t pixel_format, uint64_t fb_format_modifier)
2342 {
2343         return ALIGN(height, intel_tile_height(dev, pixel_format,
2344                                                fb_format_modifier));
2345 }
2346
2347 static int
2348 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view, struct drm_framebuffer *fb,
2349                         const struct drm_plane_state *plane_state)
2350 {
2351         struct intel_rotation_info *info = &view->rotation_info;
2352
2353         *view = i915_ggtt_view_normal;
2354
2355         if (!plane_state)
2356                 return 0;
2357
2358         if (!intel_rotation_90_or_270(plane_state->rotation))
2359                 return 0;
2360
2361         *view = i915_ggtt_view_rotated;
2362
2363         info->height = fb->height;
2364         info->pixel_format = fb->pixel_format;
2365         info->pitch = fb->pitches[0];
2366         info->fb_modifier = fb->modifier[0];
2367
2368         return 0;
2369 }
2370
2371 int
2372 intel_pin_and_fence_fb_obj(struct drm_plane *plane,
2373                            struct drm_framebuffer *fb,
2374                            const struct drm_plane_state *plane_state,
2375                            struct intel_engine_cs *pipelined)
2376 {
2377         struct drm_device *dev = fb->dev;
2378         struct drm_i915_private *dev_priv = dev->dev_private;
2379         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2380         struct i915_ggtt_view view;
2381         u32 alignment;
2382         int ret;
2383
2384         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2385
2386         switch (fb->modifier[0]) {
2387         case DRM_FORMAT_MOD_NONE:
2388                 if (INTEL_INFO(dev)->gen >= 9)
2389                         alignment = 256 * 1024;
2390                 else if (IS_BROADWATER(dev) || IS_CRESTLINE(dev))
2391                         alignment = 128 * 1024;
2392                 else if (INTEL_INFO(dev)->gen >= 4)
2393                         alignment = 4 * 1024;
2394                 else
2395                         alignment = 64 * 1024;
2396                 break;
2397         case I915_FORMAT_MOD_X_TILED:
2398                 if (INTEL_INFO(dev)->gen >= 9)
2399                         alignment = 256 * 1024;
2400                 else {
2401                         /* pin() will align the object as required by fence */
2402                         alignment = 0;
2403                 }
2404                 break;
2405         case I915_FORMAT_MOD_Y_TILED:
2406         case I915_FORMAT_MOD_Yf_TILED:
2407                 if (WARN_ONCE(INTEL_INFO(dev)->gen < 9,
2408                           "Y tiling bo slipped through, driver bug!\n"))
2409                         return -EINVAL;
2410                 alignment = 1 * 1024 * 1024;
2411                 break;
2412         default:
2413                 MISSING_CASE(fb->modifier[0]);
2414                 return -EINVAL;
2415         }
2416
2417         ret = intel_fill_fb_ggtt_view(&view, fb, plane_state);
2418         if (ret)
2419                 return ret;
2420
2421         /* Note that the w/a also requires 64 PTE of padding following the
2422          * bo. We currently fill all unused PTE with the shadow page and so
2423          * we should always have valid PTE following the scanout preventing
2424          * the VT-d warning.
2425          */
2426         if (need_vtd_wa(dev) && alignment < 256 * 1024)
2427                 alignment = 256 * 1024;
2428
2429         /*
2430          * Global gtt pte registers are special registers which actually forward
2431          * writes to a chunk of system memory. Which means that there is no risk
2432          * that the register values disappear as soon as we call
2433          * intel_runtime_pm_put(), so it is correct to wrap only the
2434          * pin/unpin/fence and not more.
2435          */
2436         intel_runtime_pm_get(dev_priv);
2437
2438         dev_priv->mm.interruptible = false;
2439         ret = i915_gem_object_pin_to_display_plane(obj, alignment, pipelined,
2440                                                    &view);
2441         if (ret)
2442                 goto err_interruptible;
2443
2444         /* Install a fence for tiled scan-out. Pre-i965 always needs a
2445          * fence, whereas 965+ only requires a fence if using
2446          * framebuffer compression.  For simplicity, we always install
2447          * a fence as the cost is not that onerous.
2448          */
2449         ret = i915_gem_object_get_fence(obj);
2450         if (ret)
2451                 goto err_unpin;
2452
2453         i915_gem_object_pin_fence(obj);
2454
2455         dev_priv->mm.interruptible = true;
2456         intel_runtime_pm_put(dev_priv);
2457         return 0;
2458
2459 err_unpin:
2460         i915_gem_object_unpin_from_display_plane(obj, &view);
2461 err_interruptible:
2462         dev_priv->mm.interruptible = true;
2463         intel_runtime_pm_put(dev_priv);
2464         return ret;
2465 }
2466
2467 static void intel_unpin_fb_obj(struct drm_framebuffer *fb,
2468                                const struct drm_plane_state *plane_state)
2469 {
2470         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2471         struct i915_ggtt_view view;
2472         int ret;
2473
2474         WARN_ON(!mutex_is_locked(&obj->base.dev->struct_mutex));
2475
2476         ret = intel_fill_fb_ggtt_view(&view, fb, plane_state);
2477         WARN_ONCE(ret, "Couldn't get view from plane state!");
2478
2479         i915_gem_object_unpin_fence(obj);
2480         i915_gem_object_unpin_from_display_plane(obj, &view);
2481 }
2482
2483 /* Computes the linear offset to the base tile and adjusts x, y. bytes per pixel
2484  * is assumed to be a power-of-two. */
2485 unsigned long intel_gen4_compute_page_offset(int *x, int *y,
2486                                              unsigned int tiling_mode,
2487                                              unsigned int cpp,
2488                                              unsigned int pitch)
2489 {
2490         if (tiling_mode != I915_TILING_NONE) {
2491                 unsigned int tile_rows, tiles;
2492
2493                 tile_rows = *y / 8;
2494                 *y %= 8;
2495
2496                 tiles = *x / (512/cpp);
2497                 *x %= 512/cpp;
2498
2499                 return tile_rows * pitch * 8 + tiles * 4096;
2500         } else {
2501                 unsigned int offset;
2502
2503                 offset = *y * pitch + *x * cpp;
2504                 *y = 0;
2505                 *x = (offset & 4095) / cpp;
2506                 return offset & -4096;
2507         }
2508 }
2509
2510 static int i9xx_format_to_fourcc(int format)
2511 {
2512         switch (format) {
2513         case DISPPLANE_8BPP:
2514                 return DRM_FORMAT_C8;
2515         case DISPPLANE_BGRX555:
2516                 return DRM_FORMAT_XRGB1555;
2517         case DISPPLANE_BGRX565:
2518                 return DRM_FORMAT_RGB565;
2519         default:
2520         case DISPPLANE_BGRX888:
2521                 return DRM_FORMAT_XRGB8888;
2522         case DISPPLANE_RGBX888:
2523                 return DRM_FORMAT_XBGR8888;
2524         case DISPPLANE_BGRX101010:
2525                 return DRM_FORMAT_XRGB2101010;
2526         case DISPPLANE_RGBX101010:
2527                 return DRM_FORMAT_XBGR2101010;
2528         }
2529 }
2530
2531 static int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2532 {
2533         switch (format) {
2534         case PLANE_CTL_FORMAT_RGB_565:
2535                 return DRM_FORMAT_RGB565;
2536         default:
2537         case PLANE_CTL_FORMAT_XRGB_8888:
2538                 if (rgb_order) {
2539                         if (alpha)
2540                                 return DRM_FORMAT_ABGR8888;
2541                         else
2542                                 return DRM_FORMAT_XBGR8888;
2543                 } else {
2544                         if (alpha)
2545                                 return DRM_FORMAT_ARGB8888;
2546                         else
2547                                 return DRM_FORMAT_XRGB8888;
2548                 }
2549         case PLANE_CTL_FORMAT_XRGB_2101010:
2550                 if (rgb_order)
2551                         return DRM_FORMAT_XBGR2101010;
2552                 else
2553                         return DRM_FORMAT_XRGB2101010;
2554         }
2555 }
2556
2557 static bool
2558 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2559                               struct intel_initial_plane_config *plane_config)
2560 {
2561         struct drm_device *dev = crtc->base.dev;
2562         struct drm_i915_gem_object *obj = NULL;
2563         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2564         struct drm_framebuffer *fb = &plane_config->fb->base;
2565         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2566         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2567                                     PAGE_SIZE);
2568
2569         size_aligned -= base_aligned;
2570
2571         if (plane_config->size == 0)
2572                 return false;
2573
2574         obj = i915_gem_object_create_stolen_for_preallocated(dev,
2575                                                              base_aligned,
2576                                                              base_aligned,
2577                                                              size_aligned);
2578         if (!obj)
2579                 return false;
2580
2581         obj->tiling_mode = plane_config->tiling;
2582         if (obj->tiling_mode == I915_TILING_X)
2583                 obj->stride = fb->pitches[0];
2584
2585         mode_cmd.pixel_format = fb->pixel_format;
2586         mode_cmd.width = fb->width;
2587         mode_cmd.height = fb->height;
2588         mode_cmd.pitches[0] = fb->pitches[0];
2589         mode_cmd.modifier[0] = fb->modifier[0];
2590         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2591
2592         mutex_lock(&dev->struct_mutex);
2593         if (intel_framebuffer_init(dev, to_intel_framebuffer(fb),
2594                                    &mode_cmd, obj)) {
2595                 DRM_DEBUG_KMS("intel fb init failed\n");
2596                 goto out_unref_obj;
2597         }
2598         mutex_unlock(&dev->struct_mutex);
2599
2600         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2601         return true;
2602
2603 out_unref_obj:
2604         drm_gem_object_unreference(&obj->base);
2605         mutex_unlock(&dev->struct_mutex);
2606         return false;
2607 }
2608
2609 /* Update plane->state->fb to match plane->fb after driver-internal updates */
2610 static void
2611 update_state_fb(struct drm_plane *plane)
2612 {
2613         if (plane->fb == plane->state->fb)
2614                 return;
2615
2616         if (plane->state->fb)
2617                 drm_framebuffer_unreference(plane->state->fb);
2618         plane->state->fb = plane->fb;
2619         if (plane->state->fb)
2620                 drm_framebuffer_reference(plane->state->fb);
2621 }
2622
2623 static void
2624 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2625                              struct intel_initial_plane_config *plane_config)
2626 {
2627         struct drm_device *dev = intel_crtc->base.dev;
2628         struct drm_i915_private *dev_priv = dev->dev_private;
2629         struct drm_crtc *c;
2630         struct intel_crtc *i;
2631         struct drm_i915_gem_object *obj;
2632         struct drm_plane *primary = intel_crtc->base.primary;
2633         struct drm_framebuffer *fb;
2634
2635         if (!plane_config->fb)
2636                 return;
2637
2638         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2639                 fb = &plane_config->fb->base;
2640                 goto valid_fb;
2641         }
2642
2643         kfree(plane_config->fb);
2644
2645         /*
2646          * Failed to alloc the obj, check to see if we should share
2647          * an fb with another CRTC instead
2648          */
2649         for_each_crtc(dev, c) {
2650                 i = to_intel_crtc(c);
2651
2652                 if (c == &intel_crtc->base)
2653                         continue;
2654
2655                 if (!i->active)
2656                         continue;
2657
2658                 fb = c->primary->fb;
2659                 if (!fb)
2660                         continue;
2661
2662                 obj = intel_fb_obj(fb);
2663                 if (i915_gem_obj_ggtt_offset(obj) == plane_config->base) {
2664                         drm_framebuffer_reference(fb);
2665                         goto valid_fb;
2666                 }
2667         }
2668
2669         return;
2670
2671 valid_fb:
2672         obj = intel_fb_obj(fb);
2673         if (obj->tiling_mode != I915_TILING_NONE)
2674                 dev_priv->preserve_bios_swizzle = true;
2675
2676         primary->fb = fb;
2677         primary->state->crtc = &intel_crtc->base;
2678         primary->crtc = &intel_crtc->base;
2679         update_state_fb(primary);
2680         obj->frontbuffer_bits |= INTEL_FRONTBUFFER_PRIMARY(intel_crtc->pipe);
2681 }
2682
2683 static void i9xx_update_primary_plane(struct drm_crtc *crtc,
2684                                       struct drm_framebuffer *fb,
2685                                       int x, int y)
2686 {
2687         struct drm_device *dev = crtc->dev;
2688         struct drm_i915_private *dev_priv = dev->dev_private;
2689         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2690         struct drm_i915_gem_object *obj;
2691         int plane = intel_crtc->plane;
2692         unsigned long linear_offset;
2693         u32 dspcntr;
2694         u32 reg = DSPCNTR(plane);
2695         int pixel_size;
2696
2697         if (!intel_crtc->primary_enabled) {
2698                 I915_WRITE(reg, 0);
2699                 if (INTEL_INFO(dev)->gen >= 4)
2700                         I915_WRITE(DSPSURF(plane), 0);
2701                 else
2702                         I915_WRITE(DSPADDR(plane), 0);
2703                 POSTING_READ(reg);
2704                 return;
2705         }
2706
2707         obj = intel_fb_obj(fb);
2708         if (WARN_ON(obj == NULL))
2709                 return;
2710
2711         pixel_size = drm_format_plane_cpp(fb->pixel_format, 0);
2712
2713         dspcntr = DISPPLANE_GAMMA_ENABLE;
2714
2715         dspcntr |= DISPLAY_PLANE_ENABLE;
2716
2717         if (INTEL_INFO(dev)->gen < 4) {
2718                 if (intel_crtc->pipe == PIPE_B)
2719                         dspcntr |= DISPPLANE_SEL_PIPE_B;
2720
2721                 /* pipesrc and dspsize control the size that is scaled from,
2722                  * which should always be the user's requested size.
2723                  */
2724                 I915_WRITE(DSPSIZE(plane),
2725                            ((intel_crtc->config->pipe_src_h - 1) << 16) |
2726                            (intel_crtc->config->pipe_src_w - 1));
2727                 I915_WRITE(DSPPOS(plane), 0);
2728         } else if (IS_CHERRYVIEW(dev) && plane == PLANE_B) {
2729                 I915_WRITE(PRIMSIZE(plane),
2730                            ((intel_crtc->config->pipe_src_h - 1) << 16) |
2731                            (intel_crtc->config->pipe_src_w - 1));
2732                 I915_WRITE(PRIMPOS(plane), 0);
2733                 I915_WRITE(PRIMCNSTALPHA(plane), 0);
2734         }
2735
2736         switch (fb->pixel_format) {
2737         case DRM_FORMAT_C8:
2738                 dspcntr |= DISPPLANE_8BPP;
2739                 break;
2740         case DRM_FORMAT_XRGB1555:
2741         case DRM_FORMAT_ARGB1555:
2742                 dspcntr |= DISPPLANE_BGRX555;
2743                 break;
2744         case DRM_FORMAT_RGB565:
2745                 dspcntr |= DISPPLANE_BGRX565;
2746                 break;
2747         case DRM_FORMAT_XRGB8888:
2748         case DRM_FORMAT_ARGB8888:
2749                 dspcntr |= DISPPLANE_BGRX888;
2750                 break;
2751         case DRM_FORMAT_XBGR8888:
2752         case DRM_FORMAT_ABGR8888:
2753                 dspcntr |= DISPPLANE_RGBX888;
2754                 break;
2755         case DRM_FORMAT_XRGB2101010:
2756         case DRM_FORMAT_ARGB2101010:
2757                 dspcntr |= DISPPLANE_BGRX101010;
2758                 break;
2759         case DRM_FORMAT_XBGR2101010:
2760         case DRM_FORMAT_ABGR2101010:
2761                 dspcntr |= DISPPLANE_RGBX101010;
2762                 break;
2763         default:
2764                 BUG();
2765         }
2766
2767         if (INTEL_INFO(dev)->gen >= 4 &&
2768             obj->tiling_mode != I915_TILING_NONE)
2769                 dspcntr |= DISPPLANE_TILED;
2770
2771         if (IS_G4X(dev))
2772                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2773
2774         linear_offset = y * fb->pitches[0] + x * pixel_size;
2775
2776         if (INTEL_INFO(dev)->gen >= 4) {
2777                 intel_crtc->dspaddr_offset =
2778                         intel_gen4_compute_page_offset(&x, &y, obj->tiling_mode,
2779                                                        pixel_size,
2780                                                        fb->pitches[0]);
2781                 linear_offset -= intel_crtc->dspaddr_offset;
2782         } else {
2783                 intel_crtc->dspaddr_offset = linear_offset;
2784         }
2785
2786         if (crtc->primary->state->rotation == BIT(DRM_ROTATE_180)) {
2787                 dspcntr |= DISPPLANE_ROTATE_180;
2788
2789                 x += (intel_crtc->config->pipe_src_w - 1);
2790                 y += (intel_crtc->config->pipe_src_h - 1);
2791
2792                 /* Finding the last pixel of the last line of the display
2793                 data and adding to linear_offset*/
2794                 linear_offset +=
2795                         (intel_crtc->config->pipe_src_h - 1) * fb->pitches[0] +
2796                         (intel_crtc->config->pipe_src_w - 1) * pixel_size;
2797         }
2798
2799         I915_WRITE(reg, dspcntr);
2800
2801         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2802         if (INTEL_INFO(dev)->gen >= 4) {
2803                 I915_WRITE(DSPSURF(plane),
2804                            i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2805                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2806                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2807         } else
2808                 I915_WRITE(DSPADDR(plane), i915_gem_obj_ggtt_offset(obj) + linear_offset);
2809         POSTING_READ(reg);
2810 }
2811
2812 static void ironlake_update_primary_plane(struct drm_crtc *crtc,
2813                                           struct drm_framebuffer *fb,
2814                                           int x, int y)
2815 {
2816         struct drm_device *dev = crtc->dev;
2817         struct drm_i915_private *dev_priv = dev->dev_private;
2818         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2819         struct drm_i915_gem_object *obj;
2820         int plane = intel_crtc->plane;
2821         unsigned long linear_offset;
2822         u32 dspcntr;
2823         u32 reg = DSPCNTR(plane);
2824         int pixel_size;
2825
2826         if (!intel_crtc->primary_enabled) {
2827                 I915_WRITE(reg, 0);
2828                 I915_WRITE(DSPSURF(plane), 0);
2829                 POSTING_READ(reg);
2830                 return;
2831         }
2832
2833         obj = intel_fb_obj(fb);
2834         if (WARN_ON(obj == NULL))
2835                 return;
2836
2837         pixel_size = drm_format_plane_cpp(fb->pixel_format, 0);
2838
2839         dspcntr = DISPPLANE_GAMMA_ENABLE;
2840
2841         dspcntr |= DISPLAY_PLANE_ENABLE;
2842
2843         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
2844                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
2845
2846         switch (fb->pixel_format) {
2847         case DRM_FORMAT_C8:
2848                 dspcntr |= DISPPLANE_8BPP;
2849                 break;
2850         case DRM_FORMAT_RGB565:
2851                 dspcntr |= DISPPLANE_BGRX565;
2852                 break;
2853         case DRM_FORMAT_XRGB8888:
2854         case DRM_FORMAT_ARGB8888:
2855                 dspcntr |= DISPPLANE_BGRX888;
2856                 break;
2857         case DRM_FORMAT_XBGR8888:
2858         case DRM_FORMAT_ABGR8888:
2859                 dspcntr |= DISPPLANE_RGBX888;
2860                 break;
2861         case DRM_FORMAT_XRGB2101010:
2862         case DRM_FORMAT_ARGB2101010:
2863                 dspcntr |= DISPPLANE_BGRX101010;
2864                 break;
2865         case DRM_FORMAT_XBGR2101010:
2866         case DRM_FORMAT_ABGR2101010:
2867                 dspcntr |= DISPPLANE_RGBX101010;
2868                 break;
2869         default:
2870                 BUG();
2871         }
2872
2873         if (obj->tiling_mode != I915_TILING_NONE)
2874                 dspcntr |= DISPPLANE_TILED;
2875
2876         if (!IS_HASWELL(dev) && !IS_BROADWELL(dev))
2877                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2878
2879         linear_offset = y * fb->pitches[0] + x * pixel_size;
2880         intel_crtc->dspaddr_offset =
2881                 intel_gen4_compute_page_offset(&x, &y, obj->tiling_mode,
2882                                                pixel_size,
2883                                                fb->pitches[0]);
2884         linear_offset -= intel_crtc->dspaddr_offset;
2885         if (crtc->primary->state->rotation == BIT(DRM_ROTATE_180)) {
2886                 dspcntr |= DISPPLANE_ROTATE_180;
2887
2888                 if (!IS_HASWELL(dev) && !IS_BROADWELL(dev)) {
2889                         x += (intel_crtc->config->pipe_src_w - 1);
2890                         y += (intel_crtc->config->pipe_src_h - 1);
2891
2892                         /* Finding the last pixel of the last line of the display
2893                         data and adding to linear_offset*/
2894                         linear_offset +=
2895                                 (intel_crtc->config->pipe_src_h - 1) * fb->pitches[0] +
2896                                 (intel_crtc->config->pipe_src_w - 1) * pixel_size;
2897                 }
2898         }
2899
2900         I915_WRITE(reg, dspcntr);
2901
2902         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2903         I915_WRITE(DSPSURF(plane),
2904                    i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2905         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
2906                 I915_WRITE(DSPOFFSET(plane), (y << 16) | x);
2907         } else {
2908                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2909                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2910         }
2911         POSTING_READ(reg);
2912 }
2913
2914 u32 intel_fb_stride_alignment(struct drm_device *dev, uint64_t fb_modifier,
2915                               uint32_t pixel_format)
2916 {
2917         u32 bits_per_pixel = drm_format_plane_cpp(pixel_format, 0) * 8;
2918
2919         /*
2920          * The stride is either expressed as a multiple of 64 bytes
2921          * chunks for linear buffers or in number of tiles for tiled
2922          * buffers.
2923          */
2924         switch (fb_modifier) {
2925         case DRM_FORMAT_MOD_NONE:
2926                 return 64;
2927         case I915_FORMAT_MOD_X_TILED:
2928                 if (INTEL_INFO(dev)->gen == 2)
2929                         return 128;
2930                 return 512;
2931         case I915_FORMAT_MOD_Y_TILED:
2932                 /* No need to check for old gens and Y tiling since this is
2933                  * about the display engine and those will be blocked before
2934                  * we get here.
2935                  */
2936                 return 128;
2937         case I915_FORMAT_MOD_Yf_TILED:
2938                 if (bits_per_pixel == 8)
2939                         return 64;
2940                 else
2941                         return 128;
2942         default:
2943                 MISSING_CASE(fb_modifier);
2944                 return 64;
2945         }
2946 }
2947
2948 unsigned long intel_plane_obj_offset(struct intel_plane *intel_plane,
2949                                      struct drm_i915_gem_object *obj)
2950 {
2951         const struct i915_ggtt_view *view = &i915_ggtt_view_normal;
2952
2953         if (intel_rotation_90_or_270(intel_plane->base.state->rotation))
2954                 view = &i915_ggtt_view_rotated;
2955
2956         return i915_gem_obj_ggtt_offset_view(obj, view);
2957 }
2958
2959 /*
2960  * This function detaches (aka. unbinds) unused scalers in hardware
2961  */
2962 void skl_detach_scalers(struct intel_crtc *intel_crtc)
2963 {
2964         struct drm_device *dev;
2965         struct drm_i915_private *dev_priv;
2966         struct intel_crtc_scaler_state *scaler_state;
2967         int i;
2968
2969         if (!intel_crtc || !intel_crtc->config)
2970                 return;
2971
2972         dev = intel_crtc->base.dev;
2973         dev_priv = dev->dev_private;
2974         scaler_state = &intel_crtc->config->scaler_state;
2975
2976         /* loop through and disable scalers that aren't in use */
2977         for (i = 0; i < intel_crtc->num_scalers; i++) {
2978                 if (!scaler_state->scalers[i].in_use) {
2979                         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, i), 0);
2980                         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, i), 0);
2981                         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, i), 0);
2982                         DRM_DEBUG_KMS("CRTC:%d Disabled scaler id %u.%u\n",
2983                                 intel_crtc->base.base.id, intel_crtc->pipe, i);
2984                 }
2985         }
2986 }
2987
2988 static void skylake_update_primary_plane(struct drm_crtc *crtc,
2989                                          struct drm_framebuffer *fb,
2990                                          int x, int y)
2991 {
2992         struct drm_device *dev = crtc->dev;
2993         struct drm_i915_private *dev_priv = dev->dev_private;
2994         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2995         struct drm_i915_gem_object *obj;
2996         int pipe = intel_crtc->pipe;
2997         u32 plane_ctl, stride_div, stride;
2998         u32 tile_height, plane_offset, plane_size;
2999         unsigned int rotation;
3000         int x_offset, y_offset;
3001         unsigned long surf_addr;
3002         struct drm_plane *plane;
3003
3004         if (!intel_crtc->primary_enabled) {
3005                 I915_WRITE(PLANE_CTL(pipe, 0), 0);
3006                 I915_WRITE(PLANE_SURF(pipe, 0), 0);
3007                 POSTING_READ(PLANE_CTL(pipe, 0));
3008                 return;
3009         }
3010
3011         plane_ctl = PLANE_CTL_ENABLE |
3012                     PLANE_CTL_PIPE_GAMMA_ENABLE |
3013                     PLANE_CTL_PIPE_CSC_ENABLE;
3014
3015         switch (fb->pixel_format) {
3016         case DRM_FORMAT_RGB565:
3017                 plane_ctl |= PLANE_CTL_FORMAT_RGB_565;
3018                 break;
3019         case DRM_FORMAT_XRGB8888:
3020                 plane_ctl |= PLANE_CTL_FORMAT_XRGB_8888;
3021                 break;
3022         case DRM_FORMAT_ARGB8888:
3023                 plane_ctl |= PLANE_CTL_FORMAT_XRGB_8888;
3024                 plane_ctl |= PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3025                 break;
3026         case DRM_FORMAT_XBGR8888:
3027                 plane_ctl |= PLANE_CTL_ORDER_RGBX;
3028                 plane_ctl |= PLANE_CTL_FORMAT_XRGB_8888;
3029                 break;
3030         case DRM_FORMAT_ABGR8888:
3031                 plane_ctl |= PLANE_CTL_ORDER_RGBX;
3032                 plane_ctl |= PLANE_CTL_FORMAT_XRGB_8888;
3033                 plane_ctl |= PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3034                 break;
3035         case DRM_FORMAT_XRGB2101010:
3036                 plane_ctl |= PLANE_CTL_FORMAT_XRGB_2101010;
3037                 break;
3038         case DRM_FORMAT_XBGR2101010:
3039                 plane_ctl |= PLANE_CTL_ORDER_RGBX;
3040                 plane_ctl |= PLANE_CTL_FORMAT_XRGB_2101010;
3041                 break;
3042         default:
3043                 BUG();
3044         }
3045
3046         switch (fb->modifier[0]) {
3047         case DRM_FORMAT_MOD_NONE:
3048                 break;
3049         case I915_FORMAT_MOD_X_TILED:
3050                 plane_ctl |= PLANE_CTL_TILED_X;
3051                 break;
3052         case I915_FORMAT_MOD_Y_TILED:
3053                 plane_ctl |= PLANE_CTL_TILED_Y;
3054                 break;
3055         case I915_FORMAT_MOD_Yf_TILED:
3056                 plane_ctl |= PLANE_CTL_TILED_YF;
3057                 break;
3058         default:
3059                 MISSING_CASE(fb->modifier[0]);
3060         }
3061
3062         plane_ctl |= PLANE_CTL_PLANE_GAMMA_DISABLE;
3063
3064         plane = crtc->primary;
3065         rotation = plane->state->rotation;
3066         switch (rotation) {
3067         case BIT(DRM_ROTATE_90):
3068                 plane_ctl |= PLANE_CTL_ROTATE_90;
3069                 break;
3070
3071         case BIT(DRM_ROTATE_180):
3072                 plane_ctl |= PLANE_CTL_ROTATE_180;
3073                 break;
3074
3075         case BIT(DRM_ROTATE_270):
3076                 plane_ctl |= PLANE_CTL_ROTATE_270;
3077                 break;
3078         }
3079
3080         obj = intel_fb_obj(fb);
3081         stride_div = intel_fb_stride_alignment(dev, fb->modifier[0],
3082                                                fb->pixel_format);
3083         surf_addr = intel_plane_obj_offset(to_intel_plane(plane), obj);
3084
3085         if (intel_rotation_90_or_270(rotation)) {
3086                 /* stride = Surface height in tiles */
3087                 tile_height = intel_tile_height(dev, fb->bits_per_pixel,
3088                                                 fb->modifier[0]);
3089                 stride = DIV_ROUND_UP(fb->height, tile_height);
3090                 x_offset = stride * tile_height - y - (plane->state->src_h >> 16);
3091                 y_offset = x;
3092                 plane_size = ((plane->state->src_w >> 16) - 1) << 16 |
3093                                         ((plane->state->src_h >> 16) - 1);
3094         } else {
3095                 stride = fb->pitches[0] / stride_div;
3096                 x_offset = x;
3097                 y_offset = y;
3098                 plane_size = ((plane->state->src_h >> 16) - 1) << 16 |
3099                         ((plane->state->src_w >> 16) - 1);
3100         }
3101         plane_offset = y_offset << 16 | x_offset;
3102
3103         I915_WRITE(PLANE_CTL(pipe, 0), plane_ctl);
3104         I915_WRITE(PLANE_POS(pipe, 0), 0);
3105         I915_WRITE(PLANE_OFFSET(pipe, 0), plane_offset);
3106         I915_WRITE(PLANE_SIZE(pipe, 0), plane_size);
3107         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
3108         I915_WRITE(PLANE_SURF(pipe, 0), surf_addr);
3109
3110         POSTING_READ(PLANE_SURF(pipe, 0));
3111 }
3112
3113 /* Assume fb object is pinned & idle & fenced and just update base pointers */
3114 static int
3115 intel_pipe_set_base_atomic(struct drm_crtc *crtc, struct drm_framebuffer *fb,
3116                            int x, int y, enum mode_set_atomic state)
3117 {
3118         struct drm_device *dev = crtc->dev;
3119         struct drm_i915_private *dev_priv = dev->dev_private;
3120
3121         if (dev_priv->display.disable_fbc)
3122                 dev_priv->display.disable_fbc(dev);
3123
3124         dev_priv->display.update_primary_plane(crtc, fb, x, y);
3125
3126         return 0;
3127 }
3128
3129 static void intel_complete_page_flips(struct drm_device *dev)
3130 {
3131         struct drm_crtc *crtc;
3132
3133         for_each_crtc(dev, crtc) {
3134                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3135                 enum plane plane = intel_crtc->plane;
3136
3137                 intel_prepare_page_flip(dev, plane);
3138                 intel_finish_page_flip_plane(dev, plane);
3139         }
3140 }
3141
3142 static void intel_update_primary_planes(struct drm_device *dev)
3143 {
3144         struct drm_i915_private *dev_priv = dev->dev_private;
3145         struct drm_crtc *crtc;
3146
3147         for_each_crtc(dev, crtc) {
3148                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3149
3150                 drm_modeset_lock(&crtc->mutex, NULL);
3151                 /*
3152                  * FIXME: Once we have proper support for primary planes (and
3153                  * disabling them without disabling the entire crtc) allow again
3154                  * a NULL crtc->primary->fb.
3155                  */
3156                 if (intel_crtc->active && crtc->primary->fb)
3157                         dev_priv->display.update_primary_plane(crtc,
3158                                                                crtc->primary->fb,
3159                                                                crtc->x,
3160                                                                crtc->y);
3161                 drm_modeset_unlock(&crtc->mutex);
3162         }
3163 }
3164
3165 void intel_prepare_reset(struct drm_device *dev)
3166 {
3167         struct drm_i915_private *dev_priv = to_i915(dev);
3168         struct intel_crtc *crtc;
3169
3170         /* no reset support for gen2 */
3171         if (IS_GEN2(dev))
3172                 return;
3173
3174         /* reset doesn't touch the display */
3175         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
3176                 return;
3177
3178         drm_modeset_lock_all(dev);
3179
3180         /*
3181          * Disabling the crtcs gracefully seems nicer. Also the
3182          * g33 docs say we should at least disable all the planes.
3183          */
3184         for_each_intel_crtc(dev, crtc) {
3185                 if (crtc->active)
3186                         dev_priv->display.crtc_disable(&crtc->base);
3187         }
3188 }
3189
3190 void intel_finish_reset(struct drm_device *dev)
3191 {
3192         struct drm_i915_private *dev_priv = to_i915(dev);
3193
3194         /*
3195          * Flips in the rings will be nuked by the reset,
3196          * so complete all pending flips so that user space
3197          * will get its events and not get stuck.
3198          */
3199         intel_complete_page_flips(dev);
3200
3201         /* no reset support for gen2 */
3202         if (IS_GEN2(dev))
3203                 return;
3204
3205         /* reset doesn't touch the display */
3206         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev)) {
3207                 /*
3208                  * Flips in the rings have been nuked by the reset,
3209                  * so update the base address of all primary
3210                  * planes to the the last fb to make sure we're
3211                  * showing the correct fb after a reset.
3212                  */
3213                 intel_update_primary_planes(dev);
3214                 return;
3215         }
3216
3217         /*
3218          * The display has been reset as well,
3219          * so need a full re-initialization.
3220          */
3221         intel_runtime_pm_disable_interrupts(dev_priv);
3222         intel_runtime_pm_enable_interrupts(dev_priv);
3223
3224         intel_modeset_init_hw(dev);
3225
3226         spin_lock_irq(&dev_priv->irq_lock);
3227         if (dev_priv->display.hpd_irq_setup)
3228                 dev_priv->display.hpd_irq_setup(dev);
3229         spin_unlock_irq(&dev_priv->irq_lock);
3230
3231         intel_modeset_setup_hw_state(dev, true);
3232
3233         intel_hpd_init(dev_priv);
3234
3235         drm_modeset_unlock_all(dev);
3236 }
3237
3238 static int
3239 intel_finish_fb(struct drm_framebuffer *old_fb)
3240 {
3241         struct drm_i915_gem_object *obj = intel_fb_obj(old_fb);
3242         struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
3243         bool was_interruptible = dev_priv->mm.interruptible;
3244         int ret;
3245
3246         /* Big Hammer, we also need to ensure that any pending
3247          * MI_WAIT_FOR_EVENT inside a user batch buffer on the
3248          * current scanout is retired before unpinning the old
3249          * framebuffer.
3250          *
3251          * This should only fail upon a hung GPU, in which case we
3252          * can safely continue.
3253          */
3254         dev_priv->mm.interruptible = false;
3255         ret = i915_gem_object_finish_gpu(obj);
3256         dev_priv->mm.interruptible = was_interruptible;
3257
3258         return ret;
3259 }
3260
3261 static bool intel_crtc_has_pending_flip(struct drm_crtc *crtc)
3262 {
3263         struct drm_device *dev = crtc->dev;
3264         struct drm_i915_private *dev_priv = dev->dev_private;
3265         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3266         bool pending;
3267
3268         if (i915_reset_in_progress(&dev_priv->gpu_error) ||
3269             intel_crtc->reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
3270                 return false;
3271
3272         spin_lock_irq(&dev->event_lock);
3273         pending = to_intel_crtc(crtc)->unpin_work != NULL;
3274         spin_unlock_irq(&dev->event_lock);
3275
3276         return pending;
3277 }
3278
3279 static void intel_update_pipe_size(struct intel_crtc *crtc)
3280 {
3281         struct drm_device *dev = crtc->base.dev;
3282         struct drm_i915_private *dev_priv = dev->dev_private;
3283         const struct drm_display_mode *adjusted_mode;
3284
3285         if (!i915.fastboot)
3286                 return;
3287
3288         /*
3289          * Update pipe size and adjust fitter if needed: the reason for this is
3290          * that in compute_mode_changes we check the native mode (not the pfit
3291          * mode) to see if we can flip rather than do a full mode set. In the
3292          * fastboot case, we'll flip, but if we don't update the pipesrc and
3293          * pfit state, we'll end up with a big fb scanned out into the wrong
3294          * sized surface.
3295          *
3296          * To fix this properly, we need to hoist the checks up into
3297          * compute_mode_changes (or above), check the actual pfit state and
3298          * whether the platform allows pfit disable with pipe active, and only
3299          * then update the pipesrc and pfit state, even on the flip path.
3300          */
3301
3302         adjusted_mode = &crtc->config->base.adjusted_mode;
3303
3304         I915_WRITE(PIPESRC(crtc->pipe),
3305                    ((adjusted_mode->crtc_hdisplay - 1) << 16) |
3306                    (adjusted_mode->crtc_vdisplay - 1));
3307         if (!crtc->config->pch_pfit.enabled &&
3308             (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS) ||
3309              intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP))) {
3310                 I915_WRITE(PF_CTL(crtc->pipe), 0);
3311                 I915_WRITE(PF_WIN_POS(crtc->pipe), 0);
3312                 I915_WRITE(PF_WIN_SZ(crtc->pipe), 0);
3313         }
3314         crtc->config->pipe_src_w = adjusted_mode->crtc_hdisplay;
3315         crtc->config->pipe_src_h = adjusted_mode->crtc_vdisplay;
3316 }
3317
3318 static void intel_fdi_normal_train(struct drm_crtc *crtc)
3319 {
3320         struct drm_device *dev = crtc->dev;
3321         struct drm_i915_private *dev_priv = dev->dev_private;
3322         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3323         int pipe = intel_crtc->pipe;
3324         u32 reg, temp;
3325
3326         /* enable normal train */
3327         reg = FDI_TX_CTL(pipe);
3328         temp = I915_READ(reg);
3329         if (IS_IVYBRIDGE(dev)) {
3330                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3331                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3332         } else {
3333                 temp &= ~FDI_LINK_TRAIN_NONE;
3334                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3335         }
3336         I915_WRITE(reg, temp);
3337
3338         reg = FDI_RX_CTL(pipe);
3339         temp = I915_READ(reg);
3340         if (HAS_PCH_CPT(dev)) {
3341                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3342                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3343         } else {
3344                 temp &= ~FDI_LINK_TRAIN_NONE;
3345                 temp |= FDI_LINK_TRAIN_NONE;
3346         }
3347         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3348
3349         /* wait one idle pattern time */
3350         POSTING_READ(reg);
3351         udelay(1000);
3352
3353         /* IVB wants error correction enabled */
3354         if (IS_IVYBRIDGE(dev))
3355                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3356                            FDI_FE_ERRC_ENABLE);
3357 }
3358
3359 /* The FDI link training functions for ILK/Ibexpeak. */
3360 static void ironlake_fdi_link_train(struct drm_crtc *crtc)
3361 {
3362         struct drm_device *dev = crtc->dev;
3363         struct drm_i915_private *dev_priv = dev->dev_private;
3364         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3365         int pipe = intel_crtc->pipe;
3366         u32 reg, temp, tries;
3367
3368         /* FDI needs bits from pipe first */
3369         assert_pipe_enabled(dev_priv, pipe);
3370
3371         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3372            for train result */
3373         reg = FDI_RX_IMR(pipe);
3374         temp = I915_READ(reg);
3375         temp &= ~FDI_RX_SYMBOL_LOCK;
3376         temp &= ~FDI_RX_BIT_LOCK;
3377         I915_WRITE(reg, temp);
3378         I915_READ(reg);
3379         udelay(150);
3380
3381         /* enable CPU FDI TX and PCH FDI RX */
3382         reg = FDI_TX_CTL(pipe);
3383         temp = I915_READ(reg);
3384         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3385         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3386         temp &= ~FDI_LINK_TRAIN_NONE;
3387         temp |= FDI_LINK_TRAIN_PATTERN_1;
3388         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3389
3390         reg = FDI_RX_CTL(pipe);
3391         temp = I915_READ(reg);
3392         temp &= ~FDI_LINK_TRAIN_NONE;
3393         temp |= FDI_LINK_TRAIN_PATTERN_1;
3394         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3395
3396         POSTING_READ(reg);
3397         udelay(150);
3398
3399         /* Ironlake workaround, enable clock pointer after FDI enable*/
3400         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3401         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3402                    FDI_RX_PHASE_SYNC_POINTER_EN);
3403
3404         reg = FDI_RX_IIR(pipe);
3405         for (tries = 0; tries < 5; tries++) {
3406                 temp = I915_READ(reg);
3407                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3408
3409                 if ((temp & FDI_RX_BIT_LOCK)) {
3410                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3411                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3412                         break;
3413                 }
3414         }
3415         if (tries == 5)
3416                 DRM_ERROR("FDI train 1 fail!\n");
3417
3418         /* Train 2 */
3419         reg = FDI_TX_CTL(pipe);
3420         temp = I915_READ(reg);
3421         temp &= ~FDI_LINK_TRAIN_NONE;
3422         temp |= FDI_LINK_TRAIN_PATTERN_2;
3423         I915_WRITE(reg, temp);
3424
3425         reg = FDI_RX_CTL(pipe);
3426         temp = I915_READ(reg);
3427         temp &= ~FDI_LINK_TRAIN_NONE;
3428         temp |= FDI_LINK_TRAIN_PATTERN_2;
3429         I915_WRITE(reg, temp);
3430
3431         POSTING_READ(reg);
3432         udelay(150);
3433
3434         reg = FDI_RX_IIR(pipe);
3435         for (tries = 0; tries < 5; tries++) {
3436                 temp = I915_READ(reg);
3437                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3438
3439                 if (temp & FDI_RX_SYMBOL_LOCK) {
3440                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3441                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3442                         break;
3443                 }
3444         }
3445         if (tries == 5)
3446                 DRM_ERROR("FDI train 2 fail!\n");
3447
3448         DRM_DEBUG_KMS("FDI train done\n");
3449
3450 }
3451
3452 static const int snb_b_fdi_train_param[] = {
3453         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3454         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3455         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3456         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3457 };
3458
3459 /* The FDI link training functions for SNB/Cougarpoint. */
3460 static void gen6_fdi_link_train(struct drm_crtc *crtc)
3461 {
3462         struct drm_device *dev = crtc->dev;
3463         struct drm_i915_private *dev_priv = dev->dev_private;
3464         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3465         int pipe = intel_crtc->pipe;
3466         u32 reg, temp, i, retry;
3467
3468         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3469            for train result */
3470         reg = FDI_RX_IMR(pipe);
3471         temp = I915_READ(reg);
3472         temp &= ~FDI_RX_SYMBOL_LOCK;
3473         temp &= ~FDI_RX_BIT_LOCK;
3474         I915_WRITE(reg, temp);
3475
3476         POSTING_READ(reg);
3477         udelay(150);
3478
3479         /* enable CPU FDI TX and PCH FDI RX */
3480         reg = FDI_TX_CTL(pipe);
3481         temp = I915_READ(reg);
3482         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3483         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3484         temp &= ~FDI_LINK_TRAIN_NONE;
3485         temp |= FDI_LINK_TRAIN_PATTERN_1;
3486         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3487         /* SNB-B */
3488         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3489         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3490
3491         I915_WRITE(FDI_RX_MISC(pipe),
3492                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3493
3494         reg = FDI_RX_CTL(pipe);
3495         temp = I915_READ(reg);
3496         if (HAS_PCH_CPT(dev)) {
3497                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3498                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3499         } else {
3500                 temp &= ~FDI_LINK_TRAIN_NONE;
3501                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3502         }
3503         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3504
3505         POSTING_READ(reg);
3506         udelay(150);
3507
3508         for (i = 0; i < 4; i++) {
3509                 reg = FDI_TX_CTL(pipe);
3510                 temp = I915_READ(reg);
3511                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3512                 temp |= snb_b_fdi_train_param[i];
3513                 I915_WRITE(reg, temp);
3514
3515                 POSTING_READ(reg);
3516                 udelay(500);
3517
3518                 for (retry = 0; retry < 5; retry++) {
3519                         reg = FDI_RX_IIR(pipe);
3520                         temp = I915_READ(reg);
3521                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3522                         if (temp & FDI_RX_BIT_LOCK) {
3523                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3524                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
3525                                 break;
3526                         }
3527                         udelay(50);
3528                 }
3529                 if (retry < 5)
3530                         break;
3531         }
3532         if (i == 4)
3533                 DRM_ERROR("FDI train 1 fail!\n");
3534
3535         /* Train 2 */
3536         reg = FDI_TX_CTL(pipe);
3537         temp = I915_READ(reg);
3538         temp &= ~FDI_LINK_TRAIN_NONE;
3539         temp |= FDI_LINK_TRAIN_PATTERN_2;
3540         if (IS_GEN6(dev)) {
3541                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3542                 /* SNB-B */
3543                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3544         }
3545         I915_WRITE(reg, temp);
3546
3547         reg = FDI_RX_CTL(pipe);
3548         temp = I915_READ(reg);
3549         if (HAS_PCH_CPT(dev)) {
3550                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3551                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3552         } else {
3553                 temp &= ~FDI_LINK_TRAIN_NONE;
3554                 temp |= FDI_LINK_TRAIN_PATTERN_2;
3555         }
3556         I915_WRITE(reg, temp);
3557
3558         POSTING_READ(reg);
3559         udelay(150);
3560
3561         for (i = 0; i < 4; i++) {
3562                 reg = FDI_TX_CTL(pipe);
3563                 temp = I915_READ(reg);
3564                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3565                 temp |= snb_b_fdi_train_param[i];
3566                 I915_WRITE(reg, temp);
3567
3568                 POSTING_READ(reg);
3569                 udelay(500);
3570
3571                 for (retry = 0; retry < 5; retry++) {
3572                         reg = FDI_RX_IIR(pipe);
3573                         temp = I915_READ(reg);
3574                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3575                         if (temp & FDI_RX_SYMBOL_LOCK) {
3576                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3577                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
3578                                 break;
3579                         }
3580                         udelay(50);
3581                 }
3582                 if (retry < 5)
3583                         break;
3584         }
3585         if (i == 4)
3586                 DRM_ERROR("FDI train 2 fail!\n");
3587
3588         DRM_DEBUG_KMS("FDI train done.\n");
3589 }
3590
3591 /* Manual link training for Ivy Bridge A0 parts */
3592 static void ivb_manual_fdi_link_train(struct drm_crtc *crtc)
3593 {
3594         struct drm_device *dev = crtc->dev;
3595         struct drm_i915_private *dev_priv = dev->dev_private;
3596         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3597         int pipe = intel_crtc->pipe;
3598         u32 reg, temp, i, j;
3599
3600         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3601            for train result */
3602         reg = FDI_RX_IMR(pipe);
3603         temp = I915_READ(reg);
3604         temp &= ~FDI_RX_SYMBOL_LOCK;
3605         temp &= ~FDI_RX_BIT_LOCK;
3606         I915_WRITE(reg, temp);
3607
3608         POSTING_READ(reg);
3609         udelay(150);
3610
3611         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
3612                       I915_READ(FDI_RX_IIR(pipe)));
3613
3614         /* Try each vswing and preemphasis setting twice before moving on */
3615         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
3616                 /* disable first in case we need to retry */
3617                 reg = FDI_TX_CTL(pipe);
3618                 temp = I915_READ(reg);
3619                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
3620                 temp &= ~FDI_TX_ENABLE;
3621                 I915_WRITE(reg, temp);
3622
3623                 reg = FDI_RX_CTL(pipe);
3624                 temp = I915_READ(reg);
3625                 temp &= ~FDI_LINK_TRAIN_AUTO;
3626                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3627                 temp &= ~FDI_RX_ENABLE;
3628                 I915_WRITE(reg, temp);
3629
3630                 /* enable CPU FDI TX and PCH FDI RX */
3631                 reg = FDI_TX_CTL(pipe);
3632                 temp = I915_READ(reg);
3633                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
3634                 temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3635                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
3636                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3637                 temp |= snb_b_fdi_train_param[j/2];
3638                 temp |= FDI_COMPOSITE_SYNC;
3639                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
3640
3641                 I915_WRITE(FDI_RX_MISC(pipe),
3642                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3643
3644                 reg = FDI_RX_CTL(pipe);
3645                 temp = I915_READ(reg);
3646                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3647                 temp |= FDI_COMPOSITE_SYNC;
3648                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
3649
3650                 POSTING_READ(reg);
3651                 udelay(1); /* should be 0.5us */
3652
3653                 for (i = 0; i < 4; i++) {
3654                         reg = FDI_RX_IIR(pipe);
3655                         temp = I915_READ(reg);
3656                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3657
3658                         if (temp & FDI_RX_BIT_LOCK ||
3659                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
3660                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3661                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
3662                                               i);
3663                                 break;
3664                         }
3665                         udelay(1); /* should be 0.5us */
3666                 }
3667                 if (i == 4) {
3668                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
3669                         continue;
3670                 }
3671
3672                 /* Train 2 */
3673                 reg = FDI_TX_CTL(pipe);
3674                 temp = I915_READ(reg);
3675                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3676                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
3677                 I915_WRITE(reg, temp);
3678
3679                 reg = FDI_RX_CTL(pipe);
3680                 temp = I915_READ(reg);
3681                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3682                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3683                 I915_WRITE(reg, temp);
3684
3685                 POSTING_READ(reg);
3686                 udelay(2); /* should be 1.5us */
3687
3688                 for (i = 0; i < 4; i++) {
3689                         reg = FDI_RX_IIR(pipe);
3690                         temp = I915_READ(reg);
3691                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3692
3693                         if (temp & FDI_RX_SYMBOL_LOCK ||
3694                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
3695                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3696                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
3697                                               i);
3698                                 goto train_done;
3699                         }
3700                         udelay(2); /* should be 1.5us */
3701                 }
3702                 if (i == 4)
3703                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
3704         }
3705
3706 train_done:
3707         DRM_DEBUG_KMS("FDI train done.\n");
3708 }
3709
3710 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
3711 {
3712         struct drm_device *dev = intel_crtc->base.dev;
3713         struct drm_i915_private *dev_priv = dev->dev_private;
3714         int pipe = intel_crtc->pipe;
3715         u32 reg, temp;
3716
3717
3718         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
3719         reg = FDI_RX_CTL(pipe);
3720         temp = I915_READ(reg);
3721         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
3722         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3723         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3724         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
3725
3726         POSTING_READ(reg);
3727         udelay(200);
3728
3729         /* Switch from Rawclk to PCDclk */
3730         temp = I915_READ(reg);
3731         I915_WRITE(reg, temp | FDI_PCDCLK);
3732
3733         POSTING_READ(reg);
3734         udelay(200);
3735
3736         /* Enable CPU FDI TX PLL, always on for Ironlake */
3737         reg = FDI_TX_CTL(pipe);
3738         temp = I915_READ(reg);
3739         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
3740                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
3741
3742                 POSTING_READ(reg);
3743                 udelay(100);
3744         }
3745 }
3746
3747 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
3748 {
3749         struct drm_device *dev = intel_crtc->base.dev;
3750         struct drm_i915_private *dev_priv = dev->dev_private;
3751         int pipe = intel_crtc->pipe;
3752         u32 reg, temp;
3753
3754         /* Switch from PCDclk to Rawclk */
3755         reg = FDI_RX_CTL(pipe);
3756         temp = I915_READ(reg);
3757         I915_WRITE(reg, temp & ~FDI_PCDCLK);
3758
3759         /* Disable CPU FDI TX PLL */
3760         reg = FDI_TX_CTL(pipe);
3761         temp = I915_READ(reg);
3762         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
3763
3764         POSTING_READ(reg);
3765         udelay(100);
3766
3767         reg = FDI_RX_CTL(pipe);
3768         temp = I915_READ(reg);
3769         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
3770
3771         /* Wait for the clocks to turn off. */
3772         POSTING_READ(reg);
3773         udelay(100);
3774 }
3775
3776 static void ironlake_fdi_disable(struct drm_crtc *crtc)
3777 {
3778         struct drm_device *dev = crtc->dev;
3779         struct drm_i915_private *dev_priv = dev->dev_private;
3780         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3781         int pipe = intel_crtc->pipe;
3782         u32 reg, temp;
3783
3784         /* disable CPU FDI tx and PCH FDI rx */
3785         reg = FDI_TX_CTL(pipe);
3786         temp = I915_READ(reg);
3787         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
3788         POSTING_READ(reg);
3789
3790         reg = FDI_RX_CTL(pipe);
3791         temp = I915_READ(reg);
3792         temp &= ~(0x7 << 16);
3793         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3794         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
3795
3796         POSTING_READ(reg);
3797         udelay(100);
3798
3799         /* Ironlake workaround, disable clock pointer after downing FDI */
3800         if (HAS_PCH_IBX(dev))
3801                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3802
3803         /* still set train pattern 1 */
3804         reg = FDI_TX_CTL(pipe);
3805         temp = I915_READ(reg);
3806         temp &= ~FDI_LINK_TRAIN_NONE;
3807         temp |= FDI_LINK_TRAIN_PATTERN_1;
3808         I915_WRITE(reg, temp);
3809
3810         reg = FDI_RX_CTL(pipe);
3811         temp = I915_READ(reg);
3812         if (HAS_PCH_CPT(dev)) {
3813                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3814                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3815         } else {
3816                 temp &= ~FDI_LINK_TRAIN_NONE;
3817                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3818         }
3819         /* BPC in FDI rx is consistent with that in PIPECONF */
3820         temp &= ~(0x07 << 16);
3821         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3822         I915_WRITE(reg, temp);
3823
3824         POSTING_READ(reg);
3825         udelay(100);
3826 }
3827
3828 bool intel_has_pending_fb_unpin(struct drm_device *dev)
3829 {
3830         struct intel_crtc *crtc;
3831
3832         /* Note that we don't need to be called with mode_config.lock here
3833          * as our list of CRTC objects is static for the lifetime of the
3834          * device and so cannot disappear as we iterate. Similarly, we can
3835          * happily treat the predicates as racy, atomic checks as userspace
3836          * cannot claim and pin a new fb without at least acquring the
3837          * struct_mutex and so serialising with us.
3838          */
3839         for_each_intel_crtc(dev, crtc) {
3840                 if (atomic_read(&crtc->unpin_work_count) == 0)
3841                         continue;
3842
3843                 if (crtc->unpin_work)
3844                         intel_wait_for_vblank(dev, crtc->pipe);
3845
3846                 return true;
3847         }
3848
3849         return false;
3850 }
3851
3852 static void page_flip_completed(struct intel_crtc *intel_crtc)
3853 {
3854         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
3855         struct intel_unpin_work *work = intel_crtc->unpin_work;
3856
3857         /* ensure that the unpin work is consistent wrt ->pending. */
3858         smp_rmb();
3859         intel_crtc->unpin_work = NULL;
3860
3861         if (work->event)
3862                 drm_send_vblank_event(intel_crtc->base.dev,
3863                                       intel_crtc->pipe,
3864                                       work->event);
3865
3866         drm_crtc_vblank_put(&intel_crtc->base);
3867
3868         wake_up_all(&dev_priv->pending_flip_queue);
3869         queue_work(dev_priv->wq, &work->work);
3870
3871         trace_i915_flip_complete(intel_crtc->plane,
3872                                  work->pending_flip_obj);
3873 }
3874
3875 void intel_crtc_wait_for_pending_flips(struct drm_crtc *crtc)
3876 {
3877         struct drm_device *dev = crtc->dev;
3878         struct drm_i915_private *dev_priv = dev->dev_private;
3879
3880         WARN_ON(waitqueue_active(&dev_priv->pending_flip_queue));
3881         if (WARN_ON(wait_event_timeout(dev_priv->pending_flip_queue,
3882                                        !intel_crtc_has_pending_flip(crtc),
3883                                        60*HZ) == 0)) {
3884                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3885
3886                 spin_lock_irq(&dev->event_lock);
3887                 if (intel_crtc->unpin_work) {
3888                         WARN_ONCE(1, "Removing stuck page flip\n");
3889                         page_flip_completed(intel_crtc);
3890                 }
3891                 spin_unlock_irq(&dev->event_lock);
3892         }
3893
3894         if (crtc->primary->fb) {
3895                 mutex_lock(&dev->struct_mutex);
3896                 intel_finish_fb(crtc->primary->fb);
3897                 mutex_unlock(&dev->struct_mutex);
3898         }
3899 }
3900
3901 /* Program iCLKIP clock to the desired frequency */
3902 static void lpt_program_iclkip(struct drm_crtc *crtc)
3903 {
3904         struct drm_device *dev = crtc->dev;
3905         struct drm_i915_private *dev_priv = dev->dev_private;
3906         int clock = to_intel_crtc(crtc)->config->base.adjusted_mode.crtc_clock;
3907         u32 divsel, phaseinc, auxdiv, phasedir = 0;
3908         u32 temp;
3909
3910         mutex_lock(&dev_priv->dpio_lock);
3911
3912         /* It is necessary to ungate the pixclk gate prior to programming
3913          * the divisors, and gate it back when it is done.
3914          */
3915         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
3916
3917         /* Disable SSCCTL */
3918         intel_sbi_write(dev_priv, SBI_SSCCTL6,
3919                         intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK) |
3920                                 SBI_SSCCTL_DISABLE,
3921                         SBI_ICLK);
3922
3923         /* 20MHz is a corner case which is out of range for the 7-bit divisor */
3924         if (clock == 20000) {
3925                 auxdiv = 1;
3926                 divsel = 0x41;
3927                 phaseinc = 0x20;
3928         } else {
3929                 /* The iCLK virtual clock root frequency is in MHz,
3930                  * but the adjusted_mode->crtc_clock in in KHz. To get the
3931                  * divisors, it is necessary to divide one by another, so we
3932                  * convert the virtual clock precision to KHz here for higher
3933                  * precision.
3934                  */
3935                 u32 iclk_virtual_root_freq = 172800 * 1000;
3936                 u32 iclk_pi_range = 64;
3937                 u32 desired_divisor, msb_divisor_value, pi_value;
3938
3939                 desired_divisor = (iclk_virtual_root_freq / clock);
3940                 msb_divisor_value = desired_divisor / iclk_pi_range;
3941                 pi_value = desired_divisor % iclk_pi_range;
3942
3943                 auxdiv = 0;
3944                 divsel = msb_divisor_value - 2;
3945                 phaseinc = pi_value;
3946         }
3947
3948         /* This should not happen with any sane values */
3949         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
3950                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
3951         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
3952                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
3953
3954         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
3955                         clock,
3956                         auxdiv,
3957                         divsel,
3958                         phasedir,
3959                         phaseinc);
3960
3961         /* Program SSCDIVINTPHASE6 */
3962         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
3963         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
3964         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
3965         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
3966         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
3967         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
3968         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
3969         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
3970
3971         /* Program SSCAUXDIV */
3972         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
3973         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
3974         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
3975         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
3976
3977         /* Enable modulator and associated divider */
3978         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3979         temp &= ~SBI_SSCCTL_DISABLE;
3980         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
3981
3982         /* Wait for initialization time */
3983         udelay(24);
3984
3985         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
3986
3987         mutex_unlock(&dev_priv->dpio_lock);
3988 }
3989
3990 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
3991                                                 enum pipe pch_transcoder)
3992 {
3993         struct drm_device *dev = crtc->base.dev;
3994         struct drm_i915_private *dev_priv = dev->dev_private;
3995         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
3996
3997         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
3998                    I915_READ(HTOTAL(cpu_transcoder)));
3999         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4000                    I915_READ(HBLANK(cpu_transcoder)));
4001         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4002                    I915_READ(HSYNC(cpu_transcoder)));
4003
4004         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4005                    I915_READ(VTOTAL(cpu_transcoder)));
4006         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4007                    I915_READ(VBLANK(cpu_transcoder)));
4008         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4009                    I915_READ(VSYNC(cpu_transcoder)));
4010         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4011                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4012 }
4013
4014 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4015 {
4016         struct drm_i915_private *dev_priv = dev->dev_private;
4017         uint32_t temp;
4018
4019         temp = I915_READ(SOUTH_CHICKEN1);
4020         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4021                 return;
4022
4023         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4024         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4025
4026         temp &= ~FDI_BC_BIFURCATION_SELECT;
4027         if (enable)
4028                 temp |= FDI_BC_BIFURCATION_SELECT;
4029
4030         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4031         I915_WRITE(SOUTH_CHICKEN1, temp);
4032         POSTING_READ(SOUTH_CHICKEN1);
4033 }
4034
4035 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4036 {
4037         struct drm_device *dev = intel_crtc->base.dev;
4038
4039         switch (intel_crtc->pipe) {
4040         case PIPE_A:
4041                 break;
4042         case PIPE_B:
4043                 if (intel_crtc->config->fdi_lanes > 2)
4044                         cpt_set_fdi_bc_bifurcation(dev, false);
4045                 else
4046                         cpt_set_fdi_bc_bifurcation(dev, true);
4047
4048                 break;
4049         case PIPE_C:
4050                 cpt_set_fdi_bc_bifurcation(dev, true);
4051
4052                 break;
4053         default:
4054                 BUG();
4055         }
4056 }
4057
4058 /*
4059  * Enable PCH resources required for PCH ports:
4060  *   - PCH PLLs
4061  *   - FDI training & RX/TX
4062  *   - update transcoder timings
4063  *   - DP transcoding bits
4064  *   - transcoder
4065  */
4066 static void ironlake_pch_enable(struct drm_crtc *crtc)
4067 {
4068         struct drm_device *dev = crtc->dev;
4069         struct drm_i915_private *dev_priv = dev->dev_private;
4070         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4071         int pipe = intel_crtc->pipe;
4072         u32 reg, temp;
4073
4074         assert_pch_transcoder_disabled(dev_priv, pipe);
4075
4076         if (IS_IVYBRIDGE(dev))
4077                 ivybridge_update_fdi_bc_bifurcation(intel_crtc);
4078
4079         /* Write the TU size bits before fdi link training, so that error
4080          * detection works. */
4081         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4082                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4083
4084         /* For PCH output, training FDI link */
4085         dev_priv->display.fdi_link_train(crtc);
4086
4087         /* We need to program the right clock selection before writing the pixel
4088          * mutliplier into the DPLL. */
4089         if (HAS_PCH_CPT(dev)) {
4090                 u32 sel;
4091
4092                 temp = I915_READ(PCH_DPLL_SEL);
4093                 temp |= TRANS_DPLL_ENABLE(pipe);
4094                 sel = TRANS_DPLLB_SEL(pipe);
4095                 if (intel_crtc->config->shared_dpll == DPLL_ID_PCH_PLL_B)
4096                         temp |= sel;
4097                 else
4098                         temp &= ~sel;
4099                 I915_WRITE(PCH_DPLL_SEL, temp);
4100         }
4101
4102         /* XXX: pch pll's can be enabled any time before we enable the PCH
4103          * transcoder, and we actually should do this to not upset any PCH
4104          * transcoder that already use the clock when we share it.
4105          *
4106          * Note that enable_shared_dpll tries to do the right thing, but
4107          * get_shared_dpll unconditionally resets the pll - we need that to have
4108          * the right LVDS enable sequence. */
4109         intel_enable_shared_dpll(intel_crtc);
4110
4111         /* set transcoder timing, panel must allow it */
4112         assert_panel_unlocked(dev_priv, pipe);
4113         ironlake_pch_transcoder_set_timings(intel_crtc, pipe);
4114
4115         intel_fdi_normal_train(crtc);
4116
4117         /* For PCH DP, enable TRANS_DP_CTL */
4118         if (HAS_PCH_CPT(dev) && intel_crtc->config->has_dp_encoder) {
4119                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4120                 reg = TRANS_DP_CTL(pipe);
4121                 temp = I915_READ(reg);
4122                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4123                           TRANS_DP_SYNC_MASK |
4124                           TRANS_DP_BPC_MASK);
4125                 temp |= (TRANS_DP_OUTPUT_ENABLE |
4126                          TRANS_DP_ENH_FRAMING);
4127                 temp |= bpc << 9; /* same format but at 11:9 */
4128
4129                 if (crtc->mode.flags & DRM_MODE_FLAG_PHSYNC)
4130                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4131                 if (crtc->mode.flags & DRM_MODE_FLAG_PVSYNC)
4132                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4133
4134                 switch (intel_trans_dp_port_sel(crtc)) {
4135                 case PCH_DP_B:
4136                         temp |= TRANS_DP_PORT_SEL_B;
4137                         break;
4138                 case PCH_DP_C:
4139                         temp |= TRANS_DP_PORT_SEL_C;
4140                         break;
4141                 case PCH_DP_D:
4142                         temp |= TRANS_DP_PORT_SEL_D;
4143                         break;
4144                 default:
4145                         BUG();
4146                 }
4147
4148                 I915_WRITE(reg, temp);
4149         }
4150
4151         ironlake_enable_pch_transcoder(dev_priv, pipe);
4152 }
4153
4154 static void lpt_pch_enable(struct drm_crtc *crtc)
4155 {
4156         struct drm_device *dev = crtc->dev;
4157         struct drm_i915_private *dev_priv = dev->dev_private;
4158         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4159         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4160
4161         assert_pch_transcoder_disabled(dev_priv, TRANSCODER_A);
4162
4163         lpt_program_iclkip(crtc);
4164
4165         /* Set transcoder timing. */
4166         ironlake_pch_transcoder_set_timings(intel_crtc, PIPE_A);
4167
4168         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4169 }
4170
4171 void intel_put_shared_dpll(struct intel_crtc *crtc)
4172 {
4173         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
4174
4175         if (pll == NULL)
4176                 return;
4177
4178         if (!(pll->config.crtc_mask & (1 << crtc->pipe))) {
4179                 WARN(1, "bad %s crtc mask\n", pll->name);
4180                 return;
4181         }
4182
4183         pll->config.crtc_mask &= ~(1 << crtc->pipe);
4184         if (pll->config.crtc_mask == 0) {
4185                 WARN_ON(pll->on);
4186                 WARN_ON(pll->active);
4187         }
4188
4189         crtc->config->shared_dpll = DPLL_ID_PRIVATE;
4190 }
4191
4192 struct intel_shared_dpll *intel_get_shared_dpll(struct intel_crtc *crtc,
4193                                                 struct intel_crtc_state *crtc_state)
4194 {
4195         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
4196         struct intel_shared_dpll *pll;
4197         enum intel_dpll_id i;
4198
4199         if (HAS_PCH_IBX(dev_priv->dev)) {
4200                 /* Ironlake PCH has a fixed PLL->PCH pipe mapping. */
4201                 i = (enum intel_dpll_id) crtc->pipe;
4202                 pll = &dev_priv->shared_dplls[i];
4203
4204                 DRM_DEBUG_KMS("CRTC:%d using pre-allocated %s\n",
4205                               crtc->base.base.id, pll->name);
4206
4207                 WARN_ON(pll->new_config->crtc_mask);
4208
4209                 goto found;
4210         }
4211
4212         if (IS_BROXTON(dev_priv->dev)) {
4213                 /* PLL is attached to port in bxt */
4214                 struct intel_encoder *encoder;
4215                 struct intel_digital_port *intel_dig_port;
4216
4217                 encoder = intel_ddi_get_crtc_new_encoder(crtc_state);
4218                 if (WARN_ON(!encoder))
4219                         return NULL;
4220
4221                 intel_dig_port = enc_to_dig_port(&encoder->base);
4222                 /* 1:1 mapping between ports and PLLs */
4223                 i = (enum intel_dpll_id)intel_dig_port->port;
4224                 pll = &dev_priv->shared_dplls[i];
4225                 DRM_DEBUG_KMS("CRTC:%d using pre-allocated %s\n",
4226                         crtc->base.base.id, pll->name);
4227                 WARN_ON(pll->new_config->crtc_mask);
4228
4229                 goto found;
4230         }
4231
4232         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4233                 pll = &dev_priv->shared_dplls[i];
4234
4235                 /* Only want to check enabled timings first */
4236                 if (pll->new_config->crtc_mask == 0)
4237                         continue;
4238
4239                 if (memcmp(&crtc_state->dpll_hw_state,
4240                            &pll->new_config->hw_state,
4241                            sizeof(pll->new_config->hw_state)) == 0) {
4242                         DRM_DEBUG_KMS("CRTC:%d sharing existing %s (crtc mask 0x%08x, ative %d)\n",
4243                                       crtc->base.base.id, pll->name,
4244                                       pll->new_config->crtc_mask,
4245                                       pll->active);
4246                         goto found;
4247                 }
4248         }
4249
4250         /* Ok no matching timings, maybe there's a free one? */
4251         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4252                 pll = &dev_priv->shared_dplls[i];
4253                 if (pll->new_config->crtc_mask == 0) {
4254                         DRM_DEBUG_KMS("CRTC:%d allocated %s\n",
4255                                       crtc->base.base.id, pll->name);
4256                         goto found;
4257                 }
4258         }
4259
4260         return NULL;
4261
4262 found:
4263         if (pll->new_config->crtc_mask == 0)
4264                 pll->new_config->hw_state = crtc_state->dpll_hw_state;
4265
4266         crtc_state->shared_dpll = i;
4267         DRM_DEBUG_DRIVER("using %s for pipe %c\n", pll->name,
4268                          pipe_name(crtc->pipe));
4269
4270         pll->new_config->crtc_mask |= 1 << crtc->pipe;
4271
4272         return pll;
4273 }
4274
4275 /**
4276  * intel_shared_dpll_start_config - start a new PLL staged config
4277  * @dev_priv: DRM device
4278  * @clear_pipes: mask of pipes that will have their PLLs freed
4279  *
4280  * Starts a new PLL staged config, copying the current config but
4281  * releasing the references of pipes specified in clear_pipes.
4282  */
4283 static int intel_shared_dpll_start_config(struct drm_i915_private *dev_priv,
4284                                           unsigned clear_pipes)
4285 {
4286         struct intel_shared_dpll *pll;
4287         enum intel_dpll_id i;
4288
4289         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4290                 pll = &dev_priv->shared_dplls[i];
4291
4292                 pll->new_config = kmemdup(&pll->config, sizeof pll->config,
4293                                           GFP_KERNEL);
4294                 if (!pll->new_config)
4295                         goto cleanup;
4296
4297                 pll->new_config->crtc_mask &= ~clear_pipes;
4298         }
4299
4300         return 0;
4301
4302 cleanup:
4303         while (--i >= 0) {
4304                 pll = &dev_priv->shared_dplls[i];
4305                 kfree(pll->new_config);
4306                 pll->new_config = NULL;
4307         }
4308
4309         return -ENOMEM;
4310 }
4311
4312 static void intel_shared_dpll_commit(struct drm_i915_private *dev_priv)
4313 {
4314         struct intel_shared_dpll *pll;
4315         enum intel_dpll_id i;
4316
4317         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4318                 pll = &dev_priv->shared_dplls[i];
4319
4320                 WARN_ON(pll->new_config == &pll->config);
4321
4322                 pll->config = *pll->new_config;
4323                 kfree(pll->new_config);
4324                 pll->new_config = NULL;
4325         }
4326 }
4327
4328 static void intel_shared_dpll_abort_config(struct drm_i915_private *dev_priv)
4329 {
4330         struct intel_shared_dpll *pll;
4331         enum intel_dpll_id i;
4332
4333         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4334                 pll = &dev_priv->shared_dplls[i];
4335
4336                 WARN_ON(pll->new_config == &pll->config);
4337
4338                 kfree(pll->new_config);
4339                 pll->new_config = NULL;
4340         }
4341 }
4342
4343 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4344 {
4345         struct drm_i915_private *dev_priv = dev->dev_private;
4346         int dslreg = PIPEDSL(pipe);
4347         u32 temp;
4348
4349         temp = I915_READ(dslreg);
4350         udelay(500);
4351         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4352                 if (wait_for(I915_READ(dslreg) != temp, 5))
4353                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4354         }
4355 }
4356
4357 /**
4358  * skl_update_scaler_users - Stages update to crtc's scaler state
4359  * @intel_crtc: crtc
4360  * @crtc_state: crtc_state
4361  * @plane: plane (NULL indicates crtc is requesting update)
4362  * @plane_state: plane's state
4363  * @force_detach: request unconditional detachment of scaler
4364  *
4365  * This function updates scaler state for requested plane or crtc.
4366  * To request scaler usage update for a plane, caller shall pass plane pointer.
4367  * To request scaler usage update for crtc, caller shall pass plane pointer
4368  * as NULL.
4369  *
4370  * Return
4371  *     0 - scaler_usage updated successfully
4372  *    error - requested scaling cannot be supported or other error condition
4373  */
4374 int
4375 skl_update_scaler_users(
4376         struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state,
4377         struct intel_plane *intel_plane, struct intel_plane_state *plane_state,
4378         int force_detach)
4379 {
4380         int need_scaling;
4381         int idx;
4382         int src_w, src_h, dst_w, dst_h;
4383         int *scaler_id;
4384         struct drm_framebuffer *fb;
4385         struct intel_crtc_scaler_state *scaler_state;
4386
4387         if (!intel_crtc || !crtc_state)
4388                 return 0;
4389
4390         scaler_state = &crtc_state->scaler_state;
4391
4392         idx = intel_plane ? drm_plane_index(&intel_plane->base) : SKL_CRTC_INDEX;
4393         fb = intel_plane ? plane_state->base.fb : NULL;
4394
4395         if (intel_plane) {
4396                 src_w = drm_rect_width(&plane_state->src) >> 16;
4397                 src_h = drm_rect_height(&plane_state->src) >> 16;
4398                 dst_w = drm_rect_width(&plane_state->dst);
4399                 dst_h = drm_rect_height(&plane_state->dst);
4400                 scaler_id = &plane_state->scaler_id;
4401         } else {
4402                 struct drm_display_mode *adjusted_mode =
4403                         &crtc_state->base.adjusted_mode;
4404                 src_w = crtc_state->pipe_src_w;
4405                 src_h = crtc_state->pipe_src_h;
4406                 dst_w = adjusted_mode->hdisplay;
4407                 dst_h = adjusted_mode->vdisplay;
4408                 scaler_id = &scaler_state->scaler_id;
4409         }
4410         need_scaling = (src_w != dst_w || src_h != dst_h);
4411
4412         /*
4413          * if plane is being disabled or scaler is no more required or force detach
4414          *  - free scaler binded to this plane/crtc
4415          *  - in order to do this, update crtc->scaler_usage
4416          *
4417          * Here scaler state in crtc_state is set free so that
4418          * scaler can be assigned to other user. Actual register
4419          * update to free the scaler is done in plane/panel-fit programming.
4420          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4421          */
4422         if (force_detach || !need_scaling || (intel_plane &&
4423                 (!fb || !plane_state->visible))) {
4424                 if (*scaler_id >= 0) {
4425                         scaler_state->scaler_users &= ~(1 << idx);
4426                         scaler_state->scalers[*scaler_id].in_use = 0;
4427
4428                         DRM_DEBUG_KMS("Staged freeing scaler id %d.%d from %s:%d "
4429                                 "crtc_state = %p scaler_users = 0x%x\n",
4430                                 intel_crtc->pipe, *scaler_id, intel_plane ? "PLANE" : "CRTC",
4431                                 intel_plane ? intel_plane->base.base.id :
4432                                 intel_crtc->base.base.id, crtc_state,
4433                                 scaler_state->scaler_users);
4434                         *scaler_id = -1;
4435                 }
4436                 return 0;
4437         }
4438
4439         /* range checks */
4440         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4441                 dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4442
4443                 src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4444                 dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H) {
4445                 DRM_DEBUG_KMS("%s:%d scaler_user index %u.%u: src %ux%u dst %ux%u "
4446                         "size is out of scaler range\n",
4447                         intel_plane ? "PLANE" : "CRTC",
4448                         intel_plane ? intel_plane->base.base.id : intel_crtc->base.base.id,
4449                         intel_crtc->pipe, idx, src_w, src_h, dst_w, dst_h);
4450                 return -EINVAL;
4451         }
4452
4453         /* check colorkey */
4454         if (intel_plane && intel_plane->ckey.flags != I915_SET_COLORKEY_NONE) {
4455                 DRM_DEBUG_KMS("PLANE:%d scaling with color key not allowed",
4456                         intel_plane->base.base.id);
4457                 return -EINVAL;
4458         }
4459
4460         /* Check src format */
4461         if (intel_plane) {
4462                 switch (fb->pixel_format) {
4463                 case DRM_FORMAT_RGB565:
4464                 case DRM_FORMAT_XBGR8888:
4465                 case DRM_FORMAT_XRGB8888:
4466                 case DRM_FORMAT_ABGR8888:
4467                 case DRM_FORMAT_ARGB8888:
4468                 case DRM_FORMAT_XRGB2101010:
4469                 case DRM_FORMAT_ARGB2101010:
4470                 case DRM_FORMAT_XBGR2101010:
4471                 case DRM_FORMAT_ABGR2101010:
4472                 case DRM_FORMAT_YUYV:
4473                 case DRM_FORMAT_YVYU:
4474                 case DRM_FORMAT_UYVY:
4475                 case DRM_FORMAT_VYUY:
4476                         break;
4477                 default:
4478                         DRM_DEBUG_KMS("PLANE:%d FB:%d unsupported scaling format 0x%x\n",
4479                                 intel_plane->base.base.id, fb->base.id, fb->pixel_format);
4480                         return -EINVAL;
4481                 }
4482         }
4483
4484         /* mark this plane as a scaler user in crtc_state */
4485         scaler_state->scaler_users |= (1 << idx);
4486         DRM_DEBUG_KMS("%s:%d staged scaling request for %ux%u->%ux%u "
4487                 "crtc_state = %p scaler_users = 0x%x\n",
4488                 intel_plane ? "PLANE" : "CRTC",
4489                 intel_plane ? intel_plane->base.base.id : intel_crtc->base.base.id,
4490                 src_w, src_h, dst_w, dst_h, crtc_state, scaler_state->scaler_users);
4491         return 0;
4492 }
4493
4494 static void skylake_pfit_update(struct intel_crtc *crtc, int enable)
4495 {
4496         struct drm_device *dev = crtc->base.dev;
4497         struct drm_i915_private *dev_priv = dev->dev_private;
4498         int pipe = crtc->pipe;
4499         struct intel_crtc_scaler_state *scaler_state =
4500                 &crtc->config->scaler_state;
4501
4502         DRM_DEBUG_KMS("for crtc_state = %p\n", crtc->config);
4503
4504         /* To update pfit, first update scaler state */
4505         skl_update_scaler_users(crtc, crtc->config, NULL, NULL, !enable);
4506         intel_atomic_setup_scalers(crtc->base.dev, crtc, crtc->config);
4507         skl_detach_scalers(crtc);
4508         if (!enable)
4509                 return;
4510
4511         if (crtc->config->pch_pfit.enabled) {
4512                 int id;
4513
4514                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0)) {
4515                         DRM_ERROR("Requesting pfit without getting a scaler first\n");
4516                         return;
4517                 }
4518
4519                 id = scaler_state->scaler_id;
4520                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4521                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4522                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
4523                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
4524
4525                 DRM_DEBUG_KMS("for crtc_state = %p scaler_id = %d\n", crtc->config, id);
4526         }
4527 }
4528
4529 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4530 {
4531         struct drm_device *dev = crtc->base.dev;
4532         struct drm_i915_private *dev_priv = dev->dev_private;
4533         int pipe = crtc->pipe;
4534
4535         if (crtc->config->pch_pfit.enabled) {
4536                 /* Force use of hard-coded filter coefficients
4537                  * as some pre-programmed values are broken,
4538                  * e.g. x201.
4539                  */
4540                 if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev))
4541                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4542                                                  PF_PIPE_SEL_IVB(pipe));
4543                 else
4544                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4545                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4546                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4547         }
4548 }
4549
4550 static void intel_enable_sprite_planes(struct drm_crtc *crtc)
4551 {
4552         struct drm_device *dev = crtc->dev;
4553         enum pipe pipe = to_intel_crtc(crtc)->pipe;
4554         struct drm_plane *plane;
4555         struct intel_plane *intel_plane;
4556
4557         drm_for_each_legacy_plane(plane, &dev->mode_config.plane_list) {
4558                 intel_plane = to_intel_plane(plane);
4559                 if (intel_plane->pipe == pipe)
4560                         intel_plane_restore(&intel_plane->base);
4561         }
4562 }
4563
4564 /*
4565  * Disable a plane internally without actually modifying the plane's state.
4566  * This will allow us to easily restore the plane later by just reprogramming
4567  * its state.
4568  */
4569 static void disable_plane_internal(struct drm_plane *plane)
4570 {
4571         struct intel_plane *intel_plane = to_intel_plane(plane);
4572         struct drm_plane_state *state =
4573                 plane->funcs->atomic_duplicate_state(plane);
4574         struct intel_plane_state *intel_state = to_intel_plane_state(state);
4575
4576         intel_state->visible = false;
4577         intel_plane->commit_plane(plane, intel_state);
4578
4579         intel_plane_destroy_state(plane, state);
4580 }
4581
4582 static void intel_disable_sprite_planes(struct drm_crtc *crtc)
4583 {
4584         struct drm_device *dev = crtc->dev;
4585         enum pipe pipe = to_intel_crtc(crtc)->pipe;
4586         struct drm_plane *plane;
4587         struct intel_plane *intel_plane;
4588
4589         drm_for_each_legacy_plane(plane, &dev->mode_config.plane_list) {
4590                 intel_plane = to_intel_plane(plane);
4591                 if (plane->fb && intel_plane->pipe == pipe)
4592                         disable_plane_internal(plane);
4593         }
4594 }
4595
4596 void hsw_enable_ips(struct intel_crtc *crtc)
4597 {
4598         struct drm_device *dev = crtc->base.dev;
4599         struct drm_i915_private *dev_priv = dev->dev_private;
4600
4601         if (!crtc->config->ips_enabled)
4602                 return;
4603
4604         /* We can only enable IPS after we enable a plane and wait for a vblank */
4605         intel_wait_for_vblank(dev, crtc->pipe);
4606
4607         assert_plane_enabled(dev_priv, crtc->plane);
4608         if (IS_BROADWELL(dev)) {
4609                 mutex_lock(&dev_priv->rps.hw_lock);
4610                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0xc0000000));
4611                 mutex_unlock(&dev_priv->rps.hw_lock);
4612                 /* Quoting Art Runyan: "its not safe to expect any particular
4613                  * value in IPS_CTL bit 31 after enabling IPS through the
4614                  * mailbox." Moreover, the mailbox may return a bogus state,
4615                  * so we need to just enable it and continue on.
4616                  */
4617         } else {
4618                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4619                 /* The bit only becomes 1 in the next vblank, so this wait here
4620                  * is essentially intel_wait_for_vblank. If we don't have this
4621                  * and don't wait for vblanks until the end of crtc_enable, then
4622                  * the HW state readout code will complain that the expected
4623                  * IPS_CTL value is not the one we read. */
4624                 if (wait_for(I915_READ_NOTRACE(IPS_CTL) & IPS_ENABLE, 50))
4625                         DRM_ERROR("Timed out waiting for IPS enable\n");
4626         }
4627 }
4628
4629 void hsw_disable_ips(struct intel_crtc *crtc)
4630 {
4631         struct drm_device *dev = crtc->base.dev;
4632         struct drm_i915_private *dev_priv = dev->dev_private;
4633
4634         if (!crtc->config->ips_enabled)
4635                 return;
4636
4637         assert_plane_enabled(dev_priv, crtc->plane);
4638         if (IS_BROADWELL(dev)) {
4639                 mutex_lock(&dev_priv->rps.hw_lock);
4640                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4641                 mutex_unlock(&dev_priv->rps.hw_lock);
4642                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4643                 if (wait_for((I915_READ(IPS_CTL) & IPS_ENABLE) == 0, 42))
4644                         DRM_ERROR("Timed out waiting for IPS disable\n");
4645         } else {
4646                 I915_WRITE(IPS_CTL, 0);
4647                 POSTING_READ(IPS_CTL);
4648         }
4649
4650         /* We need to wait for a vblank before we can disable the plane. */
4651         intel_wait_for_vblank(dev, crtc->pipe);
4652 }
4653
4654 /** Loads the palette/gamma unit for the CRTC with the prepared values */
4655 static void intel_crtc_load_lut(struct drm_crtc *crtc)
4656 {
4657         struct drm_device *dev = crtc->dev;
4658         struct drm_i915_private *dev_priv = dev->dev_private;
4659         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4660         enum pipe pipe = intel_crtc->pipe;
4661         int palreg = PALETTE(pipe);
4662         int i;
4663         bool reenable_ips = false;
4664
4665         /* The clocks have to be on to load the palette. */
4666         if (!crtc->state->enable || !intel_crtc->active)
4667                 return;
4668
4669         if (HAS_GMCH_DISPLAY(dev_priv->dev)) {
4670                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_DSI))
4671                         assert_dsi_pll_enabled(dev_priv);
4672                 else
4673                         assert_pll_enabled(dev_priv, pipe);
4674         }
4675
4676         /* use legacy palette for Ironlake */
4677         if (!HAS_GMCH_DISPLAY(dev))
4678                 palreg = LGC_PALETTE(pipe);
4679
4680         /* Workaround : Do not read or write the pipe palette/gamma data while
4681          * GAMMA_MODE is configured for split gamma and IPS_CTL has IPS enabled.
4682          */
4683         if (IS_HASWELL(dev) && intel_crtc->config->ips_enabled &&
4684             ((I915_READ(GAMMA_MODE(pipe)) & GAMMA_MODE_MODE_MASK) ==
4685              GAMMA_MODE_MODE_SPLIT)) {
4686                 hsw_disable_ips(intel_crtc);
4687                 reenable_ips = true;
4688         }
4689
4690         for (i = 0; i < 256; i++) {
4691                 I915_WRITE(palreg + 4 * i,
4692                            (intel_crtc->lut_r[i] << 16) |
4693                            (intel_crtc->lut_g[i] << 8) |
4694                            intel_crtc->lut_b[i]);
4695         }
4696
4697         if (reenable_ips)
4698                 hsw_enable_ips(intel_crtc);
4699 }
4700
4701 static void intel_crtc_dpms_overlay(struct intel_crtc *intel_crtc, bool enable)
4702 {
4703         if (!enable && intel_crtc->overlay) {
4704                 struct drm_device *dev = intel_crtc->base.dev;
4705                 struct drm_i915_private *dev_priv = dev->dev_private;
4706
4707                 mutex_lock(&dev->struct_mutex);
4708                 dev_priv->mm.interruptible = false;
4709                 (void) intel_overlay_switch_off(intel_crtc->overlay);
4710                 dev_priv->mm.interruptible = true;
4711                 mutex_unlock(&dev->struct_mutex);
4712         }
4713
4714         /* Let userspace switch the overlay on again. In most cases userspace
4715          * has to recompute where to put it anyway.
4716          */
4717 }
4718
4719 static void intel_crtc_enable_planes(struct drm_crtc *crtc)
4720 {
4721         struct drm_device *dev = crtc->dev;
4722         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4723         int pipe = intel_crtc->pipe;
4724
4725         intel_enable_primary_hw_plane(crtc->primary, crtc);
4726         intel_enable_sprite_planes(crtc);
4727         intel_crtc_update_cursor(crtc, true);
4728         intel_crtc_dpms_overlay(intel_crtc, true);
4729
4730         hsw_enable_ips(intel_crtc);
4731
4732         mutex_lock(&dev->struct_mutex);
4733         intel_fbc_update(dev);
4734         mutex_unlock(&dev->struct_mutex);
4735
4736         /*
4737          * FIXME: Once we grow proper nuclear flip support out of this we need
4738          * to compute the mask of flip planes precisely. For the time being
4739          * consider this a flip from a NULL plane.
4740          */
4741         intel_frontbuffer_flip(dev, INTEL_FRONTBUFFER_ALL_MASK(pipe));
4742 }
4743
4744 static void intel_crtc_disable_planes(struct drm_crtc *crtc)
4745 {
4746         struct drm_device *dev = crtc->dev;
4747         struct drm_i915_private *dev_priv = dev->dev_private;
4748         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4749         int pipe = intel_crtc->pipe;
4750
4751         intel_crtc_wait_for_pending_flips(crtc);
4752
4753         if (dev_priv->fbc.crtc == intel_crtc)
4754                 intel_fbc_disable(dev);
4755
4756         hsw_disable_ips(intel_crtc);
4757
4758         intel_crtc_dpms_overlay(intel_crtc, false);
4759         intel_crtc_update_cursor(crtc, false);
4760         intel_disable_sprite_planes(crtc);
4761         intel_disable_primary_hw_plane(crtc->primary, crtc);
4762
4763         /*
4764          * FIXME: Once we grow proper nuclear flip support out of this we need
4765          * to compute the mask of flip planes precisely. For the time being
4766          * consider this a flip to a NULL plane.
4767          */
4768         intel_frontbuffer_flip(dev, INTEL_FRONTBUFFER_ALL_MASK(pipe));
4769 }
4770
4771 static void ironlake_crtc_enable(struct drm_crtc *crtc)
4772 {
4773         struct drm_device *dev = crtc->dev;
4774         struct drm_i915_private *dev_priv = dev->dev_private;
4775         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4776         struct intel_encoder *encoder;
4777         int pipe = intel_crtc->pipe;
4778
4779         WARN_ON(!crtc->state->enable);
4780
4781         if (intel_crtc->active)
4782                 return;
4783
4784         if (intel_crtc->config->has_pch_encoder)
4785                 intel_prepare_shared_dpll(intel_crtc);
4786
4787         if (intel_crtc->config->has_dp_encoder)
4788                 intel_dp_set_m_n(intel_crtc, M1_N1);
4789
4790         intel_set_pipe_timings(intel_crtc);
4791
4792         if (intel_crtc->config->has_pch_encoder) {
4793                 intel_cpu_transcoder_set_m_n(intel_crtc,
4794                                      &intel_crtc->config->fdi_m_n, NULL);
4795         }
4796
4797         ironlake_set_pipeconf(crtc);
4798
4799         intel_crtc->active = true;
4800
4801         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4802         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
4803
4804         for_each_encoder_on_crtc(dev, crtc, encoder)
4805                 if (encoder->pre_enable)
4806                         encoder->pre_enable(encoder);
4807
4808         if (intel_crtc->config->has_pch_encoder) {
4809                 /* Note: FDI PLL enabling _must_ be done before we enable the
4810                  * cpu pipes, hence this is separate from all the other fdi/pch
4811                  * enabling. */
4812                 ironlake_fdi_pll_enable(intel_crtc);
4813         } else {
4814                 assert_fdi_tx_disabled(dev_priv, pipe);
4815                 assert_fdi_rx_disabled(dev_priv, pipe);
4816         }
4817
4818         ironlake_pfit_enable(intel_crtc);
4819
4820         /*
4821          * On ILK+ LUT must be loaded before the pipe is running but with
4822          * clocks enabled
4823          */
4824         intel_crtc_load_lut(crtc);
4825
4826         intel_update_watermarks(crtc);
4827         intel_enable_pipe(intel_crtc);
4828
4829         if (intel_crtc->config->has_pch_encoder)
4830                 ironlake_pch_enable(crtc);
4831
4832         assert_vblank_disabled(crtc);
4833         drm_crtc_vblank_on(crtc);
4834
4835         for_each_encoder_on_crtc(dev, crtc, encoder)
4836                 encoder->enable(encoder);
4837
4838         if (HAS_PCH_CPT(dev))
4839                 cpt_verify_modeset(dev, intel_crtc->pipe);
4840
4841         intel_crtc_enable_planes(crtc);
4842 }
4843
4844 /* IPS only exists on ULT machines and is tied to pipe A. */
4845 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
4846 {
4847         return HAS_IPS(crtc->base.dev) && crtc->pipe == PIPE_A;
4848 }
4849
4850 /*
4851  * This implements the workaround described in the "notes" section of the mode
4852  * set sequence documentation. When going from no pipes or single pipe to
4853  * multiple pipes, and planes are enabled after the pipe, we need to wait at
4854  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
4855  */
4856 static void haswell_mode_set_planes_workaround(struct intel_crtc *crtc)
4857 {
4858         struct drm_device *dev = crtc->base.dev;
4859         struct intel_crtc *crtc_it, *other_active_crtc = NULL;
4860
4861         /* We want to get the other_active_crtc only if there's only 1 other
4862          * active crtc. */
4863         for_each_intel_crtc(dev, crtc_it) {
4864                 if (!crtc_it->active || crtc_it == crtc)
4865                         continue;
4866
4867                 if (other_active_crtc)
4868                         return;
4869
4870                 other_active_crtc = crtc_it;
4871         }
4872         if (!other_active_crtc)
4873                 return;
4874
4875         intel_wait_for_vblank(dev, other_active_crtc->pipe);
4876         intel_wait_for_vblank(dev, other_active_crtc->pipe);
4877 }
4878
4879 static void haswell_crtc_enable(struct drm_crtc *crtc)
4880 {
4881         struct drm_device *dev = crtc->dev;
4882         struct drm_i915_private *dev_priv = dev->dev_private;
4883         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4884         struct intel_encoder *encoder;
4885         int pipe = intel_crtc->pipe;
4886
4887         WARN_ON(!crtc->state->enable);
4888
4889         if (intel_crtc->active)
4890                 return;
4891
4892         if (intel_crtc_to_shared_dpll(intel_crtc))
4893                 intel_enable_shared_dpll(intel_crtc);
4894
4895         if (intel_crtc->config->has_dp_encoder)
4896                 intel_dp_set_m_n(intel_crtc, M1_N1);
4897
4898         intel_set_pipe_timings(intel_crtc);
4899
4900         if (intel_crtc->config->cpu_transcoder != TRANSCODER_EDP) {
4901                 I915_WRITE(PIPE_MULT(intel_crtc->config->cpu_transcoder),
4902                            intel_crtc->config->pixel_multiplier - 1);
4903         }
4904
4905         if (intel_crtc->config->has_pch_encoder) {
4906                 intel_cpu_transcoder_set_m_n(intel_crtc,
4907                                      &intel_crtc->config->fdi_m_n, NULL);
4908         }
4909
4910         haswell_set_pipeconf(crtc);
4911
4912         intel_set_pipe_csc(crtc);
4913
4914         intel_crtc->active = true;
4915
4916         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4917         for_each_encoder_on_crtc(dev, crtc, encoder)
4918                 if (encoder->pre_enable)
4919                         encoder->pre_enable(encoder);
4920
4921         if (intel_crtc->config->has_pch_encoder) {
4922                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4923                                                       true);
4924                 dev_priv->display.fdi_link_train(crtc);
4925         }
4926
4927         intel_ddi_enable_pipe_clock(intel_crtc);
4928
4929         if (INTEL_INFO(dev)->gen == 9)
4930                 skylake_pfit_update(intel_crtc, 1);
4931         else if (INTEL_INFO(dev)->gen < 9)
4932                 ironlake_pfit_enable(intel_crtc);
4933         else
4934                 MISSING_CASE(INTEL_INFO(dev)->gen);
4935
4936         /*
4937          * On ILK+ LUT must be loaded before the pipe is running but with
4938          * clocks enabled
4939          */
4940         intel_crtc_load_lut(crtc);
4941
4942         intel_ddi_set_pipe_settings(crtc);
4943         intel_ddi_enable_transcoder_func(crtc);
4944
4945         intel_update_watermarks(crtc);
4946         intel_enable_pipe(intel_crtc);
4947
4948         if (intel_crtc->config->has_pch_encoder)
4949                 lpt_pch_enable(crtc);
4950
4951         if (intel_crtc->config->dp_encoder_is_mst)
4952                 intel_ddi_set_vc_payload_alloc(crtc, true);
4953
4954         assert_vblank_disabled(crtc);
4955         drm_crtc_vblank_on(crtc);
4956
4957         for_each_encoder_on_crtc(dev, crtc, encoder) {
4958                 encoder->enable(encoder);
4959                 intel_opregion_notify_encoder(encoder, true);
4960         }
4961
4962         /* If we change the relative order between pipe/planes enabling, we need
4963          * to change the workaround. */
4964         haswell_mode_set_planes_workaround(intel_crtc);
4965         intel_crtc_enable_planes(crtc);
4966 }
4967
4968 static void ironlake_pfit_disable(struct intel_crtc *crtc)
4969 {
4970         struct drm_device *dev = crtc->base.dev;
4971         struct drm_i915_private *dev_priv = dev->dev_private;
4972         int pipe = crtc->pipe;
4973
4974         /* To avoid upsetting the power well on haswell only disable the pfit if
4975          * it's in use. The hw state code will make sure we get this right. */
4976         if (crtc->config->pch_pfit.enabled) {
4977                 I915_WRITE(PF_CTL(pipe), 0);
4978                 I915_WRITE(PF_WIN_POS(pipe), 0);
4979                 I915_WRITE(PF_WIN_SZ(pipe), 0);
4980         }
4981 }
4982
4983 static void ironlake_crtc_disable(struct drm_crtc *crtc)
4984 {
4985         struct drm_device *dev = crtc->dev;
4986         struct drm_i915_private *dev_priv = dev->dev_private;
4987         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4988         struct intel_encoder *encoder;
4989         int pipe = intel_crtc->pipe;
4990         u32 reg, temp;
4991
4992         if (!intel_crtc->active)
4993                 return;
4994
4995         intel_crtc_disable_planes(crtc);
4996
4997         for_each_encoder_on_crtc(dev, crtc, encoder)
4998                 encoder->disable(encoder);
4999
5000         drm_crtc_vblank_off(crtc);
5001         assert_vblank_disabled(crtc);
5002
5003         if (intel_crtc->config->has_pch_encoder)
5004                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5005
5006         intel_disable_pipe(intel_crtc);
5007
5008         ironlake_pfit_disable(intel_crtc);
5009
5010         for_each_encoder_on_crtc(dev, crtc, encoder)
5011                 if (encoder->post_disable)
5012                         encoder->post_disable(encoder);
5013
5014         if (intel_crtc->config->has_pch_encoder) {
5015                 ironlake_fdi_disable(crtc);
5016
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                 /* disable PCH DPLL */
5035                 intel_disable_shared_dpll(intel_crtc);
5036
5037                 ironlake_fdi_pll_disable(intel_crtc);
5038         }
5039
5040         intel_crtc->active = false;
5041         intel_update_watermarks(crtc);
5042
5043         mutex_lock(&dev->struct_mutex);
5044         intel_fbc_update(dev);
5045         mutex_unlock(&dev->struct_mutex);
5046 }
5047
5048 static void haswell_crtc_disable(struct drm_crtc *crtc)
5049 {
5050         struct drm_device *dev = crtc->dev;
5051         struct drm_i915_private *dev_priv = dev->dev_private;
5052         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5053         struct intel_encoder *encoder;
5054         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5055
5056         if (!intel_crtc->active)
5057                 return;
5058
5059         intel_crtc_disable_planes(crtc);
5060
5061         for_each_encoder_on_crtc(dev, crtc, encoder) {
5062                 intel_opregion_notify_encoder(encoder, false);
5063                 encoder->disable(encoder);
5064         }
5065
5066         drm_crtc_vblank_off(crtc);
5067         assert_vblank_disabled(crtc);
5068
5069         if (intel_crtc->config->has_pch_encoder)
5070                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5071                                                       false);
5072         intel_disable_pipe(intel_crtc);
5073
5074         if (intel_crtc->config->dp_encoder_is_mst)
5075                 intel_ddi_set_vc_payload_alloc(crtc, false);
5076
5077         intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
5078
5079         if (INTEL_INFO(dev)->gen == 9)
5080                 skylake_pfit_update(intel_crtc, 0);
5081         else if (INTEL_INFO(dev)->gen < 9)
5082                 ironlake_pfit_disable(intel_crtc);
5083         else
5084                 MISSING_CASE(INTEL_INFO(dev)->gen);
5085
5086         intel_ddi_disable_pipe_clock(intel_crtc);
5087
5088         if (intel_crtc->config->has_pch_encoder) {
5089                 lpt_disable_pch_transcoder(dev_priv);
5090                 intel_ddi_fdi_disable(crtc);
5091         }
5092
5093         for_each_encoder_on_crtc(dev, crtc, encoder)
5094                 if (encoder->post_disable)
5095                         encoder->post_disable(encoder);
5096
5097         intel_crtc->active = false;
5098         intel_update_watermarks(crtc);
5099
5100         mutex_lock(&dev->struct_mutex);
5101         intel_fbc_update(dev);
5102         mutex_unlock(&dev->struct_mutex);
5103
5104         if (intel_crtc_to_shared_dpll(intel_crtc))
5105                 intel_disable_shared_dpll(intel_crtc);
5106 }
5107
5108 static void ironlake_crtc_off(struct drm_crtc *crtc)
5109 {
5110         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5111         intel_put_shared_dpll(intel_crtc);
5112 }
5113
5114
5115 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5116 {
5117         struct drm_device *dev = crtc->base.dev;
5118         struct drm_i915_private *dev_priv = dev->dev_private;
5119         struct intel_crtc_state *pipe_config = crtc->config;
5120
5121         if (!pipe_config->gmch_pfit.control)
5122                 return;
5123
5124         /*
5125          * The panel fitter should only be adjusted whilst the pipe is disabled,
5126          * according to register description and PRM.
5127          */
5128         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5129         assert_pipe_disabled(dev_priv, crtc->pipe);
5130
5131         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5132         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5133
5134         /* Border color in case we don't scale up to the full screen. Black by
5135          * default, change to something else for debugging. */
5136         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5137 }
5138
5139 static enum intel_display_power_domain port_to_power_domain(enum port port)
5140 {
5141         switch (port) {
5142         case PORT_A:
5143                 return POWER_DOMAIN_PORT_DDI_A_4_LANES;
5144         case PORT_B:
5145                 return POWER_DOMAIN_PORT_DDI_B_4_LANES;
5146         case PORT_C:
5147                 return POWER_DOMAIN_PORT_DDI_C_4_LANES;
5148         case PORT_D:
5149                 return POWER_DOMAIN_PORT_DDI_D_4_LANES;
5150         default:
5151                 WARN_ON_ONCE(1);
5152                 return POWER_DOMAIN_PORT_OTHER;
5153         }
5154 }
5155
5156 #define for_each_power_domain(domain, mask)                             \
5157         for ((domain) = 0; (domain) < POWER_DOMAIN_NUM; (domain)++)     \
5158                 if ((1 << (domain)) & (mask))
5159
5160 enum intel_display_power_domain
5161 intel_display_port_power_domain(struct intel_encoder *intel_encoder)
5162 {
5163         struct drm_device *dev = intel_encoder->base.dev;
5164         struct intel_digital_port *intel_dig_port;
5165
5166         switch (intel_encoder->type) {
5167         case INTEL_OUTPUT_UNKNOWN:
5168                 /* Only DDI platforms should ever use this output type */
5169                 WARN_ON_ONCE(!HAS_DDI(dev));
5170         case INTEL_OUTPUT_DISPLAYPORT:
5171         case INTEL_OUTPUT_HDMI:
5172         case INTEL_OUTPUT_EDP:
5173                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5174                 return port_to_power_domain(intel_dig_port->port);
5175         case INTEL_OUTPUT_DP_MST:
5176                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5177                 return port_to_power_domain(intel_dig_port->port);
5178         case INTEL_OUTPUT_ANALOG:
5179                 return POWER_DOMAIN_PORT_CRT;
5180         case INTEL_OUTPUT_DSI:
5181                 return POWER_DOMAIN_PORT_DSI;
5182         default:
5183                 return POWER_DOMAIN_PORT_OTHER;
5184         }
5185 }
5186
5187 static unsigned long get_crtc_power_domains(struct drm_crtc *crtc)
5188 {
5189         struct drm_device *dev = crtc->dev;
5190         struct intel_encoder *intel_encoder;
5191         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5192         enum pipe pipe = intel_crtc->pipe;
5193         unsigned long mask;
5194         enum transcoder transcoder;
5195
5196         transcoder = intel_pipe_to_cpu_transcoder(dev->dev_private, pipe);
5197
5198         mask = BIT(POWER_DOMAIN_PIPE(pipe));
5199         mask |= BIT(POWER_DOMAIN_TRANSCODER(transcoder));
5200         if (intel_crtc->config->pch_pfit.enabled ||
5201             intel_crtc->config->pch_pfit.force_thru)
5202                 mask |= BIT(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5203
5204         for_each_encoder_on_crtc(dev, crtc, intel_encoder)
5205                 mask |= BIT(intel_display_port_power_domain(intel_encoder));
5206
5207         return mask;
5208 }
5209
5210 static void modeset_update_crtc_power_domains(struct drm_atomic_state *state)
5211 {
5212         struct drm_device *dev = state->dev;
5213         struct drm_i915_private *dev_priv = dev->dev_private;
5214         unsigned long pipe_domains[I915_MAX_PIPES] = { 0, };
5215         struct intel_crtc *crtc;
5216
5217         /*
5218          * First get all needed power domains, then put all unneeded, to avoid
5219          * any unnecessary toggling of the power wells.
5220          */
5221         for_each_intel_crtc(dev, crtc) {
5222                 enum intel_display_power_domain domain;
5223
5224                 if (!crtc->base.state->enable)
5225                         continue;
5226
5227                 pipe_domains[crtc->pipe] = get_crtc_power_domains(&crtc->base);
5228
5229                 for_each_power_domain(domain, pipe_domains[crtc->pipe])
5230                         intel_display_power_get(dev_priv, domain);
5231         }
5232
5233         if (dev_priv->display.modeset_global_resources)
5234                 dev_priv->display.modeset_global_resources(state);
5235
5236         for_each_intel_crtc(dev, crtc) {
5237                 enum intel_display_power_domain domain;
5238
5239                 for_each_power_domain(domain, crtc->enabled_power_domains)
5240                         intel_display_power_put(dev_priv, domain);
5241
5242                 crtc->enabled_power_domains = pipe_domains[crtc->pipe];
5243         }
5244
5245         intel_display_set_init_power(dev_priv, false);
5246 }
5247
5248 void broxton_set_cdclk(struct drm_device *dev, int frequency)
5249 {
5250         struct drm_i915_private *dev_priv = dev->dev_private;
5251         uint32_t divider;
5252         uint32_t ratio;
5253         uint32_t current_freq;
5254         int ret;
5255
5256         /* frequency = 19.2MHz * ratio / 2 / div{1,1.5,2,4} */
5257         switch (frequency) {
5258         case 144000:
5259                 divider = BXT_CDCLK_CD2X_DIV_SEL_4;
5260                 ratio = BXT_DE_PLL_RATIO(60);
5261                 break;
5262         case 288000:
5263                 divider = BXT_CDCLK_CD2X_DIV_SEL_2;
5264                 ratio = BXT_DE_PLL_RATIO(60);
5265                 break;
5266         case 384000:
5267                 divider = BXT_CDCLK_CD2X_DIV_SEL_1_5;
5268                 ratio = BXT_DE_PLL_RATIO(60);
5269                 break;
5270         case 576000:
5271                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5272                 ratio = BXT_DE_PLL_RATIO(60);
5273                 break;
5274         case 624000:
5275                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5276                 ratio = BXT_DE_PLL_RATIO(65);
5277                 break;
5278         case 19200:
5279                 /*
5280                  * Bypass frequency with DE PLL disabled. Init ratio, divider
5281                  * to suppress GCC warning.
5282                  */
5283                 ratio = 0;
5284                 divider = 0;
5285                 break;
5286         default:
5287                 DRM_ERROR("unsupported CDCLK freq %d", frequency);
5288
5289                 return;
5290         }
5291
5292         mutex_lock(&dev_priv->rps.hw_lock);
5293         /* Inform power controller of upcoming frequency change */
5294         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5295                                       0x80000000);
5296         mutex_unlock(&dev_priv->rps.hw_lock);
5297
5298         if (ret) {
5299                 DRM_ERROR("PCode CDCLK freq change notify failed (err %d, freq %d)\n",
5300                           ret, frequency);
5301                 return;
5302         }
5303
5304         current_freq = I915_READ(CDCLK_CTL) & CDCLK_FREQ_DECIMAL_MASK;
5305         /* convert from .1 fixpoint MHz with -1MHz offset to kHz */
5306         current_freq = current_freq * 500 + 1000;
5307
5308         /*
5309          * DE PLL has to be disabled when
5310          * - setting to 19.2MHz (bypass, PLL isn't used)
5311          * - before setting to 624MHz (PLL needs toggling)
5312          * - before setting to any frequency from 624MHz (PLL needs toggling)
5313          */
5314         if (frequency == 19200 || frequency == 624000 ||
5315             current_freq == 624000) {
5316                 I915_WRITE(BXT_DE_PLL_ENABLE, ~BXT_DE_PLL_PLL_ENABLE);
5317                 /* Timeout 200us */
5318                 if (wait_for(!(I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_LOCK),
5319                              1))
5320                         DRM_ERROR("timout waiting for DE PLL unlock\n");
5321         }
5322
5323         if (frequency != 19200) {
5324                 uint32_t val;
5325
5326                 val = I915_READ(BXT_DE_PLL_CTL);
5327                 val &= ~BXT_DE_PLL_RATIO_MASK;
5328                 val |= ratio;
5329                 I915_WRITE(BXT_DE_PLL_CTL, val);
5330
5331                 I915_WRITE(BXT_DE_PLL_ENABLE, BXT_DE_PLL_PLL_ENABLE);
5332                 /* Timeout 200us */
5333                 if (wait_for(I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_LOCK, 1))
5334                         DRM_ERROR("timeout waiting for DE PLL lock\n");
5335
5336                 val = I915_READ(CDCLK_CTL);
5337                 val &= ~BXT_CDCLK_CD2X_DIV_SEL_MASK;
5338                 val |= divider;
5339                 /*
5340                  * Disable SSA Precharge when CD clock frequency < 500 MHz,
5341                  * enable otherwise.
5342                  */
5343                 val &= ~BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5344                 if (frequency >= 500000)
5345                         val |= BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5346
5347                 val &= ~CDCLK_FREQ_DECIMAL_MASK;
5348                 /* convert from kHz to .1 fixpoint MHz with -1MHz offset */
5349                 val |= (frequency - 1000) / 500;
5350                 I915_WRITE(CDCLK_CTL, val);
5351         }
5352
5353         mutex_lock(&dev_priv->rps.hw_lock);
5354         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5355                                       DIV_ROUND_UP(frequency, 25000));
5356         mutex_unlock(&dev_priv->rps.hw_lock);
5357
5358         if (ret) {
5359                 DRM_ERROR("PCode CDCLK freq set failed, (err %d, freq %d)\n",
5360                           ret, frequency);
5361                 return;
5362         }
5363
5364         dev_priv->cdclk_freq = frequency;
5365 }
5366
5367 void broxton_init_cdclk(struct drm_device *dev)
5368 {
5369         struct drm_i915_private *dev_priv = dev->dev_private;
5370         uint32_t val;
5371
5372         /*
5373          * NDE_RSTWRN_OPT RST PCH Handshake En must always be 0b on BXT
5374          * or else the reset will hang because there is no PCH to respond.
5375          * Move the handshake programming to initialization sequence.
5376          * Previously was left up to BIOS.
5377          */
5378         val = I915_READ(HSW_NDE_RSTWRN_OPT);
5379         val &= ~RESET_PCH_HANDSHAKE_ENABLE;
5380         I915_WRITE(HSW_NDE_RSTWRN_OPT, val);
5381
5382         /* Enable PG1 for cdclk */
5383         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
5384
5385         /* check if cd clock is enabled */
5386         if (I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_PLL_ENABLE) {
5387                 DRM_DEBUG_KMS("Display already initialized\n");
5388                 return;
5389         }
5390
5391         /*
5392          * FIXME:
5393          * - The initial CDCLK needs to be read from VBT.
5394          *   Need to make this change after VBT has changes for BXT.
5395          * - check if setting the max (or any) cdclk freq is really necessary
5396          *   here, it belongs to modeset time
5397          */
5398         broxton_set_cdclk(dev, 624000);
5399
5400         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) | DBUF_POWER_REQUEST);
5401         udelay(10);
5402
5403         if (!(I915_READ(DBUF_CTL) & DBUF_POWER_STATE))
5404                 DRM_ERROR("DBuf power enable timeout!\n");
5405 }
5406
5407 void broxton_uninit_cdclk(struct drm_device *dev)
5408 {
5409         struct drm_i915_private *dev_priv = dev->dev_private;
5410
5411         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) & ~DBUF_POWER_REQUEST);
5412         udelay(10);
5413
5414         if (I915_READ(DBUF_CTL) & DBUF_POWER_STATE)
5415                 DRM_ERROR("DBuf power disable timeout!\n");
5416
5417         /* Set minimum (bypass) frequency, in effect turning off the DE PLL */
5418         broxton_set_cdclk(dev, 19200);
5419
5420         intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS);
5421 }
5422
5423 /* returns HPLL frequency in kHz */
5424 static int valleyview_get_vco(struct drm_i915_private *dev_priv)
5425 {
5426         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
5427
5428         /* Obtain SKU information */
5429         mutex_lock(&dev_priv->dpio_lock);
5430         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
5431                 CCK_FUSE_HPLL_FREQ_MASK;
5432         mutex_unlock(&dev_priv->dpio_lock);
5433
5434         return vco_freq[hpll_freq] * 1000;
5435 }
5436
5437 static void vlv_update_cdclk(struct drm_device *dev)
5438 {
5439         struct drm_i915_private *dev_priv = dev->dev_private;
5440
5441         dev_priv->cdclk_freq = dev_priv->display.get_display_clock_speed(dev);
5442         DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz\n",
5443                          dev_priv->cdclk_freq);
5444
5445         /*
5446          * Program the gmbus_freq based on the cdclk frequency.
5447          * BSpec erroneously claims we should aim for 4MHz, but
5448          * in fact 1MHz is the correct frequency.
5449          */
5450         I915_WRITE(GMBUSFREQ_VLV, DIV_ROUND_UP(dev_priv->cdclk_freq, 1000));
5451 }
5452
5453 /* Adjust CDclk dividers to allow high res or save power if possible */
5454 static void valleyview_set_cdclk(struct drm_device *dev, int cdclk)
5455 {
5456         struct drm_i915_private *dev_priv = dev->dev_private;
5457         u32 val, cmd;
5458
5459         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5460                                         != dev_priv->cdclk_freq);
5461
5462         if (cdclk >= 320000) /* jump to highest voltage for 400MHz too */
5463                 cmd = 2;
5464         else if (cdclk == 266667)
5465                 cmd = 1;
5466         else
5467                 cmd = 0;
5468
5469         mutex_lock(&dev_priv->rps.hw_lock);
5470         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5471         val &= ~DSPFREQGUAR_MASK;
5472         val |= (cmd << DSPFREQGUAR_SHIFT);
5473         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5474         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5475                       DSPFREQSTAT_MASK) == (cmd << DSPFREQSTAT_SHIFT),
5476                      50)) {
5477                 DRM_ERROR("timed out waiting for CDclk change\n");
5478         }
5479         mutex_unlock(&dev_priv->rps.hw_lock);
5480
5481         if (cdclk == 400000) {
5482                 u32 divider;
5483
5484                 divider = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5485
5486                 mutex_lock(&dev_priv->dpio_lock);
5487                 /* adjust cdclk divider */
5488                 val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
5489                 val &= ~DISPLAY_FREQUENCY_VALUES;
5490                 val |= divider;
5491                 vlv_cck_write(dev_priv, CCK_DISPLAY_CLOCK_CONTROL, val);
5492
5493                 if (wait_for((vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL) &
5494                               DISPLAY_FREQUENCY_STATUS) == (divider << DISPLAY_FREQUENCY_STATUS_SHIFT),
5495                              50))
5496                         DRM_ERROR("timed out waiting for CDclk change\n");
5497                 mutex_unlock(&dev_priv->dpio_lock);
5498         }
5499
5500         mutex_lock(&dev_priv->dpio_lock);
5501         /* adjust self-refresh exit latency value */
5502         val = vlv_bunit_read(dev_priv, BUNIT_REG_BISOC);
5503         val &= ~0x7f;
5504
5505         /*
5506          * For high bandwidth configs, we set a higher latency in the bunit
5507          * so that the core display fetch happens in time to avoid underruns.
5508          */
5509         if (cdclk == 400000)
5510                 val |= 4500 / 250; /* 4.5 usec */
5511         else
5512                 val |= 3000 / 250; /* 3.0 usec */
5513         vlv_bunit_write(dev_priv, BUNIT_REG_BISOC, val);
5514         mutex_unlock(&dev_priv->dpio_lock);
5515
5516         vlv_update_cdclk(dev);
5517 }
5518
5519 static void cherryview_set_cdclk(struct drm_device *dev, int cdclk)
5520 {
5521         struct drm_i915_private *dev_priv = dev->dev_private;
5522         u32 val, cmd;
5523
5524         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5525                                                 != dev_priv->cdclk_freq);
5526
5527         switch (cdclk) {
5528         case 333333:
5529         case 320000:
5530         case 266667:
5531         case 200000:
5532                 break;
5533         default:
5534                 MISSING_CASE(cdclk);
5535                 return;
5536         }
5537
5538         /*
5539          * Specs are full of misinformation, but testing on actual
5540          * hardware has shown that we just need to write the desired
5541          * CCK divider into the Punit register.
5542          */
5543         cmd = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5544
5545         mutex_lock(&dev_priv->rps.hw_lock);
5546         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5547         val &= ~DSPFREQGUAR_MASK_CHV;
5548         val |= (cmd << DSPFREQGUAR_SHIFT_CHV);
5549         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5550         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5551                       DSPFREQSTAT_MASK_CHV) == (cmd << DSPFREQSTAT_SHIFT_CHV),
5552                      50)) {
5553                 DRM_ERROR("timed out waiting for CDclk change\n");
5554         }
5555         mutex_unlock(&dev_priv->rps.hw_lock);
5556
5557         vlv_update_cdclk(dev);
5558 }
5559
5560 static int valleyview_calc_cdclk(struct drm_i915_private *dev_priv,
5561                                  int max_pixclk)
5562 {
5563         int freq_320 = (dev_priv->hpll_freq <<  1) % 320000 != 0 ? 333333 : 320000;
5564         int limit = IS_CHERRYVIEW(dev_priv) ? 95 : 90;
5565
5566         /*
5567          * Really only a few cases to deal with, as only 4 CDclks are supported:
5568          *   200MHz
5569          *   267MHz
5570          *   320/333MHz (depends on HPLL freq)
5571          *   400MHz (VLV only)
5572          * So we check to see whether we're above 90% (VLV) or 95% (CHV)
5573          * of the lower bin and adjust if needed.
5574          *
5575          * We seem to get an unstable or solid color picture at 200MHz.
5576          * Not sure what's wrong. For now use 200MHz only when all pipes
5577          * are off.
5578          */
5579         if (!IS_CHERRYVIEW(dev_priv) &&
5580             max_pixclk > freq_320*limit/100)
5581                 return 400000;
5582         else if (max_pixclk > 266667*limit/100)
5583                 return freq_320;
5584         else if (max_pixclk > 0)
5585                 return 266667;
5586         else
5587                 return 200000;
5588 }
5589
5590 static int broxton_calc_cdclk(struct drm_i915_private *dev_priv,
5591                               int max_pixclk)
5592 {
5593         /*
5594          * FIXME:
5595          * - remove the guardband, it's not needed on BXT
5596          * - set 19.2MHz bypass frequency if there are no active pipes
5597          */
5598         if (max_pixclk > 576000*9/10)
5599                 return 624000;
5600         else if (max_pixclk > 384000*9/10)
5601                 return 576000;
5602         else if (max_pixclk > 288000*9/10)
5603                 return 384000;
5604         else if (max_pixclk > 144000*9/10)
5605                 return 288000;
5606         else
5607                 return 144000;
5608 }
5609
5610 /* compute the max pixel clock for new configuration */
5611 static int intel_mode_max_pixclk(struct drm_atomic_state *state)
5612 {
5613         struct drm_device *dev = state->dev;
5614         struct intel_crtc *intel_crtc;
5615         struct intel_crtc_state *crtc_state;
5616         int max_pixclk = 0;
5617
5618         for_each_intel_crtc(dev, intel_crtc) {
5619                 crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
5620                 if (IS_ERR(crtc_state))
5621                         return PTR_ERR(crtc_state);
5622
5623                 if (!crtc_state->base.enable)
5624                         continue;
5625
5626                 max_pixclk = max(max_pixclk,
5627                                  crtc_state->base.adjusted_mode.crtc_clock);
5628         }
5629
5630         return max_pixclk;
5631 }
5632
5633 static int valleyview_modeset_global_pipes(struct drm_atomic_state *state,
5634                                             unsigned *prepare_pipes)
5635 {
5636         struct drm_i915_private *dev_priv = to_i915(state->dev);
5637         struct intel_crtc *intel_crtc;
5638         int max_pixclk = intel_mode_max_pixclk(state);
5639         int cdclk;
5640
5641         if (max_pixclk < 0)
5642                 return max_pixclk;
5643
5644         if (IS_VALLEYVIEW(dev_priv))
5645                 cdclk = valleyview_calc_cdclk(dev_priv, max_pixclk);
5646         else
5647                 cdclk = broxton_calc_cdclk(dev_priv, max_pixclk);
5648
5649         if (cdclk == dev_priv->cdclk_freq)
5650                 return 0;
5651
5652         /* disable/enable all currently active pipes while we change cdclk */
5653         for_each_intel_crtc(state->dev, intel_crtc)
5654                 if (intel_crtc->base.state->enable)
5655                         *prepare_pipes |= (1 << intel_crtc->pipe);
5656
5657         return 0;
5658 }
5659
5660 static void vlv_program_pfi_credits(struct drm_i915_private *dev_priv)
5661 {
5662         unsigned int credits, default_credits;
5663
5664         if (IS_CHERRYVIEW(dev_priv))
5665                 default_credits = PFI_CREDIT(12);
5666         else
5667                 default_credits = PFI_CREDIT(8);
5668
5669         if (DIV_ROUND_CLOSEST(dev_priv->cdclk_freq, 1000) >= dev_priv->rps.cz_freq) {
5670                 /* CHV suggested value is 31 or 63 */
5671                 if (IS_CHERRYVIEW(dev_priv))
5672                         credits = PFI_CREDIT_31;
5673                 else
5674                         credits = PFI_CREDIT(15);
5675         } else {
5676                 credits = default_credits;
5677         }
5678
5679         /*
5680          * WA - write default credits before re-programming
5681          * FIXME: should we also set the resend bit here?
5682          */
5683         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
5684                    default_credits);
5685
5686         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
5687                    credits | PFI_CREDIT_RESEND);
5688
5689         /*
5690          * FIXME is this guaranteed to clear
5691          * immediately or should we poll for it?
5692          */
5693         WARN_ON(I915_READ(GCI_CONTROL) & PFI_CREDIT_RESEND);
5694 }
5695
5696 static void valleyview_modeset_global_resources(struct drm_atomic_state *state)
5697 {
5698         struct drm_device *dev = state->dev;
5699         struct drm_i915_private *dev_priv = dev->dev_private;
5700         int max_pixclk = intel_mode_max_pixclk(state);
5701         int req_cdclk;
5702
5703         /* The only reason this can fail is if we fail to add the crtc_state
5704          * to the atomic state. But that can't happen since the call to
5705          * intel_mode_max_pixclk() in valleyview_modeset_global_pipes() (which
5706          * can't have failed otherwise the mode set would be aborted) added all
5707          * the states already. */
5708         if (WARN_ON(max_pixclk < 0))
5709                 return;
5710
5711         req_cdclk = valleyview_calc_cdclk(dev_priv, max_pixclk);
5712
5713         if (req_cdclk != dev_priv->cdclk_freq) {
5714                 /*
5715                  * FIXME: We can end up here with all power domains off, yet
5716                  * with a CDCLK frequency other than the minimum. To account
5717                  * for this take the PIPE-A power domain, which covers the HW
5718                  * blocks needed for the following programming. This can be
5719                  * removed once it's guaranteed that we get here either with
5720                  * the minimum CDCLK set, or the required power domains
5721                  * enabled.
5722                  */
5723                 intel_display_power_get(dev_priv, POWER_DOMAIN_PIPE_A);
5724
5725                 if (IS_CHERRYVIEW(dev))
5726                         cherryview_set_cdclk(dev, req_cdclk);
5727                 else
5728                         valleyview_set_cdclk(dev, req_cdclk);
5729
5730                 vlv_program_pfi_credits(dev_priv);
5731
5732                 intel_display_power_put(dev_priv, POWER_DOMAIN_PIPE_A);
5733         }
5734 }
5735
5736 static void valleyview_crtc_enable(struct drm_crtc *crtc)
5737 {
5738         struct drm_device *dev = crtc->dev;
5739         struct drm_i915_private *dev_priv = to_i915(dev);
5740         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5741         struct intel_encoder *encoder;
5742         int pipe = intel_crtc->pipe;
5743         bool is_dsi;
5744
5745         WARN_ON(!crtc->state->enable);
5746
5747         if (intel_crtc->active)
5748                 return;
5749
5750         is_dsi = intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_DSI);
5751
5752         if (!is_dsi) {
5753                 if (IS_CHERRYVIEW(dev))
5754                         chv_prepare_pll(intel_crtc, intel_crtc->config);
5755                 else
5756                         vlv_prepare_pll(intel_crtc, intel_crtc->config);
5757         }
5758
5759         if (intel_crtc->config->has_dp_encoder)
5760                 intel_dp_set_m_n(intel_crtc, M1_N1);
5761
5762         intel_set_pipe_timings(intel_crtc);
5763
5764         if (IS_CHERRYVIEW(dev) && pipe == PIPE_B) {
5765                 struct drm_i915_private *dev_priv = dev->dev_private;
5766
5767                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
5768                 I915_WRITE(CHV_CANVAS(pipe), 0);
5769         }
5770
5771         i9xx_set_pipeconf(intel_crtc);
5772
5773         intel_crtc->active = true;
5774
5775         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5776
5777         for_each_encoder_on_crtc(dev, crtc, encoder)
5778                 if (encoder->pre_pll_enable)
5779                         encoder->pre_pll_enable(encoder);
5780
5781         if (!is_dsi) {
5782                 if (IS_CHERRYVIEW(dev))
5783                         chv_enable_pll(intel_crtc, intel_crtc->config);
5784                 else
5785                         vlv_enable_pll(intel_crtc, intel_crtc->config);
5786         }
5787
5788         for_each_encoder_on_crtc(dev, crtc, encoder)
5789                 if (encoder->pre_enable)
5790                         encoder->pre_enable(encoder);
5791
5792         i9xx_pfit_enable(intel_crtc);
5793
5794         intel_crtc_load_lut(crtc);
5795
5796         intel_update_watermarks(crtc);
5797         intel_enable_pipe(intel_crtc);
5798
5799         assert_vblank_disabled(crtc);
5800         drm_crtc_vblank_on(crtc);
5801
5802         for_each_encoder_on_crtc(dev, crtc, encoder)
5803                 encoder->enable(encoder);
5804
5805         intel_crtc_enable_planes(crtc);
5806
5807         /* Underruns don't raise interrupts, so check manually. */
5808         i9xx_check_fifo_underruns(dev_priv);
5809 }
5810
5811 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
5812 {
5813         struct drm_device *dev = crtc->base.dev;
5814         struct drm_i915_private *dev_priv = dev->dev_private;
5815
5816         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
5817         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
5818 }
5819
5820 static void i9xx_crtc_enable(struct drm_crtc *crtc)
5821 {
5822         struct drm_device *dev = crtc->dev;
5823         struct drm_i915_private *dev_priv = to_i915(dev);
5824         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5825         struct intel_encoder *encoder;
5826         int pipe = intel_crtc->pipe;
5827
5828         WARN_ON(!crtc->state->enable);
5829
5830         if (intel_crtc->active)
5831                 return;
5832
5833         i9xx_set_pll_dividers(intel_crtc);
5834
5835         if (intel_crtc->config->has_dp_encoder)
5836                 intel_dp_set_m_n(intel_crtc, M1_N1);
5837
5838         intel_set_pipe_timings(intel_crtc);
5839
5840         i9xx_set_pipeconf(intel_crtc);
5841
5842         intel_crtc->active = true;
5843
5844         if (!IS_GEN2(dev))
5845                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5846
5847         for_each_encoder_on_crtc(dev, crtc, encoder)
5848                 if (encoder->pre_enable)
5849                         encoder->pre_enable(encoder);
5850
5851         i9xx_enable_pll(intel_crtc);
5852
5853         i9xx_pfit_enable(intel_crtc);
5854
5855         intel_crtc_load_lut(crtc);
5856
5857         intel_update_watermarks(crtc);
5858         intel_enable_pipe(intel_crtc);
5859
5860         assert_vblank_disabled(crtc);
5861         drm_crtc_vblank_on(crtc);
5862
5863         for_each_encoder_on_crtc(dev, crtc, encoder)
5864                 encoder->enable(encoder);
5865
5866         intel_crtc_enable_planes(crtc);
5867
5868         /*
5869          * Gen2 reports pipe underruns whenever all planes are disabled.
5870          * So don't enable underrun reporting before at least some planes
5871          * are enabled.
5872          * FIXME: Need to fix the logic to work when we turn off all planes
5873          * but leave the pipe running.
5874          */
5875         if (IS_GEN2(dev))
5876                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5877
5878         /* Underruns don't raise interrupts, so check manually. */
5879         i9xx_check_fifo_underruns(dev_priv);
5880 }
5881
5882 static void i9xx_pfit_disable(struct intel_crtc *crtc)
5883 {
5884         struct drm_device *dev = crtc->base.dev;
5885         struct drm_i915_private *dev_priv = dev->dev_private;
5886
5887         if (!crtc->config->gmch_pfit.control)
5888                 return;
5889
5890         assert_pipe_disabled(dev_priv, crtc->pipe);
5891
5892         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
5893                          I915_READ(PFIT_CONTROL));
5894         I915_WRITE(PFIT_CONTROL, 0);
5895 }
5896
5897 static void i9xx_crtc_disable(struct drm_crtc *crtc)
5898 {
5899         struct drm_device *dev = crtc->dev;
5900         struct drm_i915_private *dev_priv = dev->dev_private;
5901         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5902         struct intel_encoder *encoder;
5903         int pipe = intel_crtc->pipe;
5904
5905         if (!intel_crtc->active)
5906                 return;
5907
5908         /*
5909          * Gen2 reports pipe underruns whenever all planes are disabled.
5910          * So diasble underrun reporting before all the planes get disabled.
5911          * FIXME: Need to fix the logic to work when we turn off all planes
5912          * but leave the pipe running.
5913          */
5914         if (IS_GEN2(dev))
5915                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5916
5917         /*
5918          * Vblank time updates from the shadow to live plane control register
5919          * are blocked if the memory self-refresh mode is active at that
5920          * moment. So to make sure the plane gets truly disabled, disable
5921          * first the self-refresh mode. The self-refresh enable bit in turn
5922          * will be checked/applied by the HW only at the next frame start
5923          * event which is after the vblank start event, so we need to have a
5924          * wait-for-vblank between disabling the plane and the pipe.
5925          */
5926         intel_set_memory_cxsr(dev_priv, false);
5927         intel_crtc_disable_planes(crtc);
5928
5929         /*
5930          * On gen2 planes are double buffered but the pipe isn't, so we must
5931          * wait for planes to fully turn off before disabling the pipe.
5932          * We also need to wait on all gmch platforms because of the
5933          * self-refresh mode constraint explained above.
5934          */
5935         intel_wait_for_vblank(dev, pipe);
5936
5937         for_each_encoder_on_crtc(dev, crtc, encoder)
5938                 encoder->disable(encoder);
5939
5940         drm_crtc_vblank_off(crtc);
5941         assert_vblank_disabled(crtc);
5942
5943         intel_disable_pipe(intel_crtc);
5944
5945         i9xx_pfit_disable(intel_crtc);
5946
5947         for_each_encoder_on_crtc(dev, crtc, encoder)
5948                 if (encoder->post_disable)
5949                         encoder->post_disable(encoder);
5950
5951         if (!intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_DSI)) {
5952                 if (IS_CHERRYVIEW(dev))
5953                         chv_disable_pll(dev_priv, pipe);
5954                 else if (IS_VALLEYVIEW(dev))
5955                         vlv_disable_pll(dev_priv, pipe);
5956                 else
5957                         i9xx_disable_pll(intel_crtc);
5958         }
5959
5960         if (!IS_GEN2(dev))
5961                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5962
5963         intel_crtc->active = false;
5964         intel_update_watermarks(crtc);
5965
5966         mutex_lock(&dev->struct_mutex);
5967         intel_fbc_update(dev);
5968         mutex_unlock(&dev->struct_mutex);
5969 }
5970
5971 static void i9xx_crtc_off(struct drm_crtc *crtc)
5972 {
5973 }
5974
5975 /* Master function to enable/disable CRTC and corresponding power wells */
5976 void intel_crtc_control(struct drm_crtc *crtc, bool enable)
5977 {
5978         struct drm_device *dev = crtc->dev;
5979         struct drm_i915_private *dev_priv = dev->dev_private;
5980         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5981         enum intel_display_power_domain domain;
5982         unsigned long domains;
5983
5984         if (enable) {
5985                 if (!intel_crtc->active) {
5986                         domains = get_crtc_power_domains(crtc);
5987                         for_each_power_domain(domain, domains)
5988                                 intel_display_power_get(dev_priv, domain);
5989                         intel_crtc->enabled_power_domains = domains;
5990
5991                         dev_priv->display.crtc_enable(crtc);
5992                 }
5993         } else {
5994                 if (intel_crtc->active) {
5995                         dev_priv->display.crtc_disable(crtc);
5996
5997                         domains = intel_crtc->enabled_power_domains;
5998                         for_each_power_domain(domain, domains)
5999                                 intel_display_power_put(dev_priv, domain);
6000                         intel_crtc->enabled_power_domains = 0;
6001                 }
6002         }
6003 }
6004
6005 /**
6006  * Sets the power management mode of the pipe and plane.
6007  */
6008 void intel_crtc_update_dpms(struct drm_crtc *crtc)
6009 {
6010         struct drm_device *dev = crtc->dev;
6011         struct intel_encoder *intel_encoder;
6012         bool enable = false;
6013
6014         for_each_encoder_on_crtc(dev, crtc, intel_encoder)
6015                 enable |= intel_encoder->connectors_active;
6016
6017         intel_crtc_control(crtc, enable);
6018 }
6019
6020 static void intel_crtc_disable(struct drm_crtc *crtc)
6021 {
6022         struct drm_device *dev = crtc->dev;
6023         struct drm_connector *connector;
6024         struct drm_i915_private *dev_priv = dev->dev_private;
6025
6026         /* crtc should still be enabled when we disable it. */
6027         WARN_ON(!crtc->state->enable);
6028
6029         dev_priv->display.crtc_disable(crtc);
6030         dev_priv->display.off(crtc);
6031
6032         drm_plane_helper_disable(crtc->primary);
6033
6034         /* Update computed state. */
6035         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
6036                 if (!connector->encoder || !connector->encoder->crtc)
6037                         continue;
6038
6039                 if (connector->encoder->crtc != crtc)
6040                         continue;
6041
6042                 connector->dpms = DRM_MODE_DPMS_OFF;
6043                 to_intel_encoder(connector->encoder)->connectors_active = false;
6044         }
6045 }
6046
6047 void intel_encoder_destroy(struct drm_encoder *encoder)
6048 {
6049         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6050
6051         drm_encoder_cleanup(encoder);
6052         kfree(intel_encoder);
6053 }
6054
6055 /* Simple dpms helper for encoders with just one connector, no cloning and only
6056  * one kind of off state. It clamps all !ON modes to fully OFF and changes the
6057  * state of the entire output pipe. */
6058 static void intel_encoder_dpms(struct intel_encoder *encoder, int mode)
6059 {
6060         if (mode == DRM_MODE_DPMS_ON) {
6061                 encoder->connectors_active = true;
6062
6063                 intel_crtc_update_dpms(encoder->base.crtc);
6064         } else {
6065                 encoder->connectors_active = false;
6066
6067                 intel_crtc_update_dpms(encoder->base.crtc);
6068         }
6069 }
6070
6071 /* Cross check the actual hw state with our own modeset state tracking (and it's
6072  * internal consistency). */
6073 static void intel_connector_check_state(struct intel_connector *connector)
6074 {
6075         if (connector->get_hw_state(connector)) {
6076                 struct intel_encoder *encoder = connector->encoder;
6077                 struct drm_crtc *crtc;
6078                 bool encoder_enabled;
6079                 enum pipe pipe;
6080
6081                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6082                               connector->base.base.id,
6083                               connector->base.name);
6084
6085                 /* there is no real hw state for MST connectors */
6086                 if (connector->mst_port)
6087                         return;
6088
6089                 I915_STATE_WARN(connector->base.dpms == DRM_MODE_DPMS_OFF,
6090                      "wrong connector dpms state\n");
6091                 I915_STATE_WARN(connector->base.encoder != &encoder->base,
6092                      "active connector not linked to encoder\n");
6093
6094                 if (encoder) {
6095                         I915_STATE_WARN(!encoder->connectors_active,
6096                              "encoder->connectors_active not set\n");
6097
6098                         encoder_enabled = encoder->get_hw_state(encoder, &pipe);
6099                         I915_STATE_WARN(!encoder_enabled, "encoder not enabled\n");
6100                         if (I915_STATE_WARN_ON(!encoder->base.crtc))
6101                                 return;
6102
6103                         crtc = encoder->base.crtc;
6104
6105                         I915_STATE_WARN(!crtc->state->enable,
6106                                         "crtc not enabled\n");
6107                         I915_STATE_WARN(!to_intel_crtc(crtc)->active, "crtc not active\n");
6108                         I915_STATE_WARN(pipe != to_intel_crtc(crtc)->pipe,
6109                              "encoder active on the wrong pipe\n");
6110                 }
6111         }
6112 }
6113
6114 int intel_connector_init(struct intel_connector *connector)
6115 {
6116         struct drm_connector_state *connector_state;
6117
6118         connector_state = kzalloc(sizeof *connector_state, GFP_KERNEL);
6119         if (!connector_state)
6120                 return -ENOMEM;
6121
6122         connector->base.state = connector_state;
6123         return 0;
6124 }
6125
6126 struct intel_connector *intel_connector_alloc(void)
6127 {
6128         struct intel_connector *connector;
6129
6130         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6131         if (!connector)
6132                 return NULL;
6133
6134         if (intel_connector_init(connector) < 0) {
6135                 kfree(connector);
6136                 return NULL;
6137         }
6138
6139         return connector;
6140 }
6141
6142 /* Even simpler default implementation, if there's really no special case to
6143  * consider. */
6144 void intel_connector_dpms(struct drm_connector *connector, int mode)
6145 {
6146         /* All the simple cases only support two dpms states. */
6147         if (mode != DRM_MODE_DPMS_ON)
6148                 mode = DRM_MODE_DPMS_OFF;
6149
6150         if (mode == connector->dpms)
6151                 return;
6152
6153         connector->dpms = mode;
6154
6155         /* Only need to change hw state when actually enabled */
6156         if (connector->encoder)
6157                 intel_encoder_dpms(to_intel_encoder(connector->encoder), mode);
6158
6159         intel_modeset_check_state(connector->dev);
6160 }
6161
6162 /* Simple connector->get_hw_state implementation for encoders that support only
6163  * one connector and no cloning and hence the encoder state determines the state
6164  * of the connector. */
6165 bool intel_connector_get_hw_state(struct intel_connector *connector)
6166 {
6167         enum pipe pipe = 0;
6168         struct intel_encoder *encoder = connector->encoder;
6169
6170         return encoder->get_hw_state(encoder, &pipe);
6171 }
6172
6173 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6174 {
6175         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6176                 return crtc_state->fdi_lanes;
6177
6178         return 0;
6179 }
6180
6181 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6182                                      struct intel_crtc_state *pipe_config)
6183 {
6184         struct drm_atomic_state *state = pipe_config->base.state;
6185         struct intel_crtc *other_crtc;
6186         struct intel_crtc_state *other_crtc_state;
6187
6188         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6189                       pipe_name(pipe), pipe_config->fdi_lanes);
6190         if (pipe_config->fdi_lanes > 4) {
6191                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6192                               pipe_name(pipe), pipe_config->fdi_lanes);
6193                 return -EINVAL;
6194         }
6195
6196         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
6197                 if (pipe_config->fdi_lanes > 2) {
6198                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6199                                       pipe_config->fdi_lanes);
6200                         return -EINVAL;
6201                 } else {
6202                         return 0;
6203                 }
6204         }
6205
6206         if (INTEL_INFO(dev)->num_pipes == 2)
6207                 return 0;
6208
6209         /* Ivybridge 3 pipe is really complicated */
6210         switch (pipe) {
6211         case PIPE_A:
6212                 return 0;
6213         case PIPE_B:
6214                 if (pipe_config->fdi_lanes <= 2)
6215                         return 0;
6216
6217                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_C));
6218                 other_crtc_state =
6219                         intel_atomic_get_crtc_state(state, other_crtc);
6220                 if (IS_ERR(other_crtc_state))
6221                         return PTR_ERR(other_crtc_state);
6222
6223                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6224                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6225                                       pipe_name(pipe), pipe_config->fdi_lanes);
6226                         return -EINVAL;
6227                 }
6228                 return 0;
6229         case PIPE_C:
6230                 if (pipe_config->fdi_lanes > 2) {
6231                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6232                                       pipe_name(pipe), pipe_config->fdi_lanes);
6233                         return -EINVAL;
6234                 }
6235
6236                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_B));
6237                 other_crtc_state =
6238                         intel_atomic_get_crtc_state(state, other_crtc);
6239                 if (IS_ERR(other_crtc_state))
6240                         return PTR_ERR(other_crtc_state);
6241
6242                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6243                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6244                         return -EINVAL;
6245                 }
6246                 return 0;
6247         default:
6248                 BUG();
6249         }
6250 }
6251
6252 #define RETRY 1
6253 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6254                                        struct intel_crtc_state *pipe_config)
6255 {
6256         struct drm_device *dev = intel_crtc->base.dev;
6257         struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6258         int lane, link_bw, fdi_dotclock, ret;
6259         bool needs_recompute = false;
6260
6261 retry:
6262         /* FDI is a binary signal running at ~2.7GHz, encoding
6263          * each output octet as 10 bits. The actual frequency
6264          * is stored as a divider into a 100MHz clock, and the
6265          * mode pixel clock is stored in units of 1KHz.
6266          * Hence the bw of each lane in terms of the mode signal
6267          * is:
6268          */
6269         link_bw = intel_fdi_link_freq(dev) * MHz(100)/KHz(1)/10;
6270
6271         fdi_dotclock = adjusted_mode->crtc_clock;
6272
6273         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6274                                            pipe_config->pipe_bpp);
6275
6276         pipe_config->fdi_lanes = lane;
6277
6278         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6279                                link_bw, &pipe_config->fdi_m_n);
6280
6281         ret = ironlake_check_fdi_lanes(intel_crtc->base.dev,
6282                                        intel_crtc->pipe, pipe_config);
6283         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6284                 pipe_config->pipe_bpp -= 2*3;
6285                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6286                               pipe_config->pipe_bpp);
6287                 needs_recompute = true;
6288                 pipe_config->bw_constrained = true;
6289
6290                 goto retry;
6291         }
6292
6293         if (needs_recompute)
6294                 return RETRY;
6295
6296         return ret;
6297 }
6298
6299 static void hsw_compute_ips_config(struct intel_crtc *crtc,
6300                                    struct intel_crtc_state *pipe_config)
6301 {
6302         pipe_config->ips_enabled = i915.enable_ips &&
6303                                    hsw_crtc_supports_ips(crtc) &&
6304                                    pipe_config->pipe_bpp <= 24;
6305 }
6306
6307 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6308                                      struct intel_crtc_state *pipe_config)
6309 {
6310         struct drm_device *dev = crtc->base.dev;
6311         struct drm_i915_private *dev_priv = dev->dev_private;
6312         struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6313         int ret;
6314
6315         /* FIXME should check pixel clock limits on all platforms */
6316         if (INTEL_INFO(dev)->gen < 4) {
6317                 int clock_limit =
6318                         dev_priv->display.get_display_clock_speed(dev);
6319
6320                 /*
6321                  * Enable pixel doubling when the dot clock
6322                  * is > 90% of the (display) core speed.
6323                  *
6324                  * GDG double wide on either pipe,
6325                  * otherwise pipe A only.
6326                  */
6327                 if ((crtc->pipe == PIPE_A || IS_I915G(dev)) &&
6328                     adjusted_mode->crtc_clock > clock_limit * 9 / 10) {
6329                         clock_limit *= 2;
6330                         pipe_config->double_wide = true;
6331                 }
6332
6333                 if (adjusted_mode->crtc_clock > clock_limit * 9 / 10)
6334                         return -EINVAL;
6335         }
6336
6337         /*
6338          * Pipe horizontal size must be even in:
6339          * - DVO ganged mode
6340          * - LVDS dual channel mode
6341          * - Double wide pipe
6342          */
6343         if ((intel_pipe_will_have_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6344              intel_is_dual_link_lvds(dev)) || pipe_config->double_wide)
6345                 pipe_config->pipe_src_w &= ~1;
6346
6347         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6348          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6349          */
6350         if ((INTEL_INFO(dev)->gen > 4 || IS_G4X(dev)) &&
6351                 adjusted_mode->hsync_start == adjusted_mode->hdisplay)
6352                 return -EINVAL;
6353
6354         if (HAS_IPS(dev))
6355                 hsw_compute_ips_config(crtc, pipe_config);
6356
6357         if (pipe_config->has_pch_encoder)
6358                 return ironlake_fdi_compute_config(crtc, pipe_config);
6359
6360         /* FIXME: remove below call once atomic mode set is place and all crtc
6361          * related checks called from atomic_crtc_check function */
6362         ret = 0;
6363         DRM_DEBUG_KMS("intel_crtc = %p drm_state (pipe_config->base.state) = %p\n",
6364                 crtc, pipe_config->base.state);
6365         ret = intel_atomic_setup_scalers(dev, crtc, pipe_config);
6366
6367         return ret;
6368 }
6369
6370 static int skylake_get_display_clock_speed(struct drm_device *dev)
6371 {
6372         struct drm_i915_private *dev_priv = to_i915(dev);
6373         uint32_t lcpll1 = I915_READ(LCPLL1_CTL);
6374         uint32_t cdctl = I915_READ(CDCLK_CTL);
6375         uint32_t linkrate;
6376
6377         if (!(lcpll1 & LCPLL_PLL_ENABLE)) {
6378                 WARN(1, "LCPLL1 not enabled\n");
6379                 return 24000; /* 24MHz is the cd freq with NSSC ref */
6380         }
6381
6382         if ((cdctl & CDCLK_FREQ_SEL_MASK) == CDCLK_FREQ_540)
6383                 return 540000;
6384
6385         linkrate = (I915_READ(DPLL_CTRL1) &
6386                     DPLL_CRTL1_LINK_RATE_MASK(SKL_DPLL0)) >> 1;
6387
6388         if (linkrate == DPLL_CRTL1_LINK_RATE_2160 ||
6389             linkrate == DPLL_CRTL1_LINK_RATE_1080) {
6390                 /* vco 8640 */
6391                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6392                 case CDCLK_FREQ_450_432:
6393                         return 432000;
6394                 case CDCLK_FREQ_337_308:
6395                         return 308570;
6396                 case CDCLK_FREQ_675_617:
6397                         return 617140;
6398                 default:
6399                         WARN(1, "Unknown cd freq selection\n");
6400                 }
6401         } else {
6402                 /* vco 8100 */
6403                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6404                 case CDCLK_FREQ_450_432:
6405                         return 450000;
6406                 case CDCLK_FREQ_337_308:
6407                         return 337500;
6408                 case CDCLK_FREQ_675_617:
6409                         return 675000;
6410                 default:
6411                         WARN(1, "Unknown cd freq selection\n");
6412                 }
6413         }
6414
6415         /* error case, do as if DPLL0 isn't enabled */
6416         return 24000;
6417 }
6418
6419 static int broadwell_get_display_clock_speed(struct drm_device *dev)
6420 {
6421         struct drm_i915_private *dev_priv = dev->dev_private;
6422         uint32_t lcpll = I915_READ(LCPLL_CTL);
6423         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6424
6425         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6426                 return 800000;
6427         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6428                 return 450000;
6429         else if (freq == LCPLL_CLK_FREQ_450)
6430                 return 450000;
6431         else if (freq == LCPLL_CLK_FREQ_54O_BDW)
6432                 return 540000;
6433         else if (freq == LCPLL_CLK_FREQ_337_5_BDW)
6434                 return 337500;
6435         else
6436                 return 675000;
6437 }
6438
6439 static int haswell_get_display_clock_speed(struct drm_device *dev)
6440 {
6441         struct drm_i915_private *dev_priv = dev->dev_private;
6442         uint32_t lcpll = I915_READ(LCPLL_CTL);
6443         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6444
6445         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6446                 return 800000;
6447         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6448                 return 450000;
6449         else if (freq == LCPLL_CLK_FREQ_450)
6450                 return 450000;
6451         else if (IS_HSW_ULT(dev))
6452                 return 337500;
6453         else
6454                 return 540000;
6455 }
6456
6457 static int valleyview_get_display_clock_speed(struct drm_device *dev)
6458 {
6459         struct drm_i915_private *dev_priv = dev->dev_private;
6460         u32 val;
6461         int divider;
6462
6463         if (dev_priv->hpll_freq == 0)
6464                 dev_priv->hpll_freq = valleyview_get_vco(dev_priv);
6465
6466         mutex_lock(&dev_priv->dpio_lock);
6467         val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
6468         mutex_unlock(&dev_priv->dpio_lock);
6469
6470         divider = val & DISPLAY_FREQUENCY_VALUES;
6471
6472         WARN((val & DISPLAY_FREQUENCY_STATUS) !=
6473              (divider << DISPLAY_FREQUENCY_STATUS_SHIFT),
6474              "cdclk change in progress\n");
6475
6476         return DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, divider + 1);
6477 }
6478
6479 static int ilk_get_display_clock_speed(struct drm_device *dev)
6480 {
6481         return 450000;
6482 }
6483
6484 static int i945_get_display_clock_speed(struct drm_device *dev)
6485 {
6486         return 400000;
6487 }
6488
6489 static int i915_get_display_clock_speed(struct drm_device *dev)
6490 {
6491         return 333333;
6492 }
6493
6494 static int i9xx_misc_get_display_clock_speed(struct drm_device *dev)
6495 {
6496         return 200000;
6497 }
6498
6499 static int pnv_get_display_clock_speed(struct drm_device *dev)
6500 {
6501         u16 gcfgc = 0;
6502
6503         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6504
6505         switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6506         case GC_DISPLAY_CLOCK_267_MHZ_PNV:
6507                 return 266667;
6508         case GC_DISPLAY_CLOCK_333_MHZ_PNV:
6509                 return 333333;
6510         case GC_DISPLAY_CLOCK_444_MHZ_PNV:
6511                 return 444444;
6512         case GC_DISPLAY_CLOCK_200_MHZ_PNV:
6513                 return 200000;
6514         default:
6515                 DRM_ERROR("Unknown pnv display core clock 0x%04x\n", gcfgc);
6516         case GC_DISPLAY_CLOCK_133_MHZ_PNV:
6517                 return 133333;
6518         case GC_DISPLAY_CLOCK_167_MHZ_PNV:
6519                 return 166667;
6520         }
6521 }
6522
6523 static int i915gm_get_display_clock_speed(struct drm_device *dev)
6524 {
6525         u16 gcfgc = 0;
6526
6527         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6528
6529         if (gcfgc & GC_LOW_FREQUENCY_ENABLE)
6530                 return 133333;
6531         else {
6532                 switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6533                 case GC_DISPLAY_CLOCK_333_MHZ:
6534                         return 333333;
6535                 default:
6536                 case GC_DISPLAY_CLOCK_190_200_MHZ:
6537                         return 190000;
6538                 }
6539         }
6540 }
6541
6542 static int i865_get_display_clock_speed(struct drm_device *dev)
6543 {
6544         return 266667;
6545 }
6546
6547 static int i855_get_display_clock_speed(struct drm_device *dev)
6548 {
6549         u16 hpllcc = 0;
6550         /* Assume that the hardware is in the high speed state.  This
6551          * should be the default.
6552          */
6553         switch (hpllcc & GC_CLOCK_CONTROL_MASK) {
6554         case GC_CLOCK_133_200:
6555         case GC_CLOCK_100_200:
6556                 return 200000;
6557         case GC_CLOCK_166_250:
6558                 return 250000;
6559         case GC_CLOCK_100_133:
6560                 return 133333;
6561         }
6562
6563         /* Shouldn't happen */
6564         return 0;
6565 }
6566
6567 static int i830_get_display_clock_speed(struct drm_device *dev)
6568 {
6569         return 133333;
6570 }
6571
6572 static void
6573 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
6574 {
6575         while (*num > DATA_LINK_M_N_MASK ||
6576                *den > DATA_LINK_M_N_MASK) {
6577                 *num >>= 1;
6578                 *den >>= 1;
6579         }
6580 }
6581
6582 static void compute_m_n(unsigned int m, unsigned int n,
6583                         uint32_t *ret_m, uint32_t *ret_n)
6584 {
6585         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
6586         *ret_m = div_u64((uint64_t) m * *ret_n, n);
6587         intel_reduce_m_n_ratio(ret_m, ret_n);
6588 }
6589
6590 void
6591 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
6592                        int pixel_clock, int link_clock,
6593                        struct intel_link_m_n *m_n)
6594 {
6595         m_n->tu = 64;
6596
6597         compute_m_n(bits_per_pixel * pixel_clock,
6598                     link_clock * nlanes * 8,
6599                     &m_n->gmch_m, &m_n->gmch_n);
6600
6601         compute_m_n(pixel_clock, link_clock,
6602                     &m_n->link_m, &m_n->link_n);
6603 }
6604
6605 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
6606 {
6607         if (i915.panel_use_ssc >= 0)
6608                 return i915.panel_use_ssc != 0;
6609         return dev_priv->vbt.lvds_use_ssc
6610                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
6611 }
6612
6613 static int i9xx_get_refclk(const struct intel_crtc_state *crtc_state,
6614                            int num_connectors)
6615 {
6616         struct drm_device *dev = crtc_state->base.crtc->dev;
6617         struct drm_i915_private *dev_priv = dev->dev_private;
6618         int refclk;
6619
6620         WARN_ON(!crtc_state->base.state);
6621
6622         if (IS_VALLEYVIEW(dev) || IS_BROXTON(dev)) {
6623                 refclk = 100000;
6624         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6625             intel_panel_use_ssc(dev_priv) && num_connectors < 2) {
6626                 refclk = dev_priv->vbt.lvds_ssc_freq;
6627                 DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
6628         } else if (!IS_GEN2(dev)) {
6629                 refclk = 96000;
6630         } else {
6631                 refclk = 48000;
6632         }
6633
6634         return refclk;
6635 }
6636
6637 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
6638 {
6639         return (1 << dpll->n) << 16 | dpll->m2;
6640 }
6641
6642 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
6643 {
6644         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
6645 }
6646
6647 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
6648                                      struct intel_crtc_state *crtc_state,
6649                                      intel_clock_t *reduced_clock)
6650 {
6651         struct drm_device *dev = crtc->base.dev;
6652         u32 fp, fp2 = 0;
6653
6654         if (IS_PINEVIEW(dev)) {
6655                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
6656                 if (reduced_clock)
6657                         fp2 = pnv_dpll_compute_fp(reduced_clock);
6658         } else {
6659                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
6660                 if (reduced_clock)
6661                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
6662         }
6663
6664         crtc_state->dpll_hw_state.fp0 = fp;
6665
6666         crtc->lowfreq_avail = false;
6667         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6668             reduced_clock) {
6669                 crtc_state->dpll_hw_state.fp1 = fp2;
6670                 crtc->lowfreq_avail = true;
6671         } else {
6672                 crtc_state->dpll_hw_state.fp1 = fp;
6673         }
6674 }
6675
6676 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
6677                 pipe)
6678 {
6679         u32 reg_val;
6680
6681         /*
6682          * PLLB opamp always calibrates to max value of 0x3f, force enable it
6683          * and set it to a reasonable value instead.
6684          */
6685         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6686         reg_val &= 0xffffff00;
6687         reg_val |= 0x00000030;
6688         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6689
6690         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6691         reg_val &= 0x8cffffff;
6692         reg_val = 0x8c000000;
6693         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6694
6695         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6696         reg_val &= 0xffffff00;
6697         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6698
6699         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6700         reg_val &= 0x00ffffff;
6701         reg_val |= 0xb0000000;
6702         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6703 }
6704
6705 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
6706                                          struct intel_link_m_n *m_n)
6707 {
6708         struct drm_device *dev = crtc->base.dev;
6709         struct drm_i915_private *dev_priv = dev->dev_private;
6710         int pipe = crtc->pipe;
6711
6712         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6713         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
6714         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
6715         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
6716 }
6717
6718 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
6719                                          struct intel_link_m_n *m_n,
6720                                          struct intel_link_m_n *m2_n2)
6721 {
6722         struct drm_device *dev = crtc->base.dev;
6723         struct drm_i915_private *dev_priv = dev->dev_private;
6724         int pipe = crtc->pipe;
6725         enum transcoder transcoder = crtc->config->cpu_transcoder;
6726
6727         if (INTEL_INFO(dev)->gen >= 5) {
6728                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
6729                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
6730                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
6731                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
6732                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
6733                  * for gen < 8) and if DRRS is supported (to make sure the
6734                  * registers are not unnecessarily accessed).
6735                  */
6736                 if (m2_n2 && (IS_CHERRYVIEW(dev) || INTEL_INFO(dev)->gen < 8) &&
6737                         crtc->config->has_drrs) {
6738                         I915_WRITE(PIPE_DATA_M2(transcoder),
6739                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
6740                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
6741                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
6742                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
6743                 }
6744         } else {
6745                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6746                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
6747                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
6748                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
6749         }
6750 }
6751
6752 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
6753 {
6754         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
6755
6756         if (m_n == M1_N1) {
6757                 dp_m_n = &crtc->config->dp_m_n;
6758                 dp_m2_n2 = &crtc->config->dp_m2_n2;
6759         } else if (m_n == M2_N2) {
6760
6761                 /*
6762                  * M2_N2 registers are not supported. Hence m2_n2 divider value
6763                  * needs to be programmed into M1_N1.
6764                  */
6765                 dp_m_n = &crtc->config->dp_m2_n2;
6766         } else {
6767                 DRM_ERROR("Unsupported divider value\n");
6768                 return;
6769         }
6770
6771         if (crtc->config->has_pch_encoder)
6772                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
6773         else
6774                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
6775 }
6776
6777 static void vlv_update_pll(struct intel_crtc *crtc,
6778                            struct intel_crtc_state *pipe_config)
6779 {
6780         u32 dpll, dpll_md;
6781
6782         /*
6783          * Enable DPIO clock input. We should never disable the reference
6784          * clock for pipe B, since VGA hotplug / manual detection depends
6785          * on it.
6786          */
6787         dpll = DPLL_EXT_BUFFER_ENABLE_VLV | DPLL_REFA_CLK_ENABLE_VLV |
6788                 DPLL_VGA_MODE_DIS | DPLL_INTEGRATED_CLOCK_VLV;
6789         /* We should never disable this, set it here for state tracking */
6790         if (crtc->pipe == PIPE_B)
6791                 dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6792         dpll |= DPLL_VCO_ENABLE;
6793         pipe_config->dpll_hw_state.dpll = dpll;
6794
6795         dpll_md = (pipe_config->pixel_multiplier - 1)
6796                 << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6797         pipe_config->dpll_hw_state.dpll_md = dpll_md;
6798 }
6799
6800 static void vlv_prepare_pll(struct intel_crtc *crtc,
6801                             const struct intel_crtc_state *pipe_config)
6802 {
6803         struct drm_device *dev = crtc->base.dev;
6804         struct drm_i915_private *dev_priv = dev->dev_private;
6805         int pipe = crtc->pipe;
6806         u32 mdiv;
6807         u32 bestn, bestm1, bestm2, bestp1, bestp2;
6808         u32 coreclk, reg_val;
6809
6810         mutex_lock(&dev_priv->dpio_lock);
6811
6812         bestn = pipe_config->dpll.n;
6813         bestm1 = pipe_config->dpll.m1;
6814         bestm2 = pipe_config->dpll.m2;
6815         bestp1 = pipe_config->dpll.p1;
6816         bestp2 = pipe_config->dpll.p2;
6817
6818         /* See eDP HDMI DPIO driver vbios notes doc */
6819
6820         /* PLL B needs special handling */
6821         if (pipe == PIPE_B)
6822                 vlv_pllb_recal_opamp(dev_priv, pipe);
6823
6824         /* Set up Tx target for periodic Rcomp update */
6825         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
6826
6827         /* Disable target IRef on PLL */
6828         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
6829         reg_val &= 0x00ffffff;
6830         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
6831
6832         /* Disable fast lock */
6833         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
6834
6835         /* Set idtafcrecal before PLL is enabled */
6836         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
6837         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
6838         mdiv |= ((bestn << DPIO_N_SHIFT));
6839         mdiv |= (1 << DPIO_K_SHIFT);
6840
6841         /*
6842          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
6843          * but we don't support that).
6844          * Note: don't use the DAC post divider as it seems unstable.
6845          */
6846         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
6847         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6848
6849         mdiv |= DPIO_ENABLE_CALIBRATION;
6850         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6851
6852         /* Set HBR and RBR LPF coefficients */
6853         if (pipe_config->port_clock == 162000 ||
6854             intel_pipe_has_type(crtc, INTEL_OUTPUT_ANALOG) ||
6855             intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI))
6856                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6857                                  0x009f0003);
6858         else
6859                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6860                                  0x00d0000f);
6861
6862         if (pipe_config->has_dp_encoder) {
6863                 /* Use SSC source */
6864                 if (pipe == PIPE_A)
6865                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6866                                          0x0df40000);
6867                 else
6868                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6869                                          0x0df70000);
6870         } else { /* HDMI or VGA */
6871                 /* Use bend source */
6872                 if (pipe == PIPE_A)
6873                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6874                                          0x0df70000);
6875                 else
6876                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6877                                          0x0df40000);
6878         }
6879
6880         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
6881         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
6882         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DISPLAYPORT) ||
6883             intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP))
6884                 coreclk |= 0x01000000;
6885         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
6886
6887         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
6888         mutex_unlock(&dev_priv->dpio_lock);
6889 }
6890
6891 static void chv_update_pll(struct intel_crtc *crtc,
6892                            struct intel_crtc_state *pipe_config)
6893 {
6894         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLOCK_CHV |
6895                 DPLL_REFA_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS |
6896                 DPLL_VCO_ENABLE;
6897         if (crtc->pipe != PIPE_A)
6898                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6899
6900         pipe_config->dpll_hw_state.dpll_md =
6901                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6902 }
6903
6904 static void chv_prepare_pll(struct intel_crtc *crtc,
6905                             const struct intel_crtc_state *pipe_config)
6906 {
6907         struct drm_device *dev = crtc->base.dev;
6908         struct drm_i915_private *dev_priv = dev->dev_private;
6909         int pipe = crtc->pipe;
6910         int dpll_reg = DPLL(crtc->pipe);
6911         enum dpio_channel port = vlv_pipe_to_channel(pipe);
6912         u32 loopfilter, tribuf_calcntr;
6913         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
6914         u32 dpio_val;
6915         int vco;
6916
6917         bestn = pipe_config->dpll.n;
6918         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
6919         bestm1 = pipe_config->dpll.m1;
6920         bestm2 = pipe_config->dpll.m2 >> 22;
6921         bestp1 = pipe_config->dpll.p1;
6922         bestp2 = pipe_config->dpll.p2;
6923         vco = pipe_config->dpll.vco;
6924         dpio_val = 0;
6925         loopfilter = 0;
6926
6927         /*
6928          * Enable Refclk and SSC
6929          */
6930         I915_WRITE(dpll_reg,
6931                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
6932
6933         mutex_lock(&dev_priv->dpio_lock);
6934
6935         /* p1 and p2 divider */
6936         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
6937                         5 << DPIO_CHV_S1_DIV_SHIFT |
6938                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
6939                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
6940                         1 << DPIO_CHV_K_DIV_SHIFT);
6941
6942         /* Feedback post-divider - m2 */
6943         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
6944
6945         /* Feedback refclk divider - n and m1 */
6946         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
6947                         DPIO_CHV_M1_DIV_BY_2 |
6948                         1 << DPIO_CHV_N_DIV_SHIFT);
6949
6950         /* M2 fraction division */
6951         if (bestm2_frac)
6952                 vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
6953
6954         /* M2 fraction division enable */
6955         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
6956         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
6957         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
6958         if (bestm2_frac)
6959                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
6960         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
6961
6962         /* Program digital lock detect threshold */
6963         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
6964         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
6965                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
6966         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
6967         if (!bestm2_frac)
6968                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
6969         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
6970
6971         /* Loop filter */
6972         if (vco == 5400000) {
6973                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
6974                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
6975                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
6976                 tribuf_calcntr = 0x9;
6977         } else if (vco <= 6200000) {
6978                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
6979                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
6980                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6981                 tribuf_calcntr = 0x9;
6982         } else if (vco <= 6480000) {
6983                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
6984                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
6985                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6986                 tribuf_calcntr = 0x8;
6987         } else {
6988                 /* Not supported. Apply the same limits as in the max case */
6989                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
6990                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
6991                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6992                 tribuf_calcntr = 0;
6993         }
6994         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
6995
6996         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
6997         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
6998         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
6999         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
7000
7001         /* AFC Recal */
7002         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
7003                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
7004                         DPIO_AFC_RECAL);
7005
7006         mutex_unlock(&dev_priv->dpio_lock);
7007 }
7008
7009 /**
7010  * vlv_force_pll_on - forcibly enable just the PLL
7011  * @dev_priv: i915 private structure
7012  * @pipe: pipe PLL to enable
7013  * @dpll: PLL configuration
7014  *
7015  * Enable the PLL for @pipe using the supplied @dpll config. To be used
7016  * in cases where we need the PLL enabled even when @pipe is not going to
7017  * be enabled.
7018  */
7019 void vlv_force_pll_on(struct drm_device *dev, enum pipe pipe,
7020                       const struct dpll *dpll)
7021 {
7022         struct intel_crtc *crtc =
7023                 to_intel_crtc(intel_get_crtc_for_pipe(dev, pipe));
7024         struct intel_crtc_state pipe_config = {
7025                 .base.crtc = &crtc->base,
7026                 .pixel_multiplier = 1,
7027                 .dpll = *dpll,
7028         };
7029
7030         if (IS_CHERRYVIEW(dev)) {
7031                 chv_update_pll(crtc, &pipe_config);
7032                 chv_prepare_pll(crtc, &pipe_config);
7033                 chv_enable_pll(crtc, &pipe_config);
7034         } else {
7035                 vlv_update_pll(crtc, &pipe_config);
7036                 vlv_prepare_pll(crtc, &pipe_config);
7037                 vlv_enable_pll(crtc, &pipe_config);
7038         }
7039 }
7040
7041 /**
7042  * vlv_force_pll_off - forcibly disable just the PLL
7043  * @dev_priv: i915 private structure
7044  * @pipe: pipe PLL to disable
7045  *
7046  * Disable the PLL for @pipe. To be used in cases where we need
7047  * the PLL enabled even when @pipe is not going to be enabled.
7048  */
7049 void vlv_force_pll_off(struct drm_device *dev, enum pipe pipe)
7050 {
7051         if (IS_CHERRYVIEW(dev))
7052                 chv_disable_pll(to_i915(dev), pipe);
7053         else
7054                 vlv_disable_pll(to_i915(dev), pipe);
7055 }
7056
7057 static void i9xx_update_pll(struct intel_crtc *crtc,
7058                             struct intel_crtc_state *crtc_state,
7059                             intel_clock_t *reduced_clock,
7060                             int num_connectors)
7061 {
7062         struct drm_device *dev = crtc->base.dev;
7063         struct drm_i915_private *dev_priv = dev->dev_private;
7064         u32 dpll;
7065         bool is_sdvo;
7066         struct dpll *clock = &crtc_state->dpll;
7067
7068         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7069
7070         is_sdvo = intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7071                 intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_HDMI);
7072
7073         dpll = DPLL_VGA_MODE_DIS;
7074
7075         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
7076                 dpll |= DPLLB_MODE_LVDS;
7077         else
7078                 dpll |= DPLLB_MODE_DAC_SERIAL;
7079
7080         if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
7081                 dpll |= (crtc_state->pixel_multiplier - 1)
7082                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7083         }
7084
7085         if (is_sdvo)
7086                 dpll |= DPLL_SDVO_HIGH_SPEED;
7087
7088         if (crtc_state->has_dp_encoder)
7089                 dpll |= DPLL_SDVO_HIGH_SPEED;
7090
7091         /* compute bitmask from p1 value */
7092         if (IS_PINEVIEW(dev))
7093                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7094         else {
7095                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7096                 if (IS_G4X(dev) && reduced_clock)
7097                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7098         }
7099         switch (clock->p2) {
7100         case 5:
7101                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7102                 break;
7103         case 7:
7104                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7105                 break;
7106         case 10:
7107                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7108                 break;
7109         case 14:
7110                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7111                 break;
7112         }
7113         if (INTEL_INFO(dev)->gen >= 4)
7114                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7115
7116         if (crtc_state->sdvo_tv_clock)
7117                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7118         else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7119                  intel_panel_use_ssc(dev_priv) && num_connectors < 2)
7120                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7121         else
7122                 dpll |= PLL_REF_INPUT_DREFCLK;
7123
7124         dpll |= DPLL_VCO_ENABLE;
7125         crtc_state->dpll_hw_state.dpll = dpll;
7126
7127         if (INTEL_INFO(dev)->gen >= 4) {
7128                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7129                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7130                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7131         }
7132 }
7133
7134 static void i8xx_update_pll(struct intel_crtc *crtc,
7135                             struct intel_crtc_state *crtc_state,
7136                             intel_clock_t *reduced_clock,
7137                             int num_connectors)
7138 {
7139         struct drm_device *dev = crtc->base.dev;
7140         struct drm_i915_private *dev_priv = dev->dev_private;
7141         u32 dpll;
7142         struct dpll *clock = &crtc_state->dpll;
7143
7144         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7145
7146         dpll = DPLL_VGA_MODE_DIS;
7147
7148         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7149                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7150         } else {
7151                 if (clock->p1 == 2)
7152                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7153                 else
7154                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7155                 if (clock->p2 == 4)
7156                         dpll |= PLL_P2_DIVIDE_BY_4;
7157         }
7158
7159         if (!IS_I830(dev) && intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_DVO))
7160                 dpll |= DPLL_DVO_2X_MODE;
7161
7162         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7163                  intel_panel_use_ssc(dev_priv) && num_connectors < 2)
7164                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7165         else
7166                 dpll |= PLL_REF_INPUT_DREFCLK;
7167
7168         dpll |= DPLL_VCO_ENABLE;
7169         crtc_state->dpll_hw_state.dpll = dpll;
7170 }
7171
7172 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
7173 {
7174         struct drm_device *dev = intel_crtc->base.dev;
7175         struct drm_i915_private *dev_priv = dev->dev_private;
7176         enum pipe pipe = intel_crtc->pipe;
7177         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
7178         struct drm_display_mode *adjusted_mode =
7179                 &intel_crtc->config->base.adjusted_mode;
7180         uint32_t crtc_vtotal, crtc_vblank_end;
7181         int vsyncshift = 0;
7182
7183         /* We need to be careful not to changed the adjusted mode, for otherwise
7184          * the hw state checker will get angry at the mismatch. */
7185         crtc_vtotal = adjusted_mode->crtc_vtotal;
7186         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7187
7188         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7189                 /* the chip adds 2 halflines automatically */
7190                 crtc_vtotal -= 1;
7191                 crtc_vblank_end -= 1;
7192
7193                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
7194                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7195                 else
7196                         vsyncshift = adjusted_mode->crtc_hsync_start -
7197                                 adjusted_mode->crtc_htotal / 2;
7198                 if (vsyncshift < 0)
7199                         vsyncshift += adjusted_mode->crtc_htotal;
7200         }
7201
7202         if (INTEL_INFO(dev)->gen > 3)
7203                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7204
7205         I915_WRITE(HTOTAL(cpu_transcoder),
7206                    (adjusted_mode->crtc_hdisplay - 1) |
7207                    ((adjusted_mode->crtc_htotal - 1) << 16));
7208         I915_WRITE(HBLANK(cpu_transcoder),
7209                    (adjusted_mode->crtc_hblank_start - 1) |
7210                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7211         I915_WRITE(HSYNC(cpu_transcoder),
7212                    (adjusted_mode->crtc_hsync_start - 1) |
7213                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7214
7215         I915_WRITE(VTOTAL(cpu_transcoder),
7216                    (adjusted_mode->crtc_vdisplay - 1) |
7217                    ((crtc_vtotal - 1) << 16));
7218         I915_WRITE(VBLANK(cpu_transcoder),
7219                    (adjusted_mode->crtc_vblank_start - 1) |
7220                    ((crtc_vblank_end - 1) << 16));
7221         I915_WRITE(VSYNC(cpu_transcoder),
7222                    (adjusted_mode->crtc_vsync_start - 1) |
7223                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7224
7225         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7226          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7227          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7228          * bits. */
7229         if (IS_HASWELL(dev) && cpu_transcoder == TRANSCODER_EDP &&
7230             (pipe == PIPE_B || pipe == PIPE_C))
7231                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7232
7233         /* pipesrc controls the size that is scaled from, which should
7234          * always be the user's requested size.
7235          */
7236         I915_WRITE(PIPESRC(pipe),
7237                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
7238                    (intel_crtc->config->pipe_src_h - 1));
7239 }
7240
7241 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7242                                    struct intel_crtc_state *pipe_config)
7243 {
7244         struct drm_device *dev = crtc->base.dev;
7245         struct drm_i915_private *dev_priv = dev->dev_private;
7246         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7247         uint32_t tmp;
7248
7249         tmp = I915_READ(HTOTAL(cpu_transcoder));
7250         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7251         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7252         tmp = I915_READ(HBLANK(cpu_transcoder));
7253         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7254         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7255         tmp = I915_READ(HSYNC(cpu_transcoder));
7256         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7257         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7258
7259         tmp = I915_READ(VTOTAL(cpu_transcoder));
7260         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7261         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7262         tmp = I915_READ(VBLANK(cpu_transcoder));
7263         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7264         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7265         tmp = I915_READ(VSYNC(cpu_transcoder));
7266         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7267         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7268
7269         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7270                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7271                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7272                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7273         }
7274
7275         tmp = I915_READ(PIPESRC(crtc->pipe));
7276         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7277         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7278
7279         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7280         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7281 }
7282
7283 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7284                                  struct intel_crtc_state *pipe_config)
7285 {
7286         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7287         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7288         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7289         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7290
7291         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7292         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7293         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7294         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7295
7296         mode->flags = pipe_config->base.adjusted_mode.flags;
7297
7298         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7299         mode->flags |= pipe_config->base.adjusted_mode.flags;
7300 }
7301
7302 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
7303 {
7304         struct drm_device *dev = intel_crtc->base.dev;
7305         struct drm_i915_private *dev_priv = dev->dev_private;
7306         uint32_t pipeconf;
7307
7308         pipeconf = 0;
7309
7310         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
7311             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
7312                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
7313
7314         if (intel_crtc->config->double_wide)
7315                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7316
7317         /* only g4x and later have fancy bpc/dither controls */
7318         if (IS_G4X(dev) || IS_VALLEYVIEW(dev)) {
7319                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7320                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
7321                         pipeconf |= PIPECONF_DITHER_EN |
7322                                     PIPECONF_DITHER_TYPE_SP;
7323
7324                 switch (intel_crtc->config->pipe_bpp) {
7325                 case 18:
7326                         pipeconf |= PIPECONF_6BPC;
7327                         break;
7328                 case 24:
7329                         pipeconf |= PIPECONF_8BPC;
7330                         break;
7331                 case 30:
7332                         pipeconf |= PIPECONF_10BPC;
7333                         break;
7334                 default:
7335                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7336                         BUG();
7337                 }
7338         }
7339
7340         if (HAS_PIPE_CXSR(dev)) {
7341                 if (intel_crtc->lowfreq_avail) {
7342                         DRM_DEBUG_KMS("enabling CxSR downclocking\n");
7343                         pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
7344                 } else {
7345                         DRM_DEBUG_KMS("disabling CxSR downclocking\n");
7346                 }
7347         }
7348
7349         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7350                 if (INTEL_INFO(dev)->gen < 4 ||
7351                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
7352                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7353                 else
7354                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7355         } else
7356                 pipeconf |= PIPECONF_PROGRESSIVE;
7357
7358         if (IS_VALLEYVIEW(dev) && intel_crtc->config->limited_color_range)
7359                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7360
7361         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
7362         POSTING_READ(PIPECONF(intel_crtc->pipe));
7363 }
7364
7365 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7366                                    struct intel_crtc_state *crtc_state)
7367 {
7368         struct drm_device *dev = crtc->base.dev;
7369         struct drm_i915_private *dev_priv = dev->dev_private;
7370         int refclk, num_connectors = 0;
7371         intel_clock_t clock, reduced_clock;
7372         bool ok, has_reduced_clock = false;
7373         bool is_lvds = false, is_dsi = false;
7374         struct intel_encoder *encoder;
7375         const intel_limit_t *limit;
7376         struct drm_atomic_state *state = crtc_state->base.state;
7377         struct drm_connector_state *connector_state;
7378         int i;
7379
7380         for (i = 0; i < state->num_connector; i++) {
7381                 if (!state->connectors[i])
7382                         continue;
7383
7384                 connector_state = state->connector_states[i];
7385                 if (connector_state->crtc != &crtc->base)
7386                         continue;
7387
7388                 encoder = to_intel_encoder(connector_state->best_encoder);
7389
7390                 switch (encoder->type) {
7391                 case INTEL_OUTPUT_LVDS:
7392                         is_lvds = true;
7393                         break;
7394                 case INTEL_OUTPUT_DSI:
7395                         is_dsi = true;
7396                         break;
7397                 default:
7398                         break;
7399                 }
7400
7401                 num_connectors++;
7402         }
7403
7404         if (is_dsi)
7405                 return 0;
7406
7407         if (!crtc_state->clock_set) {
7408                 refclk = i9xx_get_refclk(crtc_state, num_connectors);
7409
7410                 /*
7411                  * Returns a set of divisors for the desired target clock with
7412                  * the given refclk, or FALSE.  The returned values represent
7413                  * the clock equation: reflck * (5 * (m1 + 2) + (m2 + 2)) / (n +
7414                  * 2) / p1 / p2.
7415                  */
7416                 limit = intel_limit(crtc_state, refclk);
7417                 ok = dev_priv->display.find_dpll(limit, crtc_state,
7418                                                  crtc_state->port_clock,
7419                                                  refclk, NULL, &clock);
7420                 if (!ok) {
7421                         DRM_ERROR("Couldn't find PLL settings for mode!\n");
7422                         return -EINVAL;
7423                 }
7424
7425                 if (is_lvds && dev_priv->lvds_downclock_avail) {
7426                         /*
7427                          * Ensure we match the reduced clock's P to the target
7428                          * clock.  If the clocks don't match, we can't switch
7429                          * the display clock by using the FP0/FP1. In such case
7430                          * we will disable the LVDS downclock feature.
7431                          */
7432                         has_reduced_clock =
7433                                 dev_priv->display.find_dpll(limit, crtc_state,
7434                                                             dev_priv->lvds_downclock,
7435                                                             refclk, &clock,
7436                                                             &reduced_clock);
7437                 }
7438                 /* Compat-code for transition, will disappear. */
7439                 crtc_state->dpll.n = clock.n;
7440                 crtc_state->dpll.m1 = clock.m1;
7441                 crtc_state->dpll.m2 = clock.m2;
7442                 crtc_state->dpll.p1 = clock.p1;
7443                 crtc_state->dpll.p2 = clock.p2;
7444         }
7445
7446         if (IS_GEN2(dev)) {
7447                 i8xx_update_pll(crtc, crtc_state,
7448                                 has_reduced_clock ? &reduced_clock : NULL,
7449                                 num_connectors);
7450         } else if (IS_CHERRYVIEW(dev)) {
7451                 chv_update_pll(crtc, crtc_state);
7452         } else if (IS_VALLEYVIEW(dev)) {
7453                 vlv_update_pll(crtc, crtc_state);
7454         } else {
7455                 i9xx_update_pll(crtc, crtc_state,
7456                                 has_reduced_clock ? &reduced_clock : NULL,
7457                                 num_connectors);
7458         }
7459
7460         return 0;
7461 }
7462
7463 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
7464                                  struct intel_crtc_state *pipe_config)
7465 {
7466         struct drm_device *dev = crtc->base.dev;
7467         struct drm_i915_private *dev_priv = dev->dev_private;
7468         uint32_t tmp;
7469
7470         if (INTEL_INFO(dev)->gen <= 3 && (IS_I830(dev) || !IS_MOBILE(dev)))
7471                 return;
7472
7473         tmp = I915_READ(PFIT_CONTROL);
7474         if (!(tmp & PFIT_ENABLE))
7475                 return;
7476
7477         /* Check whether the pfit is attached to our pipe. */
7478         if (INTEL_INFO(dev)->gen < 4) {
7479                 if (crtc->pipe != PIPE_B)
7480                         return;
7481         } else {
7482                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
7483                         return;
7484         }
7485
7486         pipe_config->gmch_pfit.control = tmp;
7487         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
7488         if (INTEL_INFO(dev)->gen < 5)
7489                 pipe_config->gmch_pfit.lvds_border_bits =
7490                         I915_READ(LVDS) & LVDS_BORDER_ENABLE;
7491 }
7492
7493 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
7494                                struct intel_crtc_state *pipe_config)
7495 {
7496         struct drm_device *dev = crtc->base.dev;
7497         struct drm_i915_private *dev_priv = dev->dev_private;
7498         int pipe = pipe_config->cpu_transcoder;
7499         intel_clock_t clock;
7500         u32 mdiv;
7501         int refclk = 100000;
7502
7503         /* In case of MIPI DPLL will not even be used */
7504         if (!(pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE))
7505                 return;
7506
7507         mutex_lock(&dev_priv->dpio_lock);
7508         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
7509         mutex_unlock(&dev_priv->dpio_lock);
7510
7511         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
7512         clock.m2 = mdiv & DPIO_M2DIV_MASK;
7513         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
7514         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
7515         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
7516
7517         vlv_clock(refclk, &clock);
7518
7519         /* clock.dot is the fast clock */
7520         pipe_config->port_clock = clock.dot / 5;
7521 }
7522
7523 static void
7524 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
7525                               struct intel_initial_plane_config *plane_config)
7526 {
7527         struct drm_device *dev = crtc->base.dev;
7528         struct drm_i915_private *dev_priv = dev->dev_private;
7529         u32 val, base, offset;
7530         int pipe = crtc->pipe, plane = crtc->plane;
7531         int fourcc, pixel_format;
7532         unsigned int aligned_height;
7533         struct drm_framebuffer *fb;
7534         struct intel_framebuffer *intel_fb;
7535
7536         val = I915_READ(DSPCNTR(plane));
7537         if (!(val & DISPLAY_PLANE_ENABLE))
7538                 return;
7539
7540         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
7541         if (!intel_fb) {
7542                 DRM_DEBUG_KMS("failed to alloc fb\n");
7543                 return;
7544         }
7545
7546         fb = &intel_fb->base;
7547
7548         if (INTEL_INFO(dev)->gen >= 4) {
7549                 if (val & DISPPLANE_TILED) {
7550                         plane_config->tiling = I915_TILING_X;
7551                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
7552                 }
7553         }
7554
7555         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
7556         fourcc = i9xx_format_to_fourcc(pixel_format);
7557         fb->pixel_format = fourcc;
7558         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
7559
7560         if (INTEL_INFO(dev)->gen >= 4) {
7561                 if (plane_config->tiling)
7562                         offset = I915_READ(DSPTILEOFF(plane));
7563                 else
7564                         offset = I915_READ(DSPLINOFF(plane));
7565                 base = I915_READ(DSPSURF(plane)) & 0xfffff000;
7566         } else {
7567                 base = I915_READ(DSPADDR(plane));
7568         }
7569         plane_config->base = base;
7570
7571         val = I915_READ(PIPESRC(pipe));
7572         fb->width = ((val >> 16) & 0xfff) + 1;
7573         fb->height = ((val >> 0) & 0xfff) + 1;
7574
7575         val = I915_READ(DSPSTRIDE(pipe));
7576         fb->pitches[0] = val & 0xffffffc0;
7577
7578         aligned_height = intel_fb_align_height(dev, fb->height,
7579                                                fb->pixel_format,
7580                                                fb->modifier[0]);
7581
7582         plane_config->size = fb->pitches[0] * aligned_height;
7583
7584         DRM_DEBUG_KMS("pipe/plane %c/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
7585                       pipe_name(pipe), plane, fb->width, fb->height,
7586                       fb->bits_per_pixel, base, fb->pitches[0],
7587                       plane_config->size);
7588
7589         plane_config->fb = intel_fb;
7590 }
7591
7592 static void chv_crtc_clock_get(struct intel_crtc *crtc,
7593                                struct intel_crtc_state *pipe_config)
7594 {
7595         struct drm_device *dev = crtc->base.dev;
7596         struct drm_i915_private *dev_priv = dev->dev_private;
7597         int pipe = pipe_config->cpu_transcoder;
7598         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7599         intel_clock_t clock;
7600         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2;
7601         int refclk = 100000;
7602
7603         mutex_lock(&dev_priv->dpio_lock);
7604         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
7605         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
7606         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
7607         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
7608         mutex_unlock(&dev_priv->dpio_lock);
7609
7610         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
7611         clock.m2 = ((pll_dw0 & 0xff) << 22) | (pll_dw2 & 0x3fffff);
7612         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
7613         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
7614         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
7615
7616         chv_clock(refclk, &clock);
7617
7618         /* clock.dot is the fast clock */
7619         pipe_config->port_clock = clock.dot / 5;
7620 }
7621
7622 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
7623                                  struct intel_crtc_state *pipe_config)
7624 {
7625         struct drm_device *dev = crtc->base.dev;
7626         struct drm_i915_private *dev_priv = dev->dev_private;
7627         uint32_t tmp;
7628
7629         if (!intel_display_power_is_enabled(dev_priv,
7630                                             POWER_DOMAIN_PIPE(crtc->pipe)))
7631                 return false;
7632
7633         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
7634         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
7635
7636         tmp = I915_READ(PIPECONF(crtc->pipe));
7637         if (!(tmp & PIPECONF_ENABLE))
7638                 return false;
7639
7640         if (IS_G4X(dev) || IS_VALLEYVIEW(dev)) {
7641                 switch (tmp & PIPECONF_BPC_MASK) {
7642                 case PIPECONF_6BPC:
7643                         pipe_config->pipe_bpp = 18;
7644                         break;
7645                 case PIPECONF_8BPC:
7646                         pipe_config->pipe_bpp = 24;
7647                         break;
7648                 case PIPECONF_10BPC:
7649                         pipe_config->pipe_bpp = 30;
7650                         break;
7651                 default:
7652                         break;
7653                 }
7654         }
7655
7656         if (IS_VALLEYVIEW(dev) && (tmp & PIPECONF_COLOR_RANGE_SELECT))
7657                 pipe_config->limited_color_range = true;
7658
7659         if (INTEL_INFO(dev)->gen < 4)
7660                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
7661
7662         intel_get_pipe_timings(crtc, pipe_config);
7663
7664         i9xx_get_pfit_config(crtc, pipe_config);
7665
7666         if (INTEL_INFO(dev)->gen >= 4) {
7667                 tmp = I915_READ(DPLL_MD(crtc->pipe));
7668                 pipe_config->pixel_multiplier =
7669                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
7670                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
7671                 pipe_config->dpll_hw_state.dpll_md = tmp;
7672         } else if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
7673                 tmp = I915_READ(DPLL(crtc->pipe));
7674                 pipe_config->pixel_multiplier =
7675                         ((tmp & SDVO_MULTIPLIER_MASK)
7676                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
7677         } else {
7678                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
7679                  * port and will be fixed up in the encoder->get_config
7680                  * function. */
7681                 pipe_config->pixel_multiplier = 1;
7682         }
7683         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
7684         if (!IS_VALLEYVIEW(dev)) {
7685                 /*
7686                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
7687                  * on 830. Filter it out here so that we don't
7688                  * report errors due to that.
7689                  */
7690                 if (IS_I830(dev))
7691                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
7692
7693                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
7694                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
7695         } else {
7696                 /* Mask out read-only status bits. */
7697                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
7698                                                      DPLL_PORTC_READY_MASK |
7699                                                      DPLL_PORTB_READY_MASK);
7700         }
7701
7702         if (IS_CHERRYVIEW(dev))
7703                 chv_crtc_clock_get(crtc, pipe_config);
7704         else if (IS_VALLEYVIEW(dev))
7705                 vlv_crtc_clock_get(crtc, pipe_config);
7706         else
7707                 i9xx_crtc_clock_get(crtc, pipe_config);
7708
7709         return true;
7710 }
7711
7712 static void ironlake_init_pch_refclk(struct drm_device *dev)
7713 {
7714         struct drm_i915_private *dev_priv = dev->dev_private;
7715         struct intel_encoder *encoder;
7716         u32 val, final;
7717         bool has_lvds = false;
7718         bool has_cpu_edp = false;
7719         bool has_panel = false;
7720         bool has_ck505 = false;
7721         bool can_ssc = false;
7722
7723         /* We need to take the global config into account */
7724         for_each_intel_encoder(dev, encoder) {
7725                 switch (encoder->type) {
7726                 case INTEL_OUTPUT_LVDS:
7727                         has_panel = true;
7728                         has_lvds = true;
7729                         break;
7730                 case INTEL_OUTPUT_EDP:
7731                         has_panel = true;
7732                         if (enc_to_dig_port(&encoder->base)->port == PORT_A)
7733                                 has_cpu_edp = true;
7734                         break;
7735                 default:
7736                         break;
7737                 }
7738         }
7739
7740         if (HAS_PCH_IBX(dev)) {
7741                 has_ck505 = dev_priv->vbt.display_clock_mode;
7742                 can_ssc = has_ck505;
7743         } else {
7744                 has_ck505 = false;
7745                 can_ssc = true;
7746         }
7747
7748         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d\n",
7749                       has_panel, has_lvds, has_ck505);
7750
7751         /* Ironlake: try to setup display ref clock before DPLL
7752          * enabling. This is only under driver's control after
7753          * PCH B stepping, previous chipset stepping should be
7754          * ignoring this setting.
7755          */
7756         val = I915_READ(PCH_DREF_CONTROL);
7757
7758         /* As we must carefully and slowly disable/enable each source in turn,
7759          * compute the final state we want first and check if we need to
7760          * make any changes at all.
7761          */
7762         final = val;
7763         final &= ~DREF_NONSPREAD_SOURCE_MASK;
7764         if (has_ck505)
7765                 final |= DREF_NONSPREAD_CK505_ENABLE;
7766         else
7767                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
7768
7769         final &= ~DREF_SSC_SOURCE_MASK;
7770         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7771         final &= ~DREF_SSC1_ENABLE;
7772
7773         if (has_panel) {
7774                 final |= DREF_SSC_SOURCE_ENABLE;
7775
7776                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
7777                         final |= DREF_SSC1_ENABLE;
7778
7779                 if (has_cpu_edp) {
7780                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
7781                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
7782                         else
7783                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
7784                 } else
7785                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7786         } else {
7787                 final |= DREF_SSC_SOURCE_DISABLE;
7788                 final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7789         }
7790
7791         if (final == val)
7792                 return;
7793
7794         /* Always enable nonspread source */
7795         val &= ~DREF_NONSPREAD_SOURCE_MASK;
7796
7797         if (has_ck505)
7798                 val |= DREF_NONSPREAD_CK505_ENABLE;
7799         else
7800                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
7801
7802         if (has_panel) {
7803                 val &= ~DREF_SSC_SOURCE_MASK;
7804                 val |= DREF_SSC_SOURCE_ENABLE;
7805
7806                 /* SSC must be turned on before enabling the CPU output  */
7807                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
7808                         DRM_DEBUG_KMS("Using SSC on panel\n");
7809                         val |= DREF_SSC1_ENABLE;
7810                 } else
7811                         val &= ~DREF_SSC1_ENABLE;
7812
7813                 /* Get SSC going before enabling the outputs */
7814                 I915_WRITE(PCH_DREF_CONTROL, val);
7815                 POSTING_READ(PCH_DREF_CONTROL);
7816                 udelay(200);
7817
7818                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7819
7820                 /* Enable CPU source on CPU attached eDP */
7821                 if (has_cpu_edp) {
7822                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
7823                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
7824                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
7825                         } else
7826                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
7827                 } else
7828                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7829
7830                 I915_WRITE(PCH_DREF_CONTROL, val);
7831                 POSTING_READ(PCH_DREF_CONTROL);
7832                 udelay(200);
7833         } else {
7834                 DRM_DEBUG_KMS("Disabling SSC entirely\n");
7835
7836                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7837
7838                 /* Turn off CPU output */
7839                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7840
7841                 I915_WRITE(PCH_DREF_CONTROL, val);
7842                 POSTING_READ(PCH_DREF_CONTROL);
7843                 udelay(200);
7844
7845                 /* Turn off the SSC source */
7846                 val &= ~DREF_SSC_SOURCE_MASK;
7847                 val |= DREF_SSC_SOURCE_DISABLE;
7848
7849                 /* Turn off SSC1 */
7850                 val &= ~DREF_SSC1_ENABLE;
7851
7852                 I915_WRITE(PCH_DREF_CONTROL, val);
7853                 POSTING_READ(PCH_DREF_CONTROL);
7854                 udelay(200);
7855         }
7856
7857         BUG_ON(val != final);
7858 }
7859
7860 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
7861 {
7862         uint32_t tmp;
7863
7864         tmp = I915_READ(SOUTH_CHICKEN2);
7865         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
7866         I915_WRITE(SOUTH_CHICKEN2, tmp);
7867
7868         if (wait_for_atomic_us(I915_READ(SOUTH_CHICKEN2) &
7869                                FDI_MPHY_IOSFSB_RESET_STATUS, 100))
7870                 DRM_ERROR("FDI mPHY reset assert timeout\n");
7871
7872         tmp = I915_READ(SOUTH_CHICKEN2);
7873         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
7874         I915_WRITE(SOUTH_CHICKEN2, tmp);
7875
7876         if (wait_for_atomic_us((I915_READ(SOUTH_CHICKEN2) &
7877                                 FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
7878                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
7879 }
7880
7881 /* WaMPhyProgramming:hsw */
7882 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
7883 {
7884         uint32_t tmp;
7885
7886         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
7887         tmp &= ~(0xFF << 24);
7888         tmp |= (0x12 << 24);
7889         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
7890
7891         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
7892         tmp |= (1 << 11);
7893         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
7894
7895         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
7896         tmp |= (1 << 11);
7897         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
7898
7899         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
7900         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
7901         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
7902
7903         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
7904         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
7905         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
7906
7907         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
7908         tmp &= ~(7 << 13);
7909         tmp |= (5 << 13);
7910         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
7911
7912         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
7913         tmp &= ~(7 << 13);
7914         tmp |= (5 << 13);
7915         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
7916
7917         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
7918         tmp &= ~0xFF;
7919         tmp |= 0x1C;
7920         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
7921
7922         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
7923         tmp &= ~0xFF;
7924         tmp |= 0x1C;
7925         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
7926
7927         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
7928         tmp &= ~(0xFF << 16);
7929         tmp |= (0x1C << 16);
7930         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
7931
7932         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
7933         tmp &= ~(0xFF << 16);
7934         tmp |= (0x1C << 16);
7935         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
7936
7937         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
7938         tmp |= (1 << 27);
7939         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
7940
7941         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
7942         tmp |= (1 << 27);
7943         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
7944
7945         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
7946         tmp &= ~(0xF << 28);
7947         tmp |= (4 << 28);
7948         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
7949
7950         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
7951         tmp &= ~(0xF << 28);
7952         tmp |= (4 << 28);
7953         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
7954 }
7955
7956 /* Implements 3 different sequences from BSpec chapter "Display iCLK
7957  * Programming" based on the parameters passed:
7958  * - Sequence to enable CLKOUT_DP
7959  * - Sequence to enable CLKOUT_DP without spread
7960  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
7961  */
7962 static void lpt_enable_clkout_dp(struct drm_device *dev, bool with_spread,
7963                                  bool with_fdi)
7964 {
7965         struct drm_i915_private *dev_priv = dev->dev_private;
7966         uint32_t reg, tmp;
7967
7968         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
7969                 with_spread = true;
7970         if (WARN(dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE &&
7971                  with_fdi, "LP PCH doesn't have FDI\n"))
7972                 with_fdi = false;
7973
7974         mutex_lock(&dev_priv->dpio_lock);
7975
7976         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
7977         tmp &= ~SBI_SSCCTL_DISABLE;
7978         tmp |= SBI_SSCCTL_PATHALT;
7979         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
7980
7981         udelay(24);
7982
7983         if (with_spread) {
7984                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
7985                 tmp &= ~SBI_SSCCTL_PATHALT;
7986                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
7987
7988                 if (with_fdi) {
7989                         lpt_reset_fdi_mphy(dev_priv);
7990                         lpt_program_fdi_mphy(dev_priv);
7991                 }
7992         }
7993
7994         reg = (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) ?
7995                SBI_GEN0 : SBI_DBUFF0;
7996         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
7997         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
7998         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
7999
8000         mutex_unlock(&dev_priv->dpio_lock);
8001 }
8002
8003 /* Sequence to disable CLKOUT_DP */
8004 static void lpt_disable_clkout_dp(struct drm_device *dev)
8005 {
8006         struct drm_i915_private *dev_priv = dev->dev_private;
8007         uint32_t reg, tmp;
8008
8009         mutex_lock(&dev_priv->dpio_lock);
8010
8011         reg = (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) ?
8012                SBI_GEN0 : SBI_DBUFF0;
8013         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8014         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8015         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8016
8017         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8018         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8019                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8020                         tmp |= SBI_SSCCTL_PATHALT;
8021                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8022                         udelay(32);
8023                 }
8024                 tmp |= SBI_SSCCTL_DISABLE;
8025                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8026         }
8027
8028         mutex_unlock(&dev_priv->dpio_lock);
8029 }
8030
8031 static void lpt_init_pch_refclk(struct drm_device *dev)
8032 {
8033         struct intel_encoder *encoder;
8034         bool has_vga = false;
8035
8036         for_each_intel_encoder(dev, encoder) {
8037                 switch (encoder->type) {
8038                 case INTEL_OUTPUT_ANALOG:
8039                         has_vga = true;
8040                         break;
8041                 default:
8042                         break;
8043                 }
8044         }
8045
8046         if (has_vga)
8047                 lpt_enable_clkout_dp(dev, true, true);
8048         else
8049                 lpt_disable_clkout_dp(dev);
8050 }
8051
8052 /*
8053  * Initialize reference clocks when the driver loads
8054  */
8055 void intel_init_pch_refclk(struct drm_device *dev)
8056 {
8057         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
8058                 ironlake_init_pch_refclk(dev);
8059         else if (HAS_PCH_LPT(dev))
8060                 lpt_init_pch_refclk(dev);
8061 }
8062
8063 static int ironlake_get_refclk(struct intel_crtc_state *crtc_state)
8064 {
8065         struct drm_device *dev = crtc_state->base.crtc->dev;
8066         struct drm_i915_private *dev_priv = dev->dev_private;
8067         struct drm_atomic_state *state = crtc_state->base.state;
8068         struct drm_connector_state *connector_state;
8069         struct intel_encoder *encoder;
8070         int num_connectors = 0, i;
8071         bool is_lvds = false;
8072
8073         for (i = 0; i < state->num_connector; i++) {
8074                 if (!state->connectors[i])
8075                         continue;
8076
8077                 connector_state = state->connector_states[i];
8078                 if (connector_state->crtc != crtc_state->base.crtc)
8079                         continue;
8080
8081                 encoder = to_intel_encoder(connector_state->best_encoder);
8082
8083                 switch (encoder->type) {
8084                 case INTEL_OUTPUT_LVDS:
8085                         is_lvds = true;
8086                         break;
8087                 default:
8088                         break;
8089                 }
8090                 num_connectors++;
8091         }
8092
8093         if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2) {
8094                 DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8095                               dev_priv->vbt.lvds_ssc_freq);
8096                 return dev_priv->vbt.lvds_ssc_freq;
8097         }
8098
8099         return 120000;
8100 }
8101
8102 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
8103 {
8104         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
8105         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8106         int pipe = intel_crtc->pipe;
8107         uint32_t val;
8108
8109         val = 0;
8110
8111         switch (intel_crtc->config->pipe_bpp) {
8112         case 18:
8113                 val |= PIPECONF_6BPC;
8114                 break;
8115         case 24:
8116                 val |= PIPECONF_8BPC;
8117                 break;
8118         case 30:
8119                 val |= PIPECONF_10BPC;
8120                 break;
8121         case 36:
8122                 val |= PIPECONF_12BPC;
8123                 break;
8124         default:
8125                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8126                 BUG();
8127         }
8128
8129         if (intel_crtc->config->dither)
8130                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8131
8132         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8133                 val |= PIPECONF_INTERLACED_ILK;
8134         else
8135                 val |= PIPECONF_PROGRESSIVE;
8136
8137         if (intel_crtc->config->limited_color_range)
8138                 val |= PIPECONF_COLOR_RANGE_SELECT;
8139
8140         I915_WRITE(PIPECONF(pipe), val);
8141         POSTING_READ(PIPECONF(pipe));
8142 }
8143
8144 /*
8145  * Set up the pipe CSC unit.
8146  *
8147  * Currently only full range RGB to limited range RGB conversion
8148  * is supported, but eventually this should handle various
8149  * RGB<->YCbCr scenarios as well.
8150  */
8151 static void intel_set_pipe_csc(struct drm_crtc *crtc)
8152 {
8153         struct drm_device *dev = crtc->dev;
8154         struct drm_i915_private *dev_priv = dev->dev_private;
8155         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8156         int pipe = intel_crtc->pipe;
8157         uint16_t coeff = 0x7800; /* 1.0 */
8158
8159         /*
8160          * TODO: Check what kind of values actually come out of the pipe
8161          * with these coeff/postoff values and adjust to get the best
8162          * accuracy. Perhaps we even need to take the bpc value into
8163          * consideration.
8164          */
8165
8166         if (intel_crtc->config->limited_color_range)
8167                 coeff = ((235 - 16) * (1 << 12) / 255) & 0xff8; /* 0.xxx... */
8168
8169         /*
8170          * GY/GU and RY/RU should be the other way around according
8171          * to BSpec, but reality doesn't agree. Just set them up in
8172          * a way that results in the correct picture.
8173          */
8174         I915_WRITE(PIPE_CSC_COEFF_RY_GY(pipe), coeff << 16);
8175         I915_WRITE(PIPE_CSC_COEFF_BY(pipe), 0);
8176
8177         I915_WRITE(PIPE_CSC_COEFF_RU_GU(pipe), coeff);
8178         I915_WRITE(PIPE_CSC_COEFF_BU(pipe), 0);
8179
8180         I915_WRITE(PIPE_CSC_COEFF_RV_GV(pipe), 0);
8181         I915_WRITE(PIPE_CSC_COEFF_BV(pipe), coeff << 16);
8182
8183         I915_WRITE(PIPE_CSC_PREOFF_HI(pipe), 0);
8184         I915_WRITE(PIPE_CSC_PREOFF_ME(pipe), 0);
8185         I915_WRITE(PIPE_CSC_PREOFF_LO(pipe), 0);
8186
8187         if (INTEL_INFO(dev)->gen > 6) {
8188                 uint16_t postoff = 0;
8189
8190                 if (intel_crtc->config->limited_color_range)
8191                         postoff = (16 * (1 << 12) / 255) & 0x1fff;
8192
8193                 I915_WRITE(PIPE_CSC_POSTOFF_HI(pipe), postoff);
8194                 I915_WRITE(PIPE_CSC_POSTOFF_ME(pipe), postoff);
8195                 I915_WRITE(PIPE_CSC_POSTOFF_LO(pipe), postoff);
8196
8197                 I915_WRITE(PIPE_CSC_MODE(pipe), 0);
8198         } else {
8199                 uint32_t mode = CSC_MODE_YUV_TO_RGB;
8200
8201                 if (intel_crtc->config->limited_color_range)
8202                         mode |= CSC_BLACK_SCREEN_OFFSET;
8203
8204                 I915_WRITE(PIPE_CSC_MODE(pipe), mode);
8205         }
8206 }
8207
8208 static void haswell_set_pipeconf(struct drm_crtc *crtc)
8209 {
8210         struct drm_device *dev = crtc->dev;
8211         struct drm_i915_private *dev_priv = dev->dev_private;
8212         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8213         enum pipe pipe = intel_crtc->pipe;
8214         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8215         uint32_t val;
8216
8217         val = 0;
8218
8219         if (IS_HASWELL(dev) && intel_crtc->config->dither)
8220                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8221
8222         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8223                 val |= PIPECONF_INTERLACED_ILK;
8224         else
8225                 val |= PIPECONF_PROGRESSIVE;
8226
8227         I915_WRITE(PIPECONF(cpu_transcoder), val);
8228         POSTING_READ(PIPECONF(cpu_transcoder));
8229
8230         I915_WRITE(GAMMA_MODE(intel_crtc->pipe), GAMMA_MODE_MODE_8BIT);
8231         POSTING_READ(GAMMA_MODE(intel_crtc->pipe));
8232
8233         if (IS_BROADWELL(dev) || INTEL_INFO(dev)->gen >= 9) {
8234                 val = 0;
8235
8236                 switch (intel_crtc->config->pipe_bpp) {
8237                 case 18:
8238                         val |= PIPEMISC_DITHER_6_BPC;
8239                         break;
8240                 case 24:
8241                         val |= PIPEMISC_DITHER_8_BPC;
8242                         break;
8243                 case 30:
8244                         val |= PIPEMISC_DITHER_10_BPC;
8245                         break;
8246                 case 36:
8247                         val |= PIPEMISC_DITHER_12_BPC;
8248                         break;
8249                 default:
8250                         /* Case prevented by pipe_config_set_bpp. */
8251                         BUG();
8252                 }
8253
8254                 if (intel_crtc->config->dither)
8255                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8256
8257                 I915_WRITE(PIPEMISC(pipe), val);
8258         }
8259 }
8260
8261 static bool ironlake_compute_clocks(struct drm_crtc *crtc,
8262                                     struct intel_crtc_state *crtc_state,
8263                                     intel_clock_t *clock,
8264                                     bool *has_reduced_clock,
8265                                     intel_clock_t *reduced_clock)
8266 {
8267         struct drm_device *dev = crtc->dev;
8268         struct drm_i915_private *dev_priv = dev->dev_private;
8269         int refclk;
8270         const intel_limit_t *limit;
8271         bool ret, is_lvds = false;
8272
8273         is_lvds = intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS);
8274
8275         refclk = ironlake_get_refclk(crtc_state);
8276
8277         /*
8278          * Returns a set of divisors for the desired target clock with the given
8279          * refclk, or FALSE.  The returned values represent the clock equation:
8280          * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
8281          */
8282         limit = intel_limit(crtc_state, refclk);
8283         ret = dev_priv->display.find_dpll(limit, crtc_state,
8284                                           crtc_state->port_clock,
8285                                           refclk, NULL, clock);
8286         if (!ret)
8287                 return false;
8288
8289         if (is_lvds && dev_priv->lvds_downclock_avail) {
8290                 /*
8291                  * Ensure we match the reduced clock's P to the target clock.
8292                  * If the clocks don't match, we can't switch the display clock
8293                  * by using the FP0/FP1. In such case we will disable the LVDS
8294                  * downclock feature.
8295                 */
8296                 *has_reduced_clock =
8297                         dev_priv->display.find_dpll(limit, crtc_state,
8298                                                     dev_priv->lvds_downclock,
8299                                                     refclk, clock,
8300                                                     reduced_clock);
8301         }
8302
8303         return true;
8304 }
8305
8306 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8307 {
8308         /*
8309          * Account for spread spectrum to avoid
8310          * oversubscribing the link. Max center spread
8311          * is 2.5%; use 5% for safety's sake.
8312          */
8313         u32 bps = target_clock * bpp * 21 / 20;
8314         return DIV_ROUND_UP(bps, link_bw * 8);
8315 }
8316
8317 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8318 {
8319         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8320 }
8321
8322 static uint32_t ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8323                                       struct intel_crtc_state *crtc_state,
8324                                       u32 *fp,
8325                                       intel_clock_t *reduced_clock, u32 *fp2)
8326 {
8327         struct drm_crtc *crtc = &intel_crtc->base;
8328         struct drm_device *dev = crtc->dev;
8329         struct drm_i915_private *dev_priv = dev->dev_private;
8330         struct drm_atomic_state *state = crtc_state->base.state;
8331         struct drm_connector_state *connector_state;
8332         struct intel_encoder *encoder;
8333         uint32_t dpll;
8334         int factor, num_connectors = 0, i;
8335         bool is_lvds = false, is_sdvo = false;
8336
8337         for (i = 0; i < state->num_connector; i++) {
8338                 if (!state->connectors[i])
8339                         continue;
8340
8341                 connector_state = state->connector_states[i];
8342                 if (connector_state->crtc != crtc_state->base.crtc)
8343                         continue;
8344
8345                 encoder = to_intel_encoder(connector_state->best_encoder);
8346
8347                 switch (encoder->type) {
8348                 case INTEL_OUTPUT_LVDS:
8349                         is_lvds = true;
8350                         break;
8351                 case INTEL_OUTPUT_SDVO:
8352                 case INTEL_OUTPUT_HDMI:
8353                         is_sdvo = true;
8354                         break;
8355                 default:
8356                         break;
8357                 }
8358
8359                 num_connectors++;
8360         }
8361
8362         /* Enable autotuning of the PLL clock (if permissible) */
8363         factor = 21;
8364         if (is_lvds) {
8365                 if ((intel_panel_use_ssc(dev_priv) &&
8366                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8367                     (HAS_PCH_IBX(dev) && intel_is_dual_link_lvds(dev)))
8368                         factor = 25;
8369         } else if (crtc_state->sdvo_tv_clock)
8370                 factor = 20;
8371
8372         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8373                 *fp |= FP_CB_TUNE;
8374
8375         if (fp2 && (reduced_clock->m < factor * reduced_clock->n))
8376                 *fp2 |= FP_CB_TUNE;
8377
8378         dpll = 0;
8379
8380         if (is_lvds)
8381                 dpll |= DPLLB_MODE_LVDS;
8382         else
8383                 dpll |= DPLLB_MODE_DAC_SERIAL;
8384
8385         dpll |= (crtc_state->pixel_multiplier - 1)
8386                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8387
8388         if (is_sdvo)
8389                 dpll |= DPLL_SDVO_HIGH_SPEED;
8390         if (crtc_state->has_dp_encoder)
8391                 dpll |= DPLL_SDVO_HIGH_SPEED;
8392
8393         /* compute bitmask from p1 value */
8394         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8395         /* also FPA1 */
8396         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8397
8398         switch (crtc_state->dpll.p2) {
8399         case 5:
8400                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8401                 break;
8402         case 7:
8403                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8404                 break;
8405         case 10:
8406                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8407                 break;
8408         case 14:
8409                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8410                 break;
8411         }
8412
8413         if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2)
8414                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8415         else
8416                 dpll |= PLL_REF_INPUT_DREFCLK;
8417
8418         return dpll | DPLL_VCO_ENABLE;
8419 }
8420
8421 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
8422                                        struct intel_crtc_state *crtc_state)
8423 {
8424         struct drm_device *dev = crtc->base.dev;
8425         intel_clock_t clock, reduced_clock;
8426         u32 dpll = 0, fp = 0, fp2 = 0;
8427         bool ok, has_reduced_clock = false;
8428         bool is_lvds = false;
8429         struct intel_shared_dpll *pll;
8430
8431         is_lvds = intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS);
8432
8433         WARN(!(HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev)),
8434              "Unexpected PCH type %d\n", INTEL_PCH_TYPE(dev));
8435
8436         ok = ironlake_compute_clocks(&crtc->base, crtc_state, &clock,
8437                                      &has_reduced_clock, &reduced_clock);
8438         if (!ok && !crtc_state->clock_set) {
8439                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8440                 return -EINVAL;
8441         }
8442         /* Compat-code for transition, will disappear. */
8443         if (!crtc_state->clock_set) {
8444                 crtc_state->dpll.n = clock.n;
8445                 crtc_state->dpll.m1 = clock.m1;
8446                 crtc_state->dpll.m2 = clock.m2;
8447                 crtc_state->dpll.p1 = clock.p1;
8448                 crtc_state->dpll.p2 = clock.p2;
8449         }
8450
8451         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
8452         if (crtc_state->has_pch_encoder) {
8453                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8454                 if (has_reduced_clock)
8455                         fp2 = i9xx_dpll_compute_fp(&reduced_clock);
8456
8457                 dpll = ironlake_compute_dpll(crtc, crtc_state,
8458                                              &fp, &reduced_clock,
8459                                              has_reduced_clock ? &fp2 : NULL);
8460
8461                 crtc_state->dpll_hw_state.dpll = dpll;
8462                 crtc_state->dpll_hw_state.fp0 = fp;
8463                 if (has_reduced_clock)
8464                         crtc_state->dpll_hw_state.fp1 = fp2;
8465                 else
8466                         crtc_state->dpll_hw_state.fp1 = fp;
8467
8468                 pll = intel_get_shared_dpll(crtc, crtc_state);
8469                 if (pll == NULL) {
8470                         DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
8471                                          pipe_name(crtc->pipe));
8472                         return -EINVAL;
8473                 }
8474         }
8475
8476         if (is_lvds && has_reduced_clock)
8477                 crtc->lowfreq_avail = true;
8478         else
8479                 crtc->lowfreq_avail = false;
8480
8481         return 0;
8482 }
8483
8484 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
8485                                          struct intel_link_m_n *m_n)
8486 {
8487         struct drm_device *dev = crtc->base.dev;
8488         struct drm_i915_private *dev_priv = dev->dev_private;
8489         enum pipe pipe = crtc->pipe;
8490
8491         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
8492         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
8493         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
8494                 & ~TU_SIZE_MASK;
8495         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
8496         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
8497                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8498 }
8499
8500 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
8501                                          enum transcoder transcoder,
8502                                          struct intel_link_m_n *m_n,
8503                                          struct intel_link_m_n *m2_n2)
8504 {
8505         struct drm_device *dev = crtc->base.dev;
8506         struct drm_i915_private *dev_priv = dev->dev_private;
8507         enum pipe pipe = crtc->pipe;
8508
8509         if (INTEL_INFO(dev)->gen >= 5) {
8510                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
8511                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
8512                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
8513                         & ~TU_SIZE_MASK;
8514                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
8515                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
8516                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8517                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
8518                  * gen < 8) and if DRRS is supported (to make sure the
8519                  * registers are not unnecessarily read).
8520                  */
8521                 if (m2_n2 && INTEL_INFO(dev)->gen < 8 &&
8522                         crtc->config->has_drrs) {
8523                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
8524                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
8525                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
8526                                         & ~TU_SIZE_MASK;
8527                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
8528                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
8529                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8530                 }
8531         } else {
8532                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
8533                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
8534                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
8535                         & ~TU_SIZE_MASK;
8536                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
8537                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
8538                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8539         }
8540 }
8541
8542 void intel_dp_get_m_n(struct intel_crtc *crtc,
8543                       struct intel_crtc_state *pipe_config)
8544 {
8545         if (pipe_config->has_pch_encoder)
8546                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
8547         else
8548                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8549                                              &pipe_config->dp_m_n,
8550                                              &pipe_config->dp_m2_n2);
8551 }
8552
8553 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
8554                                         struct intel_crtc_state *pipe_config)
8555 {
8556         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8557                                      &pipe_config->fdi_m_n, NULL);
8558 }
8559
8560 static void skylake_get_pfit_config(struct intel_crtc *crtc,
8561                                     struct intel_crtc_state *pipe_config)
8562 {
8563         struct drm_device *dev = crtc->base.dev;
8564         struct drm_i915_private *dev_priv = dev->dev_private;
8565         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
8566         uint32_t ps_ctrl = 0;
8567         int id = -1;
8568         int i;
8569
8570         /* find scaler attached to this pipe */
8571         for (i = 0; i < crtc->num_scalers; i++) {
8572                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
8573                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
8574                         id = i;
8575                         pipe_config->pch_pfit.enabled = true;
8576                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
8577                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
8578                         break;
8579                 }
8580         }
8581
8582         scaler_state->scaler_id = id;
8583         if (id >= 0) {
8584                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
8585         } else {
8586                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
8587         }
8588 }
8589
8590 static void
8591 skylake_get_initial_plane_config(struct intel_crtc *crtc,
8592                                  struct intel_initial_plane_config *plane_config)
8593 {
8594         struct drm_device *dev = crtc->base.dev;
8595         struct drm_i915_private *dev_priv = dev->dev_private;
8596         u32 val, base, offset, stride_mult, tiling;
8597         int pipe = crtc->pipe;
8598         int fourcc, pixel_format;
8599         unsigned int aligned_height;
8600         struct drm_framebuffer *fb;
8601         struct intel_framebuffer *intel_fb;
8602
8603         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8604         if (!intel_fb) {
8605                 DRM_DEBUG_KMS("failed to alloc fb\n");
8606                 return;
8607         }
8608
8609         fb = &intel_fb->base;
8610
8611         val = I915_READ(PLANE_CTL(pipe, 0));
8612         if (!(val & PLANE_CTL_ENABLE))
8613                 goto error;
8614
8615         pixel_format = val & PLANE_CTL_FORMAT_MASK;
8616         fourcc = skl_format_to_fourcc(pixel_format,
8617                                       val & PLANE_CTL_ORDER_RGBX,
8618                                       val & PLANE_CTL_ALPHA_MASK);
8619         fb->pixel_format = fourcc;
8620         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
8621
8622         tiling = val & PLANE_CTL_TILED_MASK;
8623         switch (tiling) {
8624         case PLANE_CTL_TILED_LINEAR:
8625                 fb->modifier[0] = DRM_FORMAT_MOD_NONE;
8626                 break;
8627         case PLANE_CTL_TILED_X:
8628                 plane_config->tiling = I915_TILING_X;
8629                 fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
8630                 break;
8631         case PLANE_CTL_TILED_Y:
8632                 fb->modifier[0] = I915_FORMAT_MOD_Y_TILED;
8633                 break;
8634         case PLANE_CTL_TILED_YF:
8635                 fb->modifier[0] = I915_FORMAT_MOD_Yf_TILED;
8636                 break;
8637         default:
8638                 MISSING_CASE(tiling);
8639                 goto error;
8640         }
8641
8642         base = I915_READ(PLANE_SURF(pipe, 0)) & 0xfffff000;
8643         plane_config->base = base;
8644
8645         offset = I915_READ(PLANE_OFFSET(pipe, 0));
8646
8647         val = I915_READ(PLANE_SIZE(pipe, 0));
8648         fb->height = ((val >> 16) & 0xfff) + 1;
8649         fb->width = ((val >> 0) & 0x1fff) + 1;
8650
8651         val = I915_READ(PLANE_STRIDE(pipe, 0));
8652         stride_mult = intel_fb_stride_alignment(dev, fb->modifier[0],
8653                                                 fb->pixel_format);
8654         fb->pitches[0] = (val & 0x3ff) * stride_mult;
8655
8656         aligned_height = intel_fb_align_height(dev, fb->height,
8657                                                fb->pixel_format,
8658                                                fb->modifier[0]);
8659
8660         plane_config->size = fb->pitches[0] * aligned_height;
8661
8662         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8663                       pipe_name(pipe), fb->width, fb->height,
8664                       fb->bits_per_pixel, base, fb->pitches[0],
8665                       plane_config->size);
8666
8667         plane_config->fb = intel_fb;
8668         return;
8669
8670 error:
8671         kfree(fb);
8672 }
8673
8674 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
8675                                      struct intel_crtc_state *pipe_config)
8676 {
8677         struct drm_device *dev = crtc->base.dev;
8678         struct drm_i915_private *dev_priv = dev->dev_private;
8679         uint32_t tmp;
8680
8681         tmp = I915_READ(PF_CTL(crtc->pipe));
8682
8683         if (tmp & PF_ENABLE) {
8684                 pipe_config->pch_pfit.enabled = true;
8685                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
8686                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
8687
8688                 /* We currently do not free assignements of panel fitters on
8689                  * ivb/hsw (since we don't use the higher upscaling modes which
8690                  * differentiates them) so just WARN about this case for now. */
8691                 if (IS_GEN7(dev)) {
8692                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
8693                                 PF_PIPE_SEL_IVB(crtc->pipe));
8694                 }
8695         }
8696 }
8697
8698 static void
8699 ironlake_get_initial_plane_config(struct intel_crtc *crtc,
8700                                   struct intel_initial_plane_config *plane_config)
8701 {
8702         struct drm_device *dev = crtc->base.dev;
8703         struct drm_i915_private *dev_priv = dev->dev_private;
8704         u32 val, base, offset;
8705         int pipe = crtc->pipe;
8706         int fourcc, pixel_format;
8707         unsigned int aligned_height;
8708         struct drm_framebuffer *fb;
8709         struct intel_framebuffer *intel_fb;
8710
8711         val = I915_READ(DSPCNTR(pipe));
8712         if (!(val & DISPLAY_PLANE_ENABLE))
8713                 return;
8714
8715         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8716         if (!intel_fb) {
8717                 DRM_DEBUG_KMS("failed to alloc fb\n");
8718                 return;
8719         }
8720
8721         fb = &intel_fb->base;
8722
8723         if (INTEL_INFO(dev)->gen >= 4) {
8724                 if (val & DISPPLANE_TILED) {
8725                         plane_config->tiling = I915_TILING_X;
8726                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
8727                 }
8728         }
8729
8730         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
8731         fourcc = i9xx_format_to_fourcc(pixel_format);
8732         fb->pixel_format = fourcc;
8733         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
8734
8735         base = I915_READ(DSPSURF(pipe)) & 0xfffff000;
8736         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
8737                 offset = I915_READ(DSPOFFSET(pipe));
8738         } else {
8739                 if (plane_config->tiling)
8740                         offset = I915_READ(DSPTILEOFF(pipe));
8741                 else
8742                         offset = I915_READ(DSPLINOFF(pipe));
8743         }
8744         plane_config->base = base;
8745
8746         val = I915_READ(PIPESRC(pipe));
8747         fb->width = ((val >> 16) & 0xfff) + 1;
8748         fb->height = ((val >> 0) & 0xfff) + 1;
8749
8750         val = I915_READ(DSPSTRIDE(pipe));
8751         fb->pitches[0] = val & 0xffffffc0;
8752
8753         aligned_height = intel_fb_align_height(dev, fb->height,
8754                                                fb->pixel_format,
8755                                                fb->modifier[0]);
8756
8757         plane_config->size = fb->pitches[0] * aligned_height;
8758
8759         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8760                       pipe_name(pipe), fb->width, fb->height,
8761                       fb->bits_per_pixel, base, fb->pitches[0],
8762                       plane_config->size);
8763
8764         plane_config->fb = intel_fb;
8765 }
8766
8767 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
8768                                      struct intel_crtc_state *pipe_config)
8769 {
8770         struct drm_device *dev = crtc->base.dev;
8771         struct drm_i915_private *dev_priv = dev->dev_private;
8772         uint32_t tmp;
8773
8774         if (!intel_display_power_is_enabled(dev_priv,
8775                                             POWER_DOMAIN_PIPE(crtc->pipe)))
8776                 return false;
8777
8778         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8779         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
8780
8781         tmp = I915_READ(PIPECONF(crtc->pipe));
8782         if (!(tmp & PIPECONF_ENABLE))
8783                 return false;
8784
8785         switch (tmp & PIPECONF_BPC_MASK) {
8786         case PIPECONF_6BPC:
8787                 pipe_config->pipe_bpp = 18;
8788                 break;
8789         case PIPECONF_8BPC:
8790                 pipe_config->pipe_bpp = 24;
8791                 break;
8792         case PIPECONF_10BPC:
8793                 pipe_config->pipe_bpp = 30;
8794                 break;
8795         case PIPECONF_12BPC:
8796                 pipe_config->pipe_bpp = 36;
8797                 break;
8798         default:
8799                 break;
8800         }
8801
8802         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
8803                 pipe_config->limited_color_range = true;
8804
8805         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
8806                 struct intel_shared_dpll *pll;
8807
8808                 pipe_config->has_pch_encoder = true;
8809
8810                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
8811                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
8812                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
8813
8814                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
8815
8816                 if (HAS_PCH_IBX(dev_priv->dev)) {
8817                         pipe_config->shared_dpll =
8818                                 (enum intel_dpll_id) crtc->pipe;
8819                 } else {
8820                         tmp = I915_READ(PCH_DPLL_SEL);
8821                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
8822                                 pipe_config->shared_dpll = DPLL_ID_PCH_PLL_B;
8823                         else
8824                                 pipe_config->shared_dpll = DPLL_ID_PCH_PLL_A;
8825                 }
8826
8827                 pll = &dev_priv->shared_dplls[pipe_config->shared_dpll];
8828
8829                 WARN_ON(!pll->get_hw_state(dev_priv, pll,
8830                                            &pipe_config->dpll_hw_state));
8831
8832                 tmp = pipe_config->dpll_hw_state.dpll;
8833                 pipe_config->pixel_multiplier =
8834                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
8835                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
8836
8837                 ironlake_pch_clock_get(crtc, pipe_config);
8838         } else {
8839                 pipe_config->pixel_multiplier = 1;
8840         }
8841
8842         intel_get_pipe_timings(crtc, pipe_config);
8843
8844         ironlake_get_pfit_config(crtc, pipe_config);
8845
8846         return true;
8847 }
8848
8849 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
8850 {
8851         struct drm_device *dev = dev_priv->dev;
8852         struct intel_crtc *crtc;
8853
8854         for_each_intel_crtc(dev, crtc)
8855                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
8856                      pipe_name(crtc->pipe));
8857
8858         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_DRIVER), "Power well on\n");
8859         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
8860         I915_STATE_WARN(I915_READ(WRPLL_CTL1) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
8861         I915_STATE_WARN(I915_READ(WRPLL_CTL2) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
8862         I915_STATE_WARN(I915_READ(PCH_PP_STATUS) & PP_ON, "Panel power on\n");
8863         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
8864              "CPU PWM1 enabled\n");
8865         if (IS_HASWELL(dev))
8866                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
8867                      "CPU PWM2 enabled\n");
8868         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
8869              "PCH PWM1 enabled\n");
8870         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
8871              "Utility pin enabled\n");
8872         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
8873
8874         /*
8875          * In theory we can still leave IRQs enabled, as long as only the HPD
8876          * interrupts remain enabled. We used to check for that, but since it's
8877          * gen-specific and since we only disable LCPLL after we fully disable
8878          * the interrupts, the check below should be enough.
8879          */
8880         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
8881 }
8882
8883 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
8884 {
8885         struct drm_device *dev = dev_priv->dev;
8886
8887         if (IS_HASWELL(dev))
8888                 return I915_READ(D_COMP_HSW);
8889         else
8890                 return I915_READ(D_COMP_BDW);
8891 }
8892
8893 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
8894 {
8895         struct drm_device *dev = dev_priv->dev;
8896
8897         if (IS_HASWELL(dev)) {
8898                 mutex_lock(&dev_priv->rps.hw_lock);
8899                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
8900                                             val))
8901                         DRM_ERROR("Failed to write to D_COMP\n");
8902                 mutex_unlock(&dev_priv->rps.hw_lock);
8903         } else {
8904                 I915_WRITE(D_COMP_BDW, val);
8905                 POSTING_READ(D_COMP_BDW);
8906         }
8907 }
8908
8909 /*
8910  * This function implements pieces of two sequences from BSpec:
8911  * - Sequence for display software to disable LCPLL
8912  * - Sequence for display software to allow package C8+
8913  * The steps implemented here are just the steps that actually touch the LCPLL
8914  * register. Callers should take care of disabling all the display engine
8915  * functions, doing the mode unset, fixing interrupts, etc.
8916  */
8917 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
8918                               bool switch_to_fclk, bool allow_power_down)
8919 {
8920         uint32_t val;
8921
8922         assert_can_disable_lcpll(dev_priv);
8923
8924         val = I915_READ(LCPLL_CTL);
8925
8926         if (switch_to_fclk) {
8927                 val |= LCPLL_CD_SOURCE_FCLK;
8928                 I915_WRITE(LCPLL_CTL, val);
8929
8930                 if (wait_for_atomic_us(I915_READ(LCPLL_CTL) &
8931                                        LCPLL_CD_SOURCE_FCLK_DONE, 1))
8932                         DRM_ERROR("Switching to FCLK failed\n");
8933
8934                 val = I915_READ(LCPLL_CTL);
8935         }
8936
8937         val |= LCPLL_PLL_DISABLE;
8938         I915_WRITE(LCPLL_CTL, val);
8939         POSTING_READ(LCPLL_CTL);
8940
8941         if (wait_for((I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK) == 0, 1))
8942                 DRM_ERROR("LCPLL still locked\n");
8943
8944         val = hsw_read_dcomp(dev_priv);
8945         val |= D_COMP_COMP_DISABLE;
8946         hsw_write_dcomp(dev_priv, val);
8947         ndelay(100);
8948
8949         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
8950                      1))
8951                 DRM_ERROR("D_COMP RCOMP still in progress\n");
8952
8953         if (allow_power_down) {
8954                 val = I915_READ(LCPLL_CTL);
8955                 val |= LCPLL_POWER_DOWN_ALLOW;
8956                 I915_WRITE(LCPLL_CTL, val);
8957                 POSTING_READ(LCPLL_CTL);
8958         }
8959 }
8960
8961 /*
8962  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
8963  * source.
8964  */
8965 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
8966 {
8967         uint32_t val;
8968
8969         val = I915_READ(LCPLL_CTL);
8970
8971         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
8972                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
8973                 return;
8974
8975         /*
8976          * Make sure we're not on PC8 state before disabling PC8, otherwise
8977          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
8978          */
8979         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
8980
8981         if (val & LCPLL_POWER_DOWN_ALLOW) {
8982                 val &= ~LCPLL_POWER_DOWN_ALLOW;
8983                 I915_WRITE(LCPLL_CTL, val);
8984                 POSTING_READ(LCPLL_CTL);
8985         }
8986
8987         val = hsw_read_dcomp(dev_priv);
8988         val |= D_COMP_COMP_FORCE;
8989         val &= ~D_COMP_COMP_DISABLE;
8990         hsw_write_dcomp(dev_priv, val);
8991
8992         val = I915_READ(LCPLL_CTL);
8993         val &= ~LCPLL_PLL_DISABLE;
8994         I915_WRITE(LCPLL_CTL, val);
8995
8996         if (wait_for(I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK, 5))
8997                 DRM_ERROR("LCPLL not locked yet\n");
8998
8999         if (val & LCPLL_CD_SOURCE_FCLK) {
9000                 val = I915_READ(LCPLL_CTL);
9001                 val &= ~LCPLL_CD_SOURCE_FCLK;
9002                 I915_WRITE(LCPLL_CTL, val);
9003
9004                 if (wait_for_atomic_us((I915_READ(LCPLL_CTL) &
9005                                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9006                         DRM_ERROR("Switching back to LCPLL failed\n");
9007         }
9008
9009         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
9010 }
9011
9012 /*
9013  * Package states C8 and deeper are really deep PC states that can only be
9014  * reached when all the devices on the system allow it, so even if the graphics
9015  * device allows PC8+, it doesn't mean the system will actually get to these
9016  * states. Our driver only allows PC8+ when going into runtime PM.
9017  *
9018  * The requirements for PC8+ are that all the outputs are disabled, the power
9019  * well is disabled and most interrupts are disabled, and these are also
9020  * requirements for runtime PM. When these conditions are met, we manually do
9021  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
9022  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
9023  * hang the machine.
9024  *
9025  * When we really reach PC8 or deeper states (not just when we allow it) we lose
9026  * the state of some registers, so when we come back from PC8+ we need to
9027  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
9028  * need to take care of the registers kept by RC6. Notice that this happens even
9029  * if we don't put the device in PCI D3 state (which is what currently happens
9030  * because of the runtime PM support).
9031  *
9032  * For more, read "Display Sequences for Package C8" on the hardware
9033  * documentation.
9034  */
9035 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
9036 {
9037         struct drm_device *dev = dev_priv->dev;
9038         uint32_t val;
9039
9040         DRM_DEBUG_KMS("Enabling package C8+\n");
9041
9042         if (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) {
9043                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9044                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
9045                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9046         }
9047
9048         lpt_disable_clkout_dp(dev);
9049         hsw_disable_lcpll(dev_priv, true, true);
9050 }
9051
9052 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
9053 {
9054         struct drm_device *dev = dev_priv->dev;
9055         uint32_t val;
9056
9057         DRM_DEBUG_KMS("Disabling package C8+\n");
9058
9059         hsw_restore_lcpll(dev_priv);
9060         lpt_init_pch_refclk(dev);
9061
9062         if (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) {
9063                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9064                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
9065                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9066         }
9067
9068         intel_prepare_ddi(dev);
9069 }
9070
9071 static void broxton_modeset_global_resources(struct drm_atomic_state *state)
9072 {
9073         struct drm_device *dev = state->dev;
9074         struct drm_i915_private *dev_priv = dev->dev_private;
9075         int max_pixclk = intel_mode_max_pixclk(state);
9076         int req_cdclk;
9077
9078         /* see the comment in valleyview_modeset_global_resources */
9079         if (WARN_ON(max_pixclk < 0))
9080                 return;
9081
9082         req_cdclk = broxton_calc_cdclk(dev_priv, max_pixclk);
9083
9084         if (req_cdclk != dev_priv->cdclk_freq)
9085                 broxton_set_cdclk(dev, req_cdclk);
9086 }
9087
9088 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9089                                       struct intel_crtc_state *crtc_state)
9090 {
9091         if (!intel_ddi_pll_select(crtc, crtc_state))
9092                 return -EINVAL;
9093
9094         crtc->lowfreq_avail = false;
9095
9096         return 0;
9097 }
9098
9099 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9100                                 enum port port,
9101                                 struct intel_crtc_state *pipe_config)
9102 {
9103         switch (port) {
9104         case PORT_A:
9105                 pipe_config->ddi_pll_sel = SKL_DPLL0;
9106                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL1;
9107                 break;
9108         case PORT_B:
9109                 pipe_config->ddi_pll_sel = SKL_DPLL1;
9110                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL2;
9111                 break;
9112         case PORT_C:
9113                 pipe_config->ddi_pll_sel = SKL_DPLL2;
9114                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL3;
9115                 break;
9116         default:
9117                 DRM_ERROR("Incorrect port type\n");
9118         }
9119 }
9120
9121 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9122                                 enum port port,
9123                                 struct intel_crtc_state *pipe_config)
9124 {
9125         u32 temp, dpll_ctl1;
9126
9127         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9128         pipe_config->ddi_pll_sel = temp >> (port * 3 + 1);
9129
9130         switch (pipe_config->ddi_pll_sel) {
9131         case SKL_DPLL0:
9132                 /*
9133                  * On SKL the eDP DPLL (DPLL0 as we don't use SSC) is not part
9134                  * of the shared DPLL framework and thus needs to be read out
9135                  * separately
9136                  */
9137                 dpll_ctl1 = I915_READ(DPLL_CTRL1);
9138                 pipe_config->dpll_hw_state.ctrl1 = dpll_ctl1 & 0x3f;
9139                 break;
9140         case SKL_DPLL1:
9141                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL1;
9142                 break;
9143         case SKL_DPLL2:
9144                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL2;
9145                 break;
9146         case SKL_DPLL3:
9147                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL3;
9148                 break;
9149         }
9150 }
9151
9152 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9153                                 enum port port,
9154                                 struct intel_crtc_state *pipe_config)
9155 {
9156         pipe_config->ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9157
9158         switch (pipe_config->ddi_pll_sel) {
9159         case PORT_CLK_SEL_WRPLL1:
9160                 pipe_config->shared_dpll = DPLL_ID_WRPLL1;
9161                 break;
9162         case PORT_CLK_SEL_WRPLL2:
9163                 pipe_config->shared_dpll = DPLL_ID_WRPLL2;
9164                 break;
9165         }
9166 }
9167
9168 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9169                                        struct intel_crtc_state *pipe_config)
9170 {
9171         struct drm_device *dev = crtc->base.dev;
9172         struct drm_i915_private *dev_priv = dev->dev_private;
9173         struct intel_shared_dpll *pll;
9174         enum port port;
9175         uint32_t tmp;
9176
9177         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9178
9179         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9180
9181         if (IS_SKYLAKE(dev))
9182                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
9183         else if (IS_BROXTON(dev))
9184                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
9185         else
9186                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
9187
9188         if (pipe_config->shared_dpll >= 0) {
9189                 pll = &dev_priv->shared_dplls[pipe_config->shared_dpll];
9190
9191                 WARN_ON(!pll->get_hw_state(dev_priv, pll,
9192                                            &pipe_config->dpll_hw_state));
9193         }
9194
9195         /*
9196          * Haswell has only FDI/PCH transcoder A. It is which is connected to
9197          * DDI E. So just check whether this pipe is wired to DDI E and whether
9198          * the PCH transcoder is on.
9199          */
9200         if (INTEL_INFO(dev)->gen < 9 &&
9201             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
9202                 pipe_config->has_pch_encoder = true;
9203
9204                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
9205                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9206                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9207
9208                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9209         }
9210 }
9211
9212 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
9213                                     struct intel_crtc_state *pipe_config)
9214 {
9215         struct drm_device *dev = crtc->base.dev;
9216         struct drm_i915_private *dev_priv = dev->dev_private;
9217         enum intel_display_power_domain pfit_domain;
9218         uint32_t tmp;
9219
9220         if (!intel_display_power_is_enabled(dev_priv,
9221                                          POWER_DOMAIN_PIPE(crtc->pipe)))
9222                 return false;
9223
9224         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9225         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
9226
9227         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
9228         if (tmp & TRANS_DDI_FUNC_ENABLE) {
9229                 enum pipe trans_edp_pipe;
9230                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9231                 default:
9232                         WARN(1, "unknown pipe linked to edp transcoder\n");
9233                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9234                 case TRANS_DDI_EDP_INPUT_A_ON:
9235                         trans_edp_pipe = PIPE_A;
9236                         break;
9237                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
9238                         trans_edp_pipe = PIPE_B;
9239                         break;
9240                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
9241                         trans_edp_pipe = PIPE_C;
9242                         break;
9243                 }
9244
9245                 if (trans_edp_pipe == crtc->pipe)
9246                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
9247         }
9248
9249         if (!intel_display_power_is_enabled(dev_priv,
9250                         POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder)))
9251                 return false;
9252
9253         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
9254         if (!(tmp & PIPECONF_ENABLE))
9255                 return false;
9256
9257         haswell_get_ddi_port_state(crtc, pipe_config);
9258
9259         intel_get_pipe_timings(crtc, pipe_config);
9260
9261         if (INTEL_INFO(dev)->gen >= 9) {
9262                 skl_init_scalers(dev, crtc, pipe_config);
9263         }
9264
9265         pfit_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
9266         if (intel_display_power_is_enabled(dev_priv, pfit_domain)) {
9267                 if (INTEL_INFO(dev)->gen == 9)
9268                         skylake_get_pfit_config(crtc, pipe_config);
9269                 else if (INTEL_INFO(dev)->gen < 9)
9270                         ironlake_get_pfit_config(crtc, pipe_config);
9271                 else
9272                         MISSING_CASE(INTEL_INFO(dev)->gen);
9273
9274         } else {
9275                 pipe_config->scaler_state.scaler_id = -1;
9276                 pipe_config->scaler_state.scaler_users &= ~(1 << SKL_CRTC_INDEX);
9277         }
9278
9279         if (IS_HASWELL(dev))
9280                 pipe_config->ips_enabled = hsw_crtc_supports_ips(crtc) &&
9281                         (I915_READ(IPS_CTL) & IPS_ENABLE);
9282
9283         if (pipe_config->cpu_transcoder != TRANSCODER_EDP) {
9284                 pipe_config->pixel_multiplier =
9285                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
9286         } else {
9287                 pipe_config->pixel_multiplier = 1;
9288         }
9289
9290         return true;
9291 }
9292
9293 static void i845_update_cursor(struct drm_crtc *crtc, u32 base)
9294 {
9295         struct drm_device *dev = crtc->dev;
9296         struct drm_i915_private *dev_priv = dev->dev_private;
9297         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9298         uint32_t cntl = 0, size = 0;
9299
9300         if (base) {
9301                 unsigned int width = intel_crtc->base.cursor->state->crtc_w;
9302                 unsigned int height = intel_crtc->base.cursor->state->crtc_h;
9303                 unsigned int stride = roundup_pow_of_two(width) * 4;
9304
9305                 switch (stride) {
9306                 default:
9307                         WARN_ONCE(1, "Invalid cursor width/stride, width=%u, stride=%u\n",
9308                                   width, stride);
9309                         stride = 256;
9310                         /* fallthrough */
9311                 case 256:
9312                 case 512:
9313                 case 1024:
9314                 case 2048:
9315                         break;
9316                 }
9317
9318                 cntl |= CURSOR_ENABLE |
9319                         CURSOR_GAMMA_ENABLE |
9320                         CURSOR_FORMAT_ARGB |
9321                         CURSOR_STRIDE(stride);
9322
9323                 size = (height << 12) | width;
9324         }
9325
9326         if (intel_crtc->cursor_cntl != 0 &&
9327             (intel_crtc->cursor_base != base ||
9328              intel_crtc->cursor_size != size ||
9329              intel_crtc->cursor_cntl != cntl)) {
9330                 /* On these chipsets we can only modify the base/size/stride
9331                  * whilst the cursor is disabled.
9332                  */
9333                 I915_WRITE(_CURACNTR, 0);
9334                 POSTING_READ(_CURACNTR);
9335                 intel_crtc->cursor_cntl = 0;
9336         }
9337
9338         if (intel_crtc->cursor_base != base) {
9339                 I915_WRITE(_CURABASE, base);
9340                 intel_crtc->cursor_base = base;
9341         }
9342
9343         if (intel_crtc->cursor_size != size) {
9344                 I915_WRITE(CURSIZE, size);
9345                 intel_crtc->cursor_size = size;
9346         }
9347
9348         if (intel_crtc->cursor_cntl != cntl) {
9349                 I915_WRITE(_CURACNTR, cntl);
9350                 POSTING_READ(_CURACNTR);
9351                 intel_crtc->cursor_cntl = cntl;
9352         }
9353 }
9354
9355 static void i9xx_update_cursor(struct drm_crtc *crtc, u32 base)
9356 {
9357         struct drm_device *dev = crtc->dev;
9358         struct drm_i915_private *dev_priv = dev->dev_private;
9359         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9360         int pipe = intel_crtc->pipe;
9361         uint32_t cntl;
9362
9363         cntl = 0;
9364         if (base) {
9365                 cntl = MCURSOR_GAMMA_ENABLE;
9366                 switch (intel_crtc->base.cursor->state->crtc_w) {
9367                         case 64:
9368                                 cntl |= CURSOR_MODE_64_ARGB_AX;
9369                                 break;
9370                         case 128:
9371                                 cntl |= CURSOR_MODE_128_ARGB_AX;
9372                                 break;
9373                         case 256:
9374                                 cntl |= CURSOR_MODE_256_ARGB_AX;
9375                                 break;
9376                         default:
9377                                 MISSING_CASE(intel_crtc->base.cursor->state->crtc_w);
9378                                 return;
9379                 }
9380                 cntl |= pipe << 28; /* Connect to correct pipe */
9381
9382                 if (IS_HASWELL(dev) || IS_BROADWELL(dev))
9383                         cntl |= CURSOR_PIPE_CSC_ENABLE;
9384         }
9385
9386         if (crtc->cursor->state->rotation == BIT(DRM_ROTATE_180))
9387                 cntl |= CURSOR_ROTATE_180;
9388
9389         if (intel_crtc->cursor_cntl != cntl) {
9390                 I915_WRITE(CURCNTR(pipe), cntl);
9391                 POSTING_READ(CURCNTR(pipe));
9392                 intel_crtc->cursor_cntl = cntl;
9393         }
9394
9395         /* and commit changes on next vblank */
9396         I915_WRITE(CURBASE(pipe), base);
9397         POSTING_READ(CURBASE(pipe));
9398
9399         intel_crtc->cursor_base = base;
9400 }
9401
9402 /* If no-part of the cursor is visible on the framebuffer, then the GPU may hang... */
9403 static void intel_crtc_update_cursor(struct drm_crtc *crtc,
9404                                      bool on)
9405 {
9406         struct drm_device *dev = crtc->dev;
9407         struct drm_i915_private *dev_priv = dev->dev_private;
9408         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9409         int pipe = intel_crtc->pipe;
9410         int x = crtc->cursor_x;
9411         int y = crtc->cursor_y;
9412         u32 base = 0, pos = 0;
9413
9414         if (on)
9415                 base = intel_crtc->cursor_addr;
9416
9417         if (x >= intel_crtc->config->pipe_src_w)
9418                 base = 0;
9419
9420         if (y >= intel_crtc->config->pipe_src_h)
9421                 base = 0;
9422
9423         if (x < 0) {
9424                 if (x + intel_crtc->base.cursor->state->crtc_w <= 0)
9425                         base = 0;
9426
9427                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
9428                 x = -x;
9429         }
9430         pos |= x << CURSOR_X_SHIFT;
9431
9432         if (y < 0) {
9433                 if (y + intel_crtc->base.cursor->state->crtc_h <= 0)
9434                         base = 0;
9435
9436                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
9437                 y = -y;
9438         }
9439         pos |= y << CURSOR_Y_SHIFT;
9440
9441         if (base == 0 && intel_crtc->cursor_base == 0)
9442                 return;
9443
9444         I915_WRITE(CURPOS(pipe), pos);
9445
9446         /* ILK+ do this automagically */
9447         if (HAS_GMCH_DISPLAY(dev) &&
9448             crtc->cursor->state->rotation == BIT(DRM_ROTATE_180)) {
9449                 base += (intel_crtc->base.cursor->state->crtc_h *
9450                         intel_crtc->base.cursor->state->crtc_w - 1) * 4;
9451         }
9452
9453         if (IS_845G(dev) || IS_I865G(dev))
9454                 i845_update_cursor(crtc, base);
9455         else
9456                 i9xx_update_cursor(crtc, base);
9457 }
9458
9459 static bool cursor_size_ok(struct drm_device *dev,
9460                            uint32_t width, uint32_t height)
9461 {
9462         if (width == 0 || height == 0)
9463                 return false;
9464
9465         /*
9466          * 845g/865g are special in that they are only limited by
9467          * the width of their cursors, the height is arbitrary up to
9468          * the precision of the register. Everything else requires
9469          * square cursors, limited to a few power-of-two sizes.
9470          */
9471         if (IS_845G(dev) || IS_I865G(dev)) {
9472                 if ((width & 63) != 0)
9473                         return false;
9474
9475                 if (width > (IS_845G(dev) ? 64 : 512))
9476                         return false;
9477
9478                 if (height > 1023)
9479                         return false;
9480         } else {
9481                 switch (width | height) {
9482                 case 256:
9483                 case 128:
9484                         if (IS_GEN2(dev))
9485                                 return false;
9486                 case 64:
9487                         break;
9488                 default:
9489                         return false;
9490                 }
9491         }
9492
9493         return true;
9494 }
9495
9496 static void intel_crtc_gamma_set(struct drm_crtc *crtc, u16 *red, u16 *green,
9497                                  u16 *blue, uint32_t start, uint32_t size)
9498 {
9499         int end = (start + size > 256) ? 256 : start + size, i;
9500         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9501
9502         for (i = start; i < end; i++) {
9503                 intel_crtc->lut_r[i] = red[i] >> 8;
9504                 intel_crtc->lut_g[i] = green[i] >> 8;
9505                 intel_crtc->lut_b[i] = blue[i] >> 8;
9506         }
9507
9508         intel_crtc_load_lut(crtc);
9509 }
9510
9511 /* VESA 640x480x72Hz mode to set on the pipe */
9512 static struct drm_display_mode load_detect_mode = {
9513         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
9514                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
9515 };
9516
9517 struct drm_framebuffer *
9518 __intel_framebuffer_create(struct drm_device *dev,
9519                            struct drm_mode_fb_cmd2 *mode_cmd,
9520                            struct drm_i915_gem_object *obj)
9521 {
9522         struct intel_framebuffer *intel_fb;
9523         int ret;
9524
9525         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9526         if (!intel_fb) {
9527                 drm_gem_object_unreference(&obj->base);
9528                 return ERR_PTR(-ENOMEM);
9529         }
9530
9531         ret = intel_framebuffer_init(dev, intel_fb, mode_cmd, obj);
9532         if (ret)
9533                 goto err;
9534
9535         return &intel_fb->base;
9536 err:
9537         drm_gem_object_unreference(&obj->base);
9538         kfree(intel_fb);
9539
9540         return ERR_PTR(ret);
9541 }
9542
9543 static struct drm_framebuffer *
9544 intel_framebuffer_create(struct drm_device *dev,
9545                          struct drm_mode_fb_cmd2 *mode_cmd,
9546                          struct drm_i915_gem_object *obj)
9547 {
9548         struct drm_framebuffer *fb;
9549         int ret;
9550
9551         ret = i915_mutex_lock_interruptible(dev);
9552         if (ret)
9553                 return ERR_PTR(ret);
9554         fb = __intel_framebuffer_create(dev, mode_cmd, obj);
9555         mutex_unlock(&dev->struct_mutex);
9556
9557         return fb;
9558 }
9559
9560 static u32
9561 intel_framebuffer_pitch_for_width(int width, int bpp)
9562 {
9563         u32 pitch = DIV_ROUND_UP(width * bpp, 8);
9564         return ALIGN(pitch, 64);
9565 }
9566
9567 static u32
9568 intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
9569 {
9570         u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
9571         return PAGE_ALIGN(pitch * mode->vdisplay);
9572 }
9573
9574 static struct drm_framebuffer *
9575 intel_framebuffer_create_for_mode(struct drm_device *dev,
9576                                   struct drm_display_mode *mode,
9577                                   int depth, int bpp)
9578 {
9579         struct drm_i915_gem_object *obj;
9580         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
9581
9582         obj = i915_gem_alloc_object(dev,
9583                                     intel_framebuffer_size_for_mode(mode, bpp));
9584         if (obj == NULL)
9585                 return ERR_PTR(-ENOMEM);
9586
9587         mode_cmd.width = mode->hdisplay;
9588         mode_cmd.height = mode->vdisplay;
9589         mode_cmd.pitches[0] = intel_framebuffer_pitch_for_width(mode_cmd.width,
9590                                                                 bpp);
9591         mode_cmd.pixel_format = drm_mode_legacy_fb_format(bpp, depth);
9592
9593         return intel_framebuffer_create(dev, &mode_cmd, obj);
9594 }
9595
9596 static struct drm_framebuffer *
9597 mode_fits_in_fbdev(struct drm_device *dev,
9598                    struct drm_display_mode *mode)
9599 {
9600 #ifdef CONFIG_DRM_I915_FBDEV
9601         struct drm_i915_private *dev_priv = dev->dev_private;
9602         struct drm_i915_gem_object *obj;
9603         struct drm_framebuffer *fb;
9604
9605         if (!dev_priv->fbdev)
9606                 return NULL;
9607
9608         if (!dev_priv->fbdev->fb)
9609                 return NULL;
9610
9611         obj = dev_priv->fbdev->fb->obj;
9612         BUG_ON(!obj);
9613
9614         fb = &dev_priv->fbdev->fb->base;
9615         if (fb->pitches[0] < intel_framebuffer_pitch_for_width(mode->hdisplay,
9616                                                                fb->bits_per_pixel))
9617                 return NULL;
9618
9619         if (obj->base.size < mode->vdisplay * fb->pitches[0])
9620                 return NULL;
9621
9622         return fb;
9623 #else
9624         return NULL;
9625 #endif
9626 }
9627
9628 bool intel_get_load_detect_pipe(struct drm_connector *connector,
9629                                 struct drm_display_mode *mode,
9630                                 struct intel_load_detect_pipe *old,
9631                                 struct drm_modeset_acquire_ctx *ctx)
9632 {
9633         struct intel_crtc *intel_crtc;
9634         struct intel_encoder *intel_encoder =
9635                 intel_attached_encoder(connector);
9636         struct drm_crtc *possible_crtc;
9637         struct drm_encoder *encoder = &intel_encoder->base;
9638         struct drm_crtc *crtc = NULL;
9639         struct drm_device *dev = encoder->dev;
9640         struct drm_framebuffer *fb;
9641         struct drm_mode_config *config = &dev->mode_config;
9642         struct drm_atomic_state *state = NULL;
9643         struct drm_connector_state *connector_state;
9644         int ret, i = -1;
9645
9646         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
9647                       connector->base.id, connector->name,
9648                       encoder->base.id, encoder->name);
9649
9650 retry:
9651         ret = drm_modeset_lock(&config->connection_mutex, ctx);
9652         if (ret)
9653                 goto fail_unlock;
9654
9655         /*
9656          * Algorithm gets a little messy:
9657          *
9658          *   - if the connector already has an assigned crtc, use it (but make
9659          *     sure it's on first)
9660          *
9661          *   - try to find the first unused crtc that can drive this connector,
9662          *     and use that if we find one
9663          */
9664
9665         /* See if we already have a CRTC for this connector */
9666         if (encoder->crtc) {
9667                 crtc = encoder->crtc;
9668
9669                 ret = drm_modeset_lock(&crtc->mutex, ctx);
9670                 if (ret)
9671                         goto fail_unlock;
9672                 ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
9673                 if (ret)
9674                         goto fail_unlock;
9675
9676                 old->dpms_mode = connector->dpms;
9677                 old->load_detect_temp = false;
9678
9679                 /* Make sure the crtc and connector are running */
9680                 if (connector->dpms != DRM_MODE_DPMS_ON)
9681                         connector->funcs->dpms(connector, DRM_MODE_DPMS_ON);
9682
9683                 return true;
9684         }
9685
9686         /* Find an unused one (if possible) */
9687         for_each_crtc(dev, possible_crtc) {
9688                 i++;
9689                 if (!(encoder->possible_crtcs & (1 << i)))
9690                         continue;
9691                 if (possible_crtc->state->enable)
9692                         continue;
9693                 /* This can occur when applying the pipe A quirk on resume. */
9694                 if (to_intel_crtc(possible_crtc)->new_enabled)
9695                         continue;
9696
9697                 crtc = possible_crtc;
9698                 break;
9699         }
9700
9701         /*
9702          * If we didn't find an unused CRTC, don't use any.
9703          */
9704         if (!crtc) {
9705                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
9706                 goto fail_unlock;
9707         }
9708
9709         ret = drm_modeset_lock(&crtc->mutex, ctx);
9710         if (ret)
9711                 goto fail_unlock;
9712         ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
9713         if (ret)
9714                 goto fail_unlock;
9715         intel_encoder->new_crtc = to_intel_crtc(crtc);
9716         to_intel_connector(connector)->new_encoder = intel_encoder;
9717
9718         intel_crtc = to_intel_crtc(crtc);
9719         intel_crtc->new_enabled = true;
9720         old->dpms_mode = connector->dpms;
9721         old->load_detect_temp = true;
9722         old->release_fb = NULL;
9723
9724         state = drm_atomic_state_alloc(dev);
9725         if (!state)
9726                 return false;
9727
9728         state->acquire_ctx = ctx;
9729
9730         connector_state = drm_atomic_get_connector_state(state, connector);
9731         if (IS_ERR(connector_state)) {
9732                 ret = PTR_ERR(connector_state);
9733                 goto fail;
9734         }
9735
9736         connector_state->crtc = crtc;
9737         connector_state->best_encoder = &intel_encoder->base;
9738
9739         if (!mode)
9740                 mode = &load_detect_mode;
9741
9742         /* We need a framebuffer large enough to accommodate all accesses
9743          * that the plane may generate whilst we perform load detection.
9744          * We can not rely on the fbcon either being present (we get called
9745          * during its initialisation to detect all boot displays, or it may
9746          * not even exist) or that it is large enough to satisfy the
9747          * requested mode.
9748          */
9749         fb = mode_fits_in_fbdev(dev, mode);
9750         if (fb == NULL) {
9751                 DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
9752                 fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
9753                 old->release_fb = fb;
9754         } else
9755                 DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
9756         if (IS_ERR(fb)) {
9757                 DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
9758                 goto fail;
9759         }
9760
9761         if (intel_set_mode(crtc, mode, 0, 0, fb, state)) {
9762                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
9763                 if (old->release_fb)
9764                         old->release_fb->funcs->destroy(old->release_fb);
9765                 goto fail;
9766         }
9767         crtc->primary->crtc = crtc;
9768
9769         /* let the connector get through one full cycle before testing */
9770         intel_wait_for_vblank(dev, intel_crtc->pipe);
9771         return true;
9772
9773  fail:
9774         intel_crtc->new_enabled = crtc->state->enable;
9775 fail_unlock:
9776         if (state) {
9777                 drm_atomic_state_free(state);
9778                 state = NULL;
9779         }
9780
9781         if (ret == -EDEADLK) {
9782                 drm_modeset_backoff(ctx);
9783                 goto retry;
9784         }
9785
9786         return false;
9787 }
9788
9789 void intel_release_load_detect_pipe(struct drm_connector *connector,
9790                                     struct intel_load_detect_pipe *old,
9791                                     struct drm_modeset_acquire_ctx *ctx)
9792 {
9793         struct drm_device *dev = connector->dev;
9794         struct intel_encoder *intel_encoder =
9795                 intel_attached_encoder(connector);
9796         struct drm_encoder *encoder = &intel_encoder->base;
9797         struct drm_crtc *crtc = encoder->crtc;
9798         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9799         struct drm_atomic_state *state;
9800         struct drm_connector_state *connector_state;
9801
9802         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
9803                       connector->base.id, connector->name,
9804                       encoder->base.id, encoder->name);
9805
9806         if (old->load_detect_temp) {
9807                 state = drm_atomic_state_alloc(dev);
9808                 if (!state)
9809                         goto fail;
9810
9811                 state->acquire_ctx = ctx;
9812
9813                 connector_state = drm_atomic_get_connector_state(state, connector);
9814                 if (IS_ERR(connector_state))
9815                         goto fail;
9816
9817                 to_intel_connector(connector)->new_encoder = NULL;
9818                 intel_encoder->new_crtc = NULL;
9819                 intel_crtc->new_enabled = false;
9820
9821                 connector_state->best_encoder = NULL;
9822                 connector_state->crtc = NULL;
9823
9824                 intel_set_mode(crtc, NULL, 0, 0, NULL, state);
9825
9826                 drm_atomic_state_free(state);
9827
9828                 if (old->release_fb) {
9829                         drm_framebuffer_unregister_private(old->release_fb);
9830                         drm_framebuffer_unreference(old->release_fb);
9831                 }
9832
9833                 return;
9834         }
9835
9836         /* Switch crtc and encoder back off if necessary */
9837         if (old->dpms_mode != DRM_MODE_DPMS_ON)
9838                 connector->funcs->dpms(connector, old->dpms_mode);
9839
9840         return;
9841 fail:
9842         DRM_DEBUG_KMS("Couldn't release load detect pipe.\n");
9843         drm_atomic_state_free(state);
9844 }
9845
9846 static int i9xx_pll_refclk(struct drm_device *dev,
9847                            const struct intel_crtc_state *pipe_config)
9848 {
9849         struct drm_i915_private *dev_priv = dev->dev_private;
9850         u32 dpll = pipe_config->dpll_hw_state.dpll;
9851
9852         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
9853                 return dev_priv->vbt.lvds_ssc_freq;
9854         else if (HAS_PCH_SPLIT(dev))
9855                 return 120000;
9856         else if (!IS_GEN2(dev))
9857                 return 96000;
9858         else
9859                 return 48000;
9860 }
9861
9862 /* Returns the clock of the currently programmed mode of the given pipe. */
9863 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
9864                                 struct intel_crtc_state *pipe_config)
9865 {
9866         struct drm_device *dev = crtc->base.dev;
9867         struct drm_i915_private *dev_priv = dev->dev_private;
9868         int pipe = pipe_config->cpu_transcoder;
9869         u32 dpll = pipe_config->dpll_hw_state.dpll;
9870         u32 fp;
9871         intel_clock_t clock;
9872         int refclk = i9xx_pll_refclk(dev, pipe_config);
9873
9874         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
9875                 fp = pipe_config->dpll_hw_state.fp0;
9876         else
9877                 fp = pipe_config->dpll_hw_state.fp1;
9878
9879         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
9880         if (IS_PINEVIEW(dev)) {
9881                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
9882                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
9883         } else {
9884                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
9885                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
9886         }
9887
9888         if (!IS_GEN2(dev)) {
9889                 if (IS_PINEVIEW(dev))
9890                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
9891                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
9892                 else
9893                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
9894                                DPLL_FPA01_P1_POST_DIV_SHIFT);
9895
9896                 switch (dpll & DPLL_MODE_MASK) {
9897                 case DPLLB_MODE_DAC_SERIAL:
9898                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
9899                                 5 : 10;
9900                         break;
9901                 case DPLLB_MODE_LVDS:
9902                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
9903                                 7 : 14;
9904                         break;
9905                 default:
9906                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
9907                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
9908                         return;
9909                 }
9910
9911                 if (IS_PINEVIEW(dev))
9912                         pineview_clock(refclk, &clock);
9913                 else
9914                         i9xx_clock(refclk, &clock);
9915         } else {
9916                 u32 lvds = IS_I830(dev) ? 0 : I915_READ(LVDS);
9917                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
9918
9919                 if (is_lvds) {
9920                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
9921                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
9922
9923                         if (lvds & LVDS_CLKB_POWER_UP)
9924                                 clock.p2 = 7;
9925                         else
9926                                 clock.p2 = 14;
9927                 } else {
9928                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
9929                                 clock.p1 = 2;
9930                         else {
9931                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
9932                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
9933                         }
9934                         if (dpll & PLL_P2_DIVIDE_BY_4)
9935                                 clock.p2 = 4;
9936                         else
9937                                 clock.p2 = 2;
9938                 }
9939
9940                 i9xx_clock(refclk, &clock);
9941         }
9942
9943         /*
9944          * This value includes pixel_multiplier. We will use
9945          * port_clock to compute adjusted_mode.crtc_clock in the
9946          * encoder's get_config() function.
9947          */
9948         pipe_config->port_clock = clock.dot;
9949 }
9950
9951 int intel_dotclock_calculate(int link_freq,
9952                              const struct intel_link_m_n *m_n)
9953 {
9954         /*
9955          * The calculation for the data clock is:
9956          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
9957          * But we want to avoid losing precison if possible, so:
9958          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
9959          *
9960          * and the link clock is simpler:
9961          * link_clock = (m * link_clock) / n
9962          */
9963
9964         if (!m_n->link_n)
9965                 return 0;
9966
9967         return div_u64((u64)m_n->link_m * link_freq, m_n->link_n);
9968 }
9969
9970 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
9971                                    struct intel_crtc_state *pipe_config)
9972 {
9973         struct drm_device *dev = crtc->base.dev;
9974
9975         /* read out port_clock from the DPLL */
9976         i9xx_crtc_clock_get(crtc, pipe_config);
9977
9978         /*
9979          * This value does not include pixel_multiplier.
9980          * We will check that port_clock and adjusted_mode.crtc_clock
9981          * agree once we know their relationship in the encoder's
9982          * get_config() function.
9983          */
9984         pipe_config->base.adjusted_mode.crtc_clock =
9985                 intel_dotclock_calculate(intel_fdi_link_freq(dev) * 10000,
9986                                          &pipe_config->fdi_m_n);
9987 }
9988
9989 /** Returns the currently programmed mode of the given pipe. */
9990 struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
9991                                              struct drm_crtc *crtc)
9992 {
9993         struct drm_i915_private *dev_priv = dev->dev_private;
9994         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9995         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
9996         struct drm_display_mode *mode;
9997         struct intel_crtc_state pipe_config;
9998         int htot = I915_READ(HTOTAL(cpu_transcoder));
9999         int hsync = I915_READ(HSYNC(cpu_transcoder));
10000         int vtot = I915_READ(VTOTAL(cpu_transcoder));
10001         int vsync = I915_READ(VSYNC(cpu_transcoder));
10002         enum pipe pipe = intel_crtc->pipe;
10003
10004         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10005         if (!mode)
10006                 return NULL;
10007
10008         /*
10009          * Construct a pipe_config sufficient for getting the clock info
10010          * back out of crtc_clock_get.
10011          *
10012          * Note, if LVDS ever uses a non-1 pixel multiplier, we'll need
10013          * to use a real value here instead.
10014          */
10015         pipe_config.cpu_transcoder = (enum transcoder) pipe;
10016         pipe_config.pixel_multiplier = 1;
10017         pipe_config.dpll_hw_state.dpll = I915_READ(DPLL(pipe));
10018         pipe_config.dpll_hw_state.fp0 = I915_READ(FP0(pipe));
10019         pipe_config.dpll_hw_state.fp1 = I915_READ(FP1(pipe));
10020         i9xx_crtc_clock_get(intel_crtc, &pipe_config);
10021
10022         mode->clock = pipe_config.port_clock / pipe_config.pixel_multiplier;
10023         mode->hdisplay = (htot & 0xffff) + 1;
10024         mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
10025         mode->hsync_start = (hsync & 0xffff) + 1;
10026         mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
10027         mode->vdisplay = (vtot & 0xffff) + 1;
10028         mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
10029         mode->vsync_start = (vsync & 0xffff) + 1;
10030         mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
10031
10032         drm_mode_set_name(mode);
10033
10034         return mode;
10035 }
10036
10037 static void intel_decrease_pllclock(struct drm_crtc *crtc)
10038 {
10039         struct drm_device *dev = crtc->dev;
10040         struct drm_i915_private *dev_priv = dev->dev_private;
10041         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10042
10043         if (!HAS_GMCH_DISPLAY(dev))
10044                 return;
10045
10046         if (!dev_priv->lvds_downclock_avail)
10047                 return;
10048
10049         /*
10050          * Since this is called by a timer, we should never get here in
10051          * the manual case.
10052          */
10053         if (!HAS_PIPE_CXSR(dev) && intel_crtc->lowfreq_avail) {
10054                 int pipe = intel_crtc->pipe;
10055                 int dpll_reg = DPLL(pipe);
10056                 int dpll;
10057
10058                 DRM_DEBUG_DRIVER("downclocking LVDS\n");
10059
10060                 assert_panel_unlocked(dev_priv, pipe);
10061
10062                 dpll = I915_READ(dpll_reg);
10063                 dpll |= DISPLAY_RATE_SELECT_FPA1;
10064                 I915_WRITE(dpll_reg, dpll);
10065                 intel_wait_for_vblank(dev, pipe);
10066                 dpll = I915_READ(dpll_reg);
10067                 if (!(dpll & DISPLAY_RATE_SELECT_FPA1))
10068                         DRM_DEBUG_DRIVER("failed to downclock LVDS!\n");
10069         }
10070
10071 }
10072
10073 void intel_mark_busy(struct drm_device *dev)
10074 {
10075         struct drm_i915_private *dev_priv = dev->dev_private;
10076
10077         if (dev_priv->mm.busy)
10078                 return;
10079
10080         intel_runtime_pm_get(dev_priv);
10081         i915_update_gfx_val(dev_priv);
10082         if (INTEL_INFO(dev)->gen >= 6)
10083                 gen6_rps_busy(dev_priv);
10084         dev_priv->mm.busy = true;
10085 }
10086
10087 void intel_mark_idle(struct drm_device *dev)
10088 {
10089         struct drm_i915_private *dev_priv = dev->dev_private;
10090         struct drm_crtc *crtc;
10091
10092         if (!dev_priv->mm.busy)
10093                 return;
10094
10095         dev_priv->mm.busy = false;
10096
10097         for_each_crtc(dev, crtc) {
10098                 if (!crtc->primary->fb)
10099                         continue;
10100
10101                 intel_decrease_pllclock(crtc);
10102         }
10103
10104         if (INTEL_INFO(dev)->gen >= 6)
10105                 gen6_rps_idle(dev->dev_private);
10106
10107         intel_runtime_pm_put(dev_priv);
10108 }
10109
10110 static void intel_crtc_set_state(struct intel_crtc *crtc,
10111                                  struct intel_crtc_state *crtc_state)
10112 {
10113         kfree(crtc->config);
10114         crtc->config = crtc_state;
10115         crtc->base.state = &crtc_state->base;
10116 }
10117
10118 static void intel_crtc_destroy(struct drm_crtc *crtc)
10119 {
10120         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10121         struct drm_device *dev = crtc->dev;
10122         struct intel_unpin_work *work;
10123
10124         spin_lock_irq(&dev->event_lock);
10125         work = intel_crtc->unpin_work;
10126         intel_crtc->unpin_work = NULL;
10127         spin_unlock_irq(&dev->event_lock);
10128
10129         if (work) {
10130                 cancel_work_sync(&work->work);
10131                 kfree(work);
10132         }
10133
10134         intel_crtc_set_state(intel_crtc, NULL);
10135         drm_crtc_cleanup(crtc);
10136
10137         kfree(intel_crtc);
10138 }
10139
10140 static void intel_unpin_work_fn(struct work_struct *__work)
10141 {
10142         struct intel_unpin_work *work =
10143                 container_of(__work, struct intel_unpin_work, work);
10144         struct drm_device *dev = work->crtc->dev;
10145         enum pipe pipe = to_intel_crtc(work->crtc)->pipe;
10146
10147         mutex_lock(&dev->struct_mutex);
10148         intel_unpin_fb_obj(work->old_fb, work->crtc->primary->state);
10149         drm_gem_object_unreference(&work->pending_flip_obj->base);
10150
10151         intel_fbc_update(dev);
10152
10153         if (work->flip_queued_req)
10154                 i915_gem_request_assign(&work->flip_queued_req, NULL);
10155         mutex_unlock(&dev->struct_mutex);
10156
10157         intel_frontbuffer_flip_complete(dev, INTEL_FRONTBUFFER_PRIMARY(pipe));
10158         drm_framebuffer_unreference(work->old_fb);
10159
10160         BUG_ON(atomic_read(&to_intel_crtc(work->crtc)->unpin_work_count) == 0);
10161         atomic_dec(&to_intel_crtc(work->crtc)->unpin_work_count);
10162
10163         kfree(work);
10164 }
10165
10166 static void do_intel_finish_page_flip(struct drm_device *dev,
10167                                       struct drm_crtc *crtc)
10168 {
10169         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10170         struct intel_unpin_work *work;
10171         unsigned long flags;
10172
10173         /* Ignore early vblank irqs */
10174         if (intel_crtc == NULL)
10175                 return;
10176
10177         /*
10178          * This is called both by irq handlers and the reset code (to complete
10179          * lost pageflips) so needs the full irqsave spinlocks.
10180          */
10181         spin_lock_irqsave(&dev->event_lock, flags);
10182         work = intel_crtc->unpin_work;
10183
10184         /* Ensure we don't miss a work->pending update ... */
10185         smp_rmb();
10186
10187         if (work == NULL || atomic_read(&work->pending) < INTEL_FLIP_COMPLETE) {
10188                 spin_unlock_irqrestore(&dev->event_lock, flags);
10189                 return;
10190         }
10191
10192         page_flip_completed(intel_crtc);
10193
10194         spin_unlock_irqrestore(&dev->event_lock, flags);
10195 }
10196
10197 void intel_finish_page_flip(struct drm_device *dev, int pipe)
10198 {
10199         struct drm_i915_private *dev_priv = dev->dev_private;
10200         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
10201
10202         do_intel_finish_page_flip(dev, crtc);
10203 }
10204
10205 void intel_finish_page_flip_plane(struct drm_device *dev, int plane)
10206 {
10207         struct drm_i915_private *dev_priv = dev->dev_private;
10208         struct drm_crtc *crtc = dev_priv->plane_to_crtc_mapping[plane];
10209
10210         do_intel_finish_page_flip(dev, crtc);
10211 }
10212
10213 /* Is 'a' after or equal to 'b'? */
10214 static bool g4x_flip_count_after_eq(u32 a, u32 b)
10215 {
10216         return !((a - b) & 0x80000000);
10217 }
10218
10219 static bool page_flip_finished(struct intel_crtc *crtc)
10220 {
10221         struct drm_device *dev = crtc->base.dev;
10222         struct drm_i915_private *dev_priv = dev->dev_private;
10223
10224         if (i915_reset_in_progress(&dev_priv->gpu_error) ||
10225             crtc->reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
10226                 return true;
10227
10228         /*
10229          * The relevant registers doen't exist on pre-ctg.
10230          * As the flip done interrupt doesn't trigger for mmio
10231          * flips on gmch platforms, a flip count check isn't
10232          * really needed there. But since ctg has the registers,
10233          * include it in the check anyway.
10234          */
10235         if (INTEL_INFO(dev)->gen < 5 && !IS_G4X(dev))
10236                 return true;
10237
10238         /*
10239          * A DSPSURFLIVE check isn't enough in case the mmio and CS flips
10240          * used the same base address. In that case the mmio flip might
10241          * have completed, but the CS hasn't even executed the flip yet.
10242          *
10243          * A flip count check isn't enough as the CS might have updated
10244          * the base address just after start of vblank, but before we
10245          * managed to process the interrupt. This means we'd complete the
10246          * CS flip too soon.
10247          *
10248          * Combining both checks should get us a good enough result. It may
10249          * still happen that the CS flip has been executed, but has not
10250          * yet actually completed. But in case the base address is the same
10251          * anyway, we don't really care.
10252          */
10253         return (I915_READ(DSPSURFLIVE(crtc->plane)) & ~0xfff) ==
10254                 crtc->unpin_work->gtt_offset &&
10255                 g4x_flip_count_after_eq(I915_READ(PIPE_FLIPCOUNT_GM45(crtc->pipe)),
10256                                     crtc->unpin_work->flip_count);
10257 }
10258
10259 void intel_prepare_page_flip(struct drm_device *dev, int plane)
10260 {
10261         struct drm_i915_private *dev_priv = dev->dev_private;
10262         struct intel_crtc *intel_crtc =
10263                 to_intel_crtc(dev_priv->plane_to_crtc_mapping[plane]);
10264         unsigned long flags;
10265
10266
10267         /*
10268          * This is called both by irq handlers and the reset code (to complete
10269          * lost pageflips) so needs the full irqsave spinlocks.
10270          *
10271          * NB: An MMIO update of the plane base pointer will also
10272          * generate a page-flip completion irq, i.e. every modeset
10273          * is also accompanied by a spurious intel_prepare_page_flip().
10274          */
10275         spin_lock_irqsave(&dev->event_lock, flags);
10276         if (intel_crtc->unpin_work && page_flip_finished(intel_crtc))
10277                 atomic_inc_not_zero(&intel_crtc->unpin_work->pending);
10278         spin_unlock_irqrestore(&dev->event_lock, flags);
10279 }
10280
10281 static inline void intel_mark_page_flip_active(struct intel_crtc *intel_crtc)
10282 {
10283         /* Ensure that the work item is consistent when activating it ... */
10284         smp_wmb();
10285         atomic_set(&intel_crtc->unpin_work->pending, INTEL_FLIP_PENDING);
10286         /* and that it is marked active as soon as the irq could fire. */
10287         smp_wmb();
10288 }
10289
10290 static int intel_gen2_queue_flip(struct drm_device *dev,
10291                                  struct drm_crtc *crtc,
10292                                  struct drm_framebuffer *fb,
10293                                  struct drm_i915_gem_object *obj,
10294                                  struct intel_engine_cs *ring,
10295                                  uint32_t flags)
10296 {
10297         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10298         u32 flip_mask;
10299         int ret;
10300
10301         ret = intel_ring_begin(ring, 6);
10302         if (ret)
10303                 return ret;
10304
10305         /* Can't queue multiple flips, so wait for the previous
10306          * one to finish before executing the next.
10307          */
10308         if (intel_crtc->plane)
10309                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
10310         else
10311                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
10312         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
10313         intel_ring_emit(ring, MI_NOOP);
10314         intel_ring_emit(ring, MI_DISPLAY_FLIP |
10315                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
10316         intel_ring_emit(ring, fb->pitches[0]);
10317         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
10318         intel_ring_emit(ring, 0); /* aux display base address, unused */
10319
10320         intel_mark_page_flip_active(intel_crtc);
10321         __intel_ring_advance(ring);
10322         return 0;
10323 }
10324
10325 static int intel_gen3_queue_flip(struct drm_device *dev,
10326                                  struct drm_crtc *crtc,
10327                                  struct drm_framebuffer *fb,
10328                                  struct drm_i915_gem_object *obj,
10329                                  struct intel_engine_cs *ring,
10330                                  uint32_t flags)
10331 {
10332         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10333         u32 flip_mask;
10334         int ret;
10335
10336         ret = intel_ring_begin(ring, 6);
10337         if (ret)
10338                 return ret;
10339
10340         if (intel_crtc->plane)
10341                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
10342         else
10343                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
10344         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
10345         intel_ring_emit(ring, MI_NOOP);
10346         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 |
10347                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
10348         intel_ring_emit(ring, fb->pitches[0]);
10349         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
10350         intel_ring_emit(ring, MI_NOOP);
10351
10352         intel_mark_page_flip_active(intel_crtc);
10353         __intel_ring_advance(ring);
10354         return 0;
10355 }
10356
10357 static int intel_gen4_queue_flip(struct drm_device *dev,
10358                                  struct drm_crtc *crtc,
10359                                  struct drm_framebuffer *fb,
10360                                  struct drm_i915_gem_object *obj,
10361                                  struct intel_engine_cs *ring,
10362                                  uint32_t flags)
10363 {
10364         struct drm_i915_private *dev_priv = dev->dev_private;
10365         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10366         uint32_t pf, pipesrc;
10367         int ret;
10368
10369         ret = intel_ring_begin(ring, 4);
10370         if (ret)
10371                 return ret;
10372
10373         /* i965+ uses the linear or tiled offsets from the
10374          * Display Registers (which do not change across a page-flip)
10375          * so we need only reprogram the base address.
10376          */
10377         intel_ring_emit(ring, MI_DISPLAY_FLIP |
10378                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
10379         intel_ring_emit(ring, fb->pitches[0]);
10380         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset |
10381                         obj->tiling_mode);
10382
10383         /* XXX Enabling the panel-fitter across page-flip is so far
10384          * untested on non-native modes, so ignore it for now.
10385          * pf = I915_READ(pipe == 0 ? PFA_CTL_1 : PFB_CTL_1) & PF_ENABLE;
10386          */
10387         pf = 0;
10388         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
10389         intel_ring_emit(ring, pf | pipesrc);
10390
10391         intel_mark_page_flip_active(intel_crtc);
10392         __intel_ring_advance(ring);
10393         return 0;
10394 }
10395
10396 static int intel_gen6_queue_flip(struct drm_device *dev,
10397                                  struct drm_crtc *crtc,
10398                                  struct drm_framebuffer *fb,
10399                                  struct drm_i915_gem_object *obj,
10400                                  struct intel_engine_cs *ring,
10401                                  uint32_t flags)
10402 {
10403         struct drm_i915_private *dev_priv = dev->dev_private;
10404         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10405         uint32_t pf, pipesrc;
10406         int ret;
10407
10408         ret = intel_ring_begin(ring, 4);
10409         if (ret)
10410                 return ret;
10411
10412         intel_ring_emit(ring, MI_DISPLAY_FLIP |
10413                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
10414         intel_ring_emit(ring, fb->pitches[0] | obj->tiling_mode);
10415         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
10416
10417         /* Contrary to the suggestions in the documentation,
10418          * "Enable Panel Fitter" does not seem to be required when page
10419          * flipping with a non-native mode, and worse causes a normal
10420          * modeset to fail.
10421          * pf = I915_READ(PF_CTL(intel_crtc->pipe)) & PF_ENABLE;
10422          */
10423         pf = 0;
10424         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
10425         intel_ring_emit(ring, pf | pipesrc);
10426
10427         intel_mark_page_flip_active(intel_crtc);
10428         __intel_ring_advance(ring);
10429         return 0;
10430 }
10431
10432 static int intel_gen7_queue_flip(struct drm_device *dev,
10433                                  struct drm_crtc *crtc,
10434                                  struct drm_framebuffer *fb,
10435                                  struct drm_i915_gem_object *obj,
10436                                  struct intel_engine_cs *ring,
10437                                  uint32_t flags)
10438 {
10439         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10440         uint32_t plane_bit = 0;
10441         int len, ret;
10442
10443         switch (intel_crtc->plane) {
10444         case PLANE_A:
10445                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_A;
10446                 break;
10447         case PLANE_B:
10448                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_B;
10449                 break;
10450         case PLANE_C:
10451                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_C;
10452                 break;
10453         default:
10454                 WARN_ONCE(1, "unknown plane in flip command\n");
10455                 return -ENODEV;
10456         }
10457
10458         len = 4;
10459         if (ring->id == RCS) {
10460                 len += 6;
10461                 /*
10462                  * On Gen 8, SRM is now taking an extra dword to accommodate
10463                  * 48bits addresses, and we need a NOOP for the batch size to
10464                  * stay even.
10465                  */
10466                 if (IS_GEN8(dev))
10467                         len += 2;
10468         }
10469
10470         /*
10471          * BSpec MI_DISPLAY_FLIP for IVB:
10472          * "The full packet must be contained within the same cache line."
10473          *
10474          * Currently the LRI+SRM+MI_DISPLAY_FLIP all fit within the same
10475          * cacheline, if we ever start emitting more commands before
10476          * the MI_DISPLAY_FLIP we may need to first emit everything else,
10477          * then do the cacheline alignment, and finally emit the
10478          * MI_DISPLAY_FLIP.
10479          */
10480         ret = intel_ring_cacheline_align(ring);
10481         if (ret)
10482                 return ret;
10483
10484         ret = intel_ring_begin(ring, len);
10485         if (ret)
10486                 return ret;
10487
10488         /* Unmask the flip-done completion message. Note that the bspec says that
10489          * we should do this for both the BCS and RCS, and that we must not unmask
10490          * more than one flip event at any time (or ensure that one flip message
10491          * can be sent by waiting for flip-done prior to queueing new flips).
10492          * Experimentation says that BCS works despite DERRMR masking all
10493          * flip-done completion events and that unmasking all planes at once
10494          * for the RCS also doesn't appear to drop events. Setting the DERRMR
10495          * to zero does lead to lockups within MI_DISPLAY_FLIP.
10496          */
10497         if (ring->id == RCS) {
10498                 intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
10499                 intel_ring_emit(ring, DERRMR);
10500                 intel_ring_emit(ring, ~(DERRMR_PIPEA_PRI_FLIP_DONE |
10501                                         DERRMR_PIPEB_PRI_FLIP_DONE |
10502                                         DERRMR_PIPEC_PRI_FLIP_DONE));
10503                 if (IS_GEN8(dev))
10504                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM_GEN8(1) |
10505                                               MI_SRM_LRM_GLOBAL_GTT);
10506                 else
10507                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM(1) |
10508                                               MI_SRM_LRM_GLOBAL_GTT);
10509                 intel_ring_emit(ring, DERRMR);
10510                 intel_ring_emit(ring, ring->scratch.gtt_offset + 256);
10511                 if (IS_GEN8(dev)) {
10512                         intel_ring_emit(ring, 0);
10513                         intel_ring_emit(ring, MI_NOOP);
10514                 }
10515         }
10516
10517         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 | plane_bit);
10518         intel_ring_emit(ring, (fb->pitches[0] | obj->tiling_mode));
10519         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
10520         intel_ring_emit(ring, (MI_NOOP));
10521
10522         intel_mark_page_flip_active(intel_crtc);
10523         __intel_ring_advance(ring);
10524         return 0;
10525 }
10526
10527 static bool use_mmio_flip(struct intel_engine_cs *ring,
10528                           struct drm_i915_gem_object *obj)
10529 {
10530         /*
10531          * This is not being used for older platforms, because
10532          * non-availability of flip done interrupt forces us to use
10533          * CS flips. Older platforms derive flip done using some clever
10534          * tricks involving the flip_pending status bits and vblank irqs.
10535          * So using MMIO flips there would disrupt this mechanism.
10536          */
10537
10538         if (ring == NULL)
10539                 return true;
10540
10541         if (INTEL_INFO(ring->dev)->gen < 5)
10542                 return false;
10543
10544         if (i915.use_mmio_flip < 0)
10545                 return false;
10546         else if (i915.use_mmio_flip > 0)
10547                 return true;
10548         else if (i915.enable_execlists)
10549                 return true;
10550         else
10551                 return ring != i915_gem_request_get_ring(obj->last_read_req);
10552 }
10553
10554 static void skl_do_mmio_flip(struct intel_crtc *intel_crtc)
10555 {
10556         struct drm_device *dev = intel_crtc->base.dev;
10557         struct drm_i915_private *dev_priv = dev->dev_private;
10558         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
10559         const enum pipe pipe = intel_crtc->pipe;
10560         u32 ctl, stride;
10561
10562         ctl = I915_READ(PLANE_CTL(pipe, 0));
10563         ctl &= ~PLANE_CTL_TILED_MASK;
10564         switch (fb->modifier[0]) {
10565         case DRM_FORMAT_MOD_NONE:
10566                 break;
10567         case I915_FORMAT_MOD_X_TILED:
10568                 ctl |= PLANE_CTL_TILED_X;
10569                 break;
10570         case I915_FORMAT_MOD_Y_TILED:
10571                 ctl |= PLANE_CTL_TILED_Y;
10572                 break;
10573         case I915_FORMAT_MOD_Yf_TILED:
10574                 ctl |= PLANE_CTL_TILED_YF;
10575                 break;
10576         default:
10577                 MISSING_CASE(fb->modifier[0]);
10578         }
10579
10580         /*
10581          * The stride is either expressed as a multiple of 64 bytes chunks for
10582          * linear buffers or in number of tiles for tiled buffers.
10583          */
10584         stride = fb->pitches[0] /
10585                  intel_fb_stride_alignment(dev, fb->modifier[0],
10586                                            fb->pixel_format);
10587
10588         /*
10589          * Both PLANE_CTL and PLANE_STRIDE are not updated on vblank but on
10590          * PLANE_SURF updates, the update is then guaranteed to be atomic.
10591          */
10592         I915_WRITE(PLANE_CTL(pipe, 0), ctl);
10593         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
10594
10595         I915_WRITE(PLANE_SURF(pipe, 0), intel_crtc->unpin_work->gtt_offset);
10596         POSTING_READ(PLANE_SURF(pipe, 0));
10597 }
10598
10599 static void ilk_do_mmio_flip(struct intel_crtc *intel_crtc)
10600 {
10601         struct drm_device *dev = intel_crtc->base.dev;
10602         struct drm_i915_private *dev_priv = dev->dev_private;
10603         struct intel_framebuffer *intel_fb =
10604                 to_intel_framebuffer(intel_crtc->base.primary->fb);
10605         struct drm_i915_gem_object *obj = intel_fb->obj;
10606         u32 dspcntr;
10607         u32 reg;
10608
10609         reg = DSPCNTR(intel_crtc->plane);
10610         dspcntr = I915_READ(reg);
10611
10612         if (obj->tiling_mode != I915_TILING_NONE)
10613                 dspcntr |= DISPPLANE_TILED;
10614         else
10615                 dspcntr &= ~DISPPLANE_TILED;
10616
10617         I915_WRITE(reg, dspcntr);
10618
10619         I915_WRITE(DSPSURF(intel_crtc->plane),
10620                    intel_crtc->unpin_work->gtt_offset);
10621         POSTING_READ(DSPSURF(intel_crtc->plane));
10622
10623 }
10624
10625 /*
10626  * XXX: This is the temporary way to update the plane registers until we get
10627  * around to using the usual plane update functions for MMIO flips
10628  */
10629 static void intel_do_mmio_flip(struct intel_crtc *intel_crtc)
10630 {
10631         struct drm_device *dev = intel_crtc->base.dev;
10632         bool atomic_update;
10633         u32 start_vbl_count;
10634
10635         intel_mark_page_flip_active(intel_crtc);
10636
10637         atomic_update = intel_pipe_update_start(intel_crtc, &start_vbl_count);
10638
10639         if (INTEL_INFO(dev)->gen >= 9)
10640                 skl_do_mmio_flip(intel_crtc);
10641         else
10642                 /* use_mmio_flip() retricts MMIO flips to ilk+ */
10643                 ilk_do_mmio_flip(intel_crtc);
10644
10645         if (atomic_update)
10646                 intel_pipe_update_end(intel_crtc, start_vbl_count);
10647 }
10648
10649 static void intel_mmio_flip_work_func(struct work_struct *work)
10650 {
10651         struct intel_crtc *crtc =
10652                 container_of(work, struct intel_crtc, mmio_flip.work);
10653         struct intel_mmio_flip *mmio_flip;
10654
10655         mmio_flip = &crtc->mmio_flip;
10656         if (mmio_flip->req)
10657                 WARN_ON(__i915_wait_request(mmio_flip->req,
10658                                             crtc->reset_counter,
10659                                             false, NULL, NULL) != 0);
10660
10661         intel_do_mmio_flip(crtc);
10662         if (mmio_flip->req) {
10663                 mutex_lock(&crtc->base.dev->struct_mutex);
10664                 i915_gem_request_assign(&mmio_flip->req, NULL);
10665                 mutex_unlock(&crtc->base.dev->struct_mutex);
10666         }
10667 }
10668
10669 static int intel_queue_mmio_flip(struct drm_device *dev,
10670                                  struct drm_crtc *crtc,
10671                                  struct drm_framebuffer *fb,
10672                                  struct drm_i915_gem_object *obj,
10673                                  struct intel_engine_cs *ring,
10674                                  uint32_t flags)
10675 {
10676         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10677
10678         i915_gem_request_assign(&intel_crtc->mmio_flip.req,
10679                                 obj->last_write_req);
10680
10681         schedule_work(&intel_crtc->mmio_flip.work);
10682
10683         return 0;
10684 }
10685
10686 static int intel_default_queue_flip(struct drm_device *dev,
10687                                     struct drm_crtc *crtc,
10688                                     struct drm_framebuffer *fb,
10689                                     struct drm_i915_gem_object *obj,
10690                                     struct intel_engine_cs *ring,
10691                                     uint32_t flags)
10692 {
10693         return -ENODEV;
10694 }
10695
10696 static bool __intel_pageflip_stall_check(struct drm_device *dev,
10697                                          struct drm_crtc *crtc)
10698 {
10699         struct drm_i915_private *dev_priv = dev->dev_private;
10700         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10701         struct intel_unpin_work *work = intel_crtc->unpin_work;
10702         u32 addr;
10703
10704         if (atomic_read(&work->pending) >= INTEL_FLIP_COMPLETE)
10705                 return true;
10706
10707         if (!work->enable_stall_check)
10708                 return false;
10709
10710         if (work->flip_ready_vblank == 0) {
10711                 if (work->flip_queued_req &&
10712                     !i915_gem_request_completed(work->flip_queued_req, true))
10713                         return false;
10714
10715                 work->flip_ready_vblank = drm_crtc_vblank_count(crtc);
10716         }
10717
10718         if (drm_crtc_vblank_count(crtc) - work->flip_ready_vblank < 3)
10719                 return false;
10720
10721         /* Potential stall - if we see that the flip has happened,
10722          * assume a missed interrupt. */
10723         if (INTEL_INFO(dev)->gen >= 4)
10724                 addr = I915_HI_DISPBASE(I915_READ(DSPSURF(intel_crtc->plane)));
10725         else
10726                 addr = I915_READ(DSPADDR(intel_crtc->plane));
10727
10728         /* There is a potential issue here with a false positive after a flip
10729          * to the same address. We could address this by checking for a
10730          * non-incrementing frame counter.
10731          */
10732         return addr == work->gtt_offset;
10733 }
10734
10735 void intel_check_page_flip(struct drm_device *dev, int pipe)
10736 {
10737         struct drm_i915_private *dev_priv = dev->dev_private;
10738         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
10739         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10740         struct intel_unpin_work *work;
10741
10742         WARN_ON(!in_interrupt());
10743
10744         if (crtc == NULL)
10745                 return;
10746
10747         spin_lock(&dev->event_lock);
10748         work = intel_crtc->unpin_work;
10749         if (work != NULL && __intel_pageflip_stall_check(dev, crtc)) {
10750                 WARN_ONCE(1, "Kicking stuck page flip: queued at %d, now %d\n",
10751                          work->flip_queued_vblank, drm_vblank_count(dev, pipe));
10752                 page_flip_completed(intel_crtc);
10753                 work = NULL;
10754         }
10755         if (work != NULL &&
10756             drm_vblank_count(dev, pipe) - work->flip_queued_vblank > 1)
10757                 intel_queue_rps_boost_for_request(dev, work->flip_queued_req);
10758         spin_unlock(&dev->event_lock);
10759 }
10760
10761 static int intel_crtc_page_flip(struct drm_crtc *crtc,
10762                                 struct drm_framebuffer *fb,
10763                                 struct drm_pending_vblank_event *event,
10764                                 uint32_t page_flip_flags)
10765 {
10766         struct drm_device *dev = crtc->dev;
10767         struct drm_i915_private *dev_priv = dev->dev_private;
10768         struct drm_framebuffer *old_fb = crtc->primary->fb;
10769         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
10770         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10771         struct drm_plane *primary = crtc->primary;
10772         enum pipe pipe = intel_crtc->pipe;
10773         struct intel_unpin_work *work;
10774         struct intel_engine_cs *ring;
10775         bool mmio_flip;
10776         int ret;
10777
10778         /*
10779          * drm_mode_page_flip_ioctl() should already catch this, but double
10780          * check to be safe.  In the future we may enable pageflipping from
10781          * a disabled primary plane.
10782          */
10783         if (WARN_ON(intel_fb_obj(old_fb) == NULL))
10784                 return -EBUSY;
10785
10786         /* Can't change pixel format via MI display flips. */
10787         if (fb->pixel_format != crtc->primary->fb->pixel_format)
10788                 return -EINVAL;
10789
10790         /*
10791          * TILEOFF/LINOFF registers can't be changed via MI display flips.
10792          * Note that pitch changes could also affect these register.
10793          */
10794         if (INTEL_INFO(dev)->gen > 3 &&
10795             (fb->offsets[0] != crtc->primary->fb->offsets[0] ||
10796              fb->pitches[0] != crtc->primary->fb->pitches[0]))
10797                 return -EINVAL;
10798
10799         if (i915_terminally_wedged(&dev_priv->gpu_error))
10800                 goto out_hang;
10801
10802         work = kzalloc(sizeof(*work), GFP_KERNEL);
10803         if (work == NULL)
10804                 return -ENOMEM;
10805
10806         work->event = event;
10807         work->crtc = crtc;
10808         work->old_fb = old_fb;
10809         INIT_WORK(&work->work, intel_unpin_work_fn);
10810
10811         ret = drm_crtc_vblank_get(crtc);
10812         if (ret)
10813                 goto free_work;
10814
10815         /* We borrow the event spin lock for protecting unpin_work */
10816         spin_lock_irq(&dev->event_lock);
10817         if (intel_crtc->unpin_work) {
10818                 /* Before declaring the flip queue wedged, check if
10819                  * the hardware completed the operation behind our backs.
10820                  */
10821                 if (__intel_pageflip_stall_check(dev, crtc)) {
10822                         DRM_DEBUG_DRIVER("flip queue: previous flip completed, continuing\n");
10823                         page_flip_completed(intel_crtc);
10824                 } else {
10825                         DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
10826                         spin_unlock_irq(&dev->event_lock);
10827
10828                         drm_crtc_vblank_put(crtc);
10829                         kfree(work);
10830                         return -EBUSY;
10831                 }
10832         }
10833         intel_crtc->unpin_work = work;
10834         spin_unlock_irq(&dev->event_lock);
10835
10836         if (atomic_read(&intel_crtc->unpin_work_count) >= 2)
10837                 flush_workqueue(dev_priv->wq);
10838
10839         /* Reference the objects for the scheduled work. */
10840         drm_framebuffer_reference(work->old_fb);
10841         drm_gem_object_reference(&obj->base);
10842
10843         crtc->primary->fb = fb;
10844         update_state_fb(crtc->primary);
10845
10846         work->pending_flip_obj = obj;
10847
10848         ret = i915_mutex_lock_interruptible(dev);
10849         if (ret)
10850                 goto cleanup;
10851
10852         atomic_inc(&intel_crtc->unpin_work_count);
10853         intel_crtc->reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
10854
10855         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
10856                 work->flip_count = I915_READ(PIPE_FLIPCOUNT_GM45(pipe)) + 1;
10857
10858         if (IS_VALLEYVIEW(dev)) {
10859                 ring = &dev_priv->ring[BCS];
10860                 if (obj->tiling_mode != intel_fb_obj(work->old_fb)->tiling_mode)
10861                         /* vlv: DISPLAY_FLIP fails to change tiling */
10862                         ring = NULL;
10863         } else if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev)) {
10864                 ring = &dev_priv->ring[BCS];
10865         } else if (INTEL_INFO(dev)->gen >= 7) {
10866                 ring = i915_gem_request_get_ring(obj->last_read_req);
10867                 if (ring == NULL || ring->id != RCS)
10868                         ring = &dev_priv->ring[BCS];
10869         } else {
10870                 ring = &dev_priv->ring[RCS];
10871         }
10872
10873         mmio_flip = use_mmio_flip(ring, obj);
10874
10875         /* When using CS flips, we want to emit semaphores between rings.
10876          * However, when using mmio flips we will create a task to do the
10877          * synchronisation, so all we want here is to pin the framebuffer
10878          * into the display plane and skip any waits.
10879          */
10880         ret = intel_pin_and_fence_fb_obj(crtc->primary, fb,
10881                                          crtc->primary->state,
10882                                          mmio_flip ? i915_gem_request_get_ring(obj->last_read_req) : ring);
10883         if (ret)
10884                 goto cleanup_pending;
10885
10886         work->gtt_offset = intel_plane_obj_offset(to_intel_plane(primary), obj)
10887                                                   + intel_crtc->dspaddr_offset;
10888
10889         if (mmio_flip) {
10890                 ret = intel_queue_mmio_flip(dev, crtc, fb, obj, ring,
10891                                             page_flip_flags);
10892                 if (ret)
10893                         goto cleanup_unpin;
10894
10895                 i915_gem_request_assign(&work->flip_queued_req,
10896                                         obj->last_write_req);
10897         } else {
10898                 ret = dev_priv->display.queue_flip(dev, crtc, fb, obj, ring,
10899                                                    page_flip_flags);
10900                 if (ret)
10901                         goto cleanup_unpin;
10902
10903                 i915_gem_request_assign(&work->flip_queued_req,
10904                                         intel_ring_get_request(ring));
10905         }
10906
10907         work->flip_queued_vblank = drm_crtc_vblank_count(crtc);
10908         work->enable_stall_check = true;
10909
10910         i915_gem_track_fb(intel_fb_obj(work->old_fb), obj,
10911                           INTEL_FRONTBUFFER_PRIMARY(pipe));
10912
10913         intel_fbc_disable(dev);
10914         intel_frontbuffer_flip_prepare(dev, INTEL_FRONTBUFFER_PRIMARY(pipe));
10915         mutex_unlock(&dev->struct_mutex);
10916
10917         trace_i915_flip_request(intel_crtc->plane, obj);
10918
10919         return 0;
10920
10921 cleanup_unpin:
10922         intel_unpin_fb_obj(fb, crtc->primary->state);
10923 cleanup_pending:
10924         atomic_dec(&intel_crtc->unpin_work_count);
10925         mutex_unlock(&dev->struct_mutex);
10926 cleanup:
10927         crtc->primary->fb = old_fb;
10928         update_state_fb(crtc->primary);
10929
10930         drm_gem_object_unreference_unlocked(&obj->base);
10931         drm_framebuffer_unreference(work->old_fb);
10932
10933         spin_lock_irq(&dev->event_lock);
10934         intel_crtc->unpin_work = NULL;
10935         spin_unlock_irq(&dev->event_lock);
10936
10937         drm_crtc_vblank_put(crtc);
10938 free_work:
10939         kfree(work);
10940
10941         if (ret == -EIO) {
10942 out_hang:
10943                 ret = intel_plane_restore(primary);
10944                 if (ret == 0 && event) {
10945                         spin_lock_irq(&dev->event_lock);
10946                         drm_send_vblank_event(dev, pipe, event);
10947                         spin_unlock_irq(&dev->event_lock);
10948                 }
10949         }
10950         return ret;
10951 }
10952
10953 static struct drm_crtc_helper_funcs intel_helper_funcs = {
10954         .mode_set_base_atomic = intel_pipe_set_base_atomic,
10955         .load_lut = intel_crtc_load_lut,
10956         .atomic_begin = intel_begin_crtc_commit,
10957         .atomic_flush = intel_finish_crtc_commit,
10958 };
10959
10960 /**
10961  * intel_modeset_update_staged_output_state
10962  *
10963  * Updates the staged output configuration state, e.g. after we've read out the
10964  * current hw state.
10965  */
10966 static void intel_modeset_update_staged_output_state(struct drm_device *dev)
10967 {
10968         struct intel_crtc *crtc;
10969         struct intel_encoder *encoder;
10970         struct intel_connector *connector;
10971
10972         for_each_intel_connector(dev, connector) {
10973                 connector->new_encoder =
10974                         to_intel_encoder(connector->base.encoder);
10975         }
10976
10977         for_each_intel_encoder(dev, encoder) {
10978                 encoder->new_crtc =
10979                         to_intel_crtc(encoder->base.crtc);
10980         }
10981
10982         for_each_intel_crtc(dev, crtc) {
10983                 crtc->new_enabled = crtc->base.state->enable;
10984         }
10985 }
10986
10987 /* Transitional helper to copy current connector/encoder state to
10988  * connector->state. This is needed so that code that is partially
10989  * converted to atomic does the right thing.
10990  */
10991 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
10992 {
10993         struct intel_connector *connector;
10994
10995         for_each_intel_connector(dev, connector) {
10996                 if (connector->base.encoder) {
10997                         connector->base.state->best_encoder =
10998                                 connector->base.encoder;
10999                         connector->base.state->crtc =
11000                                 connector->base.encoder->crtc;
11001                 } else {
11002                         connector->base.state->best_encoder = NULL;
11003                         connector->base.state->crtc = NULL;
11004                 }
11005         }
11006 }
11007
11008 /**
11009  * intel_modeset_commit_output_state
11010  *
11011  * This function copies the stage display pipe configuration to the real one.
11012  */
11013 static void intel_modeset_commit_output_state(struct drm_device *dev)
11014 {
11015         struct intel_crtc *crtc;
11016         struct intel_encoder *encoder;
11017         struct intel_connector *connector;
11018
11019         for_each_intel_connector(dev, connector) {
11020                 connector->base.encoder = &connector->new_encoder->base;
11021         }
11022
11023         for_each_intel_encoder(dev, encoder) {
11024                 encoder->base.crtc = &encoder->new_crtc->base;
11025         }
11026
11027         for_each_intel_crtc(dev, crtc) {
11028                 crtc->base.state->enable = crtc->new_enabled;
11029                 crtc->base.enabled = crtc->new_enabled;
11030         }
11031
11032         intel_modeset_update_connector_atomic_state(dev);
11033 }
11034
11035 static void
11036 connected_sink_compute_bpp(struct intel_connector *connector,
11037                            struct intel_crtc_state *pipe_config)
11038 {
11039         int bpp = pipe_config->pipe_bpp;
11040
11041         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
11042                 connector->base.base.id,
11043                 connector->base.name);
11044
11045         /* Don't use an invalid EDID bpc value */
11046         if (connector->base.display_info.bpc &&
11047             connector->base.display_info.bpc * 3 < bpp) {
11048                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
11049                               bpp, connector->base.display_info.bpc*3);
11050                 pipe_config->pipe_bpp = connector->base.display_info.bpc*3;
11051         }
11052
11053         /* Clamp bpp to 8 on screens without EDID 1.4 */
11054         if (connector->base.display_info.bpc == 0 && bpp > 24) {
11055                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
11056                               bpp);
11057                 pipe_config->pipe_bpp = 24;
11058         }
11059 }
11060
11061 static int
11062 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
11063                           struct intel_crtc_state *pipe_config)
11064 {
11065         struct drm_device *dev = crtc->base.dev;
11066         struct drm_atomic_state *state;
11067         struct intel_connector *connector;
11068         int bpp, i;
11069
11070         if ((IS_G4X(dev) || IS_VALLEYVIEW(dev)))
11071                 bpp = 10*3;
11072         else if (INTEL_INFO(dev)->gen >= 5)
11073                 bpp = 12*3;
11074         else
11075                 bpp = 8*3;
11076
11077
11078         pipe_config->pipe_bpp = bpp;
11079
11080         state = pipe_config->base.state;
11081
11082         /* Clamp display bpp to EDID value */
11083         for (i = 0; i < state->num_connector; i++) {
11084                 if (!state->connectors[i])
11085                         continue;
11086
11087                 connector = to_intel_connector(state->connectors[i]);
11088                 if (state->connector_states[i]->crtc != &crtc->base)
11089                         continue;
11090
11091                 connected_sink_compute_bpp(connector, pipe_config);
11092         }
11093
11094         return bpp;
11095 }
11096
11097 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
11098 {
11099         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
11100                         "type: 0x%x flags: 0x%x\n",
11101                 mode->crtc_clock,
11102                 mode->crtc_hdisplay, mode->crtc_hsync_start,
11103                 mode->crtc_hsync_end, mode->crtc_htotal,
11104                 mode->crtc_vdisplay, mode->crtc_vsync_start,
11105                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
11106 }
11107
11108 static void intel_dump_pipe_config(struct intel_crtc *crtc,
11109                                    struct intel_crtc_state *pipe_config,
11110                                    const char *context)
11111 {
11112         struct drm_device *dev = crtc->base.dev;
11113         struct drm_plane *plane;
11114         struct intel_plane *intel_plane;
11115         struct intel_plane_state *state;
11116         struct drm_framebuffer *fb;
11117
11118         DRM_DEBUG_KMS("[CRTC:%d]%s config %p for pipe %c\n", crtc->base.base.id,
11119                       context, pipe_config, pipe_name(crtc->pipe));
11120
11121         DRM_DEBUG_KMS("cpu_transcoder: %c\n", transcoder_name(pipe_config->cpu_transcoder));
11122         DRM_DEBUG_KMS("pipe bpp: %i, dithering: %i\n",
11123                       pipe_config->pipe_bpp, pipe_config->dither);
11124         DRM_DEBUG_KMS("fdi/pch: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
11125                       pipe_config->has_pch_encoder,
11126                       pipe_config->fdi_lanes,
11127                       pipe_config->fdi_m_n.gmch_m, pipe_config->fdi_m_n.gmch_n,
11128                       pipe_config->fdi_m_n.link_m, pipe_config->fdi_m_n.link_n,
11129                       pipe_config->fdi_m_n.tu);
11130         DRM_DEBUG_KMS("dp: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
11131                       pipe_config->has_dp_encoder,
11132                       pipe_config->dp_m_n.gmch_m, pipe_config->dp_m_n.gmch_n,
11133                       pipe_config->dp_m_n.link_m, pipe_config->dp_m_n.link_n,
11134                       pipe_config->dp_m_n.tu);
11135
11136         DRM_DEBUG_KMS("dp: %i, gmch_m2: %u, gmch_n2: %u, link_m2: %u, link_n2: %u, tu2: %u\n",
11137                       pipe_config->has_dp_encoder,
11138                       pipe_config->dp_m2_n2.gmch_m,
11139                       pipe_config->dp_m2_n2.gmch_n,
11140                       pipe_config->dp_m2_n2.link_m,
11141                       pipe_config->dp_m2_n2.link_n,
11142                       pipe_config->dp_m2_n2.tu);
11143
11144         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
11145                       pipe_config->has_audio,
11146                       pipe_config->has_infoframe);
11147
11148         DRM_DEBUG_KMS("requested mode:\n");
11149         drm_mode_debug_printmodeline(&pipe_config->base.mode);
11150         DRM_DEBUG_KMS("adjusted mode:\n");
11151         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
11152         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
11153         DRM_DEBUG_KMS("port clock: %d\n", pipe_config->port_clock);
11154         DRM_DEBUG_KMS("pipe src size: %dx%d\n",
11155                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
11156         DRM_DEBUG_KMS("num_scalers: %d\n", crtc->num_scalers);
11157         DRM_DEBUG_KMS("scaler_users: 0x%x\n", pipe_config->scaler_state.scaler_users);
11158         DRM_DEBUG_KMS("scaler id: %d\n", pipe_config->scaler_state.scaler_id);
11159         DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
11160                       pipe_config->gmch_pfit.control,
11161                       pipe_config->gmch_pfit.pgm_ratios,
11162                       pipe_config->gmch_pfit.lvds_border_bits);
11163         DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
11164                       pipe_config->pch_pfit.pos,
11165                       pipe_config->pch_pfit.size,
11166                       pipe_config->pch_pfit.enabled ? "enabled" : "disabled");
11167         DRM_DEBUG_KMS("ips: %i\n", pipe_config->ips_enabled);
11168         DRM_DEBUG_KMS("double wide: %i\n", pipe_config->double_wide);
11169
11170         DRM_DEBUG_KMS("planes on this crtc\n");
11171         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
11172                 intel_plane = to_intel_plane(plane);
11173                 if (intel_plane->pipe != crtc->pipe)
11174                         continue;
11175
11176                 state = to_intel_plane_state(plane->state);
11177                 fb = state->base.fb;
11178                 if (!fb) {
11179                         DRM_DEBUG_KMS("%s PLANE:%d plane: %u.%u idx: %d "
11180                                 "disabled, scaler_id = %d\n",
11181                                 plane->type == DRM_PLANE_TYPE_CURSOR ? "CURSOR" : "STANDARD",
11182                                 plane->base.id, intel_plane->pipe,
11183                                 (crtc->base.primary == plane) ? 0 : intel_plane->plane + 1,
11184                                 drm_plane_index(plane), state->scaler_id);
11185                         continue;
11186                 }
11187
11188                 DRM_DEBUG_KMS("%s PLANE:%d plane: %u.%u idx: %d enabled",
11189                         plane->type == DRM_PLANE_TYPE_CURSOR ? "CURSOR" : "STANDARD",
11190                         plane->base.id, intel_plane->pipe,
11191                         crtc->base.primary == plane ? 0 : intel_plane->plane + 1,
11192                         drm_plane_index(plane));
11193                 DRM_DEBUG_KMS("\tFB:%d, fb = %ux%u format = 0x%x",
11194                         fb->base.id, fb->width, fb->height, fb->pixel_format);
11195                 DRM_DEBUG_KMS("\tscaler:%d src (%u, %u) %ux%u dst (%u, %u) %ux%u\n",
11196                         state->scaler_id,
11197                         state->src.x1 >> 16, state->src.y1 >> 16,
11198                         drm_rect_width(&state->src) >> 16,
11199                         drm_rect_height(&state->src) >> 16,
11200                         state->dst.x1, state->dst.y1,
11201                         drm_rect_width(&state->dst), drm_rect_height(&state->dst));
11202         }
11203 }
11204
11205 static bool encoders_cloneable(const struct intel_encoder *a,
11206                                const struct intel_encoder *b)
11207 {
11208         /* masks could be asymmetric, so check both ways */
11209         return a == b || (a->cloneable & (1 << b->type) &&
11210                           b->cloneable & (1 << a->type));
11211 }
11212
11213 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
11214                                          struct intel_crtc *crtc,
11215                                          struct intel_encoder *encoder)
11216 {
11217         struct intel_encoder *source_encoder;
11218         struct drm_connector_state *connector_state;
11219         int i;
11220
11221         for (i = 0; i < state->num_connector; i++) {
11222                 if (!state->connectors[i])
11223                         continue;
11224
11225                 connector_state = state->connector_states[i];
11226                 if (connector_state->crtc != &crtc->base)
11227                         continue;
11228
11229                 source_encoder =
11230                         to_intel_encoder(connector_state->best_encoder);
11231                 if (!encoders_cloneable(encoder, source_encoder))
11232                         return false;
11233         }
11234
11235         return true;
11236 }
11237
11238 static bool check_encoder_cloning(struct drm_atomic_state *state,
11239                                   struct intel_crtc *crtc)
11240 {
11241         struct intel_encoder *encoder;
11242         struct drm_connector_state *connector_state;
11243         int i;
11244
11245         for (i = 0; i < state->num_connector; i++) {
11246                 if (!state->connectors[i])
11247                         continue;
11248
11249                 connector_state = state->connector_states[i];
11250                 if (connector_state->crtc != &crtc->base)
11251                         continue;
11252
11253                 encoder = to_intel_encoder(connector_state->best_encoder);
11254                 if (!check_single_encoder_cloning(state, crtc, encoder))
11255                         return false;
11256         }
11257
11258         return true;
11259 }
11260
11261 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
11262 {
11263         struct drm_device *dev = state->dev;
11264         struct intel_encoder *encoder;
11265         struct drm_connector_state *connector_state;
11266         unsigned int used_ports = 0;
11267         int i;
11268
11269         /*
11270          * Walk the connector list instead of the encoder
11271          * list to detect the problem on ddi platforms
11272          * where there's just one encoder per digital port.
11273          */
11274         for (i = 0; i < state->num_connector; i++) {
11275                 if (!state->connectors[i])
11276                         continue;
11277
11278                 connector_state = state->connector_states[i];
11279                 if (!connector_state->best_encoder)
11280                         continue;
11281
11282                 encoder = to_intel_encoder(connector_state->best_encoder);
11283
11284                 WARN_ON(!connector_state->crtc);
11285
11286                 switch (encoder->type) {
11287                         unsigned int port_mask;
11288                 case INTEL_OUTPUT_UNKNOWN:
11289                         if (WARN_ON(!HAS_DDI(dev)))
11290                                 break;
11291                 case INTEL_OUTPUT_DISPLAYPORT:
11292                 case INTEL_OUTPUT_HDMI:
11293                 case INTEL_OUTPUT_EDP:
11294                         port_mask = 1 << enc_to_dig_port(&encoder->base)->port;
11295
11296                         /* the same port mustn't appear more than once */
11297                         if (used_ports & port_mask)
11298                                 return false;
11299
11300                         used_ports |= port_mask;
11301                 default:
11302                         break;
11303                 }
11304         }
11305
11306         return true;
11307 }
11308
11309 static void
11310 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
11311 {
11312         struct drm_crtc_state tmp_state;
11313         struct intel_crtc_scaler_state scaler_state;
11314
11315         /* Clear only the intel specific part of the crtc state excluding scalers */
11316         tmp_state = crtc_state->base;
11317         scaler_state = crtc_state->scaler_state;
11318         memset(crtc_state, 0, sizeof *crtc_state);
11319         crtc_state->base = tmp_state;
11320         crtc_state->scaler_state = scaler_state;
11321 }
11322
11323 static struct intel_crtc_state *
11324 intel_modeset_pipe_config(struct drm_crtc *crtc,
11325                           struct drm_display_mode *mode,
11326                           struct drm_atomic_state *state)
11327 {
11328         struct intel_encoder *encoder;
11329         struct intel_connector *connector;
11330         struct drm_connector_state *connector_state;
11331         struct intel_crtc_state *pipe_config;
11332         int base_bpp, ret = -EINVAL;
11333         int i;
11334         bool retry = true;
11335
11336         if (!check_encoder_cloning(state, to_intel_crtc(crtc))) {
11337                 DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
11338                 return ERR_PTR(-EINVAL);
11339         }
11340
11341         if (!check_digital_port_conflicts(state)) {
11342                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
11343                 return ERR_PTR(-EINVAL);
11344         }
11345
11346         pipe_config = intel_atomic_get_crtc_state(state, to_intel_crtc(crtc));
11347         if (IS_ERR(pipe_config))
11348                 return pipe_config;
11349
11350         clear_intel_crtc_state(pipe_config);
11351
11352         pipe_config->base.crtc = crtc;
11353         drm_mode_copy(&pipe_config->base.adjusted_mode, mode);
11354         drm_mode_copy(&pipe_config->base.mode, mode);
11355
11356         pipe_config->cpu_transcoder =
11357                 (enum transcoder) to_intel_crtc(crtc)->pipe;
11358         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
11359
11360         /*
11361          * Sanitize sync polarity flags based on requested ones. If neither
11362          * positive or negative polarity is requested, treat this as meaning
11363          * negative polarity.
11364          */
11365         if (!(pipe_config->base.adjusted_mode.flags &
11366               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
11367                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
11368
11369         if (!(pipe_config->base.adjusted_mode.flags &
11370               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
11371                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
11372
11373         /* Compute a starting value for pipe_config->pipe_bpp taking the source
11374          * plane pixel format and any sink constraints into account. Returns the
11375          * source plane bpp so that dithering can be selected on mismatches
11376          * after encoders and crtc also have had their say. */
11377         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
11378                                              pipe_config);
11379         if (base_bpp < 0)
11380                 goto fail;
11381
11382         /*
11383          * Determine the real pipe dimensions. Note that stereo modes can
11384          * increase the actual pipe size due to the frame doubling and
11385          * insertion of additional space for blanks between the frame. This
11386          * is stored in the crtc timings. We use the requested mode to do this
11387          * computation to clearly distinguish it from the adjusted mode, which
11388          * can be changed by the connectors in the below retry loop.
11389          */
11390         drm_crtc_get_hv_timing(&pipe_config->base.mode,
11391                                &pipe_config->pipe_src_w,
11392                                &pipe_config->pipe_src_h);
11393
11394 encoder_retry:
11395         /* Ensure the port clock defaults are reset when retrying. */
11396         pipe_config->port_clock = 0;
11397         pipe_config->pixel_multiplier = 1;
11398
11399         /* Fill in default crtc timings, allow encoders to overwrite them. */
11400         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
11401                               CRTC_STEREO_DOUBLE);
11402
11403         /* Pass our mode to the connectors and the CRTC to give them a chance to
11404          * adjust it according to limitations or connector properties, and also
11405          * a chance to reject the mode entirely.
11406          */
11407         for (i = 0; i < state->num_connector; i++) {
11408                 connector = to_intel_connector(state->connectors[i]);
11409                 if (!connector)
11410                         continue;
11411
11412                 connector_state = state->connector_states[i];
11413                 if (connector_state->crtc != crtc)
11414                         continue;
11415
11416                 encoder = to_intel_encoder(connector_state->best_encoder);
11417
11418                 if (!(encoder->compute_config(encoder, pipe_config))) {
11419                         DRM_DEBUG_KMS("Encoder config failure\n");
11420                         goto fail;
11421                 }
11422         }
11423
11424         /* Set default port clock if not overwritten by the encoder. Needs to be
11425          * done afterwards in case the encoder adjusts the mode. */
11426         if (!pipe_config->port_clock)
11427                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
11428                         * pipe_config->pixel_multiplier;
11429
11430         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
11431         if (ret < 0) {
11432                 DRM_DEBUG_KMS("CRTC fixup failed\n");
11433                 goto fail;
11434         }
11435
11436         if (ret == RETRY) {
11437                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
11438                         ret = -EINVAL;
11439                         goto fail;
11440                 }
11441
11442                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
11443                 retry = false;
11444                 goto encoder_retry;
11445         }
11446
11447         pipe_config->dither = pipe_config->pipe_bpp != base_bpp;
11448         DRM_DEBUG_KMS("plane bpp: %i, pipe bpp: %i, dithering: %i\n",
11449                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
11450
11451         return pipe_config;
11452 fail:
11453         return ERR_PTR(ret);
11454 }
11455
11456 /* Computes which crtcs are affected and sets the relevant bits in the mask. For
11457  * simplicity we use the crtc's pipe number (because it's easier to obtain). */
11458 static void
11459 intel_modeset_affected_pipes(struct drm_crtc *crtc, unsigned *modeset_pipes,
11460                              unsigned *prepare_pipes, unsigned *disable_pipes)
11461 {
11462         struct intel_crtc *intel_crtc;
11463         struct drm_device *dev = crtc->dev;
11464         struct intel_encoder *encoder;
11465         struct intel_connector *connector;
11466         struct drm_crtc *tmp_crtc;
11467
11468         *disable_pipes = *modeset_pipes = *prepare_pipes = 0;
11469
11470         /* Check which crtcs have changed outputs connected to them, these need
11471          * to be part of the prepare_pipes mask. We don't (yet) support global
11472          * modeset across multiple crtcs, so modeset_pipes will only have one
11473          * bit set at most. */
11474         for_each_intel_connector(dev, connector) {
11475                 if (connector->base.encoder == &connector->new_encoder->base)
11476                         continue;
11477
11478                 if (connector->base.encoder) {
11479                         tmp_crtc = connector->base.encoder->crtc;
11480
11481                         *prepare_pipes |= 1 << to_intel_crtc(tmp_crtc)->pipe;
11482                 }
11483
11484                 if (connector->new_encoder)
11485                         *prepare_pipes |=
11486                                 1 << connector->new_encoder->new_crtc->pipe;
11487         }
11488
11489         for_each_intel_encoder(dev, encoder) {
11490                 if (encoder->base.crtc == &encoder->new_crtc->base)
11491                         continue;
11492
11493                 if (encoder->base.crtc) {
11494                         tmp_crtc = encoder->base.crtc;
11495
11496                         *prepare_pipes |= 1 << to_intel_crtc(tmp_crtc)->pipe;
11497                 }
11498
11499                 if (encoder->new_crtc)
11500                         *prepare_pipes |= 1 << encoder->new_crtc->pipe;
11501         }
11502
11503         /* Check for pipes that will be enabled/disabled ... */
11504         for_each_intel_crtc(dev, intel_crtc) {
11505                 if (intel_crtc->base.state->enable == intel_crtc->new_enabled)
11506                         continue;
11507
11508                 if (!intel_crtc->new_enabled)
11509                         *disable_pipes |= 1 << intel_crtc->pipe;
11510                 else
11511                         *prepare_pipes |= 1 << intel_crtc->pipe;
11512         }
11513
11514
11515         /* set_mode is also used to update properties on life display pipes. */
11516         intel_crtc = to_intel_crtc(crtc);
11517         if (intel_crtc->new_enabled)
11518                 *prepare_pipes |= 1 << intel_crtc->pipe;
11519
11520         /*
11521          * For simplicity do a full modeset on any pipe where the output routing
11522          * changed. We could be more clever, but that would require us to be
11523          * more careful with calling the relevant encoder->mode_set functions.
11524          */
11525         if (*prepare_pipes)
11526                 *modeset_pipes = *prepare_pipes;
11527
11528         /* ... and mask these out. */
11529         *modeset_pipes &= ~(*disable_pipes);
11530         *prepare_pipes &= ~(*disable_pipes);
11531
11532         /*
11533          * HACK: We don't (yet) fully support global modesets. intel_set_config
11534          * obies this rule, but the modeset restore mode of
11535          * intel_modeset_setup_hw_state does not.
11536          */
11537         *modeset_pipes &= 1 << intel_crtc->pipe;
11538         *prepare_pipes &= 1 << intel_crtc->pipe;
11539
11540         DRM_DEBUG_KMS("set mode pipe masks: modeset: %x, prepare: %x, disable: %x\n",
11541                       *modeset_pipes, *prepare_pipes, *disable_pipes);
11542 }
11543
11544 static bool intel_crtc_in_use(struct drm_crtc *crtc)
11545 {
11546         struct drm_encoder *encoder;
11547         struct drm_device *dev = crtc->dev;
11548
11549         list_for_each_entry(encoder, &dev->mode_config.encoder_list, head)
11550                 if (encoder->crtc == crtc)
11551                         return true;
11552
11553         return false;
11554 }
11555
11556 static void
11557 intel_modeset_update_state(struct drm_device *dev, unsigned prepare_pipes)
11558 {
11559         struct drm_i915_private *dev_priv = dev->dev_private;
11560         struct intel_encoder *intel_encoder;
11561         struct intel_crtc *intel_crtc;
11562         struct drm_connector *connector;
11563
11564         intel_shared_dpll_commit(dev_priv);
11565
11566         for_each_intel_encoder(dev, intel_encoder) {
11567                 if (!intel_encoder->base.crtc)
11568                         continue;
11569
11570                 intel_crtc = to_intel_crtc(intel_encoder->base.crtc);
11571
11572                 if (prepare_pipes & (1 << intel_crtc->pipe))
11573                         intel_encoder->connectors_active = false;
11574         }
11575
11576         intel_modeset_commit_output_state(dev);
11577
11578         /* Double check state. */
11579         for_each_intel_crtc(dev, intel_crtc) {
11580                 WARN_ON(intel_crtc->base.state->enable != intel_crtc_in_use(&intel_crtc->base));
11581         }
11582
11583         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
11584                 if (!connector->encoder || !connector->encoder->crtc)
11585                         continue;
11586
11587                 intel_crtc = to_intel_crtc(connector->encoder->crtc);
11588
11589                 if (prepare_pipes & (1 << intel_crtc->pipe)) {
11590                         struct drm_property *dpms_property =
11591                                 dev->mode_config.dpms_property;
11592
11593                         connector->dpms = DRM_MODE_DPMS_ON;
11594                         drm_object_property_set_value(&connector->base,
11595                                                          dpms_property,
11596                                                          DRM_MODE_DPMS_ON);
11597
11598                         intel_encoder = to_intel_encoder(connector->encoder);
11599                         intel_encoder->connectors_active = true;
11600                 }
11601         }
11602
11603 }
11604
11605 static bool intel_fuzzy_clock_check(int clock1, int clock2)
11606 {
11607         int diff;
11608
11609         if (clock1 == clock2)
11610                 return true;
11611
11612         if (!clock1 || !clock2)
11613                 return false;
11614
11615         diff = abs(clock1 - clock2);
11616
11617         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
11618                 return true;
11619
11620         return false;
11621 }
11622
11623 #define for_each_intel_crtc_masked(dev, mask, intel_crtc) \
11624         list_for_each_entry((intel_crtc), \
11625                             &(dev)->mode_config.crtc_list, \
11626                             base.head) \
11627                 if (mask & (1 <<(intel_crtc)->pipe))
11628
11629 static bool
11630 intel_pipe_config_compare(struct drm_device *dev,
11631                           struct intel_crtc_state *current_config,
11632                           struct intel_crtc_state *pipe_config)
11633 {
11634 #define PIPE_CONF_CHECK_X(name) \
11635         if (current_config->name != pipe_config->name) { \
11636                 DRM_ERROR("mismatch in " #name " " \
11637                           "(expected 0x%08x, found 0x%08x)\n", \
11638                           current_config->name, \
11639                           pipe_config->name); \
11640                 return false; \
11641         }
11642
11643 #define PIPE_CONF_CHECK_I(name) \
11644         if (current_config->name != pipe_config->name) { \
11645                 DRM_ERROR("mismatch in " #name " " \
11646                           "(expected %i, found %i)\n", \
11647                           current_config->name, \
11648                           pipe_config->name); \
11649                 return false; \
11650         }
11651
11652 /* This is required for BDW+ where there is only one set of registers for
11653  * switching between high and low RR.
11654  * This macro can be used whenever a comparison has to be made between one
11655  * hw state and multiple sw state variables.
11656  */
11657 #define PIPE_CONF_CHECK_I_ALT(name, alt_name) \
11658         if ((current_config->name != pipe_config->name) && \
11659                 (current_config->alt_name != pipe_config->name)) { \
11660                         DRM_ERROR("mismatch in " #name " " \
11661                                   "(expected %i or %i, found %i)\n", \
11662                                   current_config->name, \
11663                                   current_config->alt_name, \
11664                                   pipe_config->name); \
11665                         return false; \
11666         }
11667
11668 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
11669         if ((current_config->name ^ pipe_config->name) & (mask)) { \
11670                 DRM_ERROR("mismatch in " #name "(" #mask ") "      \
11671                           "(expected %i, found %i)\n", \
11672                           current_config->name & (mask), \
11673                           pipe_config->name & (mask)); \
11674                 return false; \
11675         }
11676
11677 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
11678         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
11679                 DRM_ERROR("mismatch in " #name " " \
11680                           "(expected %i, found %i)\n", \
11681                           current_config->name, \
11682                           pipe_config->name); \
11683                 return false; \
11684         }
11685
11686 #define PIPE_CONF_QUIRK(quirk)  \
11687         ((current_config->quirks | pipe_config->quirks) & (quirk))
11688
11689         PIPE_CONF_CHECK_I(cpu_transcoder);
11690
11691         PIPE_CONF_CHECK_I(has_pch_encoder);
11692         PIPE_CONF_CHECK_I(fdi_lanes);
11693         PIPE_CONF_CHECK_I(fdi_m_n.gmch_m);
11694         PIPE_CONF_CHECK_I(fdi_m_n.gmch_n);
11695         PIPE_CONF_CHECK_I(fdi_m_n.link_m);
11696         PIPE_CONF_CHECK_I(fdi_m_n.link_n);
11697         PIPE_CONF_CHECK_I(fdi_m_n.tu);
11698
11699         PIPE_CONF_CHECK_I(has_dp_encoder);
11700
11701         if (INTEL_INFO(dev)->gen < 8) {
11702                 PIPE_CONF_CHECK_I(dp_m_n.gmch_m);
11703                 PIPE_CONF_CHECK_I(dp_m_n.gmch_n);
11704                 PIPE_CONF_CHECK_I(dp_m_n.link_m);
11705                 PIPE_CONF_CHECK_I(dp_m_n.link_n);
11706                 PIPE_CONF_CHECK_I(dp_m_n.tu);
11707
11708                 if (current_config->has_drrs) {
11709                         PIPE_CONF_CHECK_I(dp_m2_n2.gmch_m);
11710                         PIPE_CONF_CHECK_I(dp_m2_n2.gmch_n);
11711                         PIPE_CONF_CHECK_I(dp_m2_n2.link_m);
11712                         PIPE_CONF_CHECK_I(dp_m2_n2.link_n);
11713                         PIPE_CONF_CHECK_I(dp_m2_n2.tu);
11714                 }
11715         } else {
11716                 PIPE_CONF_CHECK_I_ALT(dp_m_n.gmch_m, dp_m2_n2.gmch_m);
11717                 PIPE_CONF_CHECK_I_ALT(dp_m_n.gmch_n, dp_m2_n2.gmch_n);
11718                 PIPE_CONF_CHECK_I_ALT(dp_m_n.link_m, dp_m2_n2.link_m);
11719                 PIPE_CONF_CHECK_I_ALT(dp_m_n.link_n, dp_m2_n2.link_n);
11720                 PIPE_CONF_CHECK_I_ALT(dp_m_n.tu, dp_m2_n2.tu);
11721         }
11722
11723         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
11724         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
11725         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
11726         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
11727         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
11728         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
11729
11730         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
11731         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
11732         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
11733         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
11734         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
11735         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
11736
11737         PIPE_CONF_CHECK_I(pixel_multiplier);
11738         PIPE_CONF_CHECK_I(has_hdmi_sink);
11739         if ((INTEL_INFO(dev)->gen < 8 && !IS_HASWELL(dev)) ||
11740             IS_VALLEYVIEW(dev))
11741                 PIPE_CONF_CHECK_I(limited_color_range);
11742         PIPE_CONF_CHECK_I(has_infoframe);
11743
11744         PIPE_CONF_CHECK_I(has_audio);
11745
11746         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11747                               DRM_MODE_FLAG_INTERLACE);
11748
11749         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
11750                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11751                                       DRM_MODE_FLAG_PHSYNC);
11752                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11753                                       DRM_MODE_FLAG_NHSYNC);
11754                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11755                                       DRM_MODE_FLAG_PVSYNC);
11756                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11757                                       DRM_MODE_FLAG_NVSYNC);
11758         }
11759
11760         PIPE_CONF_CHECK_I(pipe_src_w);
11761         PIPE_CONF_CHECK_I(pipe_src_h);
11762
11763         /*
11764          * FIXME: BIOS likes to set up a cloned config with lvds+external
11765          * screen. Since we don't yet re-compute the pipe config when moving
11766          * just the lvds port away to another pipe the sw tracking won't match.
11767          *
11768          * Proper atomic modesets with recomputed global state will fix this.
11769          * Until then just don't check gmch state for inherited modes.
11770          */
11771         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_INHERITED_MODE)) {
11772                 PIPE_CONF_CHECK_I(gmch_pfit.control);
11773                 /* pfit ratios are autocomputed by the hw on gen4+ */
11774                 if (INTEL_INFO(dev)->gen < 4)
11775                         PIPE_CONF_CHECK_I(gmch_pfit.pgm_ratios);
11776                 PIPE_CONF_CHECK_I(gmch_pfit.lvds_border_bits);
11777         }
11778
11779         PIPE_CONF_CHECK_I(pch_pfit.enabled);
11780         if (current_config->pch_pfit.enabled) {
11781                 PIPE_CONF_CHECK_I(pch_pfit.pos);
11782                 PIPE_CONF_CHECK_I(pch_pfit.size);
11783         }
11784
11785         PIPE_CONF_CHECK_I(scaler_state.scaler_id);
11786
11787         /* BDW+ don't expose a synchronous way to read the state */
11788         if (IS_HASWELL(dev))
11789                 PIPE_CONF_CHECK_I(ips_enabled);
11790
11791         PIPE_CONF_CHECK_I(double_wide);
11792
11793         PIPE_CONF_CHECK_X(ddi_pll_sel);
11794
11795         PIPE_CONF_CHECK_I(shared_dpll);
11796         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
11797         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
11798         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
11799         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
11800         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
11801         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
11802         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
11803         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
11804
11805         if (IS_G4X(dev) || INTEL_INFO(dev)->gen >= 5)
11806                 PIPE_CONF_CHECK_I(pipe_bpp);
11807
11808         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
11809         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
11810
11811 #undef PIPE_CONF_CHECK_X
11812 #undef PIPE_CONF_CHECK_I
11813 #undef PIPE_CONF_CHECK_I_ALT
11814 #undef PIPE_CONF_CHECK_FLAGS
11815 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
11816 #undef PIPE_CONF_QUIRK
11817
11818         return true;
11819 }
11820
11821 static void check_wm_state(struct drm_device *dev)
11822 {
11823         struct drm_i915_private *dev_priv = dev->dev_private;
11824         struct skl_ddb_allocation hw_ddb, *sw_ddb;
11825         struct intel_crtc *intel_crtc;
11826         int plane;
11827
11828         if (INTEL_INFO(dev)->gen < 9)
11829                 return;
11830
11831         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
11832         sw_ddb = &dev_priv->wm.skl_hw.ddb;
11833
11834         for_each_intel_crtc(dev, intel_crtc) {
11835                 struct skl_ddb_entry *hw_entry, *sw_entry;
11836                 const enum pipe pipe = intel_crtc->pipe;
11837
11838                 if (!intel_crtc->active)
11839                         continue;
11840
11841                 /* planes */
11842                 for_each_plane(dev_priv, pipe, plane) {
11843                         hw_entry = &hw_ddb.plane[pipe][plane];
11844                         sw_entry = &sw_ddb->plane[pipe][plane];
11845
11846                         if (skl_ddb_entry_equal(hw_entry, sw_entry))
11847                                 continue;
11848
11849                         DRM_ERROR("mismatch in DDB state pipe %c plane %d "
11850                                   "(expected (%u,%u), found (%u,%u))\n",
11851                                   pipe_name(pipe), plane + 1,
11852                                   sw_entry->start, sw_entry->end,
11853                                   hw_entry->start, hw_entry->end);
11854                 }
11855
11856                 /* cursor */
11857                 hw_entry = &hw_ddb.cursor[pipe];
11858                 sw_entry = &sw_ddb->cursor[pipe];
11859
11860                 if (skl_ddb_entry_equal(hw_entry, sw_entry))
11861                         continue;
11862
11863                 DRM_ERROR("mismatch in DDB state pipe %c cursor "
11864                           "(expected (%u,%u), found (%u,%u))\n",
11865                           pipe_name(pipe),
11866                           sw_entry->start, sw_entry->end,
11867                           hw_entry->start, hw_entry->end);
11868         }
11869 }
11870
11871 static void
11872 check_connector_state(struct drm_device *dev)
11873 {
11874         struct intel_connector *connector;
11875
11876         for_each_intel_connector(dev, connector) {
11877                 /* This also checks the encoder/connector hw state with the
11878                  * ->get_hw_state callbacks. */
11879                 intel_connector_check_state(connector);
11880
11881                 I915_STATE_WARN(&connector->new_encoder->base != connector->base.encoder,
11882                      "connector's staged encoder doesn't match current encoder\n");
11883         }
11884 }
11885
11886 static void
11887 check_encoder_state(struct drm_device *dev)
11888 {
11889         struct intel_encoder *encoder;
11890         struct intel_connector *connector;
11891
11892         for_each_intel_encoder(dev, encoder) {
11893                 bool enabled = false;
11894                 bool active = false;
11895                 enum pipe pipe, tracked_pipe;
11896
11897                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
11898                               encoder->base.base.id,
11899                               encoder->base.name);
11900
11901                 I915_STATE_WARN(&encoder->new_crtc->base != encoder->base.crtc,
11902                      "encoder's stage crtc doesn't match current crtc\n");
11903                 I915_STATE_WARN(encoder->connectors_active && !encoder->base.crtc,
11904                      "encoder's active_connectors set, but no crtc\n");
11905
11906                 for_each_intel_connector(dev, connector) {
11907                         if (connector->base.encoder != &encoder->base)
11908                                 continue;
11909                         enabled = true;
11910                         if (connector->base.dpms != DRM_MODE_DPMS_OFF)
11911                                 active = true;
11912                 }
11913                 /*
11914                  * for MST connectors if we unplug the connector is gone
11915                  * away but the encoder is still connected to a crtc
11916                  * until a modeset happens in response to the hotplug.
11917                  */
11918                 if (!enabled && encoder->base.encoder_type == DRM_MODE_ENCODER_DPMST)
11919                         continue;
11920
11921                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
11922                      "encoder's enabled state mismatch "
11923                      "(expected %i, found %i)\n",
11924                      !!encoder->base.crtc, enabled);
11925                 I915_STATE_WARN(active && !encoder->base.crtc,
11926                      "active encoder with no crtc\n");
11927
11928                 I915_STATE_WARN(encoder->connectors_active != active,
11929                      "encoder's computed active state doesn't match tracked active state "
11930                      "(expected %i, found %i)\n", active, encoder->connectors_active);
11931
11932                 active = encoder->get_hw_state(encoder, &pipe);
11933                 I915_STATE_WARN(active != encoder->connectors_active,
11934                      "encoder's hw state doesn't match sw tracking "
11935                      "(expected %i, found %i)\n",
11936                      encoder->connectors_active, active);
11937
11938                 if (!encoder->base.crtc)
11939                         continue;
11940
11941                 tracked_pipe = to_intel_crtc(encoder->base.crtc)->pipe;
11942                 I915_STATE_WARN(active && pipe != tracked_pipe,
11943                      "active encoder's pipe doesn't match"
11944                      "(expected %i, found %i)\n",
11945                      tracked_pipe, pipe);
11946
11947         }
11948 }
11949
11950 static void
11951 check_crtc_state(struct drm_device *dev)
11952 {
11953         struct drm_i915_private *dev_priv = dev->dev_private;
11954         struct intel_crtc *crtc;
11955         struct intel_encoder *encoder;
11956         struct intel_crtc_state pipe_config;
11957
11958         for_each_intel_crtc(dev, crtc) {
11959                 bool enabled = false;
11960                 bool active = false;
11961
11962                 memset(&pipe_config, 0, sizeof(pipe_config));
11963
11964                 DRM_DEBUG_KMS("[CRTC:%d]\n",
11965                               crtc->base.base.id);
11966
11967                 I915_STATE_WARN(crtc->active && !crtc->base.state->enable,
11968                      "active crtc, but not enabled in sw tracking\n");
11969
11970                 for_each_intel_encoder(dev, encoder) {
11971                         if (encoder->base.crtc != &crtc->base)
11972                                 continue;
11973                         enabled = true;
11974                         if (encoder->connectors_active)
11975                                 active = true;
11976                 }
11977
11978                 I915_STATE_WARN(active != crtc->active,
11979                      "crtc's computed active state doesn't match tracked active state "
11980                      "(expected %i, found %i)\n", active, crtc->active);
11981                 I915_STATE_WARN(enabled != crtc->base.state->enable,
11982                      "crtc's computed enabled state doesn't match tracked enabled state "
11983                      "(expected %i, found %i)\n", enabled,
11984                                 crtc->base.state->enable);
11985
11986                 active = dev_priv->display.get_pipe_config(crtc,
11987                                                            &pipe_config);
11988
11989                 /* hw state is inconsistent with the pipe quirk */
11990                 if ((crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
11991                     (crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
11992                         active = crtc->active;
11993
11994                 for_each_intel_encoder(dev, encoder) {
11995                         enum pipe pipe;
11996                         if (encoder->base.crtc != &crtc->base)
11997                                 continue;
11998                         if (encoder->get_hw_state(encoder, &pipe))
11999                                 encoder->get_config(encoder, &pipe_config);
12000                 }
12001
12002                 I915_STATE_WARN(crtc->active != active,
12003                      "crtc active state doesn't match with hw state "
12004                      "(expected %i, found %i)\n", crtc->active, active);
12005
12006                 if (active &&
12007                     !intel_pipe_config_compare(dev, crtc->config, &pipe_config)) {
12008                         I915_STATE_WARN(1, "pipe state doesn't match!\n");
12009                         intel_dump_pipe_config(crtc, &pipe_config,
12010                                                "[hw state]");
12011                         intel_dump_pipe_config(crtc, crtc->config,
12012                                                "[sw state]");
12013                 }
12014         }
12015 }
12016
12017 static void
12018 check_shared_dpll_state(struct drm_device *dev)
12019 {
12020         struct drm_i915_private *dev_priv = dev->dev_private;
12021         struct intel_crtc *crtc;
12022         struct intel_dpll_hw_state dpll_hw_state;
12023         int i;
12024
12025         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
12026                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
12027                 int enabled_crtcs = 0, active_crtcs = 0;
12028                 bool active;
12029
12030                 memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
12031
12032                 DRM_DEBUG_KMS("%s\n", pll->name);
12033
12034                 active = pll->get_hw_state(dev_priv, pll, &dpll_hw_state);
12035
12036                 I915_STATE_WARN(pll->active > hweight32(pll->config.crtc_mask),
12037                      "more active pll users than references: %i vs %i\n",
12038                      pll->active, hweight32(pll->config.crtc_mask));
12039                 I915_STATE_WARN(pll->active && !pll->on,
12040                      "pll in active use but not on in sw tracking\n");
12041                 I915_STATE_WARN(pll->on && !pll->active,
12042                      "pll in on but not on in use in sw tracking\n");
12043                 I915_STATE_WARN(pll->on != active,
12044                      "pll on state mismatch (expected %i, found %i)\n",
12045                      pll->on, active);
12046
12047                 for_each_intel_crtc(dev, crtc) {
12048                         if (crtc->base.state->enable && intel_crtc_to_shared_dpll(crtc) == pll)
12049                                 enabled_crtcs++;
12050                         if (crtc->active && intel_crtc_to_shared_dpll(crtc) == pll)
12051                                 active_crtcs++;
12052                 }
12053                 I915_STATE_WARN(pll->active != active_crtcs,
12054                      "pll active crtcs mismatch (expected %i, found %i)\n",
12055                      pll->active, active_crtcs);
12056                 I915_STATE_WARN(hweight32(pll->config.crtc_mask) != enabled_crtcs,
12057                      "pll enabled crtcs mismatch (expected %i, found %i)\n",
12058                      hweight32(pll->config.crtc_mask), enabled_crtcs);
12059
12060                 I915_STATE_WARN(pll->on && memcmp(&pll->config.hw_state, &dpll_hw_state,
12061                                        sizeof(dpll_hw_state)),
12062                      "pll hw state mismatch\n");
12063         }
12064 }
12065
12066 void
12067 intel_modeset_check_state(struct drm_device *dev)
12068 {
12069         check_wm_state(dev);
12070         check_connector_state(dev);
12071         check_encoder_state(dev);
12072         check_crtc_state(dev);
12073         check_shared_dpll_state(dev);
12074 }
12075
12076 void ironlake_check_encoder_dotclock(const struct intel_crtc_state *pipe_config,
12077                                      int dotclock)
12078 {
12079         /*
12080          * FDI already provided one idea for the dotclock.
12081          * Yell if the encoder disagrees.
12082          */
12083         WARN(!intel_fuzzy_clock_check(pipe_config->base.adjusted_mode.crtc_clock, dotclock),
12084              "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
12085              pipe_config->base.adjusted_mode.crtc_clock, dotclock);
12086 }
12087
12088 static void update_scanline_offset(struct intel_crtc *crtc)
12089 {
12090         struct drm_device *dev = crtc->base.dev;
12091
12092         /*
12093          * The scanline counter increments at the leading edge of hsync.
12094          *
12095          * On most platforms it starts counting from vtotal-1 on the
12096          * first active line. That means the scanline counter value is
12097          * always one less than what we would expect. Ie. just after
12098          * start of vblank, which also occurs at start of hsync (on the
12099          * last active line), the scanline counter will read vblank_start-1.
12100          *
12101          * On gen2 the scanline counter starts counting from 1 instead
12102          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
12103          * to keep the value positive), instead of adding one.
12104          *
12105          * On HSW+ the behaviour of the scanline counter depends on the output
12106          * type. For DP ports it behaves like most other platforms, but on HDMI
12107          * there's an extra 1 line difference. So we need to add two instead of
12108          * one to the value.
12109          */
12110         if (IS_GEN2(dev)) {
12111                 const struct drm_display_mode *mode = &crtc->config->base.adjusted_mode;
12112                 int vtotal;
12113
12114                 vtotal = mode->crtc_vtotal;
12115                 if (mode->flags & DRM_MODE_FLAG_INTERLACE)
12116                         vtotal /= 2;
12117
12118                 crtc->scanline_offset = vtotal - 1;
12119         } else if (HAS_DDI(dev) &&
12120                    intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI)) {
12121                 crtc->scanline_offset = 2;
12122         } else
12123                 crtc->scanline_offset = 1;
12124 }
12125
12126 static struct intel_crtc_state *
12127 intel_modeset_compute_config(struct drm_crtc *crtc,
12128                              struct drm_display_mode *mode,
12129                              struct drm_atomic_state *state,
12130                              unsigned *modeset_pipes,
12131                              unsigned *prepare_pipes,
12132                              unsigned *disable_pipes)
12133 {
12134         struct drm_device *dev = crtc->dev;
12135         struct intel_crtc_state *pipe_config = NULL;
12136         struct intel_crtc *intel_crtc;
12137         int ret = 0;
12138
12139         ret = drm_atomic_add_affected_connectors(state, crtc);
12140         if (ret)
12141                 return ERR_PTR(ret);
12142
12143         intel_modeset_affected_pipes(crtc, modeset_pipes,
12144                                      prepare_pipes, disable_pipes);
12145
12146         for_each_intel_crtc_masked(dev, *disable_pipes, intel_crtc) {
12147                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
12148                 if (IS_ERR(pipe_config))
12149                         return pipe_config;
12150
12151                 pipe_config->base.enable = false;
12152         }
12153
12154         /*
12155          * Note this needs changes when we start tracking multiple modes
12156          * and crtcs.  At that point we'll need to compute the whole config
12157          * (i.e. one pipe_config for each crtc) rather than just the one
12158          * for this crtc.
12159          */
12160         for_each_intel_crtc_masked(dev, *modeset_pipes, intel_crtc) {
12161                 /* FIXME: For now we still expect modeset_pipes has at most
12162                  * one bit set. */
12163                 if (WARN_ON(&intel_crtc->base != crtc))
12164                         continue;
12165
12166                 pipe_config = intel_modeset_pipe_config(crtc, mode, state);
12167                 if (IS_ERR(pipe_config))
12168                         return pipe_config;
12169
12170                 pipe_config->base.enable = true;
12171
12172                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
12173                                        "[modeset]");
12174         }
12175
12176         return intel_atomic_get_crtc_state(state, to_intel_crtc(crtc));;
12177 }
12178
12179 static int __intel_set_mode_setup_plls(struct drm_atomic_state *state,
12180                                        unsigned modeset_pipes,
12181                                        unsigned disable_pipes)
12182 {
12183         struct drm_device *dev = state->dev;
12184         struct drm_i915_private *dev_priv = to_i915(dev);
12185         unsigned clear_pipes = modeset_pipes | disable_pipes;
12186         struct intel_crtc *intel_crtc;
12187         int ret = 0;
12188
12189         if (!dev_priv->display.crtc_compute_clock)
12190                 return 0;
12191
12192         ret = intel_shared_dpll_start_config(dev_priv, clear_pipes);
12193         if (ret)
12194                 goto done;
12195
12196         for_each_intel_crtc_masked(dev, modeset_pipes, intel_crtc) {
12197                 struct intel_crtc_state *crtc_state =
12198                         intel_atomic_get_crtc_state(state, intel_crtc);
12199
12200                 /* Modeset pipes should have a new state by now */
12201                 if (WARN_ON(IS_ERR(crtc_state)))
12202                         continue;
12203
12204                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
12205                                                            crtc_state);
12206                 if (ret) {
12207                         intel_shared_dpll_abort_config(dev_priv);
12208                         goto done;
12209                 }
12210         }
12211
12212 done:
12213         return ret;
12214 }
12215
12216 static int __intel_set_mode(struct drm_crtc *crtc,
12217                             struct drm_display_mode *mode,
12218                             int x, int y, struct drm_framebuffer *fb,
12219                             struct intel_crtc_state *pipe_config,
12220                             unsigned modeset_pipes,
12221                             unsigned prepare_pipes,
12222                             unsigned disable_pipes)
12223 {
12224         struct drm_device *dev = crtc->dev;
12225         struct drm_i915_private *dev_priv = dev->dev_private;
12226         struct drm_display_mode *saved_mode;
12227         struct drm_atomic_state *state = pipe_config->base.state;
12228         struct intel_crtc_state *crtc_state_copy = NULL;
12229         struct intel_crtc *intel_crtc;
12230         int ret = 0;
12231
12232         saved_mode = kmalloc(sizeof(*saved_mode), GFP_KERNEL);
12233         if (!saved_mode)
12234                 return -ENOMEM;
12235
12236         crtc_state_copy = kmalloc(sizeof(*crtc_state_copy), GFP_KERNEL);
12237         if (!crtc_state_copy) {
12238                 ret = -ENOMEM;
12239                 goto done;
12240         }
12241
12242         *saved_mode = crtc->mode;
12243
12244         /*
12245          * See if the config requires any additional preparation, e.g.
12246          * to adjust global state with pipes off.  We need to do this
12247          * here so we can get the modeset_pipe updated config for the new
12248          * mode set on this crtc.  For other crtcs we need to use the
12249          * adjusted_mode bits in the crtc directly.
12250          */
12251         if (IS_VALLEYVIEW(dev) || IS_BROXTON(dev)) {
12252                 ret = valleyview_modeset_global_pipes(state, &prepare_pipes);
12253                 if (ret)
12254                         goto done;
12255
12256                 /* may have added more to prepare_pipes than we should */
12257                 prepare_pipes &= ~disable_pipes;
12258         }
12259
12260         ret = __intel_set_mode_setup_plls(state, modeset_pipes, disable_pipes);
12261         if (ret)
12262                 goto done;
12263
12264         for_each_intel_crtc_masked(dev, disable_pipes, intel_crtc)
12265                 intel_crtc_disable(&intel_crtc->base);
12266
12267         for_each_intel_crtc_masked(dev, prepare_pipes, intel_crtc) {
12268                 if (intel_crtc->base.state->enable)
12269                         dev_priv->display.crtc_disable(&intel_crtc->base);
12270         }
12271
12272         /* crtc->mode is already used by the ->mode_set callbacks, hence we need
12273          * to set it here already despite that we pass it down the callchain.
12274          *
12275          * Note we'll need to fix this up when we start tracking multiple
12276          * pipes; here we assume a single modeset_pipe and only track the
12277          * single crtc and mode.
12278          */
12279         if (modeset_pipes) {
12280                 crtc->mode = *mode;
12281                 /* mode_set/enable/disable functions rely on a correct pipe
12282                  * config. */
12283                 intel_crtc_set_state(to_intel_crtc(crtc), pipe_config);
12284
12285                 /*
12286                  * Calculate and store various constants which
12287                  * are later needed by vblank and swap-completion
12288                  * timestamping. They are derived from true hwmode.
12289                  */
12290                 drm_calc_timestamping_constants(crtc,
12291                                                 &pipe_config->base.adjusted_mode);
12292         }
12293
12294         /* Only after disabling all output pipelines that will be changed can we
12295          * update the the output configuration. */
12296         intel_modeset_update_state(dev, prepare_pipes);
12297
12298         modeset_update_crtc_power_domains(state);
12299
12300         for_each_intel_crtc_masked(dev, modeset_pipes, intel_crtc) {
12301                 struct drm_plane *primary = intel_crtc->base.primary;
12302                 int vdisplay, hdisplay;
12303
12304                 drm_crtc_get_hv_timing(mode, &hdisplay, &vdisplay);
12305                 ret = drm_plane_helper_update(primary, &intel_crtc->base,
12306                                               fb, 0, 0,
12307                                               hdisplay, vdisplay,
12308                                               x << 16, y << 16,
12309                                               hdisplay << 16, vdisplay << 16);
12310         }
12311
12312         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
12313         for_each_intel_crtc_masked(dev, prepare_pipes, intel_crtc) {
12314                 update_scanline_offset(intel_crtc);
12315
12316                 dev_priv->display.crtc_enable(&intel_crtc->base);
12317         }
12318
12319         /* FIXME: add subpixel order */
12320 done:
12321         if (ret && crtc->state->enable)
12322                 crtc->mode = *saved_mode;
12323
12324         if (ret == 0 && pipe_config) {
12325                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12326
12327                 /* The pipe_config will be freed with the atomic state, so
12328                  * make a copy. */
12329                 memcpy(crtc_state_copy, intel_crtc->config,
12330                        sizeof *crtc_state_copy);
12331                 intel_crtc->config = crtc_state_copy;
12332                 intel_crtc->base.state = &crtc_state_copy->base;
12333         } else {
12334                 kfree(crtc_state_copy);
12335         }
12336
12337         kfree(saved_mode);
12338         return ret;
12339 }
12340
12341 static int intel_set_mode_pipes(struct drm_crtc *crtc,
12342                                 struct drm_display_mode *mode,
12343                                 int x, int y, struct drm_framebuffer *fb,
12344                                 struct intel_crtc_state *pipe_config,
12345                                 unsigned modeset_pipes,
12346                                 unsigned prepare_pipes,
12347                                 unsigned disable_pipes)
12348 {
12349         int ret;
12350
12351         ret = __intel_set_mode(crtc, mode, x, y, fb, pipe_config, modeset_pipes,
12352                                prepare_pipes, disable_pipes);
12353
12354         if (ret == 0)
12355                 intel_modeset_check_state(crtc->dev);
12356
12357         return ret;
12358 }
12359
12360 static int intel_set_mode(struct drm_crtc *crtc,
12361                           struct drm_display_mode *mode,
12362                           int x, int y, struct drm_framebuffer *fb,
12363                           struct drm_atomic_state *state)
12364 {
12365         struct intel_crtc_state *pipe_config;
12366         unsigned modeset_pipes, prepare_pipes, disable_pipes;
12367         int ret = 0;
12368
12369         pipe_config = intel_modeset_compute_config(crtc, mode, state,
12370                                                    &modeset_pipes,
12371                                                    &prepare_pipes,
12372                                                    &disable_pipes);
12373
12374         if (IS_ERR(pipe_config)) {
12375                 ret = PTR_ERR(pipe_config);
12376                 goto out;
12377         }
12378
12379         ret = intel_set_mode_pipes(crtc, mode, x, y, fb, pipe_config,
12380                                    modeset_pipes, prepare_pipes,
12381                                    disable_pipes);
12382         if (ret)
12383                 goto out;
12384
12385 out:
12386         return ret;
12387 }
12388
12389 void intel_crtc_restore_mode(struct drm_crtc *crtc)
12390 {
12391         struct drm_device *dev = crtc->dev;
12392         struct drm_atomic_state *state;
12393         struct intel_encoder *encoder;
12394         struct intel_connector *connector;
12395         struct drm_connector_state *connector_state;
12396
12397         state = drm_atomic_state_alloc(dev);
12398         if (!state) {
12399                 DRM_DEBUG_KMS("[CRTC:%d] mode restore failed, out of memory",
12400                               crtc->base.id);
12401                 return;
12402         }
12403
12404         state->acquire_ctx = dev->mode_config.acquire_ctx;
12405
12406         /* The force restore path in the HW readout code relies on the staged
12407          * config still keeping the user requested config while the actual
12408          * state has been overwritten by the configuration read from HW. We
12409          * need to copy the staged config to the atomic state, otherwise the
12410          * mode set will just reapply the state the HW is already in. */
12411         for_each_intel_encoder(dev, encoder) {
12412                 if (&encoder->new_crtc->base != crtc)
12413                         continue;
12414
12415                 for_each_intel_connector(dev, connector) {
12416                         if (connector->new_encoder != encoder)
12417                                 continue;
12418
12419                         connector_state = drm_atomic_get_connector_state(state, &connector->base);
12420                         if (IS_ERR(connector_state)) {
12421                                 DRM_DEBUG_KMS("Failed to add [CONNECTOR:%d:%s] to state: %ld\n",
12422                                               connector->base.base.id,
12423                                               connector->base.name,
12424                                               PTR_ERR(connector_state));
12425                                 continue;
12426                         }
12427
12428                         connector_state->crtc = crtc;
12429                         connector_state->best_encoder = &encoder->base;
12430                 }
12431         }
12432
12433         intel_set_mode(crtc, &crtc->mode, crtc->x, crtc->y, crtc->primary->fb,
12434                        state);
12435
12436         drm_atomic_state_free(state);
12437 }
12438
12439 #undef for_each_intel_crtc_masked
12440
12441 static void intel_set_config_free(struct intel_set_config *config)
12442 {
12443         if (!config)
12444                 return;
12445
12446         kfree(config->save_connector_encoders);
12447         kfree(config->save_encoder_crtcs);
12448         kfree(config->save_crtc_enabled);
12449         kfree(config);
12450 }
12451
12452 static int intel_set_config_save_state(struct drm_device *dev,
12453                                        struct intel_set_config *config)
12454 {
12455         struct drm_crtc *crtc;
12456         struct drm_encoder *encoder;
12457         struct drm_connector *connector;
12458         int count;
12459
12460         config->save_crtc_enabled =
12461                 kcalloc(dev->mode_config.num_crtc,
12462                         sizeof(bool), GFP_KERNEL);
12463         if (!config->save_crtc_enabled)
12464                 return -ENOMEM;
12465
12466         config->save_encoder_crtcs =
12467                 kcalloc(dev->mode_config.num_encoder,
12468                         sizeof(struct drm_crtc *), GFP_KERNEL);
12469         if (!config->save_encoder_crtcs)
12470                 return -ENOMEM;
12471
12472         config->save_connector_encoders =
12473                 kcalloc(dev->mode_config.num_connector,
12474                         sizeof(struct drm_encoder *), GFP_KERNEL);
12475         if (!config->save_connector_encoders)
12476                 return -ENOMEM;
12477
12478         /* Copy data. Note that driver private data is not affected.
12479          * Should anything bad happen only the expected state is
12480          * restored, not the drivers personal bookkeeping.
12481          */
12482         count = 0;
12483         for_each_crtc(dev, crtc) {
12484                 config->save_crtc_enabled[count++] = crtc->state->enable;
12485         }
12486
12487         count = 0;
12488         list_for_each_entry(encoder, &dev->mode_config.encoder_list, head) {
12489                 config->save_encoder_crtcs[count++] = encoder->crtc;
12490         }
12491
12492         count = 0;
12493         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
12494                 config->save_connector_encoders[count++] = connector->encoder;
12495         }
12496
12497         return 0;
12498 }
12499
12500 static void intel_set_config_restore_state(struct drm_device *dev,
12501                                            struct intel_set_config *config)
12502 {
12503         struct intel_crtc *crtc;
12504         struct intel_encoder *encoder;
12505         struct intel_connector *connector;
12506         int count;
12507
12508         count = 0;
12509         for_each_intel_crtc(dev, crtc) {
12510                 crtc->new_enabled = config->save_crtc_enabled[count++];
12511         }
12512
12513         count = 0;
12514         for_each_intel_encoder(dev, encoder) {
12515                 encoder->new_crtc =
12516                         to_intel_crtc(config->save_encoder_crtcs[count++]);
12517         }
12518
12519         count = 0;
12520         for_each_intel_connector(dev, connector) {
12521                 connector->new_encoder =
12522                         to_intel_encoder(config->save_connector_encoders[count++]);
12523         }
12524 }
12525
12526 static bool
12527 is_crtc_connector_off(struct drm_mode_set *set)
12528 {
12529         int i;
12530
12531         if (set->num_connectors == 0)
12532                 return false;
12533
12534         if (WARN_ON(set->connectors == NULL))
12535                 return false;
12536
12537         for (i = 0; i < set->num_connectors; i++)
12538                 if (set->connectors[i]->encoder &&
12539                     set->connectors[i]->encoder->crtc == set->crtc &&
12540                     set->connectors[i]->dpms != DRM_MODE_DPMS_ON)
12541                         return true;
12542
12543         return false;
12544 }
12545
12546 static void
12547 intel_set_config_compute_mode_changes(struct drm_mode_set *set,
12548                                       struct intel_set_config *config)
12549 {
12550
12551         /* We should be able to check here if the fb has the same properties
12552          * and then just flip_or_move it */
12553         if (is_crtc_connector_off(set)) {
12554                 config->mode_changed = true;
12555         } else if (set->crtc->primary->fb != set->fb) {
12556                 /*
12557                  * If we have no fb, we can only flip as long as the crtc is
12558                  * active, otherwise we need a full mode set.  The crtc may
12559                  * be active if we've only disabled the primary plane, or
12560                  * in fastboot situations.
12561                  */
12562                 if (set->crtc->primary->fb == NULL) {
12563                         struct intel_crtc *intel_crtc =
12564                                 to_intel_crtc(set->crtc);
12565
12566                         if (intel_crtc->active) {
12567                                 DRM_DEBUG_KMS("crtc has no fb, will flip\n");
12568                                 config->fb_changed = true;
12569                         } else {
12570                                 DRM_DEBUG_KMS("inactive crtc, full mode set\n");
12571                                 config->mode_changed = true;
12572                         }
12573                 } else if (set->fb == NULL) {
12574                         config->mode_changed = true;
12575                 } else if (set->fb->pixel_format !=
12576                            set->crtc->primary->fb->pixel_format) {
12577                         config->mode_changed = true;
12578                 } else {
12579                         config->fb_changed = true;
12580                 }
12581         }
12582
12583         if (set->fb && (set->x != set->crtc->x || set->y != set->crtc->y))
12584                 config->fb_changed = true;
12585
12586         if (set->mode && !drm_mode_equal(set->mode, &set->crtc->mode)) {
12587                 DRM_DEBUG_KMS("modes are different, full mode set\n");
12588                 drm_mode_debug_printmodeline(&set->crtc->mode);
12589                 drm_mode_debug_printmodeline(set->mode);
12590                 config->mode_changed = true;
12591         }
12592
12593         DRM_DEBUG_KMS("computed changes for [CRTC:%d], mode_changed=%d, fb_changed=%d\n",
12594                         set->crtc->base.id, config->mode_changed, config->fb_changed);
12595 }
12596
12597 static int
12598 intel_modeset_stage_output_state(struct drm_device *dev,
12599                                  struct drm_mode_set *set,
12600                                  struct intel_set_config *config,
12601                                  struct drm_atomic_state *state)
12602 {
12603         struct intel_connector *connector;
12604         struct drm_connector_state *connector_state;
12605         struct intel_encoder *encoder;
12606         struct intel_crtc *crtc;
12607         int ro;
12608
12609         /* The upper layers ensure that we either disable a crtc or have a list
12610          * of connectors. For paranoia, double-check this. */
12611         WARN_ON(!set->fb && (set->num_connectors != 0));
12612         WARN_ON(set->fb && (set->num_connectors == 0));
12613
12614         for_each_intel_connector(dev, connector) {
12615                 /* Otherwise traverse passed in connector list and get encoders
12616                  * for them. */
12617                 for (ro = 0; ro < set->num_connectors; ro++) {
12618                         if (set->connectors[ro] == &connector->base) {
12619                                 connector->new_encoder = intel_find_encoder(connector, to_intel_crtc(set->crtc)->pipe);
12620                                 break;
12621                         }
12622                 }
12623
12624                 /* If we disable the crtc, disable all its connectors. Also, if
12625                  * the connector is on the changing crtc but not on the new
12626                  * connector list, disable it. */
12627                 if ((!set->fb || ro == set->num_connectors) &&
12628                     connector->base.encoder &&
12629                     connector->base.encoder->crtc == set->crtc) {
12630                         connector->new_encoder = NULL;
12631
12632                         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] to [NOCRTC]\n",
12633                                 connector->base.base.id,
12634                                 connector->base.name);
12635                 }
12636
12637
12638                 if (&connector->new_encoder->base != connector->base.encoder) {
12639                         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] encoder changed, full mode switch\n",
12640                                       connector->base.base.id,
12641                                       connector->base.name);
12642                         config->mode_changed = true;
12643                 }
12644         }
12645         /* connector->new_encoder is now updated for all connectors. */
12646
12647         /* Update crtc of enabled connectors. */
12648         for_each_intel_connector(dev, connector) {
12649                 struct drm_crtc *new_crtc;
12650
12651                 if (!connector->new_encoder)
12652                         continue;
12653
12654                 new_crtc = connector->new_encoder->base.crtc;
12655
12656                 for (ro = 0; ro < set->num_connectors; ro++) {
12657                         if (set->connectors[ro] == &connector->base)
12658                                 new_crtc = set->crtc;
12659                 }
12660
12661                 /* Make sure the new CRTC will work with the encoder */
12662                 if (!drm_encoder_crtc_ok(&connector->new_encoder->base,
12663                                          new_crtc)) {
12664                         return -EINVAL;
12665                 }
12666                 connector->new_encoder->new_crtc = to_intel_crtc(new_crtc);
12667
12668                 connector_state =
12669                         drm_atomic_get_connector_state(state, &connector->base);
12670                 if (IS_ERR(connector_state))
12671                         return PTR_ERR(connector_state);
12672
12673                 connector_state->crtc = new_crtc;
12674                 connector_state->best_encoder = &connector->new_encoder->base;
12675
12676                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] to [CRTC:%d]\n",
12677                         connector->base.base.id,
12678                         connector->base.name,
12679                         new_crtc->base.id);
12680         }
12681
12682         /* Check for any encoders that needs to be disabled. */
12683         for_each_intel_encoder(dev, encoder) {
12684                 int num_connectors = 0;
12685                 for_each_intel_connector(dev, connector) {
12686                         if (connector->new_encoder == encoder) {
12687                                 WARN_ON(!connector->new_encoder->new_crtc);
12688                                 num_connectors++;
12689                         }
12690                 }
12691
12692                 if (num_connectors == 0)
12693                         encoder->new_crtc = NULL;
12694                 else if (num_connectors > 1)
12695                         return -EINVAL;
12696
12697                 /* Only now check for crtc changes so we don't miss encoders
12698                  * that will be disabled. */
12699                 if (&encoder->new_crtc->base != encoder->base.crtc) {
12700                         DRM_DEBUG_KMS("[ENCODER:%d:%s] crtc changed, full mode switch\n",
12701                                       encoder->base.base.id,
12702                                       encoder->base.name);
12703                         config->mode_changed = true;
12704                 }
12705         }
12706         /* Now we've also updated encoder->new_crtc for all encoders. */
12707         for_each_intel_connector(dev, connector) {
12708                 connector_state =
12709                         drm_atomic_get_connector_state(state, &connector->base);
12710                 if (IS_ERR(connector_state))
12711                         return PTR_ERR(connector_state);
12712
12713                 if (connector->new_encoder) {
12714                         if (connector->new_encoder != connector->encoder)
12715                                 connector->encoder = connector->new_encoder;
12716                 } else {
12717                         connector_state->crtc = NULL;
12718                         connector_state->best_encoder = NULL;
12719                 }
12720         }
12721         for_each_intel_crtc(dev, crtc) {
12722                 crtc->new_enabled = false;
12723
12724                 for_each_intel_encoder(dev, encoder) {
12725                         if (encoder->new_crtc == crtc) {
12726                                 crtc->new_enabled = true;
12727                                 break;
12728                         }
12729                 }
12730
12731                 if (crtc->new_enabled != crtc->base.state->enable) {
12732                         DRM_DEBUG_KMS("[CRTC:%d] %sabled, full mode switch\n",
12733                                       crtc->base.base.id,
12734                                       crtc->new_enabled ? "en" : "dis");
12735                         config->mode_changed = true;
12736                 }
12737         }
12738
12739         return 0;
12740 }
12741
12742 static void disable_crtc_nofb(struct intel_crtc *crtc)
12743 {
12744         struct drm_device *dev = crtc->base.dev;
12745         struct intel_encoder *encoder;
12746         struct intel_connector *connector;
12747
12748         DRM_DEBUG_KMS("Trying to restore without FB -> disabling pipe %c\n",
12749                       pipe_name(crtc->pipe));
12750
12751         for_each_intel_connector(dev, connector) {
12752                 if (connector->new_encoder &&
12753                     connector->new_encoder->new_crtc == crtc)
12754                         connector->new_encoder = NULL;
12755         }
12756
12757         for_each_intel_encoder(dev, encoder) {
12758                 if (encoder->new_crtc == crtc)
12759                         encoder->new_crtc = NULL;
12760         }
12761
12762         crtc->new_enabled = false;
12763 }
12764
12765 static int intel_crtc_set_config(struct drm_mode_set *set)
12766 {
12767         struct drm_device *dev;
12768         struct drm_mode_set save_set;
12769         struct drm_atomic_state *state = NULL;
12770         struct intel_set_config *config;
12771         struct intel_crtc_state *pipe_config;
12772         unsigned modeset_pipes, prepare_pipes, disable_pipes;
12773         int ret;
12774
12775         BUG_ON(!set);
12776         BUG_ON(!set->crtc);
12777         BUG_ON(!set->crtc->helper_private);
12778
12779         /* Enforce sane interface api - has been abused by the fb helper. */
12780         BUG_ON(!set->mode && set->fb);
12781         BUG_ON(set->fb && set->num_connectors == 0);
12782
12783         if (set->fb) {
12784                 DRM_DEBUG_KMS("[CRTC:%d] [FB:%d] #connectors=%d (x y) (%i %i)\n",
12785                                 set->crtc->base.id, set->fb->base.id,
12786                                 (int)set->num_connectors, set->x, set->y);
12787         } else {
12788                 DRM_DEBUG_KMS("[CRTC:%d] [NOFB]\n", set->crtc->base.id);
12789         }
12790
12791         dev = set->crtc->dev;
12792
12793         ret = -ENOMEM;
12794         config = kzalloc(sizeof(*config), GFP_KERNEL);
12795         if (!config)
12796                 goto out_config;
12797
12798         ret = intel_set_config_save_state(dev, config);
12799         if (ret)
12800                 goto out_config;
12801
12802         save_set.crtc = set->crtc;
12803         save_set.mode = &set->crtc->mode;
12804         save_set.x = set->crtc->x;
12805         save_set.y = set->crtc->y;
12806         save_set.fb = set->crtc->primary->fb;
12807
12808         /* Compute whether we need a full modeset, only an fb base update or no
12809          * change at all. In the future we might also check whether only the
12810          * mode changed, e.g. for LVDS where we only change the panel fitter in
12811          * such cases. */
12812         intel_set_config_compute_mode_changes(set, config);
12813
12814         state = drm_atomic_state_alloc(dev);
12815         if (!state) {
12816                 ret = -ENOMEM;
12817                 goto out_config;
12818         }
12819
12820         state->acquire_ctx = dev->mode_config.acquire_ctx;
12821
12822         ret = intel_modeset_stage_output_state(dev, set, config, state);
12823         if (ret)
12824                 goto fail;
12825
12826         pipe_config = intel_modeset_compute_config(set->crtc, set->mode,
12827                                                    state,
12828                                                    &modeset_pipes,
12829                                                    &prepare_pipes,
12830                                                    &disable_pipes);
12831         if (IS_ERR(pipe_config)) {
12832                 ret = PTR_ERR(pipe_config);
12833                 goto fail;
12834         } else if (pipe_config) {
12835                 if (pipe_config->has_audio !=
12836                     to_intel_crtc(set->crtc)->config->has_audio)
12837                         config->mode_changed = true;
12838
12839                 /*
12840                  * Note we have an issue here with infoframes: current code
12841                  * only updates them on the full mode set path per hw
12842                  * requirements.  So here we should be checking for any
12843                  * required changes and forcing a mode set.
12844                  */
12845         }
12846
12847         intel_update_pipe_size(to_intel_crtc(set->crtc));
12848
12849         if (config->mode_changed) {
12850                 ret = intel_set_mode_pipes(set->crtc, set->mode,
12851                                            set->x, set->y, set->fb, pipe_config,
12852                                            modeset_pipes, prepare_pipes,
12853                                            disable_pipes);
12854         } else if (config->fb_changed) {
12855                 struct intel_crtc *intel_crtc = to_intel_crtc(set->crtc);
12856                 struct drm_plane *primary = set->crtc->primary;
12857                 int vdisplay, hdisplay;
12858
12859                 drm_crtc_get_hv_timing(set->mode, &hdisplay, &vdisplay);
12860                 ret = drm_plane_helper_update(primary, set->crtc, set->fb,
12861                                               0, 0, hdisplay, vdisplay,
12862                                               set->x << 16, set->y << 16,
12863                                               hdisplay << 16, vdisplay << 16);
12864
12865                 /*
12866                  * We need to make sure the primary plane is re-enabled if it
12867                  * has previously been turned off.
12868                  */
12869                 if (!intel_crtc->primary_enabled && ret == 0) {
12870                         WARN_ON(!intel_crtc->active);
12871                         intel_enable_primary_hw_plane(set->crtc->primary, set->crtc);
12872                 }
12873
12874                 /*
12875                  * In the fastboot case this may be our only check of the
12876                  * state after boot.  It would be better to only do it on
12877                  * the first update, but we don't have a nice way of doing that
12878                  * (and really, set_config isn't used much for high freq page
12879                  * flipping, so increasing its cost here shouldn't be a big
12880                  * deal).
12881                  */
12882                 if (i915.fastboot && ret == 0)
12883                         intel_modeset_check_state(set->crtc->dev);
12884         }
12885
12886         if (ret) {
12887                 DRM_DEBUG_KMS("failed to set mode on [CRTC:%d], err = %d\n",
12888                               set->crtc->base.id, ret);
12889 fail:
12890                 intel_set_config_restore_state(dev, config);
12891
12892                 drm_atomic_state_clear(state);
12893
12894                 /*
12895                  * HACK: if the pipe was on, but we didn't have a framebuffer,
12896                  * force the pipe off to avoid oopsing in the modeset code
12897                  * due to fb==NULL. This should only happen during boot since
12898                  * we don't yet reconstruct the FB from the hardware state.
12899                  */
12900                 if (to_intel_crtc(save_set.crtc)->new_enabled && !save_set.fb)
12901                         disable_crtc_nofb(to_intel_crtc(save_set.crtc));
12902
12903                 /* Try to restore the config */
12904                 if (config->mode_changed &&
12905                     intel_set_mode(save_set.crtc, save_set.mode,
12906                                    save_set.x, save_set.y, save_set.fb,
12907                                    state))
12908                         DRM_ERROR("failed to restore config after modeset failure\n");
12909         }
12910
12911 out_config:
12912         if (state)
12913                 drm_atomic_state_free(state);
12914
12915         intel_set_config_free(config);
12916         return ret;
12917 }
12918
12919 static const struct drm_crtc_funcs intel_crtc_funcs = {
12920         .gamma_set = intel_crtc_gamma_set,
12921         .set_config = intel_crtc_set_config,
12922         .destroy = intel_crtc_destroy,
12923         .page_flip = intel_crtc_page_flip,
12924         .atomic_duplicate_state = intel_crtc_duplicate_state,
12925         .atomic_destroy_state = intel_crtc_destroy_state,
12926 };
12927
12928 static bool ibx_pch_dpll_get_hw_state(struct drm_i915_private *dev_priv,
12929                                       struct intel_shared_dpll *pll,
12930                                       struct intel_dpll_hw_state *hw_state)
12931 {
12932         uint32_t val;
12933
12934         if (!intel_display_power_is_enabled(dev_priv, POWER_DOMAIN_PLLS))
12935                 return false;
12936
12937         val = I915_READ(PCH_DPLL(pll->id));
12938         hw_state->dpll = val;
12939         hw_state->fp0 = I915_READ(PCH_FP0(pll->id));
12940         hw_state->fp1 = I915_READ(PCH_FP1(pll->id));
12941
12942         return val & DPLL_VCO_ENABLE;
12943 }
12944
12945 static void ibx_pch_dpll_mode_set(struct drm_i915_private *dev_priv,
12946                                   struct intel_shared_dpll *pll)
12947 {
12948         I915_WRITE(PCH_FP0(pll->id), pll->config.hw_state.fp0);
12949         I915_WRITE(PCH_FP1(pll->id), pll->config.hw_state.fp1);
12950 }
12951
12952 static void ibx_pch_dpll_enable(struct drm_i915_private *dev_priv,
12953                                 struct intel_shared_dpll *pll)
12954 {
12955         /* PCH refclock must be enabled first */
12956         ibx_assert_pch_refclk_enabled(dev_priv);
12957
12958         I915_WRITE(PCH_DPLL(pll->id), pll->config.hw_state.dpll);
12959
12960         /* Wait for the clocks to stabilize. */
12961         POSTING_READ(PCH_DPLL(pll->id));
12962         udelay(150);
12963
12964         /* The pixel multiplier can only be updated once the
12965          * DPLL is enabled and the clocks are stable.
12966          *
12967          * So write it again.
12968          */
12969         I915_WRITE(PCH_DPLL(pll->id), pll->config.hw_state.dpll);
12970         POSTING_READ(PCH_DPLL(pll->id));
12971         udelay(200);
12972 }
12973
12974 static void ibx_pch_dpll_disable(struct drm_i915_private *dev_priv,
12975                                  struct intel_shared_dpll *pll)
12976 {
12977         struct drm_device *dev = dev_priv->dev;
12978         struct intel_crtc *crtc;
12979
12980         /* Make sure no transcoder isn't still depending on us. */
12981         for_each_intel_crtc(dev, crtc) {
12982                 if (intel_crtc_to_shared_dpll(crtc) == pll)
12983                         assert_pch_transcoder_disabled(dev_priv, crtc->pipe);
12984         }
12985
12986         I915_WRITE(PCH_DPLL(pll->id), 0);
12987         POSTING_READ(PCH_DPLL(pll->id));
12988         udelay(200);
12989 }
12990
12991 static char *ibx_pch_dpll_names[] = {
12992         "PCH DPLL A",
12993         "PCH DPLL B",
12994 };
12995
12996 static void ibx_pch_dpll_init(struct drm_device *dev)
12997 {
12998         struct drm_i915_private *dev_priv = dev->dev_private;
12999         int i;
13000
13001         dev_priv->num_shared_dpll = 2;
13002
13003         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
13004                 dev_priv->shared_dplls[i].id = i;
13005                 dev_priv->shared_dplls[i].name = ibx_pch_dpll_names[i];
13006                 dev_priv->shared_dplls[i].mode_set = ibx_pch_dpll_mode_set;
13007                 dev_priv->shared_dplls[i].enable = ibx_pch_dpll_enable;
13008                 dev_priv->shared_dplls[i].disable = ibx_pch_dpll_disable;
13009                 dev_priv->shared_dplls[i].get_hw_state =
13010                         ibx_pch_dpll_get_hw_state;
13011         }
13012 }
13013
13014 static void intel_shared_dpll_init(struct drm_device *dev)
13015 {
13016         struct drm_i915_private *dev_priv = dev->dev_private;
13017
13018         if (HAS_DDI(dev))
13019                 intel_ddi_pll_init(dev);
13020         else if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
13021                 ibx_pch_dpll_init(dev);
13022         else
13023                 dev_priv->num_shared_dpll = 0;
13024
13025         BUG_ON(dev_priv->num_shared_dpll > I915_NUM_PLLS);
13026 }
13027
13028 /**
13029  * intel_wm_need_update - Check whether watermarks need updating
13030  * @plane: drm plane
13031  * @state: new plane state
13032  *
13033  * Check current plane state versus the new one to determine whether
13034  * watermarks need to be recalculated.
13035  *
13036  * Returns true or false.
13037  */
13038 bool intel_wm_need_update(struct drm_plane *plane,
13039                           struct drm_plane_state *state)
13040 {
13041         /* Update watermarks on tiling changes. */
13042         if (!plane->state->fb || !state->fb ||
13043             plane->state->fb->modifier[0] != state->fb->modifier[0] ||
13044             plane->state->rotation != state->rotation)
13045                 return true;
13046
13047         return false;
13048 }
13049
13050 /**
13051  * intel_prepare_plane_fb - Prepare fb for usage on plane
13052  * @plane: drm plane to prepare for
13053  * @fb: framebuffer to prepare for presentation
13054  *
13055  * Prepares a framebuffer for usage on a display plane.  Generally this
13056  * involves pinning the underlying object and updating the frontbuffer tracking
13057  * bits.  Some older platforms need special physical address handling for
13058  * cursor planes.
13059  *
13060  * Returns 0 on success, negative error code on failure.
13061  */
13062 int
13063 intel_prepare_plane_fb(struct drm_plane *plane,
13064                        struct drm_framebuffer *fb,
13065                        const struct drm_plane_state *new_state)
13066 {
13067         struct drm_device *dev = plane->dev;
13068         struct intel_plane *intel_plane = to_intel_plane(plane);
13069         enum pipe pipe = intel_plane->pipe;
13070         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13071         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->fb);
13072         unsigned frontbuffer_bits = 0;
13073         int ret = 0;
13074
13075         if (!obj)
13076                 return 0;
13077
13078         switch (plane->type) {
13079         case DRM_PLANE_TYPE_PRIMARY:
13080                 frontbuffer_bits = INTEL_FRONTBUFFER_PRIMARY(pipe);
13081                 break;
13082         case DRM_PLANE_TYPE_CURSOR:
13083                 frontbuffer_bits = INTEL_FRONTBUFFER_CURSOR(pipe);
13084                 break;
13085         case DRM_PLANE_TYPE_OVERLAY:
13086                 frontbuffer_bits = INTEL_FRONTBUFFER_SPRITE(pipe);
13087                 break;
13088         }
13089
13090         mutex_lock(&dev->struct_mutex);
13091
13092         if (plane->type == DRM_PLANE_TYPE_CURSOR &&
13093             INTEL_INFO(dev)->cursor_needs_physical) {
13094                 int align = IS_I830(dev) ? 16 * 1024 : 256;
13095                 ret = i915_gem_object_attach_phys(obj, align);
13096                 if (ret)
13097                         DRM_DEBUG_KMS("failed to attach phys object\n");
13098         } else {
13099                 ret = intel_pin_and_fence_fb_obj(plane, fb, new_state, NULL);
13100         }
13101
13102         if (ret == 0)
13103                 i915_gem_track_fb(old_obj, obj, frontbuffer_bits);
13104
13105         mutex_unlock(&dev->struct_mutex);
13106
13107         return ret;
13108 }
13109
13110 /**
13111  * intel_cleanup_plane_fb - Cleans up an fb after plane use
13112  * @plane: drm plane to clean up for
13113  * @fb: old framebuffer that was on plane
13114  *
13115  * Cleans up a framebuffer that has just been removed from a plane.
13116  */
13117 void
13118 intel_cleanup_plane_fb(struct drm_plane *plane,
13119                        struct drm_framebuffer *fb,
13120                        const struct drm_plane_state *old_state)
13121 {
13122         struct drm_device *dev = plane->dev;
13123         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13124
13125         if (WARN_ON(!obj))
13126                 return;
13127
13128         if (plane->type != DRM_PLANE_TYPE_CURSOR ||
13129             !INTEL_INFO(dev)->cursor_needs_physical) {
13130                 mutex_lock(&dev->struct_mutex);
13131                 intel_unpin_fb_obj(fb, old_state);
13132                 mutex_unlock(&dev->struct_mutex);
13133         }
13134 }
13135
13136 static int
13137 intel_check_primary_plane(struct drm_plane *plane,
13138                           struct intel_plane_state *state)
13139 {
13140         struct drm_device *dev = plane->dev;
13141         struct drm_i915_private *dev_priv = dev->dev_private;
13142         struct drm_crtc *crtc = state->base.crtc;
13143         struct intel_crtc *intel_crtc;
13144         struct drm_framebuffer *fb = state->base.fb;
13145         struct drm_rect *dest = &state->dst;
13146         struct drm_rect *src = &state->src;
13147         const struct drm_rect *clip = &state->clip;
13148         bool can_position = false;
13149         int ret;
13150
13151         crtc = crtc ? crtc : plane->crtc;
13152         intel_crtc = to_intel_crtc(crtc);
13153
13154         if (INTEL_INFO(dev)->gen >= 9)
13155                 can_position = true;
13156
13157         ret = drm_plane_helper_check_update(plane, crtc, fb,
13158                                             src, dest, clip,
13159                                             DRM_PLANE_HELPER_NO_SCALING,
13160                                             DRM_PLANE_HELPER_NO_SCALING,
13161                                             can_position, true,
13162                                             &state->visible);
13163         if (ret)
13164                 return ret;
13165
13166         if (intel_crtc->active) {
13167                 intel_crtc->atomic.wait_for_flips = true;
13168
13169                 /*
13170                  * FBC does not work on some platforms for rotated
13171                  * planes, so disable it when rotation is not 0 and
13172                  * update it when rotation is set back to 0.
13173                  *
13174                  * FIXME: This is redundant with the fbc update done in
13175                  * the primary plane enable function except that that
13176                  * one is done too late. We eventually need to unify
13177                  * this.
13178                  */
13179                 if (intel_crtc->primary_enabled &&
13180                     INTEL_INFO(dev)->gen <= 4 && !IS_G4X(dev) &&
13181                     dev_priv->fbc.crtc == intel_crtc &&
13182                     state->base.rotation != BIT(DRM_ROTATE_0)) {
13183                         intel_crtc->atomic.disable_fbc = true;
13184                 }
13185
13186                 if (state->visible) {
13187                         /*
13188                          * BDW signals flip done immediately if the plane
13189                          * is disabled, even if the plane enable is already
13190                          * armed to occur at the next vblank :(
13191                          */
13192                         if (IS_BROADWELL(dev) && !intel_crtc->primary_enabled)
13193                                 intel_crtc->atomic.wait_vblank = true;
13194                 }
13195
13196                 intel_crtc->atomic.fb_bits |=
13197                         INTEL_FRONTBUFFER_PRIMARY(intel_crtc->pipe);
13198
13199                 intel_crtc->atomic.update_fbc = true;
13200
13201                 if (intel_wm_need_update(plane, &state->base))
13202                         intel_crtc->atomic.update_wm = true;
13203         }
13204
13205         return 0;
13206 }
13207
13208 static void
13209 intel_commit_primary_plane(struct drm_plane *plane,
13210                            struct intel_plane_state *state)
13211 {
13212         struct drm_crtc *crtc = state->base.crtc;
13213         struct drm_framebuffer *fb = state->base.fb;
13214         struct drm_device *dev = plane->dev;
13215         struct drm_i915_private *dev_priv = dev->dev_private;
13216         struct intel_crtc *intel_crtc;
13217         struct drm_rect *src = &state->src;
13218
13219         crtc = crtc ? crtc : plane->crtc;
13220         intel_crtc = to_intel_crtc(crtc);
13221
13222         plane->fb = fb;
13223         crtc->x = src->x1 >> 16;
13224         crtc->y = src->y1 >> 16;
13225
13226         if (intel_crtc->active) {
13227                 if (state->visible) {
13228                         /* FIXME: kill this fastboot hack */
13229                         intel_update_pipe_size(intel_crtc);
13230
13231                         intel_crtc->primary_enabled = true;
13232
13233                         dev_priv->display.update_primary_plane(crtc, plane->fb,
13234                                         crtc->x, crtc->y);
13235                 } else {
13236                         /*
13237                          * If clipping results in a non-visible primary plane,
13238                          * we'll disable the primary plane.  Note that this is
13239                          * a bit different than what happens if userspace
13240                          * explicitly disables the plane by passing fb=0
13241                          * because plane->fb still gets set and pinned.
13242                          */
13243                         intel_disable_primary_hw_plane(plane, crtc);
13244                 }
13245         }
13246 }
13247
13248 static void intel_begin_crtc_commit(struct drm_crtc *crtc)
13249 {
13250         struct drm_device *dev = crtc->dev;
13251         struct drm_i915_private *dev_priv = dev->dev_private;
13252         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13253         struct intel_plane *intel_plane;
13254         struct drm_plane *p;
13255         unsigned fb_bits = 0;
13256
13257         /* Track fb's for any planes being disabled */
13258         list_for_each_entry(p, &dev->mode_config.plane_list, head) {
13259                 intel_plane = to_intel_plane(p);
13260
13261                 if (intel_crtc->atomic.disabled_planes &
13262                     (1 << drm_plane_index(p))) {
13263                         switch (p->type) {
13264                         case DRM_PLANE_TYPE_PRIMARY:
13265                                 fb_bits = INTEL_FRONTBUFFER_PRIMARY(intel_plane->pipe);
13266                                 break;
13267                         case DRM_PLANE_TYPE_CURSOR:
13268                                 fb_bits = INTEL_FRONTBUFFER_CURSOR(intel_plane->pipe);
13269                                 break;
13270                         case DRM_PLANE_TYPE_OVERLAY:
13271                                 fb_bits = INTEL_FRONTBUFFER_SPRITE(intel_plane->pipe);
13272                                 break;
13273                         }
13274
13275                         mutex_lock(&dev->struct_mutex);
13276                         i915_gem_track_fb(intel_fb_obj(p->fb), NULL, fb_bits);
13277                         mutex_unlock(&dev->struct_mutex);
13278                 }
13279         }
13280
13281         if (intel_crtc->atomic.wait_for_flips)
13282                 intel_crtc_wait_for_pending_flips(crtc);
13283
13284         if (intel_crtc->atomic.disable_fbc)
13285                 intel_fbc_disable(dev);
13286
13287         if (intel_crtc->atomic.pre_disable_primary)
13288                 intel_pre_disable_primary(crtc);
13289
13290         if (intel_crtc->atomic.update_wm)
13291                 intel_update_watermarks(crtc);
13292
13293         intel_runtime_pm_get(dev_priv);
13294
13295         /* Perform vblank evasion around commit operation */
13296         if (intel_crtc->active)
13297                 intel_crtc->atomic.evade =
13298                         intel_pipe_update_start(intel_crtc,
13299                                                 &intel_crtc->atomic.start_vbl_count);
13300 }
13301
13302 static void intel_finish_crtc_commit(struct drm_crtc *crtc)
13303 {
13304         struct drm_device *dev = crtc->dev;
13305         struct drm_i915_private *dev_priv = dev->dev_private;
13306         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13307         struct drm_plane *p;
13308
13309         if (intel_crtc->atomic.evade)
13310                 intel_pipe_update_end(intel_crtc,
13311                                       intel_crtc->atomic.start_vbl_count);
13312
13313         intel_runtime_pm_put(dev_priv);
13314
13315         if (intel_crtc->atomic.wait_vblank)
13316                 intel_wait_for_vblank(dev, intel_crtc->pipe);
13317
13318         intel_frontbuffer_flip(dev, intel_crtc->atomic.fb_bits);
13319
13320         if (intel_crtc->atomic.update_fbc) {
13321                 mutex_lock(&dev->struct_mutex);
13322                 intel_fbc_update(dev);
13323                 mutex_unlock(&dev->struct_mutex);
13324         }
13325
13326         if (intel_crtc->atomic.post_enable_primary)
13327                 intel_post_enable_primary(crtc);
13328
13329         drm_for_each_legacy_plane(p, &dev->mode_config.plane_list)
13330                 if (intel_crtc->atomic.update_sprite_watermarks & drm_plane_index(p))
13331                         intel_update_sprite_watermarks(p, crtc, 0, 0, 0,
13332                                                        false, false);
13333
13334         memset(&intel_crtc->atomic, 0, sizeof(intel_crtc->atomic));
13335 }
13336
13337 /**
13338  * intel_plane_destroy - destroy a plane
13339  * @plane: plane to destroy
13340  *
13341  * Common destruction function for all types of planes (primary, cursor,
13342  * sprite).
13343  */
13344 void intel_plane_destroy(struct drm_plane *plane)
13345 {
13346         struct intel_plane *intel_plane = to_intel_plane(plane);
13347         drm_plane_cleanup(plane);
13348         kfree(intel_plane);
13349 }
13350
13351 const struct drm_plane_funcs intel_plane_funcs = {
13352         .update_plane = drm_atomic_helper_update_plane,
13353         .disable_plane = drm_atomic_helper_disable_plane,
13354         .destroy = intel_plane_destroy,
13355         .set_property = drm_atomic_helper_plane_set_property,
13356         .atomic_get_property = intel_plane_atomic_get_property,
13357         .atomic_set_property = intel_plane_atomic_set_property,
13358         .atomic_duplicate_state = intel_plane_duplicate_state,
13359         .atomic_destroy_state = intel_plane_destroy_state,
13360
13361 };
13362
13363 static struct drm_plane *intel_primary_plane_create(struct drm_device *dev,
13364                                                     int pipe)
13365 {
13366         struct intel_plane *primary;
13367         struct intel_plane_state *state;
13368         const uint32_t *intel_primary_formats;
13369         int num_formats;
13370
13371         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
13372         if (primary == NULL)
13373                 return NULL;
13374
13375         state = intel_create_plane_state(&primary->base);
13376         if (!state) {
13377                 kfree(primary);
13378                 return NULL;
13379         }
13380         primary->base.state = &state->base;
13381
13382         primary->can_scale = false;
13383         primary->max_downscale = 1;
13384         state->scaler_id = -1;
13385         primary->pipe = pipe;
13386         primary->plane = pipe;
13387         primary->check_plane = intel_check_primary_plane;
13388         primary->commit_plane = intel_commit_primary_plane;
13389         primary->ckey.flags = I915_SET_COLORKEY_NONE;
13390         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4)
13391                 primary->plane = !pipe;
13392
13393         if (INTEL_INFO(dev)->gen <= 3) {
13394                 intel_primary_formats = intel_primary_formats_gen2;
13395                 num_formats = ARRAY_SIZE(intel_primary_formats_gen2);
13396         } else {
13397                 intel_primary_formats = intel_primary_formats_gen4;
13398                 num_formats = ARRAY_SIZE(intel_primary_formats_gen4);
13399         }
13400
13401         drm_universal_plane_init(dev, &primary->base, 0,
13402                                  &intel_plane_funcs,
13403                                  intel_primary_formats, num_formats,
13404                                  DRM_PLANE_TYPE_PRIMARY);
13405
13406         if (INTEL_INFO(dev)->gen >= 4)
13407                 intel_create_rotation_property(dev, primary);
13408
13409         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
13410
13411         return &primary->base;
13412 }
13413
13414 void intel_create_rotation_property(struct drm_device *dev, struct intel_plane *plane)
13415 {
13416         if (!dev->mode_config.rotation_property) {
13417                 unsigned long flags = BIT(DRM_ROTATE_0) |
13418                         BIT(DRM_ROTATE_180);
13419
13420                 if (INTEL_INFO(dev)->gen >= 9)
13421                         flags |= BIT(DRM_ROTATE_90) | BIT(DRM_ROTATE_270);
13422
13423                 dev->mode_config.rotation_property =
13424                         drm_mode_create_rotation_property(dev, flags);
13425         }
13426         if (dev->mode_config.rotation_property)
13427                 drm_object_attach_property(&plane->base.base,
13428                                 dev->mode_config.rotation_property,
13429                                 plane->base.state->rotation);
13430 }
13431
13432 static int
13433 intel_check_cursor_plane(struct drm_plane *plane,
13434                          struct intel_plane_state *state)
13435 {
13436         struct drm_crtc *crtc = state->base.crtc;
13437         struct drm_device *dev = plane->dev;
13438         struct drm_framebuffer *fb = state->base.fb;
13439         struct drm_rect *dest = &state->dst;
13440         struct drm_rect *src = &state->src;
13441         const struct drm_rect *clip = &state->clip;
13442         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13443         struct intel_crtc *intel_crtc;
13444         unsigned stride;
13445         int ret;
13446
13447         crtc = crtc ? crtc : plane->crtc;
13448         intel_crtc = to_intel_crtc(crtc);
13449
13450         ret = drm_plane_helper_check_update(plane, crtc, fb,
13451                                             src, dest, clip,
13452                                             DRM_PLANE_HELPER_NO_SCALING,
13453                                             DRM_PLANE_HELPER_NO_SCALING,
13454                                             true, true, &state->visible);
13455         if (ret)
13456                 return ret;
13457
13458
13459         /* if we want to turn off the cursor ignore width and height */
13460         if (!obj)
13461                 goto finish;
13462
13463         /* Check for which cursor types we support */
13464         if (!cursor_size_ok(dev, state->base.crtc_w, state->base.crtc_h)) {
13465                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
13466                           state->base.crtc_w, state->base.crtc_h);
13467                 return -EINVAL;
13468         }
13469
13470         stride = roundup_pow_of_two(state->base.crtc_w) * 4;
13471         if (obj->base.size < stride * state->base.crtc_h) {
13472                 DRM_DEBUG_KMS("buffer is too small\n");
13473                 return -ENOMEM;
13474         }
13475
13476         if (fb->modifier[0] != DRM_FORMAT_MOD_NONE) {
13477                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
13478                 ret = -EINVAL;
13479         }
13480
13481 finish:
13482         if (intel_crtc->active) {
13483                 if (plane->state->crtc_w != state->base.crtc_w)
13484                         intel_crtc->atomic.update_wm = true;
13485
13486                 intel_crtc->atomic.fb_bits |=
13487                         INTEL_FRONTBUFFER_CURSOR(intel_crtc->pipe);
13488         }
13489
13490         return ret;
13491 }
13492
13493 static void
13494 intel_commit_cursor_plane(struct drm_plane *plane,
13495                           struct intel_plane_state *state)
13496 {
13497         struct drm_crtc *crtc = state->base.crtc;
13498         struct drm_device *dev = plane->dev;
13499         struct intel_crtc *intel_crtc;
13500         struct drm_i915_gem_object *obj = intel_fb_obj(state->base.fb);
13501         uint32_t addr;
13502
13503         crtc = crtc ? crtc : plane->crtc;
13504         intel_crtc = to_intel_crtc(crtc);
13505
13506         plane->fb = state->base.fb;
13507         crtc->cursor_x = state->base.crtc_x;
13508         crtc->cursor_y = state->base.crtc_y;
13509
13510         if (intel_crtc->cursor_bo == obj)
13511                 goto update;
13512
13513         if (!obj)
13514                 addr = 0;
13515         else if (!INTEL_INFO(dev)->cursor_needs_physical)
13516                 addr = i915_gem_obj_ggtt_offset(obj);
13517         else
13518                 addr = obj->phys_handle->busaddr;
13519
13520         intel_crtc->cursor_addr = addr;
13521         intel_crtc->cursor_bo = obj;
13522 update:
13523
13524         if (intel_crtc->active)
13525                 intel_crtc_update_cursor(crtc, state->visible);
13526 }
13527
13528 static struct drm_plane *intel_cursor_plane_create(struct drm_device *dev,
13529                                                    int pipe)
13530 {
13531         struct intel_plane *cursor;
13532         struct intel_plane_state *state;
13533
13534         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
13535         if (cursor == NULL)
13536                 return NULL;
13537
13538         state = intel_create_plane_state(&cursor->base);
13539         if (!state) {
13540                 kfree(cursor);
13541                 return NULL;
13542         }
13543         cursor->base.state = &state->base;
13544
13545         cursor->can_scale = false;
13546         cursor->max_downscale = 1;
13547         cursor->pipe = pipe;
13548         cursor->plane = pipe;
13549         state->scaler_id = -1;
13550         cursor->check_plane = intel_check_cursor_plane;
13551         cursor->commit_plane = intel_commit_cursor_plane;
13552
13553         drm_universal_plane_init(dev, &cursor->base, 0,
13554                                  &intel_plane_funcs,
13555                                  intel_cursor_formats,
13556                                  ARRAY_SIZE(intel_cursor_formats),
13557                                  DRM_PLANE_TYPE_CURSOR);
13558
13559         if (INTEL_INFO(dev)->gen >= 4) {
13560                 if (!dev->mode_config.rotation_property)
13561                         dev->mode_config.rotation_property =
13562                                 drm_mode_create_rotation_property(dev,
13563                                                         BIT(DRM_ROTATE_0) |
13564                                                         BIT(DRM_ROTATE_180));
13565                 if (dev->mode_config.rotation_property)
13566                         drm_object_attach_property(&cursor->base.base,
13567                                 dev->mode_config.rotation_property,
13568                                 state->base.rotation);
13569         }
13570
13571         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
13572
13573         return &cursor->base;
13574 }
13575
13576 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
13577         struct intel_crtc_state *crtc_state)
13578 {
13579         int i;
13580         struct intel_scaler *intel_scaler;
13581         struct intel_crtc_scaler_state *scaler_state = &crtc_state->scaler_state;
13582
13583         for (i = 0; i < intel_crtc->num_scalers; i++) {
13584                 intel_scaler = &scaler_state->scalers[i];
13585                 intel_scaler->in_use = 0;
13586                 intel_scaler->id = i;
13587
13588                 intel_scaler->mode = PS_SCALER_MODE_DYN;
13589         }
13590
13591         scaler_state->scaler_id = -1;
13592 }
13593
13594 static void intel_crtc_init(struct drm_device *dev, int pipe)
13595 {
13596         struct drm_i915_private *dev_priv = dev->dev_private;
13597         struct intel_crtc *intel_crtc;
13598         struct intel_crtc_state *crtc_state = NULL;
13599         struct drm_plane *primary = NULL;
13600         struct drm_plane *cursor = NULL;
13601         int i, ret;
13602
13603         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
13604         if (intel_crtc == NULL)
13605                 return;
13606
13607         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
13608         if (!crtc_state)
13609                 goto fail;
13610         intel_crtc_set_state(intel_crtc, crtc_state);
13611         crtc_state->base.crtc = &intel_crtc->base;
13612
13613         /* initialize shared scalers */
13614         if (INTEL_INFO(dev)->gen >= 9) {
13615                 if (pipe == PIPE_C)
13616                         intel_crtc->num_scalers = 1;
13617                 else
13618                         intel_crtc->num_scalers = SKL_NUM_SCALERS;
13619
13620                 skl_init_scalers(dev, intel_crtc, crtc_state);
13621         }
13622
13623         primary = intel_primary_plane_create(dev, pipe);
13624         if (!primary)
13625                 goto fail;
13626
13627         cursor = intel_cursor_plane_create(dev, pipe);
13628         if (!cursor)
13629                 goto fail;
13630
13631         ret = drm_crtc_init_with_planes(dev, &intel_crtc->base, primary,
13632                                         cursor, &intel_crtc_funcs);
13633         if (ret)
13634                 goto fail;
13635
13636         drm_mode_crtc_set_gamma_size(&intel_crtc->base, 256);
13637         for (i = 0; i < 256; i++) {
13638                 intel_crtc->lut_r[i] = i;
13639                 intel_crtc->lut_g[i] = i;
13640                 intel_crtc->lut_b[i] = i;
13641         }
13642
13643         /*
13644          * On gen2/3 only plane A can do fbc, but the panel fitter and lvds port
13645          * is hooked to pipe B. Hence we want plane A feeding pipe B.
13646          */
13647         intel_crtc->pipe = pipe;
13648         intel_crtc->plane = pipe;
13649         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4) {
13650                 DRM_DEBUG_KMS("swapping pipes & planes for FBC\n");
13651                 intel_crtc->plane = !pipe;
13652         }
13653
13654         intel_crtc->cursor_base = ~0;
13655         intel_crtc->cursor_cntl = ~0;
13656         intel_crtc->cursor_size = ~0;
13657
13658         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
13659                dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
13660         dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = &intel_crtc->base;
13661         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = &intel_crtc->base;
13662
13663         INIT_WORK(&intel_crtc->mmio_flip.work, intel_mmio_flip_work_func);
13664
13665         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
13666
13667         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
13668         return;
13669
13670 fail:
13671         if (primary)
13672                 drm_plane_cleanup(primary);
13673         if (cursor)
13674                 drm_plane_cleanup(cursor);
13675         kfree(crtc_state);
13676         kfree(intel_crtc);
13677 }
13678
13679 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
13680 {
13681         struct drm_encoder *encoder = connector->base.encoder;
13682         struct drm_device *dev = connector->base.dev;
13683
13684         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
13685
13686         if (!encoder || WARN_ON(!encoder->crtc))
13687                 return INVALID_PIPE;
13688
13689         return to_intel_crtc(encoder->crtc)->pipe;
13690 }
13691
13692 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
13693                                 struct drm_file *file)
13694 {
13695         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
13696         struct drm_crtc *drmmode_crtc;
13697         struct intel_crtc *crtc;
13698
13699         drmmode_crtc = drm_crtc_find(dev, pipe_from_crtc_id->crtc_id);
13700
13701         if (!drmmode_crtc) {
13702                 DRM_ERROR("no such CRTC id\n");
13703                 return -ENOENT;
13704         }
13705
13706         crtc = to_intel_crtc(drmmode_crtc);
13707         pipe_from_crtc_id->pipe = crtc->pipe;
13708
13709         return 0;
13710 }
13711
13712 static int intel_encoder_clones(struct intel_encoder *encoder)
13713 {
13714         struct drm_device *dev = encoder->base.dev;
13715         struct intel_encoder *source_encoder;
13716         int index_mask = 0;
13717         int entry = 0;
13718
13719         for_each_intel_encoder(dev, source_encoder) {
13720                 if (encoders_cloneable(encoder, source_encoder))
13721                         index_mask |= (1 << entry);
13722
13723                 entry++;
13724         }
13725
13726         return index_mask;
13727 }
13728
13729 static bool has_edp_a(struct drm_device *dev)
13730 {
13731         struct drm_i915_private *dev_priv = dev->dev_private;
13732
13733         if (!IS_MOBILE(dev))
13734                 return false;
13735
13736         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
13737                 return false;
13738
13739         if (IS_GEN5(dev) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
13740                 return false;
13741
13742         return true;
13743 }
13744
13745 static bool intel_crt_present(struct drm_device *dev)
13746 {
13747         struct drm_i915_private *dev_priv = dev->dev_private;
13748
13749         if (INTEL_INFO(dev)->gen >= 9)
13750                 return false;
13751
13752         if (IS_HSW_ULT(dev) || IS_BDW_ULT(dev))
13753                 return false;
13754
13755         if (IS_CHERRYVIEW(dev))
13756                 return false;
13757
13758         if (IS_VALLEYVIEW(dev) && !dev_priv->vbt.int_crt_support)
13759                 return false;
13760
13761         return true;
13762 }
13763
13764 static void intel_setup_outputs(struct drm_device *dev)
13765 {
13766         struct drm_i915_private *dev_priv = dev->dev_private;
13767         struct intel_encoder *encoder;
13768         bool dpd_is_edp = false;
13769
13770         intel_lvds_init(dev);
13771
13772         if (intel_crt_present(dev))
13773                 intel_crt_init(dev);
13774
13775         if (IS_BROXTON(dev)) {
13776                 /*
13777                  * FIXME: Broxton doesn't support port detection via the
13778                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
13779                  * detect the ports.
13780                  */
13781                 intel_ddi_init(dev, PORT_A);
13782                 intel_ddi_init(dev, PORT_B);
13783                 intel_ddi_init(dev, PORT_C);
13784         } else if (HAS_DDI(dev)) {
13785                 int found;
13786
13787                 /*
13788                  * Haswell uses DDI functions to detect digital outputs.
13789                  * On SKL pre-D0 the strap isn't connected, so we assume
13790                  * it's there.
13791                  */
13792                 found = I915_READ(DDI_BUF_CTL_A) & DDI_INIT_DISPLAY_DETECTED;
13793                 /* WaIgnoreDDIAStrap: skl */
13794                 if (found ||
13795                     (IS_SKYLAKE(dev) && INTEL_REVID(dev) < SKL_REVID_D0))
13796                         intel_ddi_init(dev, PORT_A);
13797
13798                 /* DDI B, C and D detection is indicated by the SFUSE_STRAP
13799                  * register */
13800                 found = I915_READ(SFUSE_STRAP);
13801
13802                 if (found & SFUSE_STRAP_DDIB_DETECTED)
13803                         intel_ddi_init(dev, PORT_B);
13804                 if (found & SFUSE_STRAP_DDIC_DETECTED)
13805                         intel_ddi_init(dev, PORT_C);
13806                 if (found & SFUSE_STRAP_DDID_DETECTED)
13807                         intel_ddi_init(dev, PORT_D);
13808         } else if (HAS_PCH_SPLIT(dev)) {
13809                 int found;
13810                 dpd_is_edp = intel_dp_is_edp(dev, PORT_D);
13811
13812                 if (has_edp_a(dev))
13813                         intel_dp_init(dev, DP_A, PORT_A);
13814
13815                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
13816                         /* PCH SDVOB multiplex with HDMIB */
13817                         found = intel_sdvo_init(dev, PCH_SDVOB, true);
13818                         if (!found)
13819                                 intel_hdmi_init(dev, PCH_HDMIB, PORT_B);
13820                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
13821                                 intel_dp_init(dev, PCH_DP_B, PORT_B);
13822                 }
13823
13824                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
13825                         intel_hdmi_init(dev, PCH_HDMIC, PORT_C);
13826
13827                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
13828                         intel_hdmi_init(dev, PCH_HDMID, PORT_D);
13829
13830                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
13831                         intel_dp_init(dev, PCH_DP_C, PORT_C);
13832
13833                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
13834                         intel_dp_init(dev, PCH_DP_D, PORT_D);
13835         } else if (IS_VALLEYVIEW(dev)) {
13836                 /*
13837                  * The DP_DETECTED bit is the latched state of the DDC
13838                  * SDA pin at boot. However since eDP doesn't require DDC
13839                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
13840                  * eDP ports may have been muxed to an alternate function.
13841                  * Thus we can't rely on the DP_DETECTED bit alone to detect
13842                  * eDP ports. Consult the VBT as well as DP_DETECTED to
13843                  * detect eDP ports.
13844                  */
13845                 if (I915_READ(VLV_DISPLAY_BASE + GEN4_HDMIB) & SDVO_DETECTED &&
13846                     !intel_dp_is_edp(dev, PORT_B))
13847                         intel_hdmi_init(dev, VLV_DISPLAY_BASE + GEN4_HDMIB,
13848                                         PORT_B);
13849                 if (I915_READ(VLV_DISPLAY_BASE + DP_B) & DP_DETECTED ||
13850                     intel_dp_is_edp(dev, PORT_B))
13851                         intel_dp_init(dev, VLV_DISPLAY_BASE + DP_B, PORT_B);
13852
13853                 if (I915_READ(VLV_DISPLAY_BASE + GEN4_HDMIC) & SDVO_DETECTED &&
13854                     !intel_dp_is_edp(dev, PORT_C))
13855                         intel_hdmi_init(dev, VLV_DISPLAY_BASE + GEN4_HDMIC,
13856                                         PORT_C);
13857                 if (I915_READ(VLV_DISPLAY_BASE + DP_C) & DP_DETECTED ||
13858                     intel_dp_is_edp(dev, PORT_C))
13859                         intel_dp_init(dev, VLV_DISPLAY_BASE + DP_C, PORT_C);
13860
13861                 if (IS_CHERRYVIEW(dev)) {
13862                         if (I915_READ(VLV_DISPLAY_BASE + CHV_HDMID) & SDVO_DETECTED)
13863                                 intel_hdmi_init(dev, VLV_DISPLAY_BASE + CHV_HDMID,
13864                                                 PORT_D);
13865                         /* eDP not supported on port D, so don't check VBT */
13866                         if (I915_READ(VLV_DISPLAY_BASE + DP_D) & DP_DETECTED)
13867                                 intel_dp_init(dev, VLV_DISPLAY_BASE + DP_D, PORT_D);
13868                 }
13869
13870                 intel_dsi_init(dev);
13871         } else if (SUPPORTS_DIGITAL_OUTPUTS(dev)) {
13872                 bool found = false;
13873
13874                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
13875                         DRM_DEBUG_KMS("probing SDVOB\n");
13876                         found = intel_sdvo_init(dev, GEN3_SDVOB, true);
13877                         if (!found && SUPPORTS_INTEGRATED_HDMI(dev)) {
13878                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
13879                                 intel_hdmi_init(dev, GEN4_HDMIB, PORT_B);
13880                         }
13881
13882                         if (!found && SUPPORTS_INTEGRATED_DP(dev))
13883                                 intel_dp_init(dev, DP_B, PORT_B);
13884                 }
13885
13886                 /* Before G4X SDVOC doesn't have its own detect register */
13887
13888                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
13889                         DRM_DEBUG_KMS("probing SDVOC\n");
13890                         found = intel_sdvo_init(dev, GEN3_SDVOC, false);
13891                 }
13892
13893                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
13894
13895                         if (SUPPORTS_INTEGRATED_HDMI(dev)) {
13896                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
13897                                 intel_hdmi_init(dev, GEN4_HDMIC, PORT_C);
13898                         }
13899                         if (SUPPORTS_INTEGRATED_DP(dev))
13900                                 intel_dp_init(dev, DP_C, PORT_C);
13901                 }
13902
13903                 if (SUPPORTS_INTEGRATED_DP(dev) &&
13904                     (I915_READ(DP_D) & DP_DETECTED))
13905                         intel_dp_init(dev, DP_D, PORT_D);
13906         } else if (IS_GEN2(dev))
13907                 intel_dvo_init(dev);
13908
13909         if (SUPPORTS_TV(dev))
13910                 intel_tv_init(dev);
13911
13912         intel_psr_init(dev);
13913
13914         for_each_intel_encoder(dev, encoder) {
13915                 encoder->base.possible_crtcs = encoder->crtc_mask;
13916                 encoder->base.possible_clones =
13917                         intel_encoder_clones(encoder);
13918         }
13919
13920         intel_init_pch_refclk(dev);
13921
13922         drm_helper_move_panel_connectors_to_head(dev);
13923 }
13924
13925 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
13926 {
13927         struct drm_device *dev = fb->dev;
13928         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
13929
13930         drm_framebuffer_cleanup(fb);
13931         mutex_lock(&dev->struct_mutex);
13932         WARN_ON(!intel_fb->obj->framebuffer_references--);
13933         drm_gem_object_unreference(&intel_fb->obj->base);
13934         mutex_unlock(&dev->struct_mutex);
13935         kfree(intel_fb);
13936 }
13937
13938 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
13939                                                 struct drm_file *file,
13940                                                 unsigned int *handle)
13941 {
13942         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
13943         struct drm_i915_gem_object *obj = intel_fb->obj;
13944
13945         return drm_gem_handle_create(file, &obj->base, handle);
13946 }
13947
13948 static const struct drm_framebuffer_funcs intel_fb_funcs = {
13949         .destroy = intel_user_framebuffer_destroy,
13950         .create_handle = intel_user_framebuffer_create_handle,
13951 };
13952
13953 static
13954 u32 intel_fb_pitch_limit(struct drm_device *dev, uint64_t fb_modifier,
13955                          uint32_t pixel_format)
13956 {
13957         u32 gen = INTEL_INFO(dev)->gen;
13958
13959         if (gen >= 9) {
13960                 /* "The stride in bytes must not exceed the of the size of 8K
13961                  *  pixels and 32K bytes."
13962                  */
13963                  return min(8192*drm_format_plane_cpp(pixel_format, 0), 32768);
13964         } else if (gen >= 5 && !IS_VALLEYVIEW(dev)) {
13965                 return 32*1024;
13966         } else if (gen >= 4) {
13967                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
13968                         return 16*1024;
13969                 else
13970                         return 32*1024;
13971         } else if (gen >= 3) {
13972                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
13973                         return 8*1024;
13974                 else
13975                         return 16*1024;
13976         } else {
13977                 /* XXX DSPC is limited to 4k tiled */
13978                 return 8*1024;
13979         }
13980 }
13981
13982 static int intel_framebuffer_init(struct drm_device *dev,
13983                                   struct intel_framebuffer *intel_fb,
13984                                   struct drm_mode_fb_cmd2 *mode_cmd,
13985                                   struct drm_i915_gem_object *obj)
13986 {
13987         unsigned int aligned_height;
13988         int ret;
13989         u32 pitch_limit, stride_alignment;
13990
13991         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
13992
13993         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
13994                 /* Enforce that fb modifier and tiling mode match, but only for
13995                  * X-tiled. This is needed for FBC. */
13996                 if (!!(obj->tiling_mode == I915_TILING_X) !=
13997                     !!(mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED)) {
13998                         DRM_DEBUG("tiling_mode doesn't match fb modifier\n");
13999                         return -EINVAL;
14000                 }
14001         } else {
14002                 if (obj->tiling_mode == I915_TILING_X)
14003                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
14004                 else if (obj->tiling_mode == I915_TILING_Y) {
14005                         DRM_DEBUG("No Y tiling for legacy addfb\n");
14006                         return -EINVAL;
14007                 }
14008         }
14009
14010         /* Passed in modifier sanity checking. */
14011         switch (mode_cmd->modifier[0]) {
14012         case I915_FORMAT_MOD_Y_TILED:
14013         case I915_FORMAT_MOD_Yf_TILED:
14014                 if (INTEL_INFO(dev)->gen < 9) {
14015                         DRM_DEBUG("Unsupported tiling 0x%llx!\n",
14016                                   mode_cmd->modifier[0]);
14017                         return -EINVAL;
14018                 }
14019         case DRM_FORMAT_MOD_NONE:
14020         case I915_FORMAT_MOD_X_TILED:
14021                 break;
14022         default:
14023                 DRM_DEBUG("Unsupported fb modifier 0x%llx!\n",
14024                           mode_cmd->modifier[0]);
14025                 return -EINVAL;
14026         }
14027
14028         stride_alignment = intel_fb_stride_alignment(dev, mode_cmd->modifier[0],
14029                                                      mode_cmd->pixel_format);
14030         if (mode_cmd->pitches[0] & (stride_alignment - 1)) {
14031                 DRM_DEBUG("pitch (%d) must be at least %u byte aligned\n",
14032                           mode_cmd->pitches[0], stride_alignment);
14033                 return -EINVAL;
14034         }
14035
14036         pitch_limit = intel_fb_pitch_limit(dev, mode_cmd->modifier[0],
14037                                            mode_cmd->pixel_format);
14038         if (mode_cmd->pitches[0] > pitch_limit) {
14039                 DRM_DEBUG("%s pitch (%u) must be at less than %d\n",
14040                           mode_cmd->modifier[0] != DRM_FORMAT_MOD_NONE ?
14041                           "tiled" : "linear",
14042                           mode_cmd->pitches[0], pitch_limit);
14043                 return -EINVAL;
14044         }
14045
14046         if (mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED &&
14047             mode_cmd->pitches[0] != obj->stride) {
14048                 DRM_DEBUG("pitch (%d) must match tiling stride (%d)\n",
14049                           mode_cmd->pitches[0], obj->stride);
14050                 return -EINVAL;
14051         }
14052
14053         /* Reject formats not supported by any plane early. */
14054         switch (mode_cmd->pixel_format) {
14055         case DRM_FORMAT_C8:
14056         case DRM_FORMAT_RGB565:
14057         case DRM_FORMAT_XRGB8888:
14058         case DRM_FORMAT_ARGB8888:
14059                 break;
14060         case DRM_FORMAT_XRGB1555:
14061         case DRM_FORMAT_ARGB1555:
14062                 if (INTEL_INFO(dev)->gen > 3) {
14063                         DRM_DEBUG("unsupported pixel format: %s\n",
14064                                   drm_get_format_name(mode_cmd->pixel_format));
14065                         return -EINVAL;
14066                 }
14067                 break;
14068         case DRM_FORMAT_XBGR8888:
14069         case DRM_FORMAT_ABGR8888:
14070         case DRM_FORMAT_XRGB2101010:
14071         case DRM_FORMAT_ARGB2101010:
14072         case DRM_FORMAT_XBGR2101010:
14073         case DRM_FORMAT_ABGR2101010:
14074                 if (INTEL_INFO(dev)->gen < 4) {
14075                         DRM_DEBUG("unsupported pixel format: %s\n",
14076                                   drm_get_format_name(mode_cmd->pixel_format));
14077                         return -EINVAL;
14078                 }
14079                 break;
14080         case DRM_FORMAT_YUYV:
14081         case DRM_FORMAT_UYVY:
14082         case DRM_FORMAT_YVYU:
14083         case DRM_FORMAT_VYUY:
14084                 if (INTEL_INFO(dev)->gen < 5) {
14085                         DRM_DEBUG("unsupported pixel format: %s\n",
14086                                   drm_get_format_name(mode_cmd->pixel_format));
14087                         return -EINVAL;
14088                 }
14089                 break;
14090         default:
14091                 DRM_DEBUG("unsupported pixel format: %s\n",
14092                           drm_get_format_name(mode_cmd->pixel_format));
14093                 return -EINVAL;
14094         }
14095
14096         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14097         if (mode_cmd->offsets[0] != 0)
14098                 return -EINVAL;
14099
14100         aligned_height = intel_fb_align_height(dev, mode_cmd->height,
14101                                                mode_cmd->pixel_format,
14102                                                mode_cmd->modifier[0]);
14103         /* FIXME drm helper for size checks (especially planar formats)? */
14104         if (obj->base.size < aligned_height * mode_cmd->pitches[0])
14105                 return -EINVAL;
14106
14107         drm_helper_mode_fill_fb_struct(&intel_fb->base, mode_cmd);
14108         intel_fb->obj = obj;
14109         intel_fb->obj->framebuffer_references++;
14110
14111         ret = drm_framebuffer_init(dev, &intel_fb->base, &intel_fb_funcs);
14112         if (ret) {
14113                 DRM_ERROR("framebuffer init failed %d\n", ret);
14114                 return ret;
14115         }
14116
14117         return 0;
14118 }
14119
14120 static struct drm_framebuffer *
14121 intel_user_framebuffer_create(struct drm_device *dev,
14122                               struct drm_file *filp,
14123                               struct drm_mode_fb_cmd2 *mode_cmd)
14124 {
14125         struct drm_i915_gem_object *obj;
14126
14127         obj = to_intel_bo(drm_gem_object_lookup(dev, filp,
14128                                                 mode_cmd->handles[0]));
14129         if (&obj->base == NULL)
14130                 return ERR_PTR(-ENOENT);
14131
14132         return intel_framebuffer_create(dev, mode_cmd, obj);
14133 }
14134
14135 #ifndef CONFIG_DRM_I915_FBDEV
14136 static inline void intel_fbdev_output_poll_changed(struct drm_device *dev)
14137 {
14138 }
14139 #endif
14140
14141 static const struct drm_mode_config_funcs intel_mode_funcs = {
14142         .fb_create = intel_user_framebuffer_create,
14143         .output_poll_changed = intel_fbdev_output_poll_changed,
14144         .atomic_check = intel_atomic_check,
14145         .atomic_commit = intel_atomic_commit,
14146 };
14147
14148 /* Set up chip specific display functions */
14149 static void intel_init_display(struct drm_device *dev)
14150 {
14151         struct drm_i915_private *dev_priv = dev->dev_private;
14152
14153         if (HAS_PCH_SPLIT(dev) || IS_G4X(dev))
14154                 dev_priv->display.find_dpll = g4x_find_best_dpll;
14155         else if (IS_CHERRYVIEW(dev))
14156                 dev_priv->display.find_dpll = chv_find_best_dpll;
14157         else if (IS_VALLEYVIEW(dev))
14158                 dev_priv->display.find_dpll = vlv_find_best_dpll;
14159         else if (IS_PINEVIEW(dev))
14160                 dev_priv->display.find_dpll = pnv_find_best_dpll;
14161         else
14162                 dev_priv->display.find_dpll = i9xx_find_best_dpll;
14163
14164         if (INTEL_INFO(dev)->gen >= 9) {
14165                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14166                 dev_priv->display.get_initial_plane_config =
14167                         skylake_get_initial_plane_config;
14168                 dev_priv->display.crtc_compute_clock =
14169                         haswell_crtc_compute_clock;
14170                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14171                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14172                 dev_priv->display.off = ironlake_crtc_off;
14173                 dev_priv->display.update_primary_plane =
14174                         skylake_update_primary_plane;
14175         } else if (HAS_DDI(dev)) {
14176                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14177                 dev_priv->display.get_initial_plane_config =
14178                         ironlake_get_initial_plane_config;
14179                 dev_priv->display.crtc_compute_clock =
14180                         haswell_crtc_compute_clock;
14181                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14182                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14183                 dev_priv->display.off = ironlake_crtc_off;
14184                 dev_priv->display.update_primary_plane =
14185                         ironlake_update_primary_plane;
14186         } else if (HAS_PCH_SPLIT(dev)) {
14187                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
14188                 dev_priv->display.get_initial_plane_config =
14189                         ironlake_get_initial_plane_config;
14190                 dev_priv->display.crtc_compute_clock =
14191                         ironlake_crtc_compute_clock;
14192                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
14193                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
14194                 dev_priv->display.off = ironlake_crtc_off;
14195                 dev_priv->display.update_primary_plane =
14196                         ironlake_update_primary_plane;
14197         } else if (IS_VALLEYVIEW(dev)) {
14198                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14199                 dev_priv->display.get_initial_plane_config =
14200                         i9xx_get_initial_plane_config;
14201                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14202                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14203                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14204                 dev_priv->display.off = i9xx_crtc_off;
14205                 dev_priv->display.update_primary_plane =
14206                         i9xx_update_primary_plane;
14207         } else {
14208                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14209                 dev_priv->display.get_initial_plane_config =
14210                         i9xx_get_initial_plane_config;
14211                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14212                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14213                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14214                 dev_priv->display.off = i9xx_crtc_off;
14215                 dev_priv->display.update_primary_plane =
14216                         i9xx_update_primary_plane;
14217         }
14218
14219         /* Returns the core display clock speed */
14220         if (IS_SKYLAKE(dev))
14221                 dev_priv->display.get_display_clock_speed =
14222                         skylake_get_display_clock_speed;
14223         else if (IS_BROADWELL(dev))
14224                 dev_priv->display.get_display_clock_speed =
14225                         broadwell_get_display_clock_speed;
14226         else if (IS_HASWELL(dev))
14227                 dev_priv->display.get_display_clock_speed =
14228                         haswell_get_display_clock_speed;
14229         else if (IS_VALLEYVIEW(dev))
14230                 dev_priv->display.get_display_clock_speed =
14231                         valleyview_get_display_clock_speed;
14232         else if (IS_GEN5(dev))
14233                 dev_priv->display.get_display_clock_speed =
14234                         ilk_get_display_clock_speed;
14235         else if (IS_I945G(dev) || IS_BROADWATER(dev) ||
14236                  IS_GEN6(dev) || IS_IVYBRIDGE(dev) || (IS_G33(dev) && !IS_PINEVIEW_M(dev)))
14237                 dev_priv->display.get_display_clock_speed =
14238                         i945_get_display_clock_speed;
14239         else if (IS_I915G(dev))
14240                 dev_priv->display.get_display_clock_speed =
14241                         i915_get_display_clock_speed;
14242         else if (IS_I945GM(dev) || IS_845G(dev))
14243                 dev_priv->display.get_display_clock_speed =
14244                         i9xx_misc_get_display_clock_speed;
14245         else if (IS_PINEVIEW(dev))
14246                 dev_priv->display.get_display_clock_speed =
14247                         pnv_get_display_clock_speed;
14248         else if (IS_I915GM(dev))
14249                 dev_priv->display.get_display_clock_speed =
14250                         i915gm_get_display_clock_speed;
14251         else if (IS_I865G(dev))
14252                 dev_priv->display.get_display_clock_speed =
14253                         i865_get_display_clock_speed;
14254         else if (IS_I85X(dev))
14255                 dev_priv->display.get_display_clock_speed =
14256                         i855_get_display_clock_speed;
14257         else /* 852, 830 */
14258                 dev_priv->display.get_display_clock_speed =
14259                         i830_get_display_clock_speed;
14260
14261         if (IS_GEN5(dev)) {
14262                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
14263         } else if (IS_GEN6(dev)) {
14264                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
14265         } else if (IS_IVYBRIDGE(dev)) {
14266                 /* FIXME: detect B0+ stepping and use auto training */
14267                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
14268         } else if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
14269                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
14270         } else if (IS_VALLEYVIEW(dev)) {
14271                 dev_priv->display.modeset_global_resources =
14272                         valleyview_modeset_global_resources;
14273         } else if (IS_BROXTON(dev)) {
14274                 dev_priv->display.modeset_global_resources =
14275                         broxton_modeset_global_resources;
14276         }
14277
14278         switch (INTEL_INFO(dev)->gen) {
14279         case 2:
14280                 dev_priv->display.queue_flip = intel_gen2_queue_flip;
14281                 break;
14282
14283         case 3:
14284                 dev_priv->display.queue_flip = intel_gen3_queue_flip;
14285                 break;
14286
14287         case 4:
14288         case 5:
14289                 dev_priv->display.queue_flip = intel_gen4_queue_flip;
14290                 break;
14291
14292         case 6:
14293                 dev_priv->display.queue_flip = intel_gen6_queue_flip;
14294                 break;
14295         case 7:
14296         case 8: /* FIXME(BDW): Check that the gen8 RCS flip works. */
14297                 dev_priv->display.queue_flip = intel_gen7_queue_flip;
14298                 break;
14299         case 9:
14300                 /* Drop through - unsupported since execlist only. */
14301         default:
14302                 /* Default just returns -ENODEV to indicate unsupported */
14303                 dev_priv->display.queue_flip = intel_default_queue_flip;
14304         }
14305
14306         intel_panel_init_backlight_funcs(dev);
14307
14308         mutex_init(&dev_priv->pps_mutex);
14309 }
14310
14311 /*
14312  * Some BIOSes insist on assuming the GPU's pipe A is enabled at suspend,
14313  * resume, or other times.  This quirk makes sure that's the case for
14314  * affected systems.
14315  */
14316 static void quirk_pipea_force(struct drm_device *dev)
14317 {
14318         struct drm_i915_private *dev_priv = dev->dev_private;
14319
14320         dev_priv->quirks |= QUIRK_PIPEA_FORCE;
14321         DRM_INFO("applying pipe a force quirk\n");
14322 }
14323
14324 static void quirk_pipeb_force(struct drm_device *dev)
14325 {
14326         struct drm_i915_private *dev_priv = dev->dev_private;
14327
14328         dev_priv->quirks |= QUIRK_PIPEB_FORCE;
14329         DRM_INFO("applying pipe b force quirk\n");
14330 }
14331
14332 /*
14333  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
14334  */
14335 static void quirk_ssc_force_disable(struct drm_device *dev)
14336 {
14337         struct drm_i915_private *dev_priv = dev->dev_private;
14338         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
14339         DRM_INFO("applying lvds SSC disable quirk\n");
14340 }
14341
14342 /*
14343  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
14344  * brightness value
14345  */
14346 static void quirk_invert_brightness(struct drm_device *dev)
14347 {
14348         struct drm_i915_private *dev_priv = dev->dev_private;
14349         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
14350         DRM_INFO("applying inverted panel brightness quirk\n");
14351 }
14352
14353 /* Some VBT's incorrectly indicate no backlight is present */
14354 static void quirk_backlight_present(struct drm_device *dev)
14355 {
14356         struct drm_i915_private *dev_priv = dev->dev_private;
14357         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
14358         DRM_INFO("applying backlight present quirk\n");
14359 }
14360
14361 struct intel_quirk {
14362         int device;
14363         int subsystem_vendor;
14364         int subsystem_device;
14365         void (*hook)(struct drm_device *dev);
14366 };
14367
14368 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
14369 struct intel_dmi_quirk {
14370         void (*hook)(struct drm_device *dev);
14371         const struct dmi_system_id (*dmi_id_list)[];
14372 };
14373
14374 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
14375 {
14376         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
14377         return 1;
14378 }
14379
14380 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
14381         {
14382                 .dmi_id_list = &(const struct dmi_system_id[]) {
14383                         {
14384                                 .callback = intel_dmi_reverse_brightness,
14385                                 .ident = "NCR Corporation",
14386                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
14387                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
14388                                 },
14389                         },
14390                         { }  /* terminating entry */
14391                 },
14392                 .hook = quirk_invert_brightness,
14393         },
14394 };
14395
14396 static struct intel_quirk intel_quirks[] = {
14397         /* HP Mini needs pipe A force quirk (LP: #322104) */
14398         { 0x27ae, 0x103c, 0x361a, quirk_pipea_force },
14399
14400         /* Toshiba Protege R-205, S-209 needs pipe A force quirk */
14401         { 0x2592, 0x1179, 0x0001, quirk_pipea_force },
14402
14403         /* ThinkPad T60 needs pipe A force quirk (bug #16494) */
14404         { 0x2782, 0x17aa, 0x201a, quirk_pipea_force },
14405
14406         /* 830 needs to leave pipe A & dpll A up */
14407         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipea_force },
14408
14409         /* 830 needs to leave pipe B & dpll B up */
14410         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipeb_force },
14411
14412         /* Lenovo U160 cannot use SSC on LVDS */
14413         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
14414
14415         /* Sony Vaio Y cannot use SSC on LVDS */
14416         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
14417
14418         /* Acer Aspire 5734Z must invert backlight brightness */
14419         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
14420
14421         /* Acer/eMachines G725 */
14422         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
14423
14424         /* Acer/eMachines e725 */
14425         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
14426
14427         /* Acer/Packard Bell NCL20 */
14428         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
14429
14430         /* Acer Aspire 4736Z */
14431         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
14432
14433         /* Acer Aspire 5336 */
14434         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
14435
14436         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
14437         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
14438
14439         /* Acer C720 Chromebook (Core i3 4005U) */
14440         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
14441
14442         /* Apple Macbook 2,1 (Core 2 T7400) */
14443         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
14444
14445         /* Toshiba CB35 Chromebook (Celeron 2955U) */
14446         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
14447
14448         /* HP Chromebook 14 (Celeron 2955U) */
14449         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
14450
14451         /* Dell Chromebook 11 */
14452         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
14453 };
14454
14455 static void intel_init_quirks(struct drm_device *dev)
14456 {
14457         struct pci_dev *d = dev->pdev;
14458         int i;
14459
14460         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
14461                 struct intel_quirk *q = &intel_quirks[i];
14462
14463                 if (d->device == q->device &&
14464                     (d->subsystem_vendor == q->subsystem_vendor ||
14465                      q->subsystem_vendor == PCI_ANY_ID) &&
14466                     (d->subsystem_device == q->subsystem_device ||
14467                      q->subsystem_device == PCI_ANY_ID))
14468                         q->hook(dev);
14469         }
14470         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
14471                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
14472                         intel_dmi_quirks[i].hook(dev);
14473         }
14474 }
14475
14476 /* Disable the VGA plane that we never use */
14477 static void i915_disable_vga(struct drm_device *dev)
14478 {
14479         struct drm_i915_private *dev_priv = dev->dev_private;
14480         u8 sr1;
14481         u32 vga_reg = i915_vgacntrl_reg(dev);
14482
14483         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
14484         vga_get_uninterruptible(dev->pdev, VGA_RSRC_LEGACY_IO);
14485         outb(SR01, VGA_SR_INDEX);
14486         sr1 = inb(VGA_SR_DATA);
14487         outb(sr1 | 1<<5, VGA_SR_DATA);
14488         vga_put(dev->pdev, VGA_RSRC_LEGACY_IO);
14489         udelay(300);
14490
14491         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
14492         POSTING_READ(vga_reg);
14493 }
14494
14495 void intel_modeset_init_hw(struct drm_device *dev)
14496 {
14497         intel_prepare_ddi(dev);
14498
14499         if (IS_VALLEYVIEW(dev))
14500                 vlv_update_cdclk(dev);
14501
14502         intel_init_clock_gating(dev);
14503
14504         intel_enable_gt_powersave(dev);
14505 }
14506
14507 void intel_modeset_init(struct drm_device *dev)
14508 {
14509         struct drm_i915_private *dev_priv = dev->dev_private;
14510         int sprite, ret;
14511         enum pipe pipe;
14512         struct intel_crtc *crtc;
14513
14514         drm_mode_config_init(dev);
14515
14516         dev->mode_config.min_width = 0;
14517         dev->mode_config.min_height = 0;
14518
14519         dev->mode_config.preferred_depth = 24;
14520         dev->mode_config.prefer_shadow = 1;
14521
14522         dev->mode_config.allow_fb_modifiers = true;
14523
14524         dev->mode_config.funcs = &intel_mode_funcs;
14525
14526         intel_init_quirks(dev);
14527
14528         intel_init_pm(dev);
14529
14530         if (INTEL_INFO(dev)->num_pipes == 0)
14531                 return;
14532
14533         intel_init_display(dev);
14534         intel_init_audio(dev);
14535
14536         if (IS_GEN2(dev)) {
14537                 dev->mode_config.max_width = 2048;
14538                 dev->mode_config.max_height = 2048;
14539         } else if (IS_GEN3(dev)) {
14540                 dev->mode_config.max_width = 4096;
14541                 dev->mode_config.max_height = 4096;
14542         } else {
14543                 dev->mode_config.max_width = 8192;
14544                 dev->mode_config.max_height = 8192;
14545         }
14546
14547         if (IS_845G(dev) || IS_I865G(dev)) {
14548                 dev->mode_config.cursor_width = IS_845G(dev) ? 64 : 512;
14549                 dev->mode_config.cursor_height = 1023;
14550         } else if (IS_GEN2(dev)) {
14551                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
14552                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
14553         } else {
14554                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
14555                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
14556         }
14557
14558         dev->mode_config.fb_base = dev_priv->gtt.mappable_base;
14559
14560         DRM_DEBUG_KMS("%d display pipe%s available.\n",
14561                       INTEL_INFO(dev)->num_pipes,
14562                       INTEL_INFO(dev)->num_pipes > 1 ? "s" : "");
14563
14564         for_each_pipe(dev_priv, pipe) {
14565                 intel_crtc_init(dev, pipe);
14566                 for_each_sprite(dev_priv, pipe, sprite) {
14567                         ret = intel_plane_init(dev, pipe, sprite);
14568                         if (ret)
14569                                 DRM_DEBUG_KMS("pipe %c sprite %c init failed: %d\n",
14570                                               pipe_name(pipe), sprite_name(pipe, sprite), ret);
14571                 }
14572         }
14573
14574         intel_init_dpio(dev);
14575
14576         intel_shared_dpll_init(dev);
14577
14578         /* Just disable it once at startup */
14579         i915_disable_vga(dev);
14580         intel_setup_outputs(dev);
14581
14582         /* Just in case the BIOS is doing something questionable. */
14583         intel_fbc_disable(dev);
14584
14585         drm_modeset_lock_all(dev);
14586         intel_modeset_setup_hw_state(dev, false);
14587         drm_modeset_unlock_all(dev);
14588
14589         for_each_intel_crtc(dev, crtc) {
14590                 if (!crtc->active)
14591                         continue;
14592
14593                 /*
14594                  * Note that reserving the BIOS fb up front prevents us
14595                  * from stuffing other stolen allocations like the ring
14596                  * on top.  This prevents some ugliness at boot time, and
14597                  * can even allow for smooth boot transitions if the BIOS
14598                  * fb is large enough for the active pipe configuration.
14599                  */
14600                 if (dev_priv->display.get_initial_plane_config) {
14601                         dev_priv->display.get_initial_plane_config(crtc,
14602                                                            &crtc->plane_config);
14603                         /*
14604                          * If the fb is shared between multiple heads, we'll
14605                          * just get the first one.
14606                          */
14607                         intel_find_initial_plane_obj(crtc, &crtc->plane_config);
14608                 }
14609         }
14610 }
14611
14612 static void intel_enable_pipe_a(struct drm_device *dev)
14613 {
14614         struct intel_connector *connector;
14615         struct drm_connector *crt = NULL;
14616         struct intel_load_detect_pipe load_detect_temp;
14617         struct drm_modeset_acquire_ctx *ctx = dev->mode_config.acquire_ctx;
14618
14619         /* We can't just switch on the pipe A, we need to set things up with a
14620          * proper mode and output configuration. As a gross hack, enable pipe A
14621          * by enabling the load detect pipe once. */
14622         for_each_intel_connector(dev, connector) {
14623                 if (connector->encoder->type == INTEL_OUTPUT_ANALOG) {
14624                         crt = &connector->base;
14625                         break;
14626                 }
14627         }
14628
14629         if (!crt)
14630                 return;
14631
14632         if (intel_get_load_detect_pipe(crt, NULL, &load_detect_temp, ctx))
14633                 intel_release_load_detect_pipe(crt, &load_detect_temp, ctx);
14634 }
14635
14636 static bool
14637 intel_check_plane_mapping(struct intel_crtc *crtc)
14638 {
14639         struct drm_device *dev = crtc->base.dev;
14640         struct drm_i915_private *dev_priv = dev->dev_private;
14641         u32 reg, val;
14642
14643         if (INTEL_INFO(dev)->num_pipes == 1)
14644                 return true;
14645
14646         reg = DSPCNTR(!crtc->plane);
14647         val = I915_READ(reg);
14648
14649         if ((val & DISPLAY_PLANE_ENABLE) &&
14650             (!!(val & DISPPLANE_SEL_PIPE_MASK) == crtc->pipe))
14651                 return false;
14652
14653         return true;
14654 }
14655
14656 static void intel_sanitize_crtc(struct intel_crtc *crtc)
14657 {
14658         struct drm_device *dev = crtc->base.dev;
14659         struct drm_i915_private *dev_priv = dev->dev_private;
14660         u32 reg;
14661
14662         /* Clear any frame start delays used for debugging left by the BIOS */
14663         reg = PIPECONF(crtc->config->cpu_transcoder);
14664         I915_WRITE(reg, I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
14665
14666         /* restore vblank interrupts to correct state */
14667         drm_crtc_vblank_reset(&crtc->base);
14668         if (crtc->active) {
14669                 update_scanline_offset(crtc);
14670                 drm_crtc_vblank_on(&crtc->base);
14671         }
14672
14673         /* We need to sanitize the plane -> pipe mapping first because this will
14674          * disable the crtc (and hence change the state) if it is wrong. Note
14675          * that gen4+ has a fixed plane -> pipe mapping.  */
14676         if (INTEL_INFO(dev)->gen < 4 && !intel_check_plane_mapping(crtc)) {
14677                 struct intel_connector *connector;
14678                 bool plane;
14679
14680                 DRM_DEBUG_KMS("[CRTC:%d] wrong plane connection detected!\n",
14681                               crtc->base.base.id);
14682
14683                 /* Pipe has the wrong plane attached and the plane is active.
14684                  * Temporarily change the plane mapping and disable everything
14685                  * ...  */
14686                 plane = crtc->plane;
14687                 crtc->plane = !plane;
14688                 crtc->primary_enabled = true;
14689                 dev_priv->display.crtc_disable(&crtc->base);
14690                 crtc->plane = plane;
14691
14692                 /* ... and break all links. */
14693                 for_each_intel_connector(dev, connector) {
14694                         if (connector->encoder->base.crtc != &crtc->base)
14695                                 continue;
14696
14697                         connector->base.dpms = DRM_MODE_DPMS_OFF;
14698                         connector->base.encoder = NULL;
14699                 }
14700                 /* multiple connectors may have the same encoder:
14701                  *  handle them and break crtc link separately */
14702                 for_each_intel_connector(dev, connector)
14703                         if (connector->encoder->base.crtc == &crtc->base) {
14704                                 connector->encoder->base.crtc = NULL;
14705                                 connector->encoder->connectors_active = false;
14706                         }
14707
14708                 WARN_ON(crtc->active);
14709                 crtc->base.state->enable = false;
14710                 crtc->base.enabled = false;
14711         }
14712
14713         if (dev_priv->quirks & QUIRK_PIPEA_FORCE &&
14714             crtc->pipe == PIPE_A && !crtc->active) {
14715                 /* BIOS forgot to enable pipe A, this mostly happens after
14716                  * resume. Force-enable the pipe to fix this, the update_dpms
14717                  * call below we restore the pipe to the right state, but leave
14718                  * the required bits on. */
14719                 intel_enable_pipe_a(dev);
14720         }
14721
14722         /* Adjust the state of the output pipe according to whether we
14723          * have active connectors/encoders. */
14724         intel_crtc_update_dpms(&crtc->base);
14725
14726         if (crtc->active != crtc->base.state->enable) {
14727                 struct intel_encoder *encoder;
14728
14729                 /* This can happen either due to bugs in the get_hw_state
14730                  * functions or because the pipe is force-enabled due to the
14731                  * pipe A quirk. */
14732                 DRM_DEBUG_KMS("[CRTC:%d] hw state adjusted, was %s, now %s\n",
14733                               crtc->base.base.id,
14734                               crtc->base.state->enable ? "enabled" : "disabled",
14735                               crtc->active ? "enabled" : "disabled");
14736
14737                 crtc->base.state->enable = crtc->active;
14738                 crtc->base.enabled = crtc->active;
14739
14740                 /* Because we only establish the connector -> encoder ->
14741                  * crtc links if something is active, this means the
14742                  * crtc is now deactivated. Break the links. connector
14743                  * -> encoder links are only establish when things are
14744                  *  actually up, hence no need to break them. */
14745                 WARN_ON(crtc->active);
14746
14747                 for_each_encoder_on_crtc(dev, &crtc->base, encoder) {
14748                         WARN_ON(encoder->connectors_active);
14749                         encoder->base.crtc = NULL;
14750                 }
14751         }
14752
14753         if (crtc->active || HAS_GMCH_DISPLAY(dev)) {
14754                 /*
14755                  * We start out with underrun reporting disabled to avoid races.
14756                  * For correct bookkeeping mark this on active crtcs.
14757                  *
14758                  * Also on gmch platforms we dont have any hardware bits to
14759                  * disable the underrun reporting. Which means we need to start
14760                  * out with underrun reporting disabled also on inactive pipes,
14761                  * since otherwise we'll complain about the garbage we read when
14762                  * e.g. coming up after runtime pm.
14763                  *
14764                  * No protection against concurrent access is required - at
14765                  * worst a fifo underrun happens which also sets this to false.
14766                  */
14767                 crtc->cpu_fifo_underrun_disabled = true;
14768                 crtc->pch_fifo_underrun_disabled = true;
14769         }
14770 }
14771
14772 static void intel_sanitize_encoder(struct intel_encoder *encoder)
14773 {
14774         struct intel_connector *connector;
14775         struct drm_device *dev = encoder->base.dev;
14776
14777         /* We need to check both for a crtc link (meaning that the
14778          * encoder is active and trying to read from a pipe) and the
14779          * pipe itself being active. */
14780         bool has_active_crtc = encoder->base.crtc &&
14781                 to_intel_crtc(encoder->base.crtc)->active;
14782
14783         if (encoder->connectors_active && !has_active_crtc) {
14784                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
14785                               encoder->base.base.id,
14786                               encoder->base.name);
14787
14788                 /* Connector is active, but has no active pipe. This is
14789                  * fallout from our resume register restoring. Disable
14790                  * the encoder manually again. */
14791                 if (encoder->base.crtc) {
14792                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
14793                                       encoder->base.base.id,
14794                                       encoder->base.name);
14795                         encoder->disable(encoder);
14796                         if (encoder->post_disable)
14797                                 encoder->post_disable(encoder);
14798                 }
14799                 encoder->base.crtc = NULL;
14800                 encoder->connectors_active = false;
14801
14802                 /* Inconsistent output/port/pipe state happens presumably due to
14803                  * a bug in one of the get_hw_state functions. Or someplace else
14804                  * in our code, like the register restore mess on resume. Clamp
14805                  * things to off as a safer default. */
14806                 for_each_intel_connector(dev, connector) {
14807                         if (connector->encoder != encoder)
14808                                 continue;
14809                         connector->base.dpms = DRM_MODE_DPMS_OFF;
14810                         connector->base.encoder = NULL;
14811                 }
14812         }
14813         /* Enabled encoders without active connectors will be fixed in
14814          * the crtc fixup. */
14815 }
14816
14817 void i915_redisable_vga_power_on(struct drm_device *dev)
14818 {
14819         struct drm_i915_private *dev_priv = dev->dev_private;
14820         u32 vga_reg = i915_vgacntrl_reg(dev);
14821
14822         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
14823                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
14824                 i915_disable_vga(dev);
14825         }
14826 }
14827
14828 void i915_redisable_vga(struct drm_device *dev)
14829 {
14830         struct drm_i915_private *dev_priv = dev->dev_private;
14831
14832         /* This function can be called both from intel_modeset_setup_hw_state or
14833          * at a very early point in our resume sequence, where the power well
14834          * structures are not yet restored. Since this function is at a very
14835          * paranoid "someone might have enabled VGA while we were not looking"
14836          * level, just check if the power well is enabled instead of trying to
14837          * follow the "don't touch the power well if we don't need it" policy
14838          * the rest of the driver uses. */
14839         if (!intel_display_power_is_enabled(dev_priv, POWER_DOMAIN_VGA))
14840                 return;
14841
14842         i915_redisable_vga_power_on(dev);
14843 }
14844
14845 static bool primary_get_hw_state(struct intel_crtc *crtc)
14846 {
14847         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
14848
14849         if (!crtc->active)
14850                 return false;
14851
14852         return I915_READ(DSPCNTR(crtc->plane)) & DISPLAY_PLANE_ENABLE;
14853 }
14854
14855 static void intel_modeset_readout_hw_state(struct drm_device *dev)
14856 {
14857         struct drm_i915_private *dev_priv = dev->dev_private;
14858         enum pipe pipe;
14859         struct intel_crtc *crtc;
14860         struct intel_encoder *encoder;
14861         struct intel_connector *connector;
14862         int i;
14863
14864         for_each_intel_crtc(dev, crtc) {
14865                 memset(crtc->config, 0, sizeof(*crtc->config));
14866
14867                 crtc->config->quirks |= PIPE_CONFIG_QUIRK_INHERITED_MODE;
14868
14869                 crtc->active = dev_priv->display.get_pipe_config(crtc,
14870                                                                  crtc->config);
14871
14872                 crtc->base.state->enable = crtc->active;
14873                 crtc->base.enabled = crtc->active;
14874                 crtc->primary_enabled = primary_get_hw_state(crtc);
14875
14876                 DRM_DEBUG_KMS("[CRTC:%d] hw state readout: %s\n",
14877                               crtc->base.base.id,
14878                               crtc->active ? "enabled" : "disabled");
14879         }
14880
14881         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
14882                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
14883
14884                 pll->on = pll->get_hw_state(dev_priv, pll,
14885                                             &pll->config.hw_state);
14886                 pll->active = 0;
14887                 pll->config.crtc_mask = 0;
14888                 for_each_intel_crtc(dev, crtc) {
14889                         if (crtc->active && intel_crtc_to_shared_dpll(crtc) == pll) {
14890                                 pll->active++;
14891                                 pll->config.crtc_mask |= 1 << crtc->pipe;
14892                         }
14893                 }
14894
14895                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
14896                               pll->name, pll->config.crtc_mask, pll->on);
14897
14898                 if (pll->config.crtc_mask)
14899                         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
14900         }
14901
14902         for_each_intel_encoder(dev, encoder) {
14903                 pipe = 0;
14904
14905                 if (encoder->get_hw_state(encoder, &pipe)) {
14906                         crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
14907                         encoder->base.crtc = &crtc->base;
14908                         encoder->get_config(encoder, crtc->config);
14909                 } else {
14910                         encoder->base.crtc = NULL;
14911                 }
14912
14913                 encoder->connectors_active = false;
14914                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
14915                               encoder->base.base.id,
14916                               encoder->base.name,
14917                               encoder->base.crtc ? "enabled" : "disabled",
14918                               pipe_name(pipe));
14919         }
14920
14921         for_each_intel_connector(dev, connector) {
14922                 if (connector->get_hw_state(connector)) {
14923                         connector->base.dpms = DRM_MODE_DPMS_ON;
14924                         connector->encoder->connectors_active = true;
14925                         connector->base.encoder = &connector->encoder->base;
14926                 } else {
14927                         connector->base.dpms = DRM_MODE_DPMS_OFF;
14928                         connector->base.encoder = NULL;
14929                 }
14930                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
14931                               connector->base.base.id,
14932                               connector->base.name,
14933                               connector->base.encoder ? "enabled" : "disabled");
14934         }
14935 }
14936
14937 /* Scan out the current hw modeset state, sanitizes it and maps it into the drm
14938  * and i915 state tracking structures. */
14939 void intel_modeset_setup_hw_state(struct drm_device *dev,
14940                                   bool force_restore)
14941 {
14942         struct drm_i915_private *dev_priv = dev->dev_private;
14943         enum pipe pipe;
14944         struct intel_crtc *crtc;
14945         struct intel_encoder *encoder;
14946         int i;
14947
14948         intel_modeset_readout_hw_state(dev);
14949
14950         /*
14951          * Now that we have the config, copy it to each CRTC struct
14952          * Note that this could go away if we move to using crtc_config
14953          * checking everywhere.
14954          */
14955         for_each_intel_crtc(dev, crtc) {
14956                 if (crtc->active && i915.fastboot) {
14957                         intel_mode_from_pipe_config(&crtc->base.mode,
14958                                                     crtc->config);
14959                         DRM_DEBUG_KMS("[CRTC:%d] found active mode: ",
14960                                       crtc->base.base.id);
14961                         drm_mode_debug_printmodeline(&crtc->base.mode);
14962                 }
14963         }
14964
14965         /* HW state is read out, now we need to sanitize this mess. */
14966         for_each_intel_encoder(dev, encoder) {
14967                 intel_sanitize_encoder(encoder);
14968         }
14969
14970         for_each_pipe(dev_priv, pipe) {
14971                 crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
14972                 intel_sanitize_crtc(crtc);
14973                 intel_dump_pipe_config(crtc, crtc->config,
14974                                        "[setup_hw_state]");
14975         }
14976
14977         intel_modeset_update_connector_atomic_state(dev);
14978
14979         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
14980                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
14981
14982                 if (!pll->on || pll->active)
14983                         continue;
14984
14985                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
14986
14987                 pll->disable(dev_priv, pll);
14988                 pll->on = false;
14989         }
14990
14991         if (IS_GEN9(dev))
14992                 skl_wm_get_hw_state(dev);
14993         else if (HAS_PCH_SPLIT(dev))
14994                 ilk_wm_get_hw_state(dev);
14995
14996         if (force_restore) {
14997                 i915_redisable_vga(dev);
14998
14999                 /*
15000                  * We need to use raw interfaces for restoring state to avoid
15001                  * checking (bogus) intermediate states.
15002                  */
15003                 for_each_pipe(dev_priv, pipe) {
15004                         struct drm_crtc *crtc =
15005                                 dev_priv->pipe_to_crtc_mapping[pipe];
15006
15007                         intel_crtc_restore_mode(crtc);
15008                 }
15009         } else {
15010                 intel_modeset_update_staged_output_state(dev);
15011         }
15012
15013         intel_modeset_check_state(dev);
15014 }
15015
15016 void intel_modeset_gem_init(struct drm_device *dev)
15017 {
15018         struct drm_i915_private *dev_priv = dev->dev_private;
15019         struct drm_crtc *c;
15020         struct drm_i915_gem_object *obj;
15021         int ret;
15022
15023         mutex_lock(&dev->struct_mutex);
15024         intel_init_gt_powersave(dev);
15025         mutex_unlock(&dev->struct_mutex);
15026
15027         /*
15028          * There may be no VBT; and if the BIOS enabled SSC we can
15029          * just keep using it to avoid unnecessary flicker.  Whereas if the
15030          * BIOS isn't using it, don't assume it will work even if the VBT
15031          * indicates as much.
15032          */
15033         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
15034                 dev_priv->vbt.lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
15035                                                 DREF_SSC1_ENABLE);
15036
15037         intel_modeset_init_hw(dev);
15038
15039         intel_setup_overlay(dev);
15040
15041         /*
15042          * Make sure any fbs we allocated at startup are properly
15043          * pinned & fenced.  When we do the allocation it's too early
15044          * for this.
15045          */
15046         for_each_crtc(dev, c) {
15047                 obj = intel_fb_obj(c->primary->fb);
15048                 if (obj == NULL)
15049                         continue;
15050
15051                 mutex_lock(&dev->struct_mutex);
15052                 ret = intel_pin_and_fence_fb_obj(c->primary,
15053                                                  c->primary->fb,
15054                                                  c->primary->state,
15055                                                  NULL);
15056                 mutex_unlock(&dev->struct_mutex);
15057                 if (ret) {
15058                         DRM_ERROR("failed to pin boot fb on pipe %d\n",
15059                                   to_intel_crtc(c)->pipe);
15060                         drm_framebuffer_unreference(c->primary->fb);
15061                         c->primary->fb = NULL;
15062                         update_state_fb(c->primary);
15063                 }
15064         }
15065
15066         intel_backlight_register(dev);
15067 }
15068
15069 void intel_connector_unregister(struct intel_connector *intel_connector)
15070 {
15071         struct drm_connector *connector = &intel_connector->base;
15072
15073         intel_panel_destroy_backlight(connector);
15074         drm_connector_unregister(connector);
15075 }
15076
15077 void intel_modeset_cleanup(struct drm_device *dev)
15078 {
15079         struct drm_i915_private *dev_priv = dev->dev_private;
15080         struct drm_connector *connector;
15081
15082         intel_disable_gt_powersave(dev);
15083
15084         intel_backlight_unregister(dev);
15085
15086         /*
15087          * Interrupts and polling as the first thing to avoid creating havoc.
15088          * Too much stuff here (turning of connectors, ...) would
15089          * experience fancy races otherwise.
15090          */
15091         intel_irq_uninstall(dev_priv);
15092
15093         /*
15094          * Due to the hpd irq storm handling the hotplug work can re-arm the
15095          * poll handlers. Hence disable polling after hpd handling is shut down.
15096          */
15097         drm_kms_helper_poll_fini(dev);
15098
15099         mutex_lock(&dev->struct_mutex);
15100
15101         intel_unregister_dsm_handler();
15102
15103         intel_fbc_disable(dev);
15104
15105         mutex_unlock(&dev->struct_mutex);
15106
15107         /* flush any delayed tasks or pending work */
15108         flush_scheduled_work();
15109
15110         /* destroy the backlight and sysfs files before encoders/connectors */
15111         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
15112                 struct intel_connector *intel_connector;
15113
15114                 intel_connector = to_intel_connector(connector);
15115                 intel_connector->unregister(intel_connector);
15116         }
15117
15118         drm_mode_config_cleanup(dev);
15119
15120         intel_cleanup_overlay(dev);
15121
15122         mutex_lock(&dev->struct_mutex);
15123         intel_cleanup_gt_powersave(dev);
15124         mutex_unlock(&dev->struct_mutex);
15125 }
15126
15127 /*
15128  * Return which encoder is currently attached for connector.
15129  */
15130 struct drm_encoder *intel_best_encoder(struct drm_connector *connector)
15131 {
15132         return &intel_attached_encoder(connector)->base;
15133 }
15134
15135 void intel_connector_attach_encoder(struct intel_connector *connector,
15136                                     struct intel_encoder *encoder)
15137 {
15138         connector->encoder = encoder;
15139         drm_mode_connector_attach_encoder(&connector->base,
15140                                           &encoder->base);
15141 }
15142
15143 /*
15144  * set vga decode state - true == enable VGA decode
15145  */
15146 int intel_modeset_vga_set_state(struct drm_device *dev, bool state)
15147 {
15148         struct drm_i915_private *dev_priv = dev->dev_private;
15149         unsigned reg = INTEL_INFO(dev)->gen >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
15150         u16 gmch_ctrl;
15151
15152         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
15153                 DRM_ERROR("failed to read control word\n");
15154                 return -EIO;
15155         }
15156
15157         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
15158                 return 0;
15159
15160         if (state)
15161                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
15162         else
15163                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
15164
15165         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
15166                 DRM_ERROR("failed to write control word\n");
15167                 return -EIO;
15168         }
15169
15170         return 0;
15171 }
15172
15173 struct intel_display_error_state {
15174
15175         u32 power_well_driver;
15176
15177         int num_transcoders;
15178
15179         struct intel_cursor_error_state {
15180                 u32 control;
15181                 u32 position;
15182                 u32 base;
15183                 u32 size;
15184         } cursor[I915_MAX_PIPES];
15185
15186         struct intel_pipe_error_state {
15187                 bool power_domain_on;
15188                 u32 source;
15189                 u32 stat;
15190         } pipe[I915_MAX_PIPES];
15191
15192         struct intel_plane_error_state {
15193                 u32 control;
15194                 u32 stride;
15195                 u32 size;
15196                 u32 pos;
15197                 u32 addr;
15198                 u32 surface;
15199                 u32 tile_offset;
15200         } plane[I915_MAX_PIPES];
15201
15202         struct intel_transcoder_error_state {
15203                 bool power_domain_on;
15204                 enum transcoder cpu_transcoder;
15205
15206                 u32 conf;
15207
15208                 u32 htotal;
15209                 u32 hblank;
15210                 u32 hsync;
15211                 u32 vtotal;
15212                 u32 vblank;
15213                 u32 vsync;
15214         } transcoder[4];
15215 };
15216
15217 struct intel_display_error_state *
15218 intel_display_capture_error_state(struct drm_device *dev)
15219 {
15220         struct drm_i915_private *dev_priv = dev->dev_private;
15221         struct intel_display_error_state *error;
15222         int transcoders[] = {
15223                 TRANSCODER_A,
15224                 TRANSCODER_B,
15225                 TRANSCODER_C,
15226                 TRANSCODER_EDP,
15227         };
15228         int i;
15229
15230         if (INTEL_INFO(dev)->num_pipes == 0)
15231                 return NULL;
15232
15233         error = kzalloc(sizeof(*error), GFP_ATOMIC);
15234         if (error == NULL)
15235                 return NULL;
15236
15237         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
15238                 error->power_well_driver = I915_READ(HSW_PWR_WELL_DRIVER);
15239
15240         for_each_pipe(dev_priv, i) {
15241                 error->pipe[i].power_domain_on =
15242                         __intel_display_power_is_enabled(dev_priv,
15243                                                          POWER_DOMAIN_PIPE(i));
15244                 if (!error->pipe[i].power_domain_on)
15245                         continue;
15246
15247                 error->cursor[i].control = I915_READ(CURCNTR(i));
15248                 error->cursor[i].position = I915_READ(CURPOS(i));
15249                 error->cursor[i].base = I915_READ(CURBASE(i));
15250
15251                 error->plane[i].control = I915_READ(DSPCNTR(i));
15252                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
15253                 if (INTEL_INFO(dev)->gen <= 3) {
15254                         error->plane[i].size = I915_READ(DSPSIZE(i));
15255                         error->plane[i].pos = I915_READ(DSPPOS(i));
15256                 }
15257                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
15258                         error->plane[i].addr = I915_READ(DSPADDR(i));
15259                 if (INTEL_INFO(dev)->gen >= 4) {
15260                         error->plane[i].surface = I915_READ(DSPSURF(i));
15261                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
15262                 }
15263
15264                 error->pipe[i].source = I915_READ(PIPESRC(i));
15265
15266                 if (HAS_GMCH_DISPLAY(dev))
15267                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
15268         }
15269
15270         error->num_transcoders = INTEL_INFO(dev)->num_pipes;
15271         if (HAS_DDI(dev_priv->dev))
15272                 error->num_transcoders++; /* Account for eDP. */
15273
15274         for (i = 0; i < error->num_transcoders; i++) {
15275                 enum transcoder cpu_transcoder = transcoders[i];
15276
15277                 error->transcoder[i].power_domain_on =
15278                         __intel_display_power_is_enabled(dev_priv,
15279                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
15280                 if (!error->transcoder[i].power_domain_on)
15281                         continue;
15282
15283                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
15284
15285                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
15286                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
15287                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
15288                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
15289                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
15290                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
15291                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
15292         }
15293
15294         return error;
15295 }
15296
15297 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
15298
15299 void
15300 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
15301                                 struct drm_device *dev,
15302                                 struct intel_display_error_state *error)
15303 {
15304         struct drm_i915_private *dev_priv = dev->dev_private;
15305         int i;
15306
15307         if (!error)
15308                 return;
15309
15310         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev)->num_pipes);
15311         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
15312                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
15313                            error->power_well_driver);
15314         for_each_pipe(dev_priv, i) {
15315                 err_printf(m, "Pipe [%d]:\n", i);
15316                 err_printf(m, "  Power: %s\n",
15317                            error->pipe[i].power_domain_on ? "on" : "off");
15318                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
15319                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
15320
15321                 err_printf(m, "Plane [%d]:\n", i);
15322                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
15323                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
15324                 if (INTEL_INFO(dev)->gen <= 3) {
15325                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
15326                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
15327                 }
15328                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
15329                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
15330                 if (INTEL_INFO(dev)->gen >= 4) {
15331                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
15332                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
15333                 }
15334
15335                 err_printf(m, "Cursor [%d]:\n", i);
15336                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
15337                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
15338                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
15339         }
15340
15341         for (i = 0; i < error->num_transcoders; i++) {
15342                 err_printf(m, "CPU transcoder: %c\n",
15343                            transcoder_name(error->transcoder[i].cpu_transcoder));
15344                 err_printf(m, "  Power: %s\n",
15345                            error->transcoder[i].power_domain_on ? "on" : "off");
15346                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
15347                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
15348                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
15349                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
15350                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
15351                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
15352                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
15353         }
15354 }
15355
15356 void intel_modeset_preclose(struct drm_device *dev, struct drm_file *file)
15357 {
15358         struct intel_crtc *crtc;
15359
15360         for_each_intel_crtc(dev, crtc) {
15361                 struct intel_unpin_work *work;
15362
15363                 spin_lock_irq(&dev->event_lock);
15364
15365                 work = crtc->unpin_work;
15366
15367                 if (work && work->event &&
15368                     work->event->base.file_priv == file) {
15369                         kfree(work->event);
15370                         work->event = NULL;
15371                 }
15372
15373                 spin_unlock_irq(&dev->event_lock);
15374         }
15375 }