drm/i915/bxt: fix panel fitter setup in crtc disable/enable
[linux-drm-fsl-dcu.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
109 static struct intel_encoder *intel_find_encoder(struct intel_connector *connector, int pipe)
110 {
111         if (!connector->mst_port)
112                 return connector->encoder;
113         else
114                 return &connector->mst_port->mst_encoders[pipe]->base;
115 }
116
117 typedef struct {
118         int     min, max;
119 } intel_range_t;
120
121 typedef struct {
122         int     dot_limit;
123         int     p2_slow, p2_fast;
124 } intel_p2_t;
125
126 typedef struct intel_limit intel_limit_t;
127 struct intel_limit {
128         intel_range_t   dot, vco, n, m, m1, m2, p, p1;
129         intel_p2_t          p2;
130 };
131
132 int
133 intel_pch_rawclk(struct drm_device *dev)
134 {
135         struct drm_i915_private *dev_priv = dev->dev_private;
136
137         WARN_ON(!HAS_PCH_SPLIT(dev));
138
139         return I915_READ(PCH_RAWCLK_FREQ) & RAWCLK_FREQ_MASK;
140 }
141
142 static inline u32 /* units of 100MHz */
143 intel_fdi_link_freq(struct drm_device *dev)
144 {
145         if (IS_GEN5(dev)) {
146                 struct drm_i915_private *dev_priv = dev->dev_private;
147                 return (I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK) + 2;
148         } else
149                 return 27;
150 }
151
152 static const intel_limit_t intel_limits_i8xx_dac = {
153         .dot = { .min = 25000, .max = 350000 },
154         .vco = { .min = 908000, .max = 1512000 },
155         .n = { .min = 2, .max = 16 },
156         .m = { .min = 96, .max = 140 },
157         .m1 = { .min = 18, .max = 26 },
158         .m2 = { .min = 6, .max = 16 },
159         .p = { .min = 4, .max = 128 },
160         .p1 = { .min = 2, .max = 33 },
161         .p2 = { .dot_limit = 165000,
162                 .p2_slow = 4, .p2_fast = 2 },
163 };
164
165 static const intel_limit_t intel_limits_i8xx_dvo = {
166         .dot = { .min = 25000, .max = 350000 },
167         .vco = { .min = 908000, .max = 1512000 },
168         .n = { .min = 2, .max = 16 },
169         .m = { .min = 96, .max = 140 },
170         .m1 = { .min = 18, .max = 26 },
171         .m2 = { .min = 6, .max = 16 },
172         .p = { .min = 4, .max = 128 },
173         .p1 = { .min = 2, .max = 33 },
174         .p2 = { .dot_limit = 165000,
175                 .p2_slow = 4, .p2_fast = 4 },
176 };
177
178 static const intel_limit_t intel_limits_i8xx_lvds = {
179         .dot = { .min = 25000, .max = 350000 },
180         .vco = { .min = 908000, .max = 1512000 },
181         .n = { .min = 2, .max = 16 },
182         .m = { .min = 96, .max = 140 },
183         .m1 = { .min = 18, .max = 26 },
184         .m2 = { .min = 6, .max = 16 },
185         .p = { .min = 4, .max = 128 },
186         .p1 = { .min = 1, .max = 6 },
187         .p2 = { .dot_limit = 165000,
188                 .p2_slow = 14, .p2_fast = 7 },
189 };
190
191 static const intel_limit_t intel_limits_i9xx_sdvo = {
192         .dot = { .min = 20000, .max = 400000 },
193         .vco = { .min = 1400000, .max = 2800000 },
194         .n = { .min = 1, .max = 6 },
195         .m = { .min = 70, .max = 120 },
196         .m1 = { .min = 8, .max = 18 },
197         .m2 = { .min = 3, .max = 7 },
198         .p = { .min = 5, .max = 80 },
199         .p1 = { .min = 1, .max = 8 },
200         .p2 = { .dot_limit = 200000,
201                 .p2_slow = 10, .p2_fast = 5 },
202 };
203
204 static const intel_limit_t intel_limits_i9xx_lvds = {
205         .dot = { .min = 20000, .max = 400000 },
206         .vco = { .min = 1400000, .max = 2800000 },
207         .n = { .min = 1, .max = 6 },
208         .m = { .min = 70, .max = 120 },
209         .m1 = { .min = 8, .max = 18 },
210         .m2 = { .min = 3, .max = 7 },
211         .p = { .min = 7, .max = 98 },
212         .p1 = { .min = 1, .max = 8 },
213         .p2 = { .dot_limit = 112000,
214                 .p2_slow = 14, .p2_fast = 7 },
215 };
216
217
218 static const intel_limit_t intel_limits_g4x_sdvo = {
219         .dot = { .min = 25000, .max = 270000 },
220         .vco = { .min = 1750000, .max = 3500000},
221         .n = { .min = 1, .max = 4 },
222         .m = { .min = 104, .max = 138 },
223         .m1 = { .min = 17, .max = 23 },
224         .m2 = { .min = 5, .max = 11 },
225         .p = { .min = 10, .max = 30 },
226         .p1 = { .min = 1, .max = 3},
227         .p2 = { .dot_limit = 270000,
228                 .p2_slow = 10,
229                 .p2_fast = 10
230         },
231 };
232
233 static const intel_limit_t intel_limits_g4x_hdmi = {
234         .dot = { .min = 22000, .max = 400000 },
235         .vco = { .min = 1750000, .max = 3500000},
236         .n = { .min = 1, .max = 4 },
237         .m = { .min = 104, .max = 138 },
238         .m1 = { .min = 16, .max = 23 },
239         .m2 = { .min = 5, .max = 11 },
240         .p = { .min = 5, .max = 80 },
241         .p1 = { .min = 1, .max = 8},
242         .p2 = { .dot_limit = 165000,
243                 .p2_slow = 10, .p2_fast = 5 },
244 };
245
246 static const intel_limit_t intel_limits_g4x_single_channel_lvds = {
247         .dot = { .min = 20000, .max = 115000 },
248         .vco = { .min = 1750000, .max = 3500000 },
249         .n = { .min = 1, .max = 3 },
250         .m = { .min = 104, .max = 138 },
251         .m1 = { .min = 17, .max = 23 },
252         .m2 = { .min = 5, .max = 11 },
253         .p = { .min = 28, .max = 112 },
254         .p1 = { .min = 2, .max = 8 },
255         .p2 = { .dot_limit = 0,
256                 .p2_slow = 14, .p2_fast = 14
257         },
258 };
259
260 static const intel_limit_t intel_limits_g4x_dual_channel_lvds = {
261         .dot = { .min = 80000, .max = 224000 },
262         .vco = { .min = 1750000, .max = 3500000 },
263         .n = { .min = 1, .max = 3 },
264         .m = { .min = 104, .max = 138 },
265         .m1 = { .min = 17, .max = 23 },
266         .m2 = { .min = 5, .max = 11 },
267         .p = { .min = 14, .max = 42 },
268         .p1 = { .min = 2, .max = 6 },
269         .p2 = { .dot_limit = 0,
270                 .p2_slow = 7, .p2_fast = 7
271         },
272 };
273
274 static const intel_limit_t intel_limits_pineview_sdvo = {
275         .dot = { .min = 20000, .max = 400000},
276         .vco = { .min = 1700000, .max = 3500000 },
277         /* Pineview's Ncounter is a ring counter */
278         .n = { .min = 3, .max = 6 },
279         .m = { .min = 2, .max = 256 },
280         /* Pineview only has one combined m divider, which we treat as m2. */
281         .m1 = { .min = 0, .max = 0 },
282         .m2 = { .min = 0, .max = 254 },
283         .p = { .min = 5, .max = 80 },
284         .p1 = { .min = 1, .max = 8 },
285         .p2 = { .dot_limit = 200000,
286                 .p2_slow = 10, .p2_fast = 5 },
287 };
288
289 static const intel_limit_t intel_limits_pineview_lvds = {
290         .dot = { .min = 20000, .max = 400000 },
291         .vco = { .min = 1700000, .max = 3500000 },
292         .n = { .min = 3, .max = 6 },
293         .m = { .min = 2, .max = 256 },
294         .m1 = { .min = 0, .max = 0 },
295         .m2 = { .min = 0, .max = 254 },
296         .p = { .min = 7, .max = 112 },
297         .p1 = { .min = 1, .max = 8 },
298         .p2 = { .dot_limit = 112000,
299                 .p2_slow = 14, .p2_fast = 14 },
300 };
301
302 /* Ironlake / Sandybridge
303  *
304  * We calculate clock using (register_value + 2) for N/M1/M2, so here
305  * the range value for them is (actual_value - 2).
306  */
307 static const intel_limit_t intel_limits_ironlake_dac = {
308         .dot = { .min = 25000, .max = 350000 },
309         .vco = { .min = 1760000, .max = 3510000 },
310         .n = { .min = 1, .max = 5 },
311         .m = { .min = 79, .max = 127 },
312         .m1 = { .min = 12, .max = 22 },
313         .m2 = { .min = 5, .max = 9 },
314         .p = { .min = 5, .max = 80 },
315         .p1 = { .min = 1, .max = 8 },
316         .p2 = { .dot_limit = 225000,
317                 .p2_slow = 10, .p2_fast = 5 },
318 };
319
320 static const intel_limit_t intel_limits_ironlake_single_lvds = {
321         .dot = { .min = 25000, .max = 350000 },
322         .vco = { .min = 1760000, .max = 3510000 },
323         .n = { .min = 1, .max = 3 },
324         .m = { .min = 79, .max = 118 },
325         .m1 = { .min = 12, .max = 22 },
326         .m2 = { .min = 5, .max = 9 },
327         .p = { .min = 28, .max = 112 },
328         .p1 = { .min = 2, .max = 8 },
329         .p2 = { .dot_limit = 225000,
330                 .p2_slow = 14, .p2_fast = 14 },
331 };
332
333 static const intel_limit_t intel_limits_ironlake_dual_lvds = {
334         .dot = { .min = 25000, .max = 350000 },
335         .vco = { .min = 1760000, .max = 3510000 },
336         .n = { .min = 1, .max = 3 },
337         .m = { .min = 79, .max = 127 },
338         .m1 = { .min = 12, .max = 22 },
339         .m2 = { .min = 5, .max = 9 },
340         .p = { .min = 14, .max = 56 },
341         .p1 = { .min = 2, .max = 8 },
342         .p2 = { .dot_limit = 225000,
343                 .p2_slow = 7, .p2_fast = 7 },
344 };
345
346 /* LVDS 100mhz refclk limits. */
347 static const intel_limit_t intel_limits_ironlake_single_lvds_100m = {
348         .dot = { .min = 25000, .max = 350000 },
349         .vco = { .min = 1760000, .max = 3510000 },
350         .n = { .min = 1, .max = 2 },
351         .m = { .min = 79, .max = 126 },
352         .m1 = { .min = 12, .max = 22 },
353         .m2 = { .min = 5, .max = 9 },
354         .p = { .min = 28, .max = 112 },
355         .p1 = { .min = 2, .max = 8 },
356         .p2 = { .dot_limit = 225000,
357                 .p2_slow = 14, .p2_fast = 14 },
358 };
359
360 static const intel_limit_t intel_limits_ironlake_dual_lvds_100m = {
361         .dot = { .min = 25000, .max = 350000 },
362         .vco = { .min = 1760000, .max = 3510000 },
363         .n = { .min = 1, .max = 3 },
364         .m = { .min = 79, .max = 126 },
365         .m1 = { .min = 12, .max = 22 },
366         .m2 = { .min = 5, .max = 9 },
367         .p = { .min = 14, .max = 42 },
368         .p1 = { .min = 2, .max = 6 },
369         .p2 = { .dot_limit = 225000,
370                 .p2_slow = 7, .p2_fast = 7 },
371 };
372
373 static const intel_limit_t intel_limits_vlv = {
374          /*
375           * These are the data rate limits (measured in fast clocks)
376           * since those are the strictest limits we have. The fast
377           * clock and actual rate limits are more relaxed, so checking
378           * them would make no difference.
379           */
380         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
381         .vco = { .min = 4000000, .max = 6000000 },
382         .n = { .min = 1, .max = 7 },
383         .m1 = { .min = 2, .max = 3 },
384         .m2 = { .min = 11, .max = 156 },
385         .p1 = { .min = 2, .max = 3 },
386         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
387 };
388
389 static const intel_limit_t intel_limits_chv = {
390         /*
391          * These are the data rate limits (measured in fast clocks)
392          * since those are the strictest limits we have.  The fast
393          * clock and actual rate limits are more relaxed, so checking
394          * them would make no difference.
395          */
396         .dot = { .min = 25000 * 5, .max = 540000 * 5},
397         .vco = { .min = 4800000, .max = 6480000 },
398         .n = { .min = 1, .max = 1 },
399         .m1 = { .min = 2, .max = 2 },
400         .m2 = { .min = 24 << 22, .max = 175 << 22 },
401         .p1 = { .min = 2, .max = 4 },
402         .p2 = { .p2_slow = 1, .p2_fast = 14 },
403 };
404
405 static void vlv_clock(int refclk, intel_clock_t *clock)
406 {
407         clock->m = clock->m1 * clock->m2;
408         clock->p = clock->p1 * clock->p2;
409         if (WARN_ON(clock->n == 0 || clock->p == 0))
410                 return;
411         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
412         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
413 }
414
415 /**
416  * Returns whether any output on the specified pipe is of the specified type
417  */
418 bool intel_pipe_has_type(struct intel_crtc *crtc, enum intel_output_type type)
419 {
420         struct drm_device *dev = crtc->base.dev;
421         struct intel_encoder *encoder;
422
423         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
424                 if (encoder->type == type)
425                         return true;
426
427         return false;
428 }
429
430 /**
431  * Returns whether any output on the specified pipe will have the specified
432  * type after a staged modeset is complete, i.e., the same as
433  * intel_pipe_has_type() but looking at encoder->new_crtc instead of
434  * encoder->crtc.
435  */
436 static bool intel_pipe_will_have_type(const struct intel_crtc_state *crtc_state,
437                                       int type)
438 {
439         struct drm_atomic_state *state = crtc_state->base.state;
440         struct drm_connector_state *connector_state;
441         struct intel_encoder *encoder;
442         int i, num_connectors = 0;
443
444         for (i = 0; i < state->num_connector; i++) {
445                 if (!state->connectors[i])
446                         continue;
447
448                 connector_state = state->connector_states[i];
449                 if (connector_state->crtc != crtc_state->base.crtc)
450                         continue;
451
452                 num_connectors++;
453
454                 encoder = to_intel_encoder(connector_state->best_encoder);
455                 if (encoder->type == type)
456                         return true;
457         }
458
459         WARN_ON(num_connectors == 0);
460
461         return false;
462 }
463
464 static const intel_limit_t *
465 intel_ironlake_limit(struct intel_crtc_state *crtc_state, int refclk)
466 {
467         struct drm_device *dev = crtc_state->base.crtc->dev;
468         const intel_limit_t *limit;
469
470         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
471                 if (intel_is_dual_link_lvds(dev)) {
472                         if (refclk == 100000)
473                                 limit = &intel_limits_ironlake_dual_lvds_100m;
474                         else
475                                 limit = &intel_limits_ironlake_dual_lvds;
476                 } else {
477                         if (refclk == 100000)
478                                 limit = &intel_limits_ironlake_single_lvds_100m;
479                         else
480                                 limit = &intel_limits_ironlake_single_lvds;
481                 }
482         } else
483                 limit = &intel_limits_ironlake_dac;
484
485         return limit;
486 }
487
488 static const intel_limit_t *
489 intel_g4x_limit(struct intel_crtc_state *crtc_state)
490 {
491         struct drm_device *dev = crtc_state->base.crtc->dev;
492         const intel_limit_t *limit;
493
494         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
495                 if (intel_is_dual_link_lvds(dev))
496                         limit = &intel_limits_g4x_dual_channel_lvds;
497                 else
498                         limit = &intel_limits_g4x_single_channel_lvds;
499         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_HDMI) ||
500                    intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
501                 limit = &intel_limits_g4x_hdmi;
502         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_SDVO)) {
503                 limit = &intel_limits_g4x_sdvo;
504         } else /* The option is for other outputs */
505                 limit = &intel_limits_i9xx_sdvo;
506
507         return limit;
508 }
509
510 static const intel_limit_t *
511 intel_limit(struct intel_crtc_state *crtc_state, int refclk)
512 {
513         struct drm_device *dev = crtc_state->base.crtc->dev;
514         const intel_limit_t *limit;
515
516         if (HAS_PCH_SPLIT(dev))
517                 limit = intel_ironlake_limit(crtc_state, refclk);
518         else if (IS_G4X(dev)) {
519                 limit = intel_g4x_limit(crtc_state);
520         } else if (IS_PINEVIEW(dev)) {
521                 if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
522                         limit = &intel_limits_pineview_lvds;
523                 else
524                         limit = &intel_limits_pineview_sdvo;
525         } else if (IS_CHERRYVIEW(dev)) {
526                 limit = &intel_limits_chv;
527         } else if (IS_VALLEYVIEW(dev)) {
528                 limit = &intel_limits_vlv;
529         } else if (!IS_GEN2(dev)) {
530                 if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
531                         limit = &intel_limits_i9xx_lvds;
532                 else
533                         limit = &intel_limits_i9xx_sdvo;
534         } else {
535                 if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
536                         limit = &intel_limits_i8xx_lvds;
537                 else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_DVO))
538                         limit = &intel_limits_i8xx_dvo;
539                 else
540                         limit = &intel_limits_i8xx_dac;
541         }
542         return limit;
543 }
544
545 /* m1 is reserved as 0 in Pineview, n is a ring counter */
546 static void pineview_clock(int refclk, intel_clock_t *clock)
547 {
548         clock->m = clock->m2 + 2;
549         clock->p = clock->p1 * clock->p2;
550         if (WARN_ON(clock->n == 0 || clock->p == 0))
551                 return;
552         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
553         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
554 }
555
556 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
557 {
558         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
559 }
560
561 static void i9xx_clock(int refclk, intel_clock_t *clock)
562 {
563         clock->m = i9xx_dpll_compute_m(clock);
564         clock->p = clock->p1 * clock->p2;
565         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
566                 return;
567         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
568         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
569 }
570
571 static void chv_clock(int refclk, intel_clock_t *clock)
572 {
573         clock->m = clock->m1 * clock->m2;
574         clock->p = clock->p1 * clock->p2;
575         if (WARN_ON(clock->n == 0 || clock->p == 0))
576                 return;
577         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
578                         clock->n << 22);
579         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
580 }
581
582 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
583 /**
584  * Returns whether the given set of divisors are valid for a given refclk with
585  * the given connectors.
586  */
587
588 static bool intel_PLL_is_valid(struct drm_device *dev,
589                                const intel_limit_t *limit,
590                                const intel_clock_t *clock)
591 {
592         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
593                 INTELPllInvalid("n out of range\n");
594         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
595                 INTELPllInvalid("p1 out of range\n");
596         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
597                 INTELPllInvalid("m2 out of range\n");
598         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
599                 INTELPllInvalid("m1 out of range\n");
600
601         if (!IS_PINEVIEW(dev) && !IS_VALLEYVIEW(dev))
602                 if (clock->m1 <= clock->m2)
603                         INTELPllInvalid("m1 <= m2\n");
604
605         if (!IS_VALLEYVIEW(dev)) {
606                 if (clock->p < limit->p.min || limit->p.max < clock->p)
607                         INTELPllInvalid("p out of range\n");
608                 if (clock->m < limit->m.min || limit->m.max < clock->m)
609                         INTELPllInvalid("m out of range\n");
610         }
611
612         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
613                 INTELPllInvalid("vco out of range\n");
614         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
615          * connector, etc., rather than just a single range.
616          */
617         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
618                 INTELPllInvalid("dot out of range\n");
619
620         return true;
621 }
622
623 static bool
624 i9xx_find_best_dpll(const intel_limit_t *limit,
625                     struct intel_crtc_state *crtc_state,
626                     int target, int refclk, intel_clock_t *match_clock,
627                     intel_clock_t *best_clock)
628 {
629         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
630         struct drm_device *dev = crtc->base.dev;
631         intel_clock_t clock;
632         int err = target;
633
634         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
635                 /*
636                  * For LVDS just rely on its current settings for dual-channel.
637                  * We haven't figured out how to reliably set up different
638                  * single/dual channel state, if we even can.
639                  */
640                 if (intel_is_dual_link_lvds(dev))
641                         clock.p2 = limit->p2.p2_fast;
642                 else
643                         clock.p2 = limit->p2.p2_slow;
644         } else {
645                 if (target < limit->p2.dot_limit)
646                         clock.p2 = limit->p2.p2_slow;
647                 else
648                         clock.p2 = limit->p2.p2_fast;
649         }
650
651         memset(best_clock, 0, sizeof(*best_clock));
652
653         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
654              clock.m1++) {
655                 for (clock.m2 = limit->m2.min;
656                      clock.m2 <= limit->m2.max; clock.m2++) {
657                         if (clock.m2 >= clock.m1)
658                                 break;
659                         for (clock.n = limit->n.min;
660                              clock.n <= limit->n.max; clock.n++) {
661                                 for (clock.p1 = limit->p1.min;
662                                         clock.p1 <= limit->p1.max; clock.p1++) {
663                                         int this_err;
664
665                                         i9xx_clock(refclk, &clock);
666                                         if (!intel_PLL_is_valid(dev, limit,
667                                                                 &clock))
668                                                 continue;
669                                         if (match_clock &&
670                                             clock.p != match_clock->p)
671                                                 continue;
672
673                                         this_err = abs(clock.dot - target);
674                                         if (this_err < err) {
675                                                 *best_clock = clock;
676                                                 err = this_err;
677                                         }
678                                 }
679                         }
680                 }
681         }
682
683         return (err != target);
684 }
685
686 static bool
687 pnv_find_best_dpll(const intel_limit_t *limit,
688                    struct intel_crtc_state *crtc_state,
689                    int target, int refclk, intel_clock_t *match_clock,
690                    intel_clock_t *best_clock)
691 {
692         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
693         struct drm_device *dev = crtc->base.dev;
694         intel_clock_t clock;
695         int err = target;
696
697         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
698                 /*
699                  * For LVDS just rely on its current settings for dual-channel.
700                  * We haven't figured out how to reliably set up different
701                  * single/dual channel state, if we even can.
702                  */
703                 if (intel_is_dual_link_lvds(dev))
704                         clock.p2 = limit->p2.p2_fast;
705                 else
706                         clock.p2 = limit->p2.p2_slow;
707         } else {
708                 if (target < limit->p2.dot_limit)
709                         clock.p2 = limit->p2.p2_slow;
710                 else
711                         clock.p2 = limit->p2.p2_fast;
712         }
713
714         memset(best_clock, 0, sizeof(*best_clock));
715
716         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
717              clock.m1++) {
718                 for (clock.m2 = limit->m2.min;
719                      clock.m2 <= limit->m2.max; clock.m2++) {
720                         for (clock.n = limit->n.min;
721                              clock.n <= limit->n.max; clock.n++) {
722                                 for (clock.p1 = limit->p1.min;
723                                         clock.p1 <= limit->p1.max; clock.p1++) {
724                                         int this_err;
725
726                                         pineview_clock(refclk, &clock);
727                                         if (!intel_PLL_is_valid(dev, limit,
728                                                                 &clock))
729                                                 continue;
730                                         if (match_clock &&
731                                             clock.p != match_clock->p)
732                                                 continue;
733
734                                         this_err = abs(clock.dot - target);
735                                         if (this_err < err) {
736                                                 *best_clock = clock;
737                                                 err = this_err;
738                                         }
739                                 }
740                         }
741                 }
742         }
743
744         return (err != target);
745 }
746
747 static bool
748 g4x_find_best_dpll(const intel_limit_t *limit,
749                    struct intel_crtc_state *crtc_state,
750                    int target, int refclk, intel_clock_t *match_clock,
751                    intel_clock_t *best_clock)
752 {
753         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
754         struct drm_device *dev = crtc->base.dev;
755         intel_clock_t clock;
756         int max_n;
757         bool found;
758         /* approximately equals target * 0.00585 */
759         int err_most = (target >> 8) + (target >> 9);
760         found = false;
761
762         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
763                 if (intel_is_dual_link_lvds(dev))
764                         clock.p2 = limit->p2.p2_fast;
765                 else
766                         clock.p2 = limit->p2.p2_slow;
767         } else {
768                 if (target < limit->p2.dot_limit)
769                         clock.p2 = limit->p2.p2_slow;
770                 else
771                         clock.p2 = limit->p2.p2_fast;
772         }
773
774         memset(best_clock, 0, sizeof(*best_clock));
775         max_n = limit->n.max;
776         /* based on hardware requirement, prefer smaller n to precision */
777         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
778                 /* based on hardware requirement, prefere larger m1,m2 */
779                 for (clock.m1 = limit->m1.max;
780                      clock.m1 >= limit->m1.min; clock.m1--) {
781                         for (clock.m2 = limit->m2.max;
782                              clock.m2 >= limit->m2.min; clock.m2--) {
783                                 for (clock.p1 = limit->p1.max;
784                                      clock.p1 >= limit->p1.min; clock.p1--) {
785                                         int this_err;
786
787                                         i9xx_clock(refclk, &clock);
788                                         if (!intel_PLL_is_valid(dev, limit,
789                                                                 &clock))
790                                                 continue;
791
792                                         this_err = abs(clock.dot - target);
793                                         if (this_err < err_most) {
794                                                 *best_clock = clock;
795                                                 err_most = this_err;
796                                                 max_n = clock.n;
797                                                 found = true;
798                                         }
799                                 }
800                         }
801                 }
802         }
803         return found;
804 }
805
806 /*
807  * Check if the calculated PLL configuration is more optimal compared to the
808  * best configuration and error found so far. Return the calculated error.
809  */
810 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
811                                const intel_clock_t *calculated_clock,
812                                const intel_clock_t *best_clock,
813                                unsigned int best_error_ppm,
814                                unsigned int *error_ppm)
815 {
816         /*
817          * For CHV ignore the error and consider only the P value.
818          * Prefer a bigger P value based on HW requirements.
819          */
820         if (IS_CHERRYVIEW(dev)) {
821                 *error_ppm = 0;
822
823                 return calculated_clock->p > best_clock->p;
824         }
825
826         if (WARN_ON_ONCE(!target_freq))
827                 return false;
828
829         *error_ppm = div_u64(1000000ULL *
830                                 abs(target_freq - calculated_clock->dot),
831                              target_freq);
832         /*
833          * Prefer a better P value over a better (smaller) error if the error
834          * is small. Ensure this preference for future configurations too by
835          * setting the error to 0.
836          */
837         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
838                 *error_ppm = 0;
839
840                 return true;
841         }
842
843         return *error_ppm + 10 < best_error_ppm;
844 }
845
846 static bool
847 vlv_find_best_dpll(const intel_limit_t *limit,
848                    struct intel_crtc_state *crtc_state,
849                    int target, int refclk, intel_clock_t *match_clock,
850                    intel_clock_t *best_clock)
851 {
852         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
853         struct drm_device *dev = crtc->base.dev;
854         intel_clock_t clock;
855         unsigned int bestppm = 1000000;
856         /* min update 19.2 MHz */
857         int max_n = min(limit->n.max, refclk / 19200);
858         bool found = false;
859
860         target *= 5; /* fast clock */
861
862         memset(best_clock, 0, sizeof(*best_clock));
863
864         /* based on hardware requirement, prefer smaller n to precision */
865         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
866                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
867                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
868                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
869                                 clock.p = clock.p1 * clock.p2;
870                                 /* based on hardware requirement, prefer bigger m1,m2 values */
871                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
872                                         unsigned int ppm;
873
874                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
875                                                                      refclk * clock.m1);
876
877                                         vlv_clock(refclk, &clock);
878
879                                         if (!intel_PLL_is_valid(dev, limit,
880                                                                 &clock))
881                                                 continue;
882
883                                         if (!vlv_PLL_is_optimal(dev, target,
884                                                                 &clock,
885                                                                 best_clock,
886                                                                 bestppm, &ppm))
887                                                 continue;
888
889                                         *best_clock = clock;
890                                         bestppm = ppm;
891                                         found = true;
892                                 }
893                         }
894                 }
895         }
896
897         return found;
898 }
899
900 static bool
901 chv_find_best_dpll(const intel_limit_t *limit,
902                    struct intel_crtc_state *crtc_state,
903                    int target, int refclk, intel_clock_t *match_clock,
904                    intel_clock_t *best_clock)
905 {
906         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
907         struct drm_device *dev = crtc->base.dev;
908         unsigned int best_error_ppm;
909         intel_clock_t clock;
910         uint64_t m2;
911         int found = false;
912
913         memset(best_clock, 0, sizeof(*best_clock));
914         best_error_ppm = 1000000;
915
916         /*
917          * Based on hardware doc, the n always set to 1, and m1 always
918          * set to 2.  If requires to support 200Mhz refclk, we need to
919          * revisit this because n may not 1 anymore.
920          */
921         clock.n = 1, clock.m1 = 2;
922         target *= 5;    /* fast clock */
923
924         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
925                 for (clock.p2 = limit->p2.p2_fast;
926                                 clock.p2 >= limit->p2.p2_slow;
927                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
928                         unsigned int error_ppm;
929
930                         clock.p = clock.p1 * clock.p2;
931
932                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
933                                         clock.n) << 22, refclk * clock.m1);
934
935                         if (m2 > INT_MAX/clock.m1)
936                                 continue;
937
938                         clock.m2 = m2;
939
940                         chv_clock(refclk, &clock);
941
942                         if (!intel_PLL_is_valid(dev, limit, &clock))
943                                 continue;
944
945                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
946                                                 best_error_ppm, &error_ppm))
947                                 continue;
948
949                         *best_clock = clock;
950                         best_error_ppm = error_ppm;
951                         found = true;
952                 }
953         }
954
955         return found;
956 }
957
958 bool intel_crtc_active(struct drm_crtc *crtc)
959 {
960         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
961
962         /* Be paranoid as we can arrive here with only partial
963          * state retrieved from the hardware during setup.
964          *
965          * We can ditch the adjusted_mode.crtc_clock check as soon
966          * as Haswell has gained clock readout/fastboot support.
967          *
968          * We can ditch the crtc->primary->fb check as soon as we can
969          * properly reconstruct framebuffers.
970          *
971          * FIXME: The intel_crtc->active here should be switched to
972          * crtc->state->active once we have proper CRTC states wired up
973          * for atomic.
974          */
975         return intel_crtc->active && crtc->primary->state->fb &&
976                 intel_crtc->config->base.adjusted_mode.crtc_clock;
977 }
978
979 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
980                                              enum pipe pipe)
981 {
982         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
983         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
984
985         return intel_crtc->config->cpu_transcoder;
986 }
987
988 static bool pipe_dsl_stopped(struct drm_device *dev, enum pipe pipe)
989 {
990         struct drm_i915_private *dev_priv = dev->dev_private;
991         u32 reg = PIPEDSL(pipe);
992         u32 line1, line2;
993         u32 line_mask;
994
995         if (IS_GEN2(dev))
996                 line_mask = DSL_LINEMASK_GEN2;
997         else
998                 line_mask = DSL_LINEMASK_GEN3;
999
1000         line1 = I915_READ(reg) & line_mask;
1001         mdelay(5);
1002         line2 = I915_READ(reg) & line_mask;
1003
1004         return line1 == line2;
1005 }
1006
1007 /*
1008  * intel_wait_for_pipe_off - wait for pipe to turn off
1009  * @crtc: crtc whose pipe to wait for
1010  *
1011  * After disabling a pipe, we can't wait for vblank in the usual way,
1012  * spinning on the vblank interrupt status bit, since we won't actually
1013  * see an interrupt when the pipe is disabled.
1014  *
1015  * On Gen4 and above:
1016  *   wait for the pipe register state bit to turn off
1017  *
1018  * Otherwise:
1019  *   wait for the display line value to settle (it usually
1020  *   ends up stopping at the start of the next frame).
1021  *
1022  */
1023 static void intel_wait_for_pipe_off(struct intel_crtc *crtc)
1024 {
1025         struct drm_device *dev = crtc->base.dev;
1026         struct drm_i915_private *dev_priv = dev->dev_private;
1027         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1028         enum pipe pipe = crtc->pipe;
1029
1030         if (INTEL_INFO(dev)->gen >= 4) {
1031                 int reg = PIPECONF(cpu_transcoder);
1032
1033                 /* Wait for the Pipe State to go off */
1034                 if (wait_for((I915_READ(reg) & I965_PIPECONF_ACTIVE) == 0,
1035                              100))
1036                         WARN(1, "pipe_off wait timed out\n");
1037         } else {
1038                 /* Wait for the display line to settle */
1039                 if (wait_for(pipe_dsl_stopped(dev, pipe), 100))
1040                         WARN(1, "pipe_off wait timed out\n");
1041         }
1042 }
1043
1044 /*
1045  * ibx_digital_port_connected - is the specified port connected?
1046  * @dev_priv: i915 private structure
1047  * @port: the port to test
1048  *
1049  * Returns true if @port is connected, false otherwise.
1050  */
1051 bool ibx_digital_port_connected(struct drm_i915_private *dev_priv,
1052                                 struct intel_digital_port *port)
1053 {
1054         u32 bit;
1055
1056         if (HAS_PCH_IBX(dev_priv->dev)) {
1057                 switch (port->port) {
1058                 case PORT_B:
1059                         bit = SDE_PORTB_HOTPLUG;
1060                         break;
1061                 case PORT_C:
1062                         bit = SDE_PORTC_HOTPLUG;
1063                         break;
1064                 case PORT_D:
1065                         bit = SDE_PORTD_HOTPLUG;
1066                         break;
1067                 default:
1068                         return true;
1069                 }
1070         } else {
1071                 switch (port->port) {
1072                 case PORT_B:
1073                         bit = SDE_PORTB_HOTPLUG_CPT;
1074                         break;
1075                 case PORT_C:
1076                         bit = SDE_PORTC_HOTPLUG_CPT;
1077                         break;
1078                 case PORT_D:
1079                         bit = SDE_PORTD_HOTPLUG_CPT;
1080                         break;
1081                 default:
1082                         return true;
1083                 }
1084         }
1085
1086         return I915_READ(SDEISR) & bit;
1087 }
1088
1089 static const char *state_string(bool enabled)
1090 {
1091         return enabled ? "on" : "off";
1092 }
1093
1094 /* Only for pre-ILK configs */
1095 void assert_pll(struct drm_i915_private *dev_priv,
1096                 enum pipe pipe, bool state)
1097 {
1098         int reg;
1099         u32 val;
1100         bool cur_state;
1101
1102         reg = DPLL(pipe);
1103         val = I915_READ(reg);
1104         cur_state = !!(val & DPLL_VCO_ENABLE);
1105         I915_STATE_WARN(cur_state != state,
1106              "PLL state assertion failure (expected %s, current %s)\n",
1107              state_string(state), state_string(cur_state));
1108 }
1109
1110 /* XXX: the dsi pll is shared between MIPI DSI ports */
1111 static void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1112 {
1113         u32 val;
1114         bool cur_state;
1115
1116         mutex_lock(&dev_priv->dpio_lock);
1117         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1118         mutex_unlock(&dev_priv->dpio_lock);
1119
1120         cur_state = val & DSI_PLL_VCO_EN;
1121         I915_STATE_WARN(cur_state != state,
1122              "DSI PLL state assertion failure (expected %s, current %s)\n",
1123              state_string(state), state_string(cur_state));
1124 }
1125 #define assert_dsi_pll_enabled(d) assert_dsi_pll(d, true)
1126 #define assert_dsi_pll_disabled(d) assert_dsi_pll(d, false)
1127
1128 struct intel_shared_dpll *
1129 intel_crtc_to_shared_dpll(struct intel_crtc *crtc)
1130 {
1131         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
1132
1133         if (crtc->config->shared_dpll < 0)
1134                 return NULL;
1135
1136         return &dev_priv->shared_dplls[crtc->config->shared_dpll];
1137 }
1138
1139 /* For ILK+ */
1140 void assert_shared_dpll(struct drm_i915_private *dev_priv,
1141                         struct intel_shared_dpll *pll,
1142                         bool state)
1143 {
1144         bool cur_state;
1145         struct intel_dpll_hw_state hw_state;
1146
1147         if (WARN (!pll,
1148                   "asserting DPLL %s with no DPLL\n", state_string(state)))
1149                 return;
1150
1151         cur_state = pll->get_hw_state(dev_priv, pll, &hw_state);
1152         I915_STATE_WARN(cur_state != state,
1153              "%s assertion failure (expected %s, current %s)\n",
1154              pll->name, state_string(state), state_string(cur_state));
1155 }
1156
1157 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1158                           enum pipe pipe, bool state)
1159 {
1160         int reg;
1161         u32 val;
1162         bool cur_state;
1163         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1164                                                                       pipe);
1165
1166         if (HAS_DDI(dev_priv->dev)) {
1167                 /* DDI does not have a specific FDI_TX register */
1168                 reg = TRANS_DDI_FUNC_CTL(cpu_transcoder);
1169                 val = I915_READ(reg);
1170                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1171         } else {
1172                 reg = FDI_TX_CTL(pipe);
1173                 val = I915_READ(reg);
1174                 cur_state = !!(val & FDI_TX_ENABLE);
1175         }
1176         I915_STATE_WARN(cur_state != state,
1177              "FDI TX state assertion failure (expected %s, current %s)\n",
1178              state_string(state), state_string(cur_state));
1179 }
1180 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1181 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1182
1183 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1184                           enum pipe pipe, bool state)
1185 {
1186         int reg;
1187         u32 val;
1188         bool cur_state;
1189
1190         reg = FDI_RX_CTL(pipe);
1191         val = I915_READ(reg);
1192         cur_state = !!(val & FDI_RX_ENABLE);
1193         I915_STATE_WARN(cur_state != state,
1194              "FDI RX state assertion failure (expected %s, current %s)\n",
1195              state_string(state), state_string(cur_state));
1196 }
1197 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1198 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1199
1200 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1201                                       enum pipe pipe)
1202 {
1203         int reg;
1204         u32 val;
1205
1206         /* ILK FDI PLL is always enabled */
1207         if (INTEL_INFO(dev_priv->dev)->gen == 5)
1208                 return;
1209
1210         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1211         if (HAS_DDI(dev_priv->dev))
1212                 return;
1213
1214         reg = FDI_TX_CTL(pipe);
1215         val = I915_READ(reg);
1216         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1217 }
1218
1219 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1220                        enum pipe pipe, bool state)
1221 {
1222         int reg;
1223         u32 val;
1224         bool cur_state;
1225
1226         reg = FDI_RX_CTL(pipe);
1227         val = I915_READ(reg);
1228         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1229         I915_STATE_WARN(cur_state != state,
1230              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1231              state_string(state), state_string(cur_state));
1232 }
1233
1234 void assert_panel_unlocked(struct drm_i915_private *dev_priv,
1235                            enum pipe pipe)
1236 {
1237         struct drm_device *dev = dev_priv->dev;
1238         int pp_reg;
1239         u32 val;
1240         enum pipe panel_pipe = PIPE_A;
1241         bool locked = true;
1242
1243         if (WARN_ON(HAS_DDI(dev)))
1244                 return;
1245
1246         if (HAS_PCH_SPLIT(dev)) {
1247                 u32 port_sel;
1248
1249                 pp_reg = PCH_PP_CONTROL;
1250                 port_sel = I915_READ(PCH_PP_ON_DELAYS) & PANEL_PORT_SELECT_MASK;
1251
1252                 if (port_sel == PANEL_PORT_SELECT_LVDS &&
1253                     I915_READ(PCH_LVDS) & LVDS_PIPEB_SELECT)
1254                         panel_pipe = PIPE_B;
1255                 /* XXX: else fix for eDP */
1256         } else if (IS_VALLEYVIEW(dev)) {
1257                 /* presumably write lock depends on pipe, not port select */
1258                 pp_reg = VLV_PIPE_PP_CONTROL(pipe);
1259                 panel_pipe = pipe;
1260         } else {
1261                 pp_reg = PP_CONTROL;
1262                 if (I915_READ(LVDS) & LVDS_PIPEB_SELECT)
1263                         panel_pipe = PIPE_B;
1264         }
1265
1266         val = I915_READ(pp_reg);
1267         if (!(val & PANEL_POWER_ON) ||
1268             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1269                 locked = false;
1270
1271         I915_STATE_WARN(panel_pipe == pipe && locked,
1272              "panel assertion failure, pipe %c regs locked\n",
1273              pipe_name(pipe));
1274 }
1275
1276 static void assert_cursor(struct drm_i915_private *dev_priv,
1277                           enum pipe pipe, bool state)
1278 {
1279         struct drm_device *dev = dev_priv->dev;
1280         bool cur_state;
1281
1282         if (IS_845G(dev) || IS_I865G(dev))
1283                 cur_state = I915_READ(_CURACNTR) & CURSOR_ENABLE;
1284         else
1285                 cur_state = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
1286
1287         I915_STATE_WARN(cur_state != state,
1288              "cursor on pipe %c assertion failure (expected %s, current %s)\n",
1289              pipe_name(pipe), state_string(state), state_string(cur_state));
1290 }
1291 #define assert_cursor_enabled(d, p) assert_cursor(d, p, true)
1292 #define assert_cursor_disabled(d, p) assert_cursor(d, p, false)
1293
1294 void assert_pipe(struct drm_i915_private *dev_priv,
1295                  enum pipe pipe, bool state)
1296 {
1297         int reg;
1298         u32 val;
1299         bool cur_state;
1300         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1301                                                                       pipe);
1302
1303         /* if we need the pipe quirk it must be always on */
1304         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1305             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1306                 state = true;
1307
1308         if (!intel_display_power_is_enabled(dev_priv,
1309                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder))) {
1310                 cur_state = false;
1311         } else {
1312                 reg = PIPECONF(cpu_transcoder);
1313                 val = I915_READ(reg);
1314                 cur_state = !!(val & PIPECONF_ENABLE);
1315         }
1316
1317         I915_STATE_WARN(cur_state != state,
1318              "pipe %c assertion failure (expected %s, current %s)\n",
1319              pipe_name(pipe), state_string(state), state_string(cur_state));
1320 }
1321
1322 static void assert_plane(struct drm_i915_private *dev_priv,
1323                          enum plane plane, bool state)
1324 {
1325         int reg;
1326         u32 val;
1327         bool cur_state;
1328
1329         reg = DSPCNTR(plane);
1330         val = I915_READ(reg);
1331         cur_state = !!(val & DISPLAY_PLANE_ENABLE);
1332         I915_STATE_WARN(cur_state != state,
1333              "plane %c assertion failure (expected %s, current %s)\n",
1334              plane_name(plane), state_string(state), state_string(cur_state));
1335 }
1336
1337 #define assert_plane_enabled(d, p) assert_plane(d, p, true)
1338 #define assert_plane_disabled(d, p) assert_plane(d, p, false)
1339
1340 static void assert_planes_disabled(struct drm_i915_private *dev_priv,
1341                                    enum pipe pipe)
1342 {
1343         struct drm_device *dev = dev_priv->dev;
1344         int reg, i;
1345         u32 val;
1346         int cur_pipe;
1347
1348         /* Primary planes are fixed to pipes on gen4+ */
1349         if (INTEL_INFO(dev)->gen >= 4) {
1350                 reg = DSPCNTR(pipe);
1351                 val = I915_READ(reg);
1352                 I915_STATE_WARN(val & DISPLAY_PLANE_ENABLE,
1353                      "plane %c assertion failure, should be disabled but not\n",
1354                      plane_name(pipe));
1355                 return;
1356         }
1357
1358         /* Need to check both planes against the pipe */
1359         for_each_pipe(dev_priv, i) {
1360                 reg = DSPCNTR(i);
1361                 val = I915_READ(reg);
1362                 cur_pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
1363                         DISPPLANE_SEL_PIPE_SHIFT;
1364                 I915_STATE_WARN((val & DISPLAY_PLANE_ENABLE) && pipe == cur_pipe,
1365                      "plane %c assertion failure, should be off on pipe %c but is still active\n",
1366                      plane_name(i), pipe_name(pipe));
1367         }
1368 }
1369
1370 static void assert_sprites_disabled(struct drm_i915_private *dev_priv,
1371                                     enum pipe pipe)
1372 {
1373         struct drm_device *dev = dev_priv->dev;
1374         int reg, sprite;
1375         u32 val;
1376
1377         if (INTEL_INFO(dev)->gen >= 9) {
1378                 for_each_sprite(dev_priv, pipe, sprite) {
1379                         val = I915_READ(PLANE_CTL(pipe, sprite));
1380                         I915_STATE_WARN(val & PLANE_CTL_ENABLE,
1381                              "plane %d assertion failure, should be off on pipe %c but is still active\n",
1382                              sprite, pipe_name(pipe));
1383                 }
1384         } else if (IS_VALLEYVIEW(dev)) {
1385                 for_each_sprite(dev_priv, pipe, sprite) {
1386                         reg = SPCNTR(pipe, sprite);
1387                         val = I915_READ(reg);
1388                         I915_STATE_WARN(val & SP_ENABLE,
1389                              "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1390                              sprite_name(pipe, sprite), pipe_name(pipe));
1391                 }
1392         } else if (INTEL_INFO(dev)->gen >= 7) {
1393                 reg = SPRCTL(pipe);
1394                 val = I915_READ(reg);
1395                 I915_STATE_WARN(val & SPRITE_ENABLE,
1396                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1397                      plane_name(pipe), pipe_name(pipe));
1398         } else if (INTEL_INFO(dev)->gen >= 5) {
1399                 reg = DVSCNTR(pipe);
1400                 val = I915_READ(reg);
1401                 I915_STATE_WARN(val & DVS_ENABLE,
1402                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1403                      plane_name(pipe), pipe_name(pipe));
1404         }
1405 }
1406
1407 static void assert_vblank_disabled(struct drm_crtc *crtc)
1408 {
1409         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1410                 drm_crtc_vblank_put(crtc);
1411 }
1412
1413 static void ibx_assert_pch_refclk_enabled(struct drm_i915_private *dev_priv)
1414 {
1415         u32 val;
1416         bool enabled;
1417
1418         I915_STATE_WARN_ON(!(HAS_PCH_IBX(dev_priv->dev) || HAS_PCH_CPT(dev_priv->dev)));
1419
1420         val = I915_READ(PCH_DREF_CONTROL);
1421         enabled = !!(val & (DREF_SSC_SOURCE_MASK | DREF_NONSPREAD_SOURCE_MASK |
1422                             DREF_SUPERSPREAD_SOURCE_MASK));
1423         I915_STATE_WARN(!enabled, "PCH refclk assertion failure, should be active but is disabled\n");
1424 }
1425
1426 static void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1427                                            enum pipe pipe)
1428 {
1429         int reg;
1430         u32 val;
1431         bool enabled;
1432
1433         reg = PCH_TRANSCONF(pipe);
1434         val = I915_READ(reg);
1435         enabled = !!(val & TRANS_ENABLE);
1436         I915_STATE_WARN(enabled,
1437              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1438              pipe_name(pipe));
1439 }
1440
1441 static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1442                             enum pipe pipe, u32 port_sel, u32 val)
1443 {
1444         if ((val & DP_PORT_EN) == 0)
1445                 return false;
1446
1447         if (HAS_PCH_CPT(dev_priv->dev)) {
1448                 u32     trans_dp_ctl_reg = TRANS_DP_CTL(pipe);
1449                 u32     trans_dp_ctl = I915_READ(trans_dp_ctl_reg);
1450                 if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1451                         return false;
1452         } else if (IS_CHERRYVIEW(dev_priv->dev)) {
1453                 if ((val & DP_PIPE_MASK_CHV) != DP_PIPE_SELECT_CHV(pipe))
1454                         return false;
1455         } else {
1456                 if ((val & DP_PIPE_MASK) != (pipe << 30))
1457                         return false;
1458         }
1459         return true;
1460 }
1461
1462 static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1463                               enum pipe pipe, u32 val)
1464 {
1465         if ((val & SDVO_ENABLE) == 0)
1466                 return false;
1467
1468         if (HAS_PCH_CPT(dev_priv->dev)) {
1469                 if ((val & SDVO_PIPE_SEL_MASK_CPT) != SDVO_PIPE_SEL_CPT(pipe))
1470                         return false;
1471         } else if (IS_CHERRYVIEW(dev_priv->dev)) {
1472                 if ((val & SDVO_PIPE_SEL_MASK_CHV) != SDVO_PIPE_SEL_CHV(pipe))
1473                         return false;
1474         } else {
1475                 if ((val & SDVO_PIPE_SEL_MASK) != SDVO_PIPE_SEL(pipe))
1476                         return false;
1477         }
1478         return true;
1479 }
1480
1481 static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1482                               enum pipe pipe, u32 val)
1483 {
1484         if ((val & LVDS_PORT_EN) == 0)
1485                 return false;
1486
1487         if (HAS_PCH_CPT(dev_priv->dev)) {
1488                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1489                         return false;
1490         } else {
1491                 if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1492                         return false;
1493         }
1494         return true;
1495 }
1496
1497 static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1498                               enum pipe pipe, u32 val)
1499 {
1500         if ((val & ADPA_DAC_ENABLE) == 0)
1501                 return false;
1502         if (HAS_PCH_CPT(dev_priv->dev)) {
1503                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1504                         return false;
1505         } else {
1506                 if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1507                         return false;
1508         }
1509         return true;
1510 }
1511
1512 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1513                                    enum pipe pipe, int reg, u32 port_sel)
1514 {
1515         u32 val = I915_READ(reg);
1516         I915_STATE_WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1517              "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1518              reg, pipe_name(pipe));
1519
1520         I915_STATE_WARN(HAS_PCH_IBX(dev_priv->dev) && (val & DP_PORT_EN) == 0
1521              && (val & DP_PIPEB_SELECT),
1522              "IBX PCH dp port still using transcoder B\n");
1523 }
1524
1525 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1526                                      enum pipe pipe, int reg)
1527 {
1528         u32 val = I915_READ(reg);
1529         I915_STATE_WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1530              "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1531              reg, pipe_name(pipe));
1532
1533         I915_STATE_WARN(HAS_PCH_IBX(dev_priv->dev) && (val & SDVO_ENABLE) == 0
1534              && (val & SDVO_PIPE_B_SELECT),
1535              "IBX PCH hdmi port still using transcoder B\n");
1536 }
1537
1538 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1539                                       enum pipe pipe)
1540 {
1541         int reg;
1542         u32 val;
1543
1544         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1545         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1546         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1547
1548         reg = PCH_ADPA;
1549         val = I915_READ(reg);
1550         I915_STATE_WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1551              "PCH VGA enabled on transcoder %c, should be disabled\n",
1552              pipe_name(pipe));
1553
1554         reg = PCH_LVDS;
1555         val = I915_READ(reg);
1556         I915_STATE_WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1557              "PCH LVDS enabled on transcoder %c, should be disabled\n",
1558              pipe_name(pipe));
1559
1560         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIB);
1561         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIC);
1562         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMID);
1563 }
1564
1565 static void intel_init_dpio(struct drm_device *dev)
1566 {
1567         struct drm_i915_private *dev_priv = dev->dev_private;
1568
1569         if (!IS_VALLEYVIEW(dev))
1570                 return;
1571
1572         /*
1573          * IOSF_PORT_DPIO is used for VLV x2 PHY (DP/HDMI B and C),
1574          * CHV x1 PHY (DP/HDMI D)
1575          * IOSF_PORT_DPIO_2 is used for CHV x2 PHY (DP/HDMI B and C)
1576          */
1577         if (IS_CHERRYVIEW(dev)) {
1578                 DPIO_PHY_IOSF_PORT(DPIO_PHY0) = IOSF_PORT_DPIO_2;
1579                 DPIO_PHY_IOSF_PORT(DPIO_PHY1) = IOSF_PORT_DPIO;
1580         } else {
1581                 DPIO_PHY_IOSF_PORT(DPIO_PHY0) = IOSF_PORT_DPIO;
1582         }
1583 }
1584
1585 static void vlv_enable_pll(struct intel_crtc *crtc,
1586                            const struct intel_crtc_state *pipe_config)
1587 {
1588         struct drm_device *dev = crtc->base.dev;
1589         struct drm_i915_private *dev_priv = dev->dev_private;
1590         int reg = DPLL(crtc->pipe);
1591         u32 dpll = pipe_config->dpll_hw_state.dpll;
1592
1593         assert_pipe_disabled(dev_priv, crtc->pipe);
1594
1595         /* No really, not for ILK+ */
1596         BUG_ON(!IS_VALLEYVIEW(dev_priv->dev));
1597
1598         /* PLL is protected by panel, make sure we can write it */
1599         if (IS_MOBILE(dev_priv->dev))
1600                 assert_panel_unlocked(dev_priv, crtc->pipe);
1601
1602         I915_WRITE(reg, dpll);
1603         POSTING_READ(reg);
1604         udelay(150);
1605
1606         if (wait_for(((I915_READ(reg) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1607                 DRM_ERROR("DPLL %d failed to lock\n", crtc->pipe);
1608
1609         I915_WRITE(DPLL_MD(crtc->pipe), pipe_config->dpll_hw_state.dpll_md);
1610         POSTING_READ(DPLL_MD(crtc->pipe));
1611
1612         /* We do this three times for luck */
1613         I915_WRITE(reg, dpll);
1614         POSTING_READ(reg);
1615         udelay(150); /* wait for warmup */
1616         I915_WRITE(reg, dpll);
1617         POSTING_READ(reg);
1618         udelay(150); /* wait for warmup */
1619         I915_WRITE(reg, dpll);
1620         POSTING_READ(reg);
1621         udelay(150); /* wait for warmup */
1622 }
1623
1624 static void chv_enable_pll(struct intel_crtc *crtc,
1625                            const struct intel_crtc_state *pipe_config)
1626 {
1627         struct drm_device *dev = crtc->base.dev;
1628         struct drm_i915_private *dev_priv = dev->dev_private;
1629         int pipe = crtc->pipe;
1630         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1631         u32 tmp;
1632
1633         assert_pipe_disabled(dev_priv, crtc->pipe);
1634
1635         BUG_ON(!IS_CHERRYVIEW(dev_priv->dev));
1636
1637         mutex_lock(&dev_priv->dpio_lock);
1638
1639         /* Enable back the 10bit clock to display controller */
1640         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1641         tmp |= DPIO_DCLKP_EN;
1642         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1643
1644         /*
1645          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1646          */
1647         udelay(1);
1648
1649         /* Enable PLL */
1650         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1651
1652         /* Check PLL is locked */
1653         if (wait_for(((I915_READ(DPLL(pipe)) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1654                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1655
1656         /* not sure when this should be written */
1657         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1658         POSTING_READ(DPLL_MD(pipe));
1659
1660         mutex_unlock(&dev_priv->dpio_lock);
1661 }
1662
1663 static int intel_num_dvo_pipes(struct drm_device *dev)
1664 {
1665         struct intel_crtc *crtc;
1666         int count = 0;
1667
1668         for_each_intel_crtc(dev, crtc)
1669                 count += crtc->active &&
1670                         intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO);
1671
1672         return count;
1673 }
1674
1675 static void i9xx_enable_pll(struct intel_crtc *crtc)
1676 {
1677         struct drm_device *dev = crtc->base.dev;
1678         struct drm_i915_private *dev_priv = dev->dev_private;
1679         int reg = DPLL(crtc->pipe);
1680         u32 dpll = crtc->config->dpll_hw_state.dpll;
1681
1682         assert_pipe_disabled(dev_priv, crtc->pipe);
1683
1684         /* No really, not for ILK+ */
1685         BUG_ON(INTEL_INFO(dev)->gen >= 5);
1686
1687         /* PLL is protected by panel, make sure we can write it */
1688         if (IS_MOBILE(dev) && !IS_I830(dev))
1689                 assert_panel_unlocked(dev_priv, crtc->pipe);
1690
1691         /* Enable DVO 2x clock on both PLLs if necessary */
1692         if (IS_I830(dev) && intel_num_dvo_pipes(dev) > 0) {
1693                 /*
1694                  * It appears to be important that we don't enable this
1695                  * for the current pipe before otherwise configuring the
1696                  * PLL. No idea how this should be handled if multiple
1697                  * DVO outputs are enabled simultaneosly.
1698                  */
1699                 dpll |= DPLL_DVO_2X_MODE;
1700                 I915_WRITE(DPLL(!crtc->pipe),
1701                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1702         }
1703
1704         /* Wait for the clocks to stabilize. */
1705         POSTING_READ(reg);
1706         udelay(150);
1707
1708         if (INTEL_INFO(dev)->gen >= 4) {
1709                 I915_WRITE(DPLL_MD(crtc->pipe),
1710                            crtc->config->dpll_hw_state.dpll_md);
1711         } else {
1712                 /* The pixel multiplier can only be updated once the
1713                  * DPLL is enabled and the clocks are stable.
1714                  *
1715                  * So write it again.
1716                  */
1717                 I915_WRITE(reg, dpll);
1718         }
1719
1720         /* We do this three times for luck */
1721         I915_WRITE(reg, dpll);
1722         POSTING_READ(reg);
1723         udelay(150); /* wait for warmup */
1724         I915_WRITE(reg, dpll);
1725         POSTING_READ(reg);
1726         udelay(150); /* wait for warmup */
1727         I915_WRITE(reg, dpll);
1728         POSTING_READ(reg);
1729         udelay(150); /* wait for warmup */
1730 }
1731
1732 /**
1733  * i9xx_disable_pll - disable a PLL
1734  * @dev_priv: i915 private structure
1735  * @pipe: pipe PLL to disable
1736  *
1737  * Disable the PLL for @pipe, making sure the pipe is off first.
1738  *
1739  * Note!  This is for pre-ILK only.
1740  */
1741 static void i9xx_disable_pll(struct intel_crtc *crtc)
1742 {
1743         struct drm_device *dev = crtc->base.dev;
1744         struct drm_i915_private *dev_priv = dev->dev_private;
1745         enum pipe pipe = crtc->pipe;
1746
1747         /* Disable DVO 2x clock on both PLLs if necessary */
1748         if (IS_I830(dev) &&
1749             intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO) &&
1750             intel_num_dvo_pipes(dev) == 1) {
1751                 I915_WRITE(DPLL(PIPE_B),
1752                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1753                 I915_WRITE(DPLL(PIPE_A),
1754                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1755         }
1756
1757         /* Don't disable pipe or pipe PLLs if needed */
1758         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1759             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1760                 return;
1761
1762         /* Make sure the pipe isn't still relying on us */
1763         assert_pipe_disabled(dev_priv, pipe);
1764
1765         I915_WRITE(DPLL(pipe), 0);
1766         POSTING_READ(DPLL(pipe));
1767 }
1768
1769 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1770 {
1771         u32 val = 0;
1772
1773         /* Make sure the pipe isn't still relying on us */
1774         assert_pipe_disabled(dev_priv, pipe);
1775
1776         /*
1777          * Leave integrated clock source and reference clock enabled for pipe B.
1778          * The latter is needed for VGA hotplug / manual detection.
1779          */
1780         if (pipe == PIPE_B)
1781                 val = DPLL_INTEGRATED_CRI_CLK_VLV | DPLL_REFA_CLK_ENABLE_VLV;
1782         I915_WRITE(DPLL(pipe), val);
1783         POSTING_READ(DPLL(pipe));
1784
1785 }
1786
1787 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1788 {
1789         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1790         u32 val;
1791
1792         /* Make sure the pipe isn't still relying on us */
1793         assert_pipe_disabled(dev_priv, pipe);
1794
1795         /* Set PLL en = 0 */
1796         val = DPLL_SSC_REF_CLOCK_CHV | DPLL_REFA_CLK_ENABLE_VLV;
1797         if (pipe != PIPE_A)
1798                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1799         I915_WRITE(DPLL(pipe), val);
1800         POSTING_READ(DPLL(pipe));
1801
1802         mutex_lock(&dev_priv->dpio_lock);
1803
1804         /* Disable 10bit clock to display controller */
1805         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1806         val &= ~DPIO_DCLKP_EN;
1807         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1808
1809         /* disable left/right clock distribution */
1810         if (pipe != PIPE_B) {
1811                 val = vlv_dpio_read(dev_priv, pipe, _CHV_CMN_DW5_CH0);
1812                 val &= ~(CHV_BUFLEFTENA1_MASK | CHV_BUFRIGHTENA1_MASK);
1813                 vlv_dpio_write(dev_priv, pipe, _CHV_CMN_DW5_CH0, val);
1814         } else {
1815                 val = vlv_dpio_read(dev_priv, pipe, _CHV_CMN_DW1_CH1);
1816                 val &= ~(CHV_BUFLEFTENA2_MASK | CHV_BUFRIGHTENA2_MASK);
1817                 vlv_dpio_write(dev_priv, pipe, _CHV_CMN_DW1_CH1, val);
1818         }
1819
1820         mutex_unlock(&dev_priv->dpio_lock);
1821 }
1822
1823 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1824                 struct intel_digital_port *dport)
1825 {
1826         u32 port_mask;
1827         int dpll_reg;
1828
1829         switch (dport->port) {
1830         case PORT_B:
1831                 port_mask = DPLL_PORTB_READY_MASK;
1832                 dpll_reg = DPLL(0);
1833                 break;
1834         case PORT_C:
1835                 port_mask = DPLL_PORTC_READY_MASK;
1836                 dpll_reg = DPLL(0);
1837                 break;
1838         case PORT_D:
1839                 port_mask = DPLL_PORTD_READY_MASK;
1840                 dpll_reg = DPIO_PHY_STATUS;
1841                 break;
1842         default:
1843                 BUG();
1844         }
1845
1846         if (wait_for((I915_READ(dpll_reg) & port_mask) == 0, 1000))
1847                 WARN(1, "timed out waiting for port %c ready: 0x%08x\n",
1848                      port_name(dport->port), I915_READ(dpll_reg));
1849 }
1850
1851 static void intel_prepare_shared_dpll(struct intel_crtc *crtc)
1852 {
1853         struct drm_device *dev = crtc->base.dev;
1854         struct drm_i915_private *dev_priv = dev->dev_private;
1855         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1856
1857         if (WARN_ON(pll == NULL))
1858                 return;
1859
1860         WARN_ON(!pll->config.crtc_mask);
1861         if (pll->active == 0) {
1862                 DRM_DEBUG_DRIVER("setting up %s\n", pll->name);
1863                 WARN_ON(pll->on);
1864                 assert_shared_dpll_disabled(dev_priv, pll);
1865
1866                 pll->mode_set(dev_priv, pll);
1867         }
1868 }
1869
1870 /**
1871  * intel_enable_shared_dpll - enable PCH PLL
1872  * @dev_priv: i915 private structure
1873  * @pipe: pipe PLL to enable
1874  *
1875  * The PCH PLL needs to be enabled before the PCH transcoder, since it
1876  * drives the transcoder clock.
1877  */
1878 static void intel_enable_shared_dpll(struct intel_crtc *crtc)
1879 {
1880         struct drm_device *dev = crtc->base.dev;
1881         struct drm_i915_private *dev_priv = dev->dev_private;
1882         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1883
1884         if (WARN_ON(pll == NULL))
1885                 return;
1886
1887         if (WARN_ON(pll->config.crtc_mask == 0))
1888                 return;
1889
1890         DRM_DEBUG_KMS("enable %s (active %d, on? %d) for crtc %d\n",
1891                       pll->name, pll->active, pll->on,
1892                       crtc->base.base.id);
1893
1894         if (pll->active++) {
1895                 WARN_ON(!pll->on);
1896                 assert_shared_dpll_enabled(dev_priv, pll);
1897                 return;
1898         }
1899         WARN_ON(pll->on);
1900
1901         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
1902
1903         DRM_DEBUG_KMS("enabling %s\n", pll->name);
1904         pll->enable(dev_priv, pll);
1905         pll->on = true;
1906 }
1907
1908 static void intel_disable_shared_dpll(struct intel_crtc *crtc)
1909 {
1910         struct drm_device *dev = crtc->base.dev;
1911         struct drm_i915_private *dev_priv = dev->dev_private;
1912         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1913
1914         /* PCH only available on ILK+ */
1915         BUG_ON(INTEL_INFO(dev)->gen < 5);
1916         if (WARN_ON(pll == NULL))
1917                return;
1918
1919         if (WARN_ON(pll->config.crtc_mask == 0))
1920                 return;
1921
1922         DRM_DEBUG_KMS("disable %s (active %d, on? %d) for crtc %d\n",
1923                       pll->name, pll->active, pll->on,
1924                       crtc->base.base.id);
1925
1926         if (WARN_ON(pll->active == 0)) {
1927                 assert_shared_dpll_disabled(dev_priv, pll);
1928                 return;
1929         }
1930
1931         assert_shared_dpll_enabled(dev_priv, pll);
1932         WARN_ON(!pll->on);
1933         if (--pll->active)
1934                 return;
1935
1936         DRM_DEBUG_KMS("disabling %s\n", pll->name);
1937         pll->disable(dev_priv, pll);
1938         pll->on = false;
1939
1940         intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS);
1941 }
1942
1943 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1944                                            enum pipe pipe)
1945 {
1946         struct drm_device *dev = dev_priv->dev;
1947         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1948         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1949         uint32_t reg, val, pipeconf_val;
1950
1951         /* PCH only available on ILK+ */
1952         BUG_ON(!HAS_PCH_SPLIT(dev));
1953
1954         /* Make sure PCH DPLL is enabled */
1955         assert_shared_dpll_enabled(dev_priv,
1956                                    intel_crtc_to_shared_dpll(intel_crtc));
1957
1958         /* FDI must be feeding us bits for PCH ports */
1959         assert_fdi_tx_enabled(dev_priv, pipe);
1960         assert_fdi_rx_enabled(dev_priv, pipe);
1961
1962         if (HAS_PCH_CPT(dev)) {
1963                 /* Workaround: Set the timing override bit before enabling the
1964                  * pch transcoder. */
1965                 reg = TRANS_CHICKEN2(pipe);
1966                 val = I915_READ(reg);
1967                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1968                 I915_WRITE(reg, val);
1969         }
1970
1971         reg = PCH_TRANSCONF(pipe);
1972         val = I915_READ(reg);
1973         pipeconf_val = I915_READ(PIPECONF(pipe));
1974
1975         if (HAS_PCH_IBX(dev_priv->dev)) {
1976                 /*
1977                  * make the BPC in transcoder be consistent with
1978                  * that in pipeconf reg.
1979                  */
1980                 val &= ~PIPECONF_BPC_MASK;
1981                 val |= pipeconf_val & PIPECONF_BPC_MASK;
1982         }
1983
1984         val &= ~TRANS_INTERLACE_MASK;
1985         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1986                 if (HAS_PCH_IBX(dev_priv->dev) &&
1987                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
1988                         val |= TRANS_LEGACY_INTERLACED_ILK;
1989                 else
1990                         val |= TRANS_INTERLACED;
1991         else
1992                 val |= TRANS_PROGRESSIVE;
1993
1994         I915_WRITE(reg, val | TRANS_ENABLE);
1995         if (wait_for(I915_READ(reg) & TRANS_STATE_ENABLE, 100))
1996                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1997 }
1998
1999 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
2000                                       enum transcoder cpu_transcoder)
2001 {
2002         u32 val, pipeconf_val;
2003
2004         /* PCH only available on ILK+ */
2005         BUG_ON(!HAS_PCH_SPLIT(dev_priv->dev));
2006
2007         /* FDI must be feeding us bits for PCH ports */
2008         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
2009         assert_fdi_rx_enabled(dev_priv, TRANSCODER_A);
2010
2011         /* Workaround: set timing override bit. */
2012         val = I915_READ(_TRANSA_CHICKEN2);
2013         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
2014         I915_WRITE(_TRANSA_CHICKEN2, val);
2015
2016         val = TRANS_ENABLE;
2017         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
2018
2019         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
2020             PIPECONF_INTERLACED_ILK)
2021                 val |= TRANS_INTERLACED;
2022         else
2023                 val |= TRANS_PROGRESSIVE;
2024
2025         I915_WRITE(LPT_TRANSCONF, val);
2026         if (wait_for(I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE, 100))
2027                 DRM_ERROR("Failed to enable PCH transcoder\n");
2028 }
2029
2030 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
2031                                             enum pipe pipe)
2032 {
2033         struct drm_device *dev = dev_priv->dev;
2034         uint32_t reg, val;
2035
2036         /* FDI relies on the transcoder */
2037         assert_fdi_tx_disabled(dev_priv, pipe);
2038         assert_fdi_rx_disabled(dev_priv, pipe);
2039
2040         /* Ports must be off as well */
2041         assert_pch_ports_disabled(dev_priv, pipe);
2042
2043         reg = PCH_TRANSCONF(pipe);
2044         val = I915_READ(reg);
2045         val &= ~TRANS_ENABLE;
2046         I915_WRITE(reg, val);
2047         /* wait for PCH transcoder off, transcoder state */
2048         if (wait_for((I915_READ(reg) & TRANS_STATE_ENABLE) == 0, 50))
2049                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
2050
2051         if (!HAS_PCH_IBX(dev)) {
2052                 /* Workaround: Clear the timing override chicken bit again. */
2053                 reg = TRANS_CHICKEN2(pipe);
2054                 val = I915_READ(reg);
2055                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
2056                 I915_WRITE(reg, val);
2057         }
2058 }
2059
2060 static void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
2061 {
2062         u32 val;
2063
2064         val = I915_READ(LPT_TRANSCONF);
2065         val &= ~TRANS_ENABLE;
2066         I915_WRITE(LPT_TRANSCONF, val);
2067         /* wait for PCH transcoder off, transcoder state */
2068         if (wait_for((I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE) == 0, 50))
2069                 DRM_ERROR("Failed to disable PCH transcoder\n");
2070
2071         /* Workaround: clear timing override bit. */
2072         val = I915_READ(_TRANSA_CHICKEN2);
2073         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
2074         I915_WRITE(_TRANSA_CHICKEN2, val);
2075 }
2076
2077 /**
2078  * intel_enable_pipe - enable a pipe, asserting requirements
2079  * @crtc: crtc responsible for the pipe
2080  *
2081  * Enable @crtc's pipe, making sure that various hardware specific requirements
2082  * are met, if applicable, e.g. PLL enabled, LVDS pairs enabled, etc.
2083  */
2084 static void intel_enable_pipe(struct intel_crtc *crtc)
2085 {
2086         struct drm_device *dev = crtc->base.dev;
2087         struct drm_i915_private *dev_priv = dev->dev_private;
2088         enum pipe pipe = crtc->pipe;
2089         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
2090                                                                       pipe);
2091         enum pipe pch_transcoder;
2092         int reg;
2093         u32 val;
2094
2095         assert_planes_disabled(dev_priv, pipe);
2096         assert_cursor_disabled(dev_priv, pipe);
2097         assert_sprites_disabled(dev_priv, pipe);
2098
2099         if (HAS_PCH_LPT(dev_priv->dev))
2100                 pch_transcoder = TRANSCODER_A;
2101         else
2102                 pch_transcoder = pipe;
2103
2104         /*
2105          * A pipe without a PLL won't actually be able to drive bits from
2106          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
2107          * need the check.
2108          */
2109         if (!HAS_PCH_SPLIT(dev_priv->dev))
2110                 if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DSI))
2111                         assert_dsi_pll_enabled(dev_priv);
2112                 else
2113                         assert_pll_enabled(dev_priv, pipe);
2114         else {
2115                 if (crtc->config->has_pch_encoder) {
2116                         /* if driving the PCH, we need FDI enabled */
2117                         assert_fdi_rx_pll_enabled(dev_priv, pch_transcoder);
2118                         assert_fdi_tx_pll_enabled(dev_priv,
2119                                                   (enum pipe) cpu_transcoder);
2120                 }
2121                 /* FIXME: assert CPU port conditions for SNB+ */
2122         }
2123
2124         reg = PIPECONF(cpu_transcoder);
2125         val = I915_READ(reg);
2126         if (val & PIPECONF_ENABLE) {
2127                 WARN_ON(!((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
2128                           (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE)));
2129                 return;
2130         }
2131
2132         I915_WRITE(reg, val | PIPECONF_ENABLE);
2133         POSTING_READ(reg);
2134 }
2135
2136 /**
2137  * intel_disable_pipe - disable a pipe, asserting requirements
2138  * @crtc: crtc whose pipes is to be disabled
2139  *
2140  * Disable the pipe of @crtc, making sure that various hardware
2141  * specific requirements are met, if applicable, e.g. plane
2142  * disabled, panel fitter off, etc.
2143  *
2144  * Will wait until the pipe has shut down before returning.
2145  */
2146 static void intel_disable_pipe(struct intel_crtc *crtc)
2147 {
2148         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
2149         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
2150         enum pipe pipe = crtc->pipe;
2151         int reg;
2152         u32 val;
2153
2154         /*
2155          * Make sure planes won't keep trying to pump pixels to us,
2156          * or we might hang the display.
2157          */
2158         assert_planes_disabled(dev_priv, pipe);
2159         assert_cursor_disabled(dev_priv, pipe);
2160         assert_sprites_disabled(dev_priv, pipe);
2161
2162         reg = PIPECONF(cpu_transcoder);
2163         val = I915_READ(reg);
2164         if ((val & PIPECONF_ENABLE) == 0)
2165                 return;
2166
2167         /*
2168          * Double wide has implications for planes
2169          * so best keep it disabled when not needed.
2170          */
2171         if (crtc->config->double_wide)
2172                 val &= ~PIPECONF_DOUBLE_WIDE;
2173
2174         /* Don't disable pipe or pipe PLLs if needed */
2175         if (!(pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) &&
2176             !(pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
2177                 val &= ~PIPECONF_ENABLE;
2178
2179         I915_WRITE(reg, val);
2180         if ((val & PIPECONF_ENABLE) == 0)
2181                 intel_wait_for_pipe_off(crtc);
2182 }
2183
2184 /*
2185  * Plane regs are double buffered, going from enabled->disabled needs a
2186  * trigger in order to latch.  The display address reg provides this.
2187  */
2188 void intel_flush_primary_plane(struct drm_i915_private *dev_priv,
2189                                enum plane plane)
2190 {
2191         struct drm_device *dev = dev_priv->dev;
2192         u32 reg = INTEL_INFO(dev)->gen >= 4 ? DSPSURF(plane) : DSPADDR(plane);
2193
2194         I915_WRITE(reg, I915_READ(reg));
2195         POSTING_READ(reg);
2196 }
2197
2198 /**
2199  * intel_enable_primary_hw_plane - enable the primary plane on a given pipe
2200  * @plane:  plane to be enabled
2201  * @crtc: crtc for the plane
2202  *
2203  * Enable @plane on @crtc, making sure that the pipe is running first.
2204  */
2205 static void intel_enable_primary_hw_plane(struct drm_plane *plane,
2206                                           struct drm_crtc *crtc)
2207 {
2208         struct drm_device *dev = plane->dev;
2209         struct drm_i915_private *dev_priv = dev->dev_private;
2210         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2211
2212         /* If the pipe isn't enabled, we can't pump pixels and may hang */
2213         assert_pipe_enabled(dev_priv, intel_crtc->pipe);
2214
2215         if (intel_crtc->primary_enabled)
2216                 return;
2217
2218         intel_crtc->primary_enabled = true;
2219
2220         dev_priv->display.update_primary_plane(crtc, plane->fb,
2221                                                crtc->x, crtc->y);
2222
2223         /*
2224          * BDW signals flip done immediately if the plane
2225          * is disabled, even if the plane enable is already
2226          * armed to occur at the next vblank :(
2227          */
2228         if (IS_BROADWELL(dev))
2229                 intel_wait_for_vblank(dev, intel_crtc->pipe);
2230 }
2231
2232 /**
2233  * intel_disable_primary_hw_plane - disable the primary hardware plane
2234  * @plane: plane to be disabled
2235  * @crtc: crtc for the plane
2236  *
2237  * Disable @plane on @crtc, making sure that the pipe is running first.
2238  */
2239 static void intel_disable_primary_hw_plane(struct drm_plane *plane,
2240                                            struct drm_crtc *crtc)
2241 {
2242         struct drm_device *dev = plane->dev;
2243         struct drm_i915_private *dev_priv = dev->dev_private;
2244         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2245
2246         if (WARN_ON(!intel_crtc->active))
2247                 return;
2248
2249         if (!intel_crtc->primary_enabled)
2250                 return;
2251
2252         intel_crtc->primary_enabled = false;
2253
2254         dev_priv->display.update_primary_plane(crtc, plane->fb,
2255                                                crtc->x, crtc->y);
2256 }
2257
2258 static bool need_vtd_wa(struct drm_device *dev)
2259 {
2260 #ifdef CONFIG_INTEL_IOMMU
2261         if (INTEL_INFO(dev)->gen >= 6 && intel_iommu_gfx_mapped)
2262                 return true;
2263 #endif
2264         return false;
2265 }
2266
2267 unsigned int
2268 intel_tile_height(struct drm_device *dev, uint32_t pixel_format,
2269                   uint64_t fb_format_modifier)
2270 {
2271         unsigned int tile_height;
2272         uint32_t pixel_bytes;
2273
2274         switch (fb_format_modifier) {
2275         case DRM_FORMAT_MOD_NONE:
2276                 tile_height = 1;
2277                 break;
2278         case I915_FORMAT_MOD_X_TILED:
2279                 tile_height = IS_GEN2(dev) ? 16 : 8;
2280                 break;
2281         case I915_FORMAT_MOD_Y_TILED:
2282                 tile_height = 32;
2283                 break;
2284         case I915_FORMAT_MOD_Yf_TILED:
2285                 pixel_bytes = drm_format_plane_cpp(pixel_format, 0);
2286                 switch (pixel_bytes) {
2287                 default:
2288                 case 1:
2289                         tile_height = 64;
2290                         break;
2291                 case 2:
2292                 case 4:
2293                         tile_height = 32;
2294                         break;
2295                 case 8:
2296                         tile_height = 16;
2297                         break;
2298                 case 16:
2299                         WARN_ONCE(1,
2300                                   "128-bit pixels are not supported for display!");
2301                         tile_height = 16;
2302                         break;
2303                 }
2304                 break;
2305         default:
2306                 MISSING_CASE(fb_format_modifier);
2307                 tile_height = 1;
2308                 break;
2309         }
2310
2311         return tile_height;
2312 }
2313
2314 unsigned int
2315 intel_fb_align_height(struct drm_device *dev, unsigned int height,
2316                       uint32_t pixel_format, uint64_t fb_format_modifier)
2317 {
2318         return ALIGN(height, intel_tile_height(dev, pixel_format,
2319                                                fb_format_modifier));
2320 }
2321
2322 static int
2323 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view, struct drm_framebuffer *fb,
2324                         const struct drm_plane_state *plane_state)
2325 {
2326         struct intel_rotation_info *info = &view->rotation_info;
2327
2328         *view = i915_ggtt_view_normal;
2329
2330         if (!plane_state)
2331                 return 0;
2332
2333         if (!intel_rotation_90_or_270(plane_state->rotation))
2334                 return 0;
2335
2336         *view = i915_ggtt_view_rotated;
2337
2338         info->height = fb->height;
2339         info->pixel_format = fb->pixel_format;
2340         info->pitch = fb->pitches[0];
2341         info->fb_modifier = fb->modifier[0];
2342
2343         return 0;
2344 }
2345
2346 int
2347 intel_pin_and_fence_fb_obj(struct drm_plane *plane,
2348                            struct drm_framebuffer *fb,
2349                            const struct drm_plane_state *plane_state,
2350                            struct intel_engine_cs *pipelined)
2351 {
2352         struct drm_device *dev = fb->dev;
2353         struct drm_i915_private *dev_priv = dev->dev_private;
2354         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2355         struct i915_ggtt_view view;
2356         u32 alignment;
2357         int ret;
2358
2359         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2360
2361         switch (fb->modifier[0]) {
2362         case DRM_FORMAT_MOD_NONE:
2363                 if (INTEL_INFO(dev)->gen >= 9)
2364                         alignment = 256 * 1024;
2365                 else if (IS_BROADWATER(dev) || IS_CRESTLINE(dev))
2366                         alignment = 128 * 1024;
2367                 else if (INTEL_INFO(dev)->gen >= 4)
2368                         alignment = 4 * 1024;
2369                 else
2370                         alignment = 64 * 1024;
2371                 break;
2372         case I915_FORMAT_MOD_X_TILED:
2373                 if (INTEL_INFO(dev)->gen >= 9)
2374                         alignment = 256 * 1024;
2375                 else {
2376                         /* pin() will align the object as required by fence */
2377                         alignment = 0;
2378                 }
2379                 break;
2380         case I915_FORMAT_MOD_Y_TILED:
2381         case I915_FORMAT_MOD_Yf_TILED:
2382                 if (WARN_ONCE(INTEL_INFO(dev)->gen < 9,
2383                           "Y tiling bo slipped through, driver bug!\n"))
2384                         return -EINVAL;
2385                 alignment = 1 * 1024 * 1024;
2386                 break;
2387         default:
2388                 MISSING_CASE(fb->modifier[0]);
2389                 return -EINVAL;
2390         }
2391
2392         ret = intel_fill_fb_ggtt_view(&view, fb, plane_state);
2393         if (ret)
2394                 return ret;
2395
2396         /* Note that the w/a also requires 64 PTE of padding following the
2397          * bo. We currently fill all unused PTE with the shadow page and so
2398          * we should always have valid PTE following the scanout preventing
2399          * the VT-d warning.
2400          */
2401         if (need_vtd_wa(dev) && alignment < 256 * 1024)
2402                 alignment = 256 * 1024;
2403
2404         /*
2405          * Global gtt pte registers are special registers which actually forward
2406          * writes to a chunk of system memory. Which means that there is no risk
2407          * that the register values disappear as soon as we call
2408          * intel_runtime_pm_put(), so it is correct to wrap only the
2409          * pin/unpin/fence and not more.
2410          */
2411         intel_runtime_pm_get(dev_priv);
2412
2413         dev_priv->mm.interruptible = false;
2414         ret = i915_gem_object_pin_to_display_plane(obj, alignment, pipelined,
2415                                                    &view);
2416         if (ret)
2417                 goto err_interruptible;
2418
2419         /* Install a fence for tiled scan-out. Pre-i965 always needs a
2420          * fence, whereas 965+ only requires a fence if using
2421          * framebuffer compression.  For simplicity, we always install
2422          * a fence as the cost is not that onerous.
2423          */
2424         ret = i915_gem_object_get_fence(obj);
2425         if (ret)
2426                 goto err_unpin;
2427
2428         i915_gem_object_pin_fence(obj);
2429
2430         dev_priv->mm.interruptible = true;
2431         intel_runtime_pm_put(dev_priv);
2432         return 0;
2433
2434 err_unpin:
2435         i915_gem_object_unpin_from_display_plane(obj, &view);
2436 err_interruptible:
2437         dev_priv->mm.interruptible = true;
2438         intel_runtime_pm_put(dev_priv);
2439         return ret;
2440 }
2441
2442 static void intel_unpin_fb_obj(struct drm_framebuffer *fb,
2443                                const struct drm_plane_state *plane_state)
2444 {
2445         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2446         struct i915_ggtt_view view;
2447         int ret;
2448
2449         WARN_ON(!mutex_is_locked(&obj->base.dev->struct_mutex));
2450
2451         ret = intel_fill_fb_ggtt_view(&view, fb, plane_state);
2452         WARN_ONCE(ret, "Couldn't get view from plane state!");
2453
2454         i915_gem_object_unpin_fence(obj);
2455         i915_gem_object_unpin_from_display_plane(obj, &view);
2456 }
2457
2458 /* Computes the linear offset to the base tile and adjusts x, y. bytes per pixel
2459  * is assumed to be a power-of-two. */
2460 unsigned long intel_gen4_compute_page_offset(int *x, int *y,
2461                                              unsigned int tiling_mode,
2462                                              unsigned int cpp,
2463                                              unsigned int pitch)
2464 {
2465         if (tiling_mode != I915_TILING_NONE) {
2466                 unsigned int tile_rows, tiles;
2467
2468                 tile_rows = *y / 8;
2469                 *y %= 8;
2470
2471                 tiles = *x / (512/cpp);
2472                 *x %= 512/cpp;
2473
2474                 return tile_rows * pitch * 8 + tiles * 4096;
2475         } else {
2476                 unsigned int offset;
2477
2478                 offset = *y * pitch + *x * cpp;
2479                 *y = 0;
2480                 *x = (offset & 4095) / cpp;
2481                 return offset & -4096;
2482         }
2483 }
2484
2485 static int i9xx_format_to_fourcc(int format)
2486 {
2487         switch (format) {
2488         case DISPPLANE_8BPP:
2489                 return DRM_FORMAT_C8;
2490         case DISPPLANE_BGRX555:
2491                 return DRM_FORMAT_XRGB1555;
2492         case DISPPLANE_BGRX565:
2493                 return DRM_FORMAT_RGB565;
2494         default:
2495         case DISPPLANE_BGRX888:
2496                 return DRM_FORMAT_XRGB8888;
2497         case DISPPLANE_RGBX888:
2498                 return DRM_FORMAT_XBGR8888;
2499         case DISPPLANE_BGRX101010:
2500                 return DRM_FORMAT_XRGB2101010;
2501         case DISPPLANE_RGBX101010:
2502                 return DRM_FORMAT_XBGR2101010;
2503         }
2504 }
2505
2506 static int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2507 {
2508         switch (format) {
2509         case PLANE_CTL_FORMAT_RGB_565:
2510                 return DRM_FORMAT_RGB565;
2511         default:
2512         case PLANE_CTL_FORMAT_XRGB_8888:
2513                 if (rgb_order) {
2514                         if (alpha)
2515                                 return DRM_FORMAT_ABGR8888;
2516                         else
2517                                 return DRM_FORMAT_XBGR8888;
2518                 } else {
2519                         if (alpha)
2520                                 return DRM_FORMAT_ARGB8888;
2521                         else
2522                                 return DRM_FORMAT_XRGB8888;
2523                 }
2524         case PLANE_CTL_FORMAT_XRGB_2101010:
2525                 if (rgb_order)
2526                         return DRM_FORMAT_XBGR2101010;
2527                 else
2528                         return DRM_FORMAT_XRGB2101010;
2529         }
2530 }
2531
2532 static bool
2533 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2534                               struct intel_initial_plane_config *plane_config)
2535 {
2536         struct drm_device *dev = crtc->base.dev;
2537         struct drm_i915_gem_object *obj = NULL;
2538         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2539         struct drm_framebuffer *fb = &plane_config->fb->base;
2540         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2541         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2542                                     PAGE_SIZE);
2543
2544         size_aligned -= base_aligned;
2545
2546         if (plane_config->size == 0)
2547                 return false;
2548
2549         obj = i915_gem_object_create_stolen_for_preallocated(dev,
2550                                                              base_aligned,
2551                                                              base_aligned,
2552                                                              size_aligned);
2553         if (!obj)
2554                 return false;
2555
2556         obj->tiling_mode = plane_config->tiling;
2557         if (obj->tiling_mode == I915_TILING_X)
2558                 obj->stride = fb->pitches[0];
2559
2560         mode_cmd.pixel_format = fb->pixel_format;
2561         mode_cmd.width = fb->width;
2562         mode_cmd.height = fb->height;
2563         mode_cmd.pitches[0] = fb->pitches[0];
2564         mode_cmd.modifier[0] = fb->modifier[0];
2565         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2566
2567         mutex_lock(&dev->struct_mutex);
2568         if (intel_framebuffer_init(dev, to_intel_framebuffer(fb),
2569                                    &mode_cmd, obj)) {
2570                 DRM_DEBUG_KMS("intel fb init failed\n");
2571                 goto out_unref_obj;
2572         }
2573         mutex_unlock(&dev->struct_mutex);
2574
2575         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2576         return true;
2577
2578 out_unref_obj:
2579         drm_gem_object_unreference(&obj->base);
2580         mutex_unlock(&dev->struct_mutex);
2581         return false;
2582 }
2583
2584 /* Update plane->state->fb to match plane->fb after driver-internal updates */
2585 static void
2586 update_state_fb(struct drm_plane *plane)
2587 {
2588         if (plane->fb == plane->state->fb)
2589                 return;
2590
2591         if (plane->state->fb)
2592                 drm_framebuffer_unreference(plane->state->fb);
2593         plane->state->fb = plane->fb;
2594         if (plane->state->fb)
2595                 drm_framebuffer_reference(plane->state->fb);
2596 }
2597
2598 static void
2599 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2600                              struct intel_initial_plane_config *plane_config)
2601 {
2602         struct drm_device *dev = intel_crtc->base.dev;
2603         struct drm_i915_private *dev_priv = dev->dev_private;
2604         struct drm_crtc *c;
2605         struct intel_crtc *i;
2606         struct drm_i915_gem_object *obj;
2607         struct drm_plane *primary = intel_crtc->base.primary;
2608         struct drm_framebuffer *fb;
2609
2610         if (!plane_config->fb)
2611                 return;
2612
2613         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2614                 fb = &plane_config->fb->base;
2615                 goto valid_fb;
2616         }
2617
2618         kfree(plane_config->fb);
2619
2620         /*
2621          * Failed to alloc the obj, check to see if we should share
2622          * an fb with another CRTC instead
2623          */
2624         for_each_crtc(dev, c) {
2625                 i = to_intel_crtc(c);
2626
2627                 if (c == &intel_crtc->base)
2628                         continue;
2629
2630                 if (!i->active)
2631                         continue;
2632
2633                 fb = c->primary->fb;
2634                 if (!fb)
2635                         continue;
2636
2637                 obj = intel_fb_obj(fb);
2638                 if (i915_gem_obj_ggtt_offset(obj) == plane_config->base) {
2639                         drm_framebuffer_reference(fb);
2640                         goto valid_fb;
2641                 }
2642         }
2643
2644         return;
2645
2646 valid_fb:
2647         obj = intel_fb_obj(fb);
2648         if (obj->tiling_mode != I915_TILING_NONE)
2649                 dev_priv->preserve_bios_swizzle = true;
2650
2651         primary->fb = fb;
2652         primary->state->crtc = &intel_crtc->base;
2653         primary->crtc = &intel_crtc->base;
2654         update_state_fb(primary);
2655         obj->frontbuffer_bits |= INTEL_FRONTBUFFER_PRIMARY(intel_crtc->pipe);
2656 }
2657
2658 static void i9xx_update_primary_plane(struct drm_crtc *crtc,
2659                                       struct drm_framebuffer *fb,
2660                                       int x, int y)
2661 {
2662         struct drm_device *dev = crtc->dev;
2663         struct drm_i915_private *dev_priv = dev->dev_private;
2664         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2665         struct drm_i915_gem_object *obj;
2666         int plane = intel_crtc->plane;
2667         unsigned long linear_offset;
2668         u32 dspcntr;
2669         u32 reg = DSPCNTR(plane);
2670         int pixel_size;
2671
2672         if (!intel_crtc->primary_enabled) {
2673                 I915_WRITE(reg, 0);
2674                 if (INTEL_INFO(dev)->gen >= 4)
2675                         I915_WRITE(DSPSURF(plane), 0);
2676                 else
2677                         I915_WRITE(DSPADDR(plane), 0);
2678                 POSTING_READ(reg);
2679                 return;
2680         }
2681
2682         obj = intel_fb_obj(fb);
2683         if (WARN_ON(obj == NULL))
2684                 return;
2685
2686         pixel_size = drm_format_plane_cpp(fb->pixel_format, 0);
2687
2688         dspcntr = DISPPLANE_GAMMA_ENABLE;
2689
2690         dspcntr |= DISPLAY_PLANE_ENABLE;
2691
2692         if (INTEL_INFO(dev)->gen < 4) {
2693                 if (intel_crtc->pipe == PIPE_B)
2694                         dspcntr |= DISPPLANE_SEL_PIPE_B;
2695
2696                 /* pipesrc and dspsize control the size that is scaled from,
2697                  * which should always be the user's requested size.
2698                  */
2699                 I915_WRITE(DSPSIZE(plane),
2700                            ((intel_crtc->config->pipe_src_h - 1) << 16) |
2701                            (intel_crtc->config->pipe_src_w - 1));
2702                 I915_WRITE(DSPPOS(plane), 0);
2703         } else if (IS_CHERRYVIEW(dev) && plane == PLANE_B) {
2704                 I915_WRITE(PRIMSIZE(plane),
2705                            ((intel_crtc->config->pipe_src_h - 1) << 16) |
2706                            (intel_crtc->config->pipe_src_w - 1));
2707                 I915_WRITE(PRIMPOS(plane), 0);
2708                 I915_WRITE(PRIMCNSTALPHA(plane), 0);
2709         }
2710
2711         switch (fb->pixel_format) {
2712         case DRM_FORMAT_C8:
2713                 dspcntr |= DISPPLANE_8BPP;
2714                 break;
2715         case DRM_FORMAT_XRGB1555:
2716         case DRM_FORMAT_ARGB1555:
2717                 dspcntr |= DISPPLANE_BGRX555;
2718                 break;
2719         case DRM_FORMAT_RGB565:
2720                 dspcntr |= DISPPLANE_BGRX565;
2721                 break;
2722         case DRM_FORMAT_XRGB8888:
2723         case DRM_FORMAT_ARGB8888:
2724                 dspcntr |= DISPPLANE_BGRX888;
2725                 break;
2726         case DRM_FORMAT_XBGR8888:
2727         case DRM_FORMAT_ABGR8888:
2728                 dspcntr |= DISPPLANE_RGBX888;
2729                 break;
2730         case DRM_FORMAT_XRGB2101010:
2731         case DRM_FORMAT_ARGB2101010:
2732                 dspcntr |= DISPPLANE_BGRX101010;
2733                 break;
2734         case DRM_FORMAT_XBGR2101010:
2735         case DRM_FORMAT_ABGR2101010:
2736                 dspcntr |= DISPPLANE_RGBX101010;
2737                 break;
2738         default:
2739                 BUG();
2740         }
2741
2742         if (INTEL_INFO(dev)->gen >= 4 &&
2743             obj->tiling_mode != I915_TILING_NONE)
2744                 dspcntr |= DISPPLANE_TILED;
2745
2746         if (IS_G4X(dev))
2747                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2748
2749         linear_offset = y * fb->pitches[0] + x * pixel_size;
2750
2751         if (INTEL_INFO(dev)->gen >= 4) {
2752                 intel_crtc->dspaddr_offset =
2753                         intel_gen4_compute_page_offset(&x, &y, obj->tiling_mode,
2754                                                        pixel_size,
2755                                                        fb->pitches[0]);
2756                 linear_offset -= intel_crtc->dspaddr_offset;
2757         } else {
2758                 intel_crtc->dspaddr_offset = linear_offset;
2759         }
2760
2761         if (crtc->primary->state->rotation == BIT(DRM_ROTATE_180)) {
2762                 dspcntr |= DISPPLANE_ROTATE_180;
2763
2764                 x += (intel_crtc->config->pipe_src_w - 1);
2765                 y += (intel_crtc->config->pipe_src_h - 1);
2766
2767                 /* Finding the last pixel of the last line of the display
2768                 data and adding to linear_offset*/
2769                 linear_offset +=
2770                         (intel_crtc->config->pipe_src_h - 1) * fb->pitches[0] +
2771                         (intel_crtc->config->pipe_src_w - 1) * pixel_size;
2772         }
2773
2774         I915_WRITE(reg, dspcntr);
2775
2776         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2777         if (INTEL_INFO(dev)->gen >= 4) {
2778                 I915_WRITE(DSPSURF(plane),
2779                            i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2780                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2781                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2782         } else
2783                 I915_WRITE(DSPADDR(plane), i915_gem_obj_ggtt_offset(obj) + linear_offset);
2784         POSTING_READ(reg);
2785 }
2786
2787 static void ironlake_update_primary_plane(struct drm_crtc *crtc,
2788                                           struct drm_framebuffer *fb,
2789                                           int x, int y)
2790 {
2791         struct drm_device *dev = crtc->dev;
2792         struct drm_i915_private *dev_priv = dev->dev_private;
2793         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2794         struct drm_i915_gem_object *obj;
2795         int plane = intel_crtc->plane;
2796         unsigned long linear_offset;
2797         u32 dspcntr;
2798         u32 reg = DSPCNTR(plane);
2799         int pixel_size;
2800
2801         if (!intel_crtc->primary_enabled) {
2802                 I915_WRITE(reg, 0);
2803                 I915_WRITE(DSPSURF(plane), 0);
2804                 POSTING_READ(reg);
2805                 return;
2806         }
2807
2808         obj = intel_fb_obj(fb);
2809         if (WARN_ON(obj == NULL))
2810                 return;
2811
2812         pixel_size = drm_format_plane_cpp(fb->pixel_format, 0);
2813
2814         dspcntr = DISPPLANE_GAMMA_ENABLE;
2815
2816         dspcntr |= DISPLAY_PLANE_ENABLE;
2817
2818         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
2819                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
2820
2821         switch (fb->pixel_format) {
2822         case DRM_FORMAT_C8:
2823                 dspcntr |= DISPPLANE_8BPP;
2824                 break;
2825         case DRM_FORMAT_RGB565:
2826                 dspcntr |= DISPPLANE_BGRX565;
2827                 break;
2828         case DRM_FORMAT_XRGB8888:
2829         case DRM_FORMAT_ARGB8888:
2830                 dspcntr |= DISPPLANE_BGRX888;
2831                 break;
2832         case DRM_FORMAT_XBGR8888:
2833         case DRM_FORMAT_ABGR8888:
2834                 dspcntr |= DISPPLANE_RGBX888;
2835                 break;
2836         case DRM_FORMAT_XRGB2101010:
2837         case DRM_FORMAT_ARGB2101010:
2838                 dspcntr |= DISPPLANE_BGRX101010;
2839                 break;
2840         case DRM_FORMAT_XBGR2101010:
2841         case DRM_FORMAT_ABGR2101010:
2842                 dspcntr |= DISPPLANE_RGBX101010;
2843                 break;
2844         default:
2845                 BUG();
2846         }
2847
2848         if (obj->tiling_mode != I915_TILING_NONE)
2849                 dspcntr |= DISPPLANE_TILED;
2850
2851         if (!IS_HASWELL(dev) && !IS_BROADWELL(dev))
2852                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2853
2854         linear_offset = y * fb->pitches[0] + x * pixel_size;
2855         intel_crtc->dspaddr_offset =
2856                 intel_gen4_compute_page_offset(&x, &y, obj->tiling_mode,
2857                                                pixel_size,
2858                                                fb->pitches[0]);
2859         linear_offset -= intel_crtc->dspaddr_offset;
2860         if (crtc->primary->state->rotation == BIT(DRM_ROTATE_180)) {
2861                 dspcntr |= DISPPLANE_ROTATE_180;
2862
2863                 if (!IS_HASWELL(dev) && !IS_BROADWELL(dev)) {
2864                         x += (intel_crtc->config->pipe_src_w - 1);
2865                         y += (intel_crtc->config->pipe_src_h - 1);
2866
2867                         /* Finding the last pixel of the last line of the display
2868                         data and adding to linear_offset*/
2869                         linear_offset +=
2870                                 (intel_crtc->config->pipe_src_h - 1) * fb->pitches[0] +
2871                                 (intel_crtc->config->pipe_src_w - 1) * pixel_size;
2872                 }
2873         }
2874
2875         I915_WRITE(reg, dspcntr);
2876
2877         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2878         I915_WRITE(DSPSURF(plane),
2879                    i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2880         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
2881                 I915_WRITE(DSPOFFSET(plane), (y << 16) | x);
2882         } else {
2883                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2884                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2885         }
2886         POSTING_READ(reg);
2887 }
2888
2889 u32 intel_fb_stride_alignment(struct drm_device *dev, uint64_t fb_modifier,
2890                               uint32_t pixel_format)
2891 {
2892         u32 bits_per_pixel = drm_format_plane_cpp(pixel_format, 0) * 8;
2893
2894         /*
2895          * The stride is either expressed as a multiple of 64 bytes
2896          * chunks for linear buffers or in number of tiles for tiled
2897          * buffers.
2898          */
2899         switch (fb_modifier) {
2900         case DRM_FORMAT_MOD_NONE:
2901                 return 64;
2902         case I915_FORMAT_MOD_X_TILED:
2903                 if (INTEL_INFO(dev)->gen == 2)
2904                         return 128;
2905                 return 512;
2906         case I915_FORMAT_MOD_Y_TILED:
2907                 /* No need to check for old gens and Y tiling since this is
2908                  * about the display engine and those will be blocked before
2909                  * we get here.
2910                  */
2911                 return 128;
2912         case I915_FORMAT_MOD_Yf_TILED:
2913                 if (bits_per_pixel == 8)
2914                         return 64;
2915                 else
2916                         return 128;
2917         default:
2918                 MISSING_CASE(fb_modifier);
2919                 return 64;
2920         }
2921 }
2922
2923 unsigned long intel_plane_obj_offset(struct intel_plane *intel_plane,
2924                                      struct drm_i915_gem_object *obj)
2925 {
2926         const struct i915_ggtt_view *view = &i915_ggtt_view_normal;
2927
2928         if (intel_rotation_90_or_270(intel_plane->base.state->rotation))
2929                 view = &i915_ggtt_view_rotated;
2930
2931         return i915_gem_obj_ggtt_offset_view(obj, view);
2932 }
2933
2934 /*
2935  * This function detaches (aka. unbinds) unused scalers in hardware
2936  */
2937 void skl_detach_scalers(struct intel_crtc *intel_crtc)
2938 {
2939         struct drm_device *dev;
2940         struct drm_i915_private *dev_priv;
2941         struct intel_crtc_scaler_state *scaler_state;
2942         int i;
2943
2944         if (!intel_crtc || !intel_crtc->config)
2945                 return;
2946
2947         dev = intel_crtc->base.dev;
2948         dev_priv = dev->dev_private;
2949         scaler_state = &intel_crtc->config->scaler_state;
2950
2951         /* loop through and disable scalers that aren't in use */
2952         for (i = 0; i < intel_crtc->num_scalers; i++) {
2953                 if (!scaler_state->scalers[i].in_use) {
2954                         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, i), 0);
2955                         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, i), 0);
2956                         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, i), 0);
2957                         DRM_DEBUG_KMS("CRTC:%d Disabled scaler id %u.%u\n",
2958                                 intel_crtc->base.base.id, intel_crtc->pipe, i);
2959                 }
2960         }
2961 }
2962
2963 static void skylake_update_primary_plane(struct drm_crtc *crtc,
2964                                          struct drm_framebuffer *fb,
2965                                          int x, int y)
2966 {
2967         struct drm_device *dev = crtc->dev;
2968         struct drm_i915_private *dev_priv = dev->dev_private;
2969         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2970         struct drm_i915_gem_object *obj;
2971         int pipe = intel_crtc->pipe;
2972         u32 plane_ctl, stride_div, stride;
2973         u32 tile_height, plane_offset, plane_size;
2974         unsigned int rotation;
2975         int x_offset, y_offset;
2976         unsigned long surf_addr;
2977         struct drm_plane *plane;
2978
2979         if (!intel_crtc->primary_enabled) {
2980                 I915_WRITE(PLANE_CTL(pipe, 0), 0);
2981                 I915_WRITE(PLANE_SURF(pipe, 0), 0);
2982                 POSTING_READ(PLANE_CTL(pipe, 0));
2983                 return;
2984         }
2985
2986         plane_ctl = PLANE_CTL_ENABLE |
2987                     PLANE_CTL_PIPE_GAMMA_ENABLE |
2988                     PLANE_CTL_PIPE_CSC_ENABLE;
2989
2990         switch (fb->pixel_format) {
2991         case DRM_FORMAT_RGB565:
2992                 plane_ctl |= PLANE_CTL_FORMAT_RGB_565;
2993                 break;
2994         case DRM_FORMAT_XRGB8888:
2995                 plane_ctl |= PLANE_CTL_FORMAT_XRGB_8888;
2996                 break;
2997         case DRM_FORMAT_ARGB8888:
2998                 plane_ctl |= PLANE_CTL_FORMAT_XRGB_8888;
2999                 plane_ctl |= PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3000                 break;
3001         case DRM_FORMAT_XBGR8888:
3002                 plane_ctl |= PLANE_CTL_ORDER_RGBX;
3003                 plane_ctl |= PLANE_CTL_FORMAT_XRGB_8888;
3004                 break;
3005         case DRM_FORMAT_ABGR8888:
3006                 plane_ctl |= PLANE_CTL_ORDER_RGBX;
3007                 plane_ctl |= PLANE_CTL_FORMAT_XRGB_8888;
3008                 plane_ctl |= PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3009                 break;
3010         case DRM_FORMAT_XRGB2101010:
3011                 plane_ctl |= PLANE_CTL_FORMAT_XRGB_2101010;
3012                 break;
3013         case DRM_FORMAT_XBGR2101010:
3014                 plane_ctl |= PLANE_CTL_ORDER_RGBX;
3015                 plane_ctl |= PLANE_CTL_FORMAT_XRGB_2101010;
3016                 break;
3017         default:
3018                 BUG();
3019         }
3020
3021         switch (fb->modifier[0]) {
3022         case DRM_FORMAT_MOD_NONE:
3023                 break;
3024         case I915_FORMAT_MOD_X_TILED:
3025                 plane_ctl |= PLANE_CTL_TILED_X;
3026                 break;
3027         case I915_FORMAT_MOD_Y_TILED:
3028                 plane_ctl |= PLANE_CTL_TILED_Y;
3029                 break;
3030         case I915_FORMAT_MOD_Yf_TILED:
3031                 plane_ctl |= PLANE_CTL_TILED_YF;
3032                 break;
3033         default:
3034                 MISSING_CASE(fb->modifier[0]);
3035         }
3036
3037         plane_ctl |= PLANE_CTL_PLANE_GAMMA_DISABLE;
3038
3039         plane = crtc->primary;
3040         rotation = plane->state->rotation;
3041         switch (rotation) {
3042         case BIT(DRM_ROTATE_90):
3043                 plane_ctl |= PLANE_CTL_ROTATE_90;
3044                 break;
3045
3046         case BIT(DRM_ROTATE_180):
3047                 plane_ctl |= PLANE_CTL_ROTATE_180;
3048                 break;
3049
3050         case BIT(DRM_ROTATE_270):
3051                 plane_ctl |= PLANE_CTL_ROTATE_270;
3052                 break;
3053         }
3054
3055         obj = intel_fb_obj(fb);
3056         stride_div = intel_fb_stride_alignment(dev, fb->modifier[0],
3057                                                fb->pixel_format);
3058         surf_addr = intel_plane_obj_offset(to_intel_plane(plane), obj);
3059
3060         if (intel_rotation_90_or_270(rotation)) {
3061                 /* stride = Surface height in tiles */
3062                 tile_height = intel_tile_height(dev, fb->bits_per_pixel,
3063                                                 fb->modifier[0]);
3064                 stride = DIV_ROUND_UP(fb->height, tile_height);
3065                 x_offset = stride * tile_height - y - (plane->state->src_h >> 16);
3066                 y_offset = x;
3067                 plane_size = ((plane->state->src_w >> 16) - 1) << 16 |
3068                                         ((plane->state->src_h >> 16) - 1);
3069         } else {
3070                 stride = fb->pitches[0] / stride_div;
3071                 x_offset = x;
3072                 y_offset = y;
3073                 plane_size = ((plane->state->src_h >> 16) - 1) << 16 |
3074                         ((plane->state->src_w >> 16) - 1);
3075         }
3076         plane_offset = y_offset << 16 | x_offset;
3077
3078         I915_WRITE(PLANE_CTL(pipe, 0), plane_ctl);
3079         I915_WRITE(PLANE_POS(pipe, 0), 0);
3080         I915_WRITE(PLANE_OFFSET(pipe, 0), plane_offset);
3081         I915_WRITE(PLANE_SIZE(pipe, 0), plane_size);
3082         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
3083         I915_WRITE(PLANE_SURF(pipe, 0), surf_addr);
3084
3085         POSTING_READ(PLANE_SURF(pipe, 0));
3086 }
3087
3088 /* Assume fb object is pinned & idle & fenced and just update base pointers */
3089 static int
3090 intel_pipe_set_base_atomic(struct drm_crtc *crtc, struct drm_framebuffer *fb,
3091                            int x, int y, enum mode_set_atomic state)
3092 {
3093         struct drm_device *dev = crtc->dev;
3094         struct drm_i915_private *dev_priv = dev->dev_private;
3095
3096         if (dev_priv->display.disable_fbc)
3097                 dev_priv->display.disable_fbc(dev);
3098
3099         dev_priv->display.update_primary_plane(crtc, fb, x, y);
3100
3101         return 0;
3102 }
3103
3104 static void intel_complete_page_flips(struct drm_device *dev)
3105 {
3106         struct drm_crtc *crtc;
3107
3108         for_each_crtc(dev, crtc) {
3109                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3110                 enum plane plane = intel_crtc->plane;
3111
3112                 intel_prepare_page_flip(dev, plane);
3113                 intel_finish_page_flip_plane(dev, plane);
3114         }
3115 }
3116
3117 static void intel_update_primary_planes(struct drm_device *dev)
3118 {
3119         struct drm_i915_private *dev_priv = dev->dev_private;
3120         struct drm_crtc *crtc;
3121
3122         for_each_crtc(dev, crtc) {
3123                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3124
3125                 drm_modeset_lock(&crtc->mutex, NULL);
3126                 /*
3127                  * FIXME: Once we have proper support for primary planes (and
3128                  * disabling them without disabling the entire crtc) allow again
3129                  * a NULL crtc->primary->fb.
3130                  */
3131                 if (intel_crtc->active && crtc->primary->fb)
3132                         dev_priv->display.update_primary_plane(crtc,
3133                                                                crtc->primary->fb,
3134                                                                crtc->x,
3135                                                                crtc->y);
3136                 drm_modeset_unlock(&crtc->mutex);
3137         }
3138 }
3139
3140 void intel_prepare_reset(struct drm_device *dev)
3141 {
3142         struct drm_i915_private *dev_priv = to_i915(dev);
3143         struct intel_crtc *crtc;
3144
3145         /* no reset support for gen2 */
3146         if (IS_GEN2(dev))
3147                 return;
3148
3149         /* reset doesn't touch the display */
3150         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
3151                 return;
3152
3153         drm_modeset_lock_all(dev);
3154
3155         /*
3156          * Disabling the crtcs gracefully seems nicer. Also the
3157          * g33 docs say we should at least disable all the planes.
3158          */
3159         for_each_intel_crtc(dev, crtc) {
3160                 if (crtc->active)
3161                         dev_priv->display.crtc_disable(&crtc->base);
3162         }
3163 }
3164
3165 void intel_finish_reset(struct drm_device *dev)
3166 {
3167         struct drm_i915_private *dev_priv = to_i915(dev);
3168
3169         /*
3170          * Flips in the rings will be nuked by the reset,
3171          * so complete all pending flips so that user space
3172          * will get its events and not get stuck.
3173          */
3174         intel_complete_page_flips(dev);
3175
3176         /* no reset support for gen2 */
3177         if (IS_GEN2(dev))
3178                 return;
3179
3180         /* reset doesn't touch the display */
3181         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev)) {
3182                 /*
3183                  * Flips in the rings have been nuked by the reset,
3184                  * so update the base address of all primary
3185                  * planes to the the last fb to make sure we're
3186                  * showing the correct fb after a reset.
3187                  */
3188                 intel_update_primary_planes(dev);
3189                 return;
3190         }
3191
3192         /*
3193          * The display has been reset as well,
3194          * so need a full re-initialization.
3195          */
3196         intel_runtime_pm_disable_interrupts(dev_priv);
3197         intel_runtime_pm_enable_interrupts(dev_priv);
3198
3199         intel_modeset_init_hw(dev);
3200
3201         spin_lock_irq(&dev_priv->irq_lock);
3202         if (dev_priv->display.hpd_irq_setup)
3203                 dev_priv->display.hpd_irq_setup(dev);
3204         spin_unlock_irq(&dev_priv->irq_lock);
3205
3206         intel_modeset_setup_hw_state(dev, true);
3207
3208         intel_hpd_init(dev_priv);
3209
3210         drm_modeset_unlock_all(dev);
3211 }
3212
3213 static int
3214 intel_finish_fb(struct drm_framebuffer *old_fb)
3215 {
3216         struct drm_i915_gem_object *obj = intel_fb_obj(old_fb);
3217         struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
3218         bool was_interruptible = dev_priv->mm.interruptible;
3219         int ret;
3220
3221         /* Big Hammer, we also need to ensure that any pending
3222          * MI_WAIT_FOR_EVENT inside a user batch buffer on the
3223          * current scanout is retired before unpinning the old
3224          * framebuffer.
3225          *
3226          * This should only fail upon a hung GPU, in which case we
3227          * can safely continue.
3228          */
3229         dev_priv->mm.interruptible = false;
3230         ret = i915_gem_object_finish_gpu(obj);
3231         dev_priv->mm.interruptible = was_interruptible;
3232
3233         return ret;
3234 }
3235
3236 static bool intel_crtc_has_pending_flip(struct drm_crtc *crtc)
3237 {
3238         struct drm_device *dev = crtc->dev;
3239         struct drm_i915_private *dev_priv = dev->dev_private;
3240         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3241         bool pending;
3242
3243         if (i915_reset_in_progress(&dev_priv->gpu_error) ||
3244             intel_crtc->reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
3245                 return false;
3246
3247         spin_lock_irq(&dev->event_lock);
3248         pending = to_intel_crtc(crtc)->unpin_work != NULL;
3249         spin_unlock_irq(&dev->event_lock);
3250
3251         return pending;
3252 }
3253
3254 static void intel_update_pipe_size(struct intel_crtc *crtc)
3255 {
3256         struct drm_device *dev = crtc->base.dev;
3257         struct drm_i915_private *dev_priv = dev->dev_private;
3258         const struct drm_display_mode *adjusted_mode;
3259
3260         if (!i915.fastboot)
3261                 return;
3262
3263         /*
3264          * Update pipe size and adjust fitter if needed: the reason for this is
3265          * that in compute_mode_changes we check the native mode (not the pfit
3266          * mode) to see if we can flip rather than do a full mode set. In the
3267          * fastboot case, we'll flip, but if we don't update the pipesrc and
3268          * pfit state, we'll end up with a big fb scanned out into the wrong
3269          * sized surface.
3270          *
3271          * To fix this properly, we need to hoist the checks up into
3272          * compute_mode_changes (or above), check the actual pfit state and
3273          * whether the platform allows pfit disable with pipe active, and only
3274          * then update the pipesrc and pfit state, even on the flip path.
3275          */
3276
3277         adjusted_mode = &crtc->config->base.adjusted_mode;
3278
3279         I915_WRITE(PIPESRC(crtc->pipe),
3280                    ((adjusted_mode->crtc_hdisplay - 1) << 16) |
3281                    (adjusted_mode->crtc_vdisplay - 1));
3282         if (!crtc->config->pch_pfit.enabled &&
3283             (intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS) ||
3284              intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP))) {
3285                 I915_WRITE(PF_CTL(crtc->pipe), 0);
3286                 I915_WRITE(PF_WIN_POS(crtc->pipe), 0);
3287                 I915_WRITE(PF_WIN_SZ(crtc->pipe), 0);
3288         }
3289         crtc->config->pipe_src_w = adjusted_mode->crtc_hdisplay;
3290         crtc->config->pipe_src_h = adjusted_mode->crtc_vdisplay;
3291 }
3292
3293 static void intel_fdi_normal_train(struct drm_crtc *crtc)
3294 {
3295         struct drm_device *dev = crtc->dev;
3296         struct drm_i915_private *dev_priv = dev->dev_private;
3297         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3298         int pipe = intel_crtc->pipe;
3299         u32 reg, temp;
3300
3301         /* enable normal train */
3302         reg = FDI_TX_CTL(pipe);
3303         temp = I915_READ(reg);
3304         if (IS_IVYBRIDGE(dev)) {
3305                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3306                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3307         } else {
3308                 temp &= ~FDI_LINK_TRAIN_NONE;
3309                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3310         }
3311         I915_WRITE(reg, temp);
3312
3313         reg = FDI_RX_CTL(pipe);
3314         temp = I915_READ(reg);
3315         if (HAS_PCH_CPT(dev)) {
3316                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3317                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3318         } else {
3319                 temp &= ~FDI_LINK_TRAIN_NONE;
3320                 temp |= FDI_LINK_TRAIN_NONE;
3321         }
3322         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3323
3324         /* wait one idle pattern time */
3325         POSTING_READ(reg);
3326         udelay(1000);
3327
3328         /* IVB wants error correction enabled */
3329         if (IS_IVYBRIDGE(dev))
3330                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3331                            FDI_FE_ERRC_ENABLE);
3332 }
3333
3334 /* The FDI link training functions for ILK/Ibexpeak. */
3335 static void ironlake_fdi_link_train(struct drm_crtc *crtc)
3336 {
3337         struct drm_device *dev = crtc->dev;
3338         struct drm_i915_private *dev_priv = dev->dev_private;
3339         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3340         int pipe = intel_crtc->pipe;
3341         u32 reg, temp, tries;
3342
3343         /* FDI needs bits from pipe first */
3344         assert_pipe_enabled(dev_priv, pipe);
3345
3346         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3347            for train result */
3348         reg = FDI_RX_IMR(pipe);
3349         temp = I915_READ(reg);
3350         temp &= ~FDI_RX_SYMBOL_LOCK;
3351         temp &= ~FDI_RX_BIT_LOCK;
3352         I915_WRITE(reg, temp);
3353         I915_READ(reg);
3354         udelay(150);
3355
3356         /* enable CPU FDI TX and PCH FDI RX */
3357         reg = FDI_TX_CTL(pipe);
3358         temp = I915_READ(reg);
3359         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3360         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3361         temp &= ~FDI_LINK_TRAIN_NONE;
3362         temp |= FDI_LINK_TRAIN_PATTERN_1;
3363         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3364
3365         reg = FDI_RX_CTL(pipe);
3366         temp = I915_READ(reg);
3367         temp &= ~FDI_LINK_TRAIN_NONE;
3368         temp |= FDI_LINK_TRAIN_PATTERN_1;
3369         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3370
3371         POSTING_READ(reg);
3372         udelay(150);
3373
3374         /* Ironlake workaround, enable clock pointer after FDI enable*/
3375         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3376         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3377                    FDI_RX_PHASE_SYNC_POINTER_EN);
3378
3379         reg = FDI_RX_IIR(pipe);
3380         for (tries = 0; tries < 5; tries++) {
3381                 temp = I915_READ(reg);
3382                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3383
3384                 if ((temp & FDI_RX_BIT_LOCK)) {
3385                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3386                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3387                         break;
3388                 }
3389         }
3390         if (tries == 5)
3391                 DRM_ERROR("FDI train 1 fail!\n");
3392
3393         /* Train 2 */
3394         reg = FDI_TX_CTL(pipe);
3395         temp = I915_READ(reg);
3396         temp &= ~FDI_LINK_TRAIN_NONE;
3397         temp |= FDI_LINK_TRAIN_PATTERN_2;
3398         I915_WRITE(reg, temp);
3399
3400         reg = FDI_RX_CTL(pipe);
3401         temp = I915_READ(reg);
3402         temp &= ~FDI_LINK_TRAIN_NONE;
3403         temp |= FDI_LINK_TRAIN_PATTERN_2;
3404         I915_WRITE(reg, temp);
3405
3406         POSTING_READ(reg);
3407         udelay(150);
3408
3409         reg = FDI_RX_IIR(pipe);
3410         for (tries = 0; tries < 5; tries++) {
3411                 temp = I915_READ(reg);
3412                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3413
3414                 if (temp & FDI_RX_SYMBOL_LOCK) {
3415                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3416                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3417                         break;
3418                 }
3419         }
3420         if (tries == 5)
3421                 DRM_ERROR("FDI train 2 fail!\n");
3422
3423         DRM_DEBUG_KMS("FDI train done\n");
3424
3425 }
3426
3427 static const int snb_b_fdi_train_param[] = {
3428         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3429         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3430         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3431         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3432 };
3433
3434 /* The FDI link training functions for SNB/Cougarpoint. */
3435 static void gen6_fdi_link_train(struct drm_crtc *crtc)
3436 {
3437         struct drm_device *dev = crtc->dev;
3438         struct drm_i915_private *dev_priv = dev->dev_private;
3439         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3440         int pipe = intel_crtc->pipe;
3441         u32 reg, temp, i, retry;
3442
3443         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3444            for train result */
3445         reg = FDI_RX_IMR(pipe);
3446         temp = I915_READ(reg);
3447         temp &= ~FDI_RX_SYMBOL_LOCK;
3448         temp &= ~FDI_RX_BIT_LOCK;
3449         I915_WRITE(reg, temp);
3450
3451         POSTING_READ(reg);
3452         udelay(150);
3453
3454         /* enable CPU FDI TX and PCH FDI RX */
3455         reg = FDI_TX_CTL(pipe);
3456         temp = I915_READ(reg);
3457         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3458         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3459         temp &= ~FDI_LINK_TRAIN_NONE;
3460         temp |= FDI_LINK_TRAIN_PATTERN_1;
3461         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3462         /* SNB-B */
3463         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3464         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3465
3466         I915_WRITE(FDI_RX_MISC(pipe),
3467                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3468
3469         reg = FDI_RX_CTL(pipe);
3470         temp = I915_READ(reg);
3471         if (HAS_PCH_CPT(dev)) {
3472                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3473                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3474         } else {
3475                 temp &= ~FDI_LINK_TRAIN_NONE;
3476                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3477         }
3478         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3479
3480         POSTING_READ(reg);
3481         udelay(150);
3482
3483         for (i = 0; i < 4; i++) {
3484                 reg = FDI_TX_CTL(pipe);
3485                 temp = I915_READ(reg);
3486                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3487                 temp |= snb_b_fdi_train_param[i];
3488                 I915_WRITE(reg, temp);
3489
3490                 POSTING_READ(reg);
3491                 udelay(500);
3492
3493                 for (retry = 0; retry < 5; retry++) {
3494                         reg = FDI_RX_IIR(pipe);
3495                         temp = I915_READ(reg);
3496                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3497                         if (temp & FDI_RX_BIT_LOCK) {
3498                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3499                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
3500                                 break;
3501                         }
3502                         udelay(50);
3503                 }
3504                 if (retry < 5)
3505                         break;
3506         }
3507         if (i == 4)
3508                 DRM_ERROR("FDI train 1 fail!\n");
3509
3510         /* Train 2 */
3511         reg = FDI_TX_CTL(pipe);
3512         temp = I915_READ(reg);
3513         temp &= ~FDI_LINK_TRAIN_NONE;
3514         temp |= FDI_LINK_TRAIN_PATTERN_2;
3515         if (IS_GEN6(dev)) {
3516                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3517                 /* SNB-B */
3518                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3519         }
3520         I915_WRITE(reg, temp);
3521
3522         reg = FDI_RX_CTL(pipe);
3523         temp = I915_READ(reg);
3524         if (HAS_PCH_CPT(dev)) {
3525                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3526                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3527         } else {
3528                 temp &= ~FDI_LINK_TRAIN_NONE;
3529                 temp |= FDI_LINK_TRAIN_PATTERN_2;
3530         }
3531         I915_WRITE(reg, temp);
3532
3533         POSTING_READ(reg);
3534         udelay(150);
3535
3536         for (i = 0; i < 4; i++) {
3537                 reg = FDI_TX_CTL(pipe);
3538                 temp = I915_READ(reg);
3539                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3540                 temp |= snb_b_fdi_train_param[i];
3541                 I915_WRITE(reg, temp);
3542
3543                 POSTING_READ(reg);
3544                 udelay(500);
3545
3546                 for (retry = 0; retry < 5; retry++) {
3547                         reg = FDI_RX_IIR(pipe);
3548                         temp = I915_READ(reg);
3549                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3550                         if (temp & FDI_RX_SYMBOL_LOCK) {
3551                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3552                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
3553                                 break;
3554                         }
3555                         udelay(50);
3556                 }
3557                 if (retry < 5)
3558                         break;
3559         }
3560         if (i == 4)
3561                 DRM_ERROR("FDI train 2 fail!\n");
3562
3563         DRM_DEBUG_KMS("FDI train done.\n");
3564 }
3565
3566 /* Manual link training for Ivy Bridge A0 parts */
3567 static void ivb_manual_fdi_link_train(struct drm_crtc *crtc)
3568 {
3569         struct drm_device *dev = crtc->dev;
3570         struct drm_i915_private *dev_priv = dev->dev_private;
3571         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3572         int pipe = intel_crtc->pipe;
3573         u32 reg, temp, i, j;
3574
3575         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3576            for train result */
3577         reg = FDI_RX_IMR(pipe);
3578         temp = I915_READ(reg);
3579         temp &= ~FDI_RX_SYMBOL_LOCK;
3580         temp &= ~FDI_RX_BIT_LOCK;
3581         I915_WRITE(reg, temp);
3582
3583         POSTING_READ(reg);
3584         udelay(150);
3585
3586         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
3587                       I915_READ(FDI_RX_IIR(pipe)));
3588
3589         /* Try each vswing and preemphasis setting twice before moving on */
3590         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
3591                 /* disable first in case we need to retry */
3592                 reg = FDI_TX_CTL(pipe);
3593                 temp = I915_READ(reg);
3594                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
3595                 temp &= ~FDI_TX_ENABLE;
3596                 I915_WRITE(reg, temp);
3597
3598                 reg = FDI_RX_CTL(pipe);
3599                 temp = I915_READ(reg);
3600                 temp &= ~FDI_LINK_TRAIN_AUTO;
3601                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3602                 temp &= ~FDI_RX_ENABLE;
3603                 I915_WRITE(reg, temp);
3604
3605                 /* enable CPU FDI TX and PCH FDI RX */
3606                 reg = FDI_TX_CTL(pipe);
3607                 temp = I915_READ(reg);
3608                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
3609                 temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3610                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
3611                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3612                 temp |= snb_b_fdi_train_param[j/2];
3613                 temp |= FDI_COMPOSITE_SYNC;
3614                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
3615
3616                 I915_WRITE(FDI_RX_MISC(pipe),
3617                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3618
3619                 reg = FDI_RX_CTL(pipe);
3620                 temp = I915_READ(reg);
3621                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3622                 temp |= FDI_COMPOSITE_SYNC;
3623                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
3624
3625                 POSTING_READ(reg);
3626                 udelay(1); /* should be 0.5us */
3627
3628                 for (i = 0; i < 4; i++) {
3629                         reg = FDI_RX_IIR(pipe);
3630                         temp = I915_READ(reg);
3631                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3632
3633                         if (temp & FDI_RX_BIT_LOCK ||
3634                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
3635                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3636                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
3637                                               i);
3638                                 break;
3639                         }
3640                         udelay(1); /* should be 0.5us */
3641                 }
3642                 if (i == 4) {
3643                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
3644                         continue;
3645                 }
3646
3647                 /* Train 2 */
3648                 reg = FDI_TX_CTL(pipe);
3649                 temp = I915_READ(reg);
3650                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3651                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
3652                 I915_WRITE(reg, temp);
3653
3654                 reg = FDI_RX_CTL(pipe);
3655                 temp = I915_READ(reg);
3656                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3657                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3658                 I915_WRITE(reg, temp);
3659
3660                 POSTING_READ(reg);
3661                 udelay(2); /* should be 1.5us */
3662
3663                 for (i = 0; i < 4; i++) {
3664                         reg = FDI_RX_IIR(pipe);
3665                         temp = I915_READ(reg);
3666                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3667
3668                         if (temp & FDI_RX_SYMBOL_LOCK ||
3669                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
3670                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3671                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
3672                                               i);
3673                                 goto train_done;
3674                         }
3675                         udelay(2); /* should be 1.5us */
3676                 }
3677                 if (i == 4)
3678                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
3679         }
3680
3681 train_done:
3682         DRM_DEBUG_KMS("FDI train done.\n");
3683 }
3684
3685 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
3686 {
3687         struct drm_device *dev = intel_crtc->base.dev;
3688         struct drm_i915_private *dev_priv = dev->dev_private;
3689         int pipe = intel_crtc->pipe;
3690         u32 reg, temp;
3691
3692
3693         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
3694         reg = FDI_RX_CTL(pipe);
3695         temp = I915_READ(reg);
3696         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
3697         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3698         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3699         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
3700
3701         POSTING_READ(reg);
3702         udelay(200);
3703
3704         /* Switch from Rawclk to PCDclk */
3705         temp = I915_READ(reg);
3706         I915_WRITE(reg, temp | FDI_PCDCLK);
3707
3708         POSTING_READ(reg);
3709         udelay(200);
3710
3711         /* Enable CPU FDI TX PLL, always on for Ironlake */
3712         reg = FDI_TX_CTL(pipe);
3713         temp = I915_READ(reg);
3714         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
3715                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
3716
3717                 POSTING_READ(reg);
3718                 udelay(100);
3719         }
3720 }
3721
3722 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
3723 {
3724         struct drm_device *dev = intel_crtc->base.dev;
3725         struct drm_i915_private *dev_priv = dev->dev_private;
3726         int pipe = intel_crtc->pipe;
3727         u32 reg, temp;
3728
3729         /* Switch from PCDclk to Rawclk */
3730         reg = FDI_RX_CTL(pipe);
3731         temp = I915_READ(reg);
3732         I915_WRITE(reg, temp & ~FDI_PCDCLK);
3733
3734         /* Disable CPU FDI TX PLL */
3735         reg = FDI_TX_CTL(pipe);
3736         temp = I915_READ(reg);
3737         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
3738
3739         POSTING_READ(reg);
3740         udelay(100);
3741
3742         reg = FDI_RX_CTL(pipe);
3743         temp = I915_READ(reg);
3744         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
3745
3746         /* Wait for the clocks to turn off. */
3747         POSTING_READ(reg);
3748         udelay(100);
3749 }
3750
3751 static void ironlake_fdi_disable(struct drm_crtc *crtc)
3752 {
3753         struct drm_device *dev = crtc->dev;
3754         struct drm_i915_private *dev_priv = dev->dev_private;
3755         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3756         int pipe = intel_crtc->pipe;
3757         u32 reg, temp;
3758
3759         /* disable CPU FDI tx and PCH FDI rx */
3760         reg = FDI_TX_CTL(pipe);
3761         temp = I915_READ(reg);
3762         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
3763         POSTING_READ(reg);
3764
3765         reg = FDI_RX_CTL(pipe);
3766         temp = I915_READ(reg);
3767         temp &= ~(0x7 << 16);
3768         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3769         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
3770
3771         POSTING_READ(reg);
3772         udelay(100);
3773
3774         /* Ironlake workaround, disable clock pointer after downing FDI */
3775         if (HAS_PCH_IBX(dev))
3776                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3777
3778         /* still set train pattern 1 */
3779         reg = FDI_TX_CTL(pipe);
3780         temp = I915_READ(reg);
3781         temp &= ~FDI_LINK_TRAIN_NONE;
3782         temp |= FDI_LINK_TRAIN_PATTERN_1;
3783         I915_WRITE(reg, temp);
3784
3785         reg = FDI_RX_CTL(pipe);
3786         temp = I915_READ(reg);
3787         if (HAS_PCH_CPT(dev)) {
3788                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3789                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3790         } else {
3791                 temp &= ~FDI_LINK_TRAIN_NONE;
3792                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3793         }
3794         /* BPC in FDI rx is consistent with that in PIPECONF */
3795         temp &= ~(0x07 << 16);
3796         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3797         I915_WRITE(reg, temp);
3798
3799         POSTING_READ(reg);
3800         udelay(100);
3801 }
3802
3803 bool intel_has_pending_fb_unpin(struct drm_device *dev)
3804 {
3805         struct intel_crtc *crtc;
3806
3807         /* Note that we don't need to be called with mode_config.lock here
3808          * as our list of CRTC objects is static for the lifetime of the
3809          * device and so cannot disappear as we iterate. Similarly, we can
3810          * happily treat the predicates as racy, atomic checks as userspace
3811          * cannot claim and pin a new fb without at least acquring the
3812          * struct_mutex and so serialising with us.
3813          */
3814         for_each_intel_crtc(dev, crtc) {
3815                 if (atomic_read(&crtc->unpin_work_count) == 0)
3816                         continue;
3817
3818                 if (crtc->unpin_work)
3819                         intel_wait_for_vblank(dev, crtc->pipe);
3820
3821                 return true;
3822         }
3823
3824         return false;
3825 }
3826
3827 static void page_flip_completed(struct intel_crtc *intel_crtc)
3828 {
3829         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
3830         struct intel_unpin_work *work = intel_crtc->unpin_work;
3831
3832         /* ensure that the unpin work is consistent wrt ->pending. */
3833         smp_rmb();
3834         intel_crtc->unpin_work = NULL;
3835
3836         if (work->event)
3837                 drm_send_vblank_event(intel_crtc->base.dev,
3838                                       intel_crtc->pipe,
3839                                       work->event);
3840
3841         drm_crtc_vblank_put(&intel_crtc->base);
3842
3843         wake_up_all(&dev_priv->pending_flip_queue);
3844         queue_work(dev_priv->wq, &work->work);
3845
3846         trace_i915_flip_complete(intel_crtc->plane,
3847                                  work->pending_flip_obj);
3848 }
3849
3850 void intel_crtc_wait_for_pending_flips(struct drm_crtc *crtc)
3851 {
3852         struct drm_device *dev = crtc->dev;
3853         struct drm_i915_private *dev_priv = dev->dev_private;
3854
3855         WARN_ON(waitqueue_active(&dev_priv->pending_flip_queue));
3856         if (WARN_ON(wait_event_timeout(dev_priv->pending_flip_queue,
3857                                        !intel_crtc_has_pending_flip(crtc),
3858                                        60*HZ) == 0)) {
3859                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3860
3861                 spin_lock_irq(&dev->event_lock);
3862                 if (intel_crtc->unpin_work) {
3863                         WARN_ONCE(1, "Removing stuck page flip\n");
3864                         page_flip_completed(intel_crtc);
3865                 }
3866                 spin_unlock_irq(&dev->event_lock);
3867         }
3868
3869         if (crtc->primary->fb) {
3870                 mutex_lock(&dev->struct_mutex);
3871                 intel_finish_fb(crtc->primary->fb);
3872                 mutex_unlock(&dev->struct_mutex);
3873         }
3874 }
3875
3876 /* Program iCLKIP clock to the desired frequency */
3877 static void lpt_program_iclkip(struct drm_crtc *crtc)
3878 {
3879         struct drm_device *dev = crtc->dev;
3880         struct drm_i915_private *dev_priv = dev->dev_private;
3881         int clock = to_intel_crtc(crtc)->config->base.adjusted_mode.crtc_clock;
3882         u32 divsel, phaseinc, auxdiv, phasedir = 0;
3883         u32 temp;
3884
3885         mutex_lock(&dev_priv->dpio_lock);
3886
3887         /* It is necessary to ungate the pixclk gate prior to programming
3888          * the divisors, and gate it back when it is done.
3889          */
3890         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
3891
3892         /* Disable SSCCTL */
3893         intel_sbi_write(dev_priv, SBI_SSCCTL6,
3894                         intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK) |
3895                                 SBI_SSCCTL_DISABLE,
3896                         SBI_ICLK);
3897
3898         /* 20MHz is a corner case which is out of range for the 7-bit divisor */
3899         if (clock == 20000) {
3900                 auxdiv = 1;
3901                 divsel = 0x41;
3902                 phaseinc = 0x20;
3903         } else {
3904                 /* The iCLK virtual clock root frequency is in MHz,
3905                  * but the adjusted_mode->crtc_clock in in KHz. To get the
3906                  * divisors, it is necessary to divide one by another, so we
3907                  * convert the virtual clock precision to KHz here for higher
3908                  * precision.
3909                  */
3910                 u32 iclk_virtual_root_freq = 172800 * 1000;
3911                 u32 iclk_pi_range = 64;
3912                 u32 desired_divisor, msb_divisor_value, pi_value;
3913
3914                 desired_divisor = (iclk_virtual_root_freq / clock);
3915                 msb_divisor_value = desired_divisor / iclk_pi_range;
3916                 pi_value = desired_divisor % iclk_pi_range;
3917
3918                 auxdiv = 0;
3919                 divsel = msb_divisor_value - 2;
3920                 phaseinc = pi_value;
3921         }
3922
3923         /* This should not happen with any sane values */
3924         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
3925                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
3926         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
3927                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
3928
3929         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
3930                         clock,
3931                         auxdiv,
3932                         divsel,
3933                         phasedir,
3934                         phaseinc);
3935
3936         /* Program SSCDIVINTPHASE6 */
3937         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
3938         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
3939         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
3940         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
3941         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
3942         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
3943         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
3944         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
3945
3946         /* Program SSCAUXDIV */
3947         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
3948         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
3949         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
3950         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
3951
3952         /* Enable modulator and associated divider */
3953         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3954         temp &= ~SBI_SSCCTL_DISABLE;
3955         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
3956
3957         /* Wait for initialization time */
3958         udelay(24);
3959
3960         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
3961
3962         mutex_unlock(&dev_priv->dpio_lock);
3963 }
3964
3965 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
3966                                                 enum pipe pch_transcoder)
3967 {
3968         struct drm_device *dev = crtc->base.dev;
3969         struct drm_i915_private *dev_priv = dev->dev_private;
3970         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
3971
3972         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
3973                    I915_READ(HTOTAL(cpu_transcoder)));
3974         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
3975                    I915_READ(HBLANK(cpu_transcoder)));
3976         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
3977                    I915_READ(HSYNC(cpu_transcoder)));
3978
3979         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
3980                    I915_READ(VTOTAL(cpu_transcoder)));
3981         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
3982                    I915_READ(VBLANK(cpu_transcoder)));
3983         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
3984                    I915_READ(VSYNC(cpu_transcoder)));
3985         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
3986                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
3987 }
3988
3989 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
3990 {
3991         struct drm_i915_private *dev_priv = dev->dev_private;
3992         uint32_t temp;
3993
3994         temp = I915_READ(SOUTH_CHICKEN1);
3995         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
3996                 return;
3997
3998         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
3999         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4000
4001         temp &= ~FDI_BC_BIFURCATION_SELECT;
4002         if (enable)
4003                 temp |= FDI_BC_BIFURCATION_SELECT;
4004
4005         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4006         I915_WRITE(SOUTH_CHICKEN1, temp);
4007         POSTING_READ(SOUTH_CHICKEN1);
4008 }
4009
4010 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4011 {
4012         struct drm_device *dev = intel_crtc->base.dev;
4013
4014         switch (intel_crtc->pipe) {
4015         case PIPE_A:
4016                 break;
4017         case PIPE_B:
4018                 if (intel_crtc->config->fdi_lanes > 2)
4019                         cpt_set_fdi_bc_bifurcation(dev, false);
4020                 else
4021                         cpt_set_fdi_bc_bifurcation(dev, true);
4022
4023                 break;
4024         case PIPE_C:
4025                 cpt_set_fdi_bc_bifurcation(dev, true);
4026
4027                 break;
4028         default:
4029                 BUG();
4030         }
4031 }
4032
4033 /*
4034  * Enable PCH resources required for PCH ports:
4035  *   - PCH PLLs
4036  *   - FDI training & RX/TX
4037  *   - update transcoder timings
4038  *   - DP transcoding bits
4039  *   - transcoder
4040  */
4041 static void ironlake_pch_enable(struct drm_crtc *crtc)
4042 {
4043         struct drm_device *dev = crtc->dev;
4044         struct drm_i915_private *dev_priv = dev->dev_private;
4045         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4046         int pipe = intel_crtc->pipe;
4047         u32 reg, temp;
4048
4049         assert_pch_transcoder_disabled(dev_priv, pipe);
4050
4051         if (IS_IVYBRIDGE(dev))
4052                 ivybridge_update_fdi_bc_bifurcation(intel_crtc);
4053
4054         /* Write the TU size bits before fdi link training, so that error
4055          * detection works. */
4056         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4057                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4058
4059         /* For PCH output, training FDI link */
4060         dev_priv->display.fdi_link_train(crtc);
4061
4062         /* We need to program the right clock selection before writing the pixel
4063          * mutliplier into the DPLL. */
4064         if (HAS_PCH_CPT(dev)) {
4065                 u32 sel;
4066
4067                 temp = I915_READ(PCH_DPLL_SEL);
4068                 temp |= TRANS_DPLL_ENABLE(pipe);
4069                 sel = TRANS_DPLLB_SEL(pipe);
4070                 if (intel_crtc->config->shared_dpll == DPLL_ID_PCH_PLL_B)
4071                         temp |= sel;
4072                 else
4073                         temp &= ~sel;
4074                 I915_WRITE(PCH_DPLL_SEL, temp);
4075         }
4076
4077         /* XXX: pch pll's can be enabled any time before we enable the PCH
4078          * transcoder, and we actually should do this to not upset any PCH
4079          * transcoder that already use the clock when we share it.
4080          *
4081          * Note that enable_shared_dpll tries to do the right thing, but
4082          * get_shared_dpll unconditionally resets the pll - we need that to have
4083          * the right LVDS enable sequence. */
4084         intel_enable_shared_dpll(intel_crtc);
4085
4086         /* set transcoder timing, panel must allow it */
4087         assert_panel_unlocked(dev_priv, pipe);
4088         ironlake_pch_transcoder_set_timings(intel_crtc, pipe);
4089
4090         intel_fdi_normal_train(crtc);
4091
4092         /* For PCH DP, enable TRANS_DP_CTL */
4093         if (HAS_PCH_CPT(dev) && intel_crtc->config->has_dp_encoder) {
4094                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4095                 reg = TRANS_DP_CTL(pipe);
4096                 temp = I915_READ(reg);
4097                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4098                           TRANS_DP_SYNC_MASK |
4099                           TRANS_DP_BPC_MASK);
4100                 temp |= (TRANS_DP_OUTPUT_ENABLE |
4101                          TRANS_DP_ENH_FRAMING);
4102                 temp |= bpc << 9; /* same format but at 11:9 */
4103
4104                 if (crtc->mode.flags & DRM_MODE_FLAG_PHSYNC)
4105                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4106                 if (crtc->mode.flags & DRM_MODE_FLAG_PVSYNC)
4107                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4108
4109                 switch (intel_trans_dp_port_sel(crtc)) {
4110                 case PCH_DP_B:
4111                         temp |= TRANS_DP_PORT_SEL_B;
4112                         break;
4113                 case PCH_DP_C:
4114                         temp |= TRANS_DP_PORT_SEL_C;
4115                         break;
4116                 case PCH_DP_D:
4117                         temp |= TRANS_DP_PORT_SEL_D;
4118                         break;
4119                 default:
4120                         BUG();
4121                 }
4122
4123                 I915_WRITE(reg, temp);
4124         }
4125
4126         ironlake_enable_pch_transcoder(dev_priv, pipe);
4127 }
4128
4129 static void lpt_pch_enable(struct drm_crtc *crtc)
4130 {
4131         struct drm_device *dev = crtc->dev;
4132         struct drm_i915_private *dev_priv = dev->dev_private;
4133         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4134         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4135
4136         assert_pch_transcoder_disabled(dev_priv, TRANSCODER_A);
4137
4138         lpt_program_iclkip(crtc);
4139
4140         /* Set transcoder timing. */
4141         ironlake_pch_transcoder_set_timings(intel_crtc, PIPE_A);
4142
4143         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4144 }
4145
4146 void intel_put_shared_dpll(struct intel_crtc *crtc)
4147 {
4148         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
4149
4150         if (pll == NULL)
4151                 return;
4152
4153         if (!(pll->config.crtc_mask & (1 << crtc->pipe))) {
4154                 WARN(1, "bad %s crtc mask\n", pll->name);
4155                 return;
4156         }
4157
4158         pll->config.crtc_mask &= ~(1 << crtc->pipe);
4159         if (pll->config.crtc_mask == 0) {
4160                 WARN_ON(pll->on);
4161                 WARN_ON(pll->active);
4162         }
4163
4164         crtc->config->shared_dpll = DPLL_ID_PRIVATE;
4165 }
4166
4167 struct intel_shared_dpll *intel_get_shared_dpll(struct intel_crtc *crtc,
4168                                                 struct intel_crtc_state *crtc_state)
4169 {
4170         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
4171         struct intel_shared_dpll *pll;
4172         enum intel_dpll_id i;
4173
4174         if (HAS_PCH_IBX(dev_priv->dev)) {
4175                 /* Ironlake PCH has a fixed PLL->PCH pipe mapping. */
4176                 i = (enum intel_dpll_id) crtc->pipe;
4177                 pll = &dev_priv->shared_dplls[i];
4178
4179                 DRM_DEBUG_KMS("CRTC:%d using pre-allocated %s\n",
4180                               crtc->base.base.id, pll->name);
4181
4182                 WARN_ON(pll->new_config->crtc_mask);
4183
4184                 goto found;
4185         }
4186
4187         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4188                 pll = &dev_priv->shared_dplls[i];
4189
4190                 /* Only want to check enabled timings first */
4191                 if (pll->new_config->crtc_mask == 0)
4192                         continue;
4193
4194                 if (memcmp(&crtc_state->dpll_hw_state,
4195                            &pll->new_config->hw_state,
4196                            sizeof(pll->new_config->hw_state)) == 0) {
4197                         DRM_DEBUG_KMS("CRTC:%d sharing existing %s (crtc mask 0x%08x, ative %d)\n",
4198                                       crtc->base.base.id, pll->name,
4199                                       pll->new_config->crtc_mask,
4200                                       pll->active);
4201                         goto found;
4202                 }
4203         }
4204
4205         /* Ok no matching timings, maybe there's a free one? */
4206         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4207                 pll = &dev_priv->shared_dplls[i];
4208                 if (pll->new_config->crtc_mask == 0) {
4209                         DRM_DEBUG_KMS("CRTC:%d allocated %s\n",
4210                                       crtc->base.base.id, pll->name);
4211                         goto found;
4212                 }
4213         }
4214
4215         return NULL;
4216
4217 found:
4218         if (pll->new_config->crtc_mask == 0)
4219                 pll->new_config->hw_state = crtc_state->dpll_hw_state;
4220
4221         crtc_state->shared_dpll = i;
4222         DRM_DEBUG_DRIVER("using %s for pipe %c\n", pll->name,
4223                          pipe_name(crtc->pipe));
4224
4225         pll->new_config->crtc_mask |= 1 << crtc->pipe;
4226
4227         return pll;
4228 }
4229
4230 /**
4231  * intel_shared_dpll_start_config - start a new PLL staged config
4232  * @dev_priv: DRM device
4233  * @clear_pipes: mask of pipes that will have their PLLs freed
4234  *
4235  * Starts a new PLL staged config, copying the current config but
4236  * releasing the references of pipes specified in clear_pipes.
4237  */
4238 static int intel_shared_dpll_start_config(struct drm_i915_private *dev_priv,
4239                                           unsigned clear_pipes)
4240 {
4241         struct intel_shared_dpll *pll;
4242         enum intel_dpll_id i;
4243
4244         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4245                 pll = &dev_priv->shared_dplls[i];
4246
4247                 pll->new_config = kmemdup(&pll->config, sizeof pll->config,
4248                                           GFP_KERNEL);
4249                 if (!pll->new_config)
4250                         goto cleanup;
4251
4252                 pll->new_config->crtc_mask &= ~clear_pipes;
4253         }
4254
4255         return 0;
4256
4257 cleanup:
4258         while (--i >= 0) {
4259                 pll = &dev_priv->shared_dplls[i];
4260                 kfree(pll->new_config);
4261                 pll->new_config = NULL;
4262         }
4263
4264         return -ENOMEM;
4265 }
4266
4267 static void intel_shared_dpll_commit(struct drm_i915_private *dev_priv)
4268 {
4269         struct intel_shared_dpll *pll;
4270         enum intel_dpll_id i;
4271
4272         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4273                 pll = &dev_priv->shared_dplls[i];
4274
4275                 WARN_ON(pll->new_config == &pll->config);
4276
4277                 pll->config = *pll->new_config;
4278                 kfree(pll->new_config);
4279                 pll->new_config = NULL;
4280         }
4281 }
4282
4283 static void intel_shared_dpll_abort_config(struct drm_i915_private *dev_priv)
4284 {
4285         struct intel_shared_dpll *pll;
4286         enum intel_dpll_id i;
4287
4288         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4289                 pll = &dev_priv->shared_dplls[i];
4290
4291                 WARN_ON(pll->new_config == &pll->config);
4292
4293                 kfree(pll->new_config);
4294                 pll->new_config = NULL;
4295         }
4296 }
4297
4298 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4299 {
4300         struct drm_i915_private *dev_priv = dev->dev_private;
4301         int dslreg = PIPEDSL(pipe);
4302         u32 temp;
4303
4304         temp = I915_READ(dslreg);
4305         udelay(500);
4306         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4307                 if (wait_for(I915_READ(dslreg) != temp, 5))
4308                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4309         }
4310 }
4311
4312 /**
4313  * skl_update_scaler_users - Stages update to crtc's scaler state
4314  * @intel_crtc: crtc
4315  * @crtc_state: crtc_state
4316  * @plane: plane (NULL indicates crtc is requesting update)
4317  * @plane_state: plane's state
4318  * @force_detach: request unconditional detachment of scaler
4319  *
4320  * This function updates scaler state for requested plane or crtc.
4321  * To request scaler usage update for a plane, caller shall pass plane pointer.
4322  * To request scaler usage update for crtc, caller shall pass plane pointer
4323  * as NULL.
4324  *
4325  * Return
4326  *     0 - scaler_usage updated successfully
4327  *    error - requested scaling cannot be supported or other error condition
4328  */
4329 int
4330 skl_update_scaler_users(
4331         struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state,
4332         struct intel_plane *intel_plane, struct intel_plane_state *plane_state,
4333         int force_detach)
4334 {
4335         int need_scaling;
4336         int idx;
4337         int src_w, src_h, dst_w, dst_h;
4338         int *scaler_id;
4339         struct drm_framebuffer *fb;
4340         struct intel_crtc_scaler_state *scaler_state;
4341
4342         if (!intel_crtc || !crtc_state)
4343                 return 0;
4344
4345         scaler_state = &crtc_state->scaler_state;
4346
4347         idx = intel_plane ? drm_plane_index(&intel_plane->base) : SKL_CRTC_INDEX;
4348         fb = intel_plane ? plane_state->base.fb : NULL;
4349
4350         if (intel_plane) {
4351                 src_w = drm_rect_width(&plane_state->src) >> 16;
4352                 src_h = drm_rect_height(&plane_state->src) >> 16;
4353                 dst_w = drm_rect_width(&plane_state->dst);
4354                 dst_h = drm_rect_height(&plane_state->dst);
4355                 scaler_id = &plane_state->scaler_id;
4356         } else {
4357                 struct drm_display_mode *adjusted_mode =
4358                         &crtc_state->base.adjusted_mode;
4359                 src_w = crtc_state->pipe_src_w;
4360                 src_h = crtc_state->pipe_src_h;
4361                 dst_w = adjusted_mode->hdisplay;
4362                 dst_h = adjusted_mode->vdisplay;
4363                 scaler_id = &scaler_state->scaler_id;
4364         }
4365         need_scaling = (src_w != dst_w || src_h != dst_h);
4366
4367         /*
4368          * if plane is being disabled or scaler is no more required or force detach
4369          *  - free scaler binded to this plane/crtc
4370          *  - in order to do this, update crtc->scaler_usage
4371          *
4372          * Here scaler state in crtc_state is set free so that
4373          * scaler can be assigned to other user. Actual register
4374          * update to free the scaler is done in plane/panel-fit programming.
4375          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4376          */
4377         if (force_detach || !need_scaling || (intel_plane &&
4378                 (!fb || !plane_state->visible))) {
4379                 if (*scaler_id >= 0) {
4380                         scaler_state->scaler_users &= ~(1 << idx);
4381                         scaler_state->scalers[*scaler_id].in_use = 0;
4382
4383                         DRM_DEBUG_KMS("Staged freeing scaler id %d.%d from %s:%d "
4384                                 "crtc_state = %p scaler_users = 0x%x\n",
4385                                 intel_crtc->pipe, *scaler_id, intel_plane ? "PLANE" : "CRTC",
4386                                 intel_plane ? intel_plane->base.base.id :
4387                                 intel_crtc->base.base.id, crtc_state,
4388                                 scaler_state->scaler_users);
4389                         *scaler_id = -1;
4390                 }
4391                 return 0;
4392         }
4393
4394         /* range checks */
4395         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4396                 dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4397
4398                 src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4399                 dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H) {
4400                 DRM_DEBUG_KMS("%s:%d scaler_user index %u.%u: src %ux%u dst %ux%u "
4401                         "size is out of scaler range\n",
4402                         intel_plane ? "PLANE" : "CRTC",
4403                         intel_plane ? intel_plane->base.base.id : intel_crtc->base.base.id,
4404                         intel_crtc->pipe, idx, src_w, src_h, dst_w, dst_h);
4405                 return -EINVAL;
4406         }
4407
4408         /* check colorkey */
4409         if (intel_plane && intel_plane->ckey.flags != I915_SET_COLORKEY_NONE) {
4410                 DRM_DEBUG_KMS("PLANE:%d scaling with color key not allowed",
4411                         intel_plane->base.base.id);
4412                 return -EINVAL;
4413         }
4414
4415         /* Check src format */
4416         if (intel_plane) {
4417                 switch (fb->pixel_format) {
4418                 case DRM_FORMAT_RGB565:
4419                 case DRM_FORMAT_XBGR8888:
4420                 case DRM_FORMAT_XRGB8888:
4421                 case DRM_FORMAT_ABGR8888:
4422                 case DRM_FORMAT_ARGB8888:
4423                 case DRM_FORMAT_XRGB2101010:
4424                 case DRM_FORMAT_ARGB2101010:
4425                 case DRM_FORMAT_XBGR2101010:
4426                 case DRM_FORMAT_ABGR2101010:
4427                 case DRM_FORMAT_YUYV:
4428                 case DRM_FORMAT_YVYU:
4429                 case DRM_FORMAT_UYVY:
4430                 case DRM_FORMAT_VYUY:
4431                         break;
4432                 default:
4433                         DRM_DEBUG_KMS("PLANE:%d FB:%d unsupported scaling format 0x%x\n",
4434                                 intel_plane->base.base.id, fb->base.id, fb->pixel_format);
4435                         return -EINVAL;
4436                 }
4437         }
4438
4439         /* mark this plane as a scaler user in crtc_state */
4440         scaler_state->scaler_users |= (1 << idx);
4441         DRM_DEBUG_KMS("%s:%d staged scaling request for %ux%u->%ux%u "
4442                 "crtc_state = %p scaler_users = 0x%x\n",
4443                 intel_plane ? "PLANE" : "CRTC",
4444                 intel_plane ? intel_plane->base.base.id : intel_crtc->base.base.id,
4445                 src_w, src_h, dst_w, dst_h, crtc_state, scaler_state->scaler_users);
4446         return 0;
4447 }
4448
4449 static void skylake_pfit_update(struct intel_crtc *crtc, int enable)
4450 {
4451         struct drm_device *dev = crtc->base.dev;
4452         struct drm_i915_private *dev_priv = dev->dev_private;
4453         int pipe = crtc->pipe;
4454         struct intel_crtc_scaler_state *scaler_state =
4455                 &crtc->config->scaler_state;
4456
4457         DRM_DEBUG_KMS("for crtc_state = %p\n", crtc->config);
4458
4459         /* To update pfit, first update scaler state */
4460         skl_update_scaler_users(crtc, crtc->config, NULL, NULL, !enable);
4461         intel_atomic_setup_scalers(crtc->base.dev, crtc, crtc->config);
4462         skl_detach_scalers(crtc);
4463         if (!enable)
4464                 return;
4465
4466         if (crtc->config->pch_pfit.enabled) {
4467                 int id;
4468
4469                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0)) {
4470                         DRM_ERROR("Requesting pfit without getting a scaler first\n");
4471                         return;
4472                 }
4473
4474                 id = scaler_state->scaler_id;
4475                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4476                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4477                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
4478                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
4479
4480                 DRM_DEBUG_KMS("for crtc_state = %p scaler_id = %d\n", crtc->config, id);
4481         }
4482 }
4483
4484 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4485 {
4486         struct drm_device *dev = crtc->base.dev;
4487         struct drm_i915_private *dev_priv = dev->dev_private;
4488         int pipe = crtc->pipe;
4489
4490         if (crtc->config->pch_pfit.enabled) {
4491                 /* Force use of hard-coded filter coefficients
4492                  * as some pre-programmed values are broken,
4493                  * e.g. x201.
4494                  */
4495                 if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev))
4496                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4497                                                  PF_PIPE_SEL_IVB(pipe));
4498                 else
4499                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4500                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4501                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4502         }
4503 }
4504
4505 static void intel_enable_sprite_planes(struct drm_crtc *crtc)
4506 {
4507         struct drm_device *dev = crtc->dev;
4508         enum pipe pipe = to_intel_crtc(crtc)->pipe;
4509         struct drm_plane *plane;
4510         struct intel_plane *intel_plane;
4511
4512         drm_for_each_legacy_plane(plane, &dev->mode_config.plane_list) {
4513                 intel_plane = to_intel_plane(plane);
4514                 if (intel_plane->pipe == pipe)
4515                         intel_plane_restore(&intel_plane->base);
4516         }
4517 }
4518
4519 /*
4520  * Disable a plane internally without actually modifying the plane's state.
4521  * This will allow us to easily restore the plane later by just reprogramming
4522  * its state.
4523  */
4524 static void disable_plane_internal(struct drm_plane *plane)
4525 {
4526         struct intel_plane *intel_plane = to_intel_plane(plane);
4527         struct drm_plane_state *state =
4528                 plane->funcs->atomic_duplicate_state(plane);
4529         struct intel_plane_state *intel_state = to_intel_plane_state(state);
4530
4531         intel_state->visible = false;
4532         intel_plane->commit_plane(plane, intel_state);
4533
4534         intel_plane_destroy_state(plane, state);
4535 }
4536
4537 static void intel_disable_sprite_planes(struct drm_crtc *crtc)
4538 {
4539         struct drm_device *dev = crtc->dev;
4540         enum pipe pipe = to_intel_crtc(crtc)->pipe;
4541         struct drm_plane *plane;
4542         struct intel_plane *intel_plane;
4543
4544         drm_for_each_legacy_plane(plane, &dev->mode_config.plane_list) {
4545                 intel_plane = to_intel_plane(plane);
4546                 if (plane->fb && intel_plane->pipe == pipe)
4547                         disable_plane_internal(plane);
4548         }
4549 }
4550
4551 void hsw_enable_ips(struct intel_crtc *crtc)
4552 {
4553         struct drm_device *dev = crtc->base.dev;
4554         struct drm_i915_private *dev_priv = dev->dev_private;
4555
4556         if (!crtc->config->ips_enabled)
4557                 return;
4558
4559         /* We can only enable IPS after we enable a plane and wait for a vblank */
4560         intel_wait_for_vblank(dev, crtc->pipe);
4561
4562         assert_plane_enabled(dev_priv, crtc->plane);
4563         if (IS_BROADWELL(dev)) {
4564                 mutex_lock(&dev_priv->rps.hw_lock);
4565                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0xc0000000));
4566                 mutex_unlock(&dev_priv->rps.hw_lock);
4567                 /* Quoting Art Runyan: "its not safe to expect any particular
4568                  * value in IPS_CTL bit 31 after enabling IPS through the
4569                  * mailbox." Moreover, the mailbox may return a bogus state,
4570                  * so we need to just enable it and continue on.
4571                  */
4572         } else {
4573                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4574                 /* The bit only becomes 1 in the next vblank, so this wait here
4575                  * is essentially intel_wait_for_vblank. If we don't have this
4576                  * and don't wait for vblanks until the end of crtc_enable, then
4577                  * the HW state readout code will complain that the expected
4578                  * IPS_CTL value is not the one we read. */
4579                 if (wait_for(I915_READ_NOTRACE(IPS_CTL) & IPS_ENABLE, 50))
4580                         DRM_ERROR("Timed out waiting for IPS enable\n");
4581         }
4582 }
4583
4584 void hsw_disable_ips(struct intel_crtc *crtc)
4585 {
4586         struct drm_device *dev = crtc->base.dev;
4587         struct drm_i915_private *dev_priv = dev->dev_private;
4588
4589         if (!crtc->config->ips_enabled)
4590                 return;
4591
4592         assert_plane_enabled(dev_priv, crtc->plane);
4593         if (IS_BROADWELL(dev)) {
4594                 mutex_lock(&dev_priv->rps.hw_lock);
4595                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4596                 mutex_unlock(&dev_priv->rps.hw_lock);
4597                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4598                 if (wait_for((I915_READ(IPS_CTL) & IPS_ENABLE) == 0, 42))
4599                         DRM_ERROR("Timed out waiting for IPS disable\n");
4600         } else {
4601                 I915_WRITE(IPS_CTL, 0);
4602                 POSTING_READ(IPS_CTL);
4603         }
4604
4605         /* We need to wait for a vblank before we can disable the plane. */
4606         intel_wait_for_vblank(dev, crtc->pipe);
4607 }
4608
4609 /** Loads the palette/gamma unit for the CRTC with the prepared values */
4610 static void intel_crtc_load_lut(struct drm_crtc *crtc)
4611 {
4612         struct drm_device *dev = crtc->dev;
4613         struct drm_i915_private *dev_priv = dev->dev_private;
4614         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4615         enum pipe pipe = intel_crtc->pipe;
4616         int palreg = PALETTE(pipe);
4617         int i;
4618         bool reenable_ips = false;
4619
4620         /* The clocks have to be on to load the palette. */
4621         if (!crtc->state->enable || !intel_crtc->active)
4622                 return;
4623
4624         if (!HAS_PCH_SPLIT(dev_priv->dev)) {
4625                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_DSI))
4626                         assert_dsi_pll_enabled(dev_priv);
4627                 else
4628                         assert_pll_enabled(dev_priv, pipe);
4629         }
4630
4631         /* use legacy palette for Ironlake */
4632         if (!HAS_GMCH_DISPLAY(dev))
4633                 palreg = LGC_PALETTE(pipe);
4634
4635         /* Workaround : Do not read or write the pipe palette/gamma data while
4636          * GAMMA_MODE is configured for split gamma and IPS_CTL has IPS enabled.
4637          */
4638         if (IS_HASWELL(dev) && intel_crtc->config->ips_enabled &&
4639             ((I915_READ(GAMMA_MODE(pipe)) & GAMMA_MODE_MODE_MASK) ==
4640              GAMMA_MODE_MODE_SPLIT)) {
4641                 hsw_disable_ips(intel_crtc);
4642                 reenable_ips = true;
4643         }
4644
4645         for (i = 0; i < 256; i++) {
4646                 I915_WRITE(palreg + 4 * i,
4647                            (intel_crtc->lut_r[i] << 16) |
4648                            (intel_crtc->lut_g[i] << 8) |
4649                            intel_crtc->lut_b[i]);
4650         }
4651
4652         if (reenable_ips)
4653                 hsw_enable_ips(intel_crtc);
4654 }
4655
4656 static void intel_crtc_dpms_overlay(struct intel_crtc *intel_crtc, bool enable)
4657 {
4658         if (!enable && intel_crtc->overlay) {
4659                 struct drm_device *dev = intel_crtc->base.dev;
4660                 struct drm_i915_private *dev_priv = dev->dev_private;
4661
4662                 mutex_lock(&dev->struct_mutex);
4663                 dev_priv->mm.interruptible = false;
4664                 (void) intel_overlay_switch_off(intel_crtc->overlay);
4665                 dev_priv->mm.interruptible = true;
4666                 mutex_unlock(&dev->struct_mutex);
4667         }
4668
4669         /* Let userspace switch the overlay on again. In most cases userspace
4670          * has to recompute where to put it anyway.
4671          */
4672 }
4673
4674 static void intel_crtc_enable_planes(struct drm_crtc *crtc)
4675 {
4676         struct drm_device *dev = crtc->dev;
4677         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4678         int pipe = intel_crtc->pipe;
4679
4680         intel_enable_primary_hw_plane(crtc->primary, crtc);
4681         intel_enable_sprite_planes(crtc);
4682         intel_crtc_update_cursor(crtc, true);
4683         intel_crtc_dpms_overlay(intel_crtc, true);
4684
4685         hsw_enable_ips(intel_crtc);
4686
4687         mutex_lock(&dev->struct_mutex);
4688         intel_fbc_update(dev);
4689         mutex_unlock(&dev->struct_mutex);
4690
4691         /*
4692          * FIXME: Once we grow proper nuclear flip support out of this we need
4693          * to compute the mask of flip planes precisely. For the time being
4694          * consider this a flip from a NULL plane.
4695          */
4696         intel_frontbuffer_flip(dev, INTEL_FRONTBUFFER_ALL_MASK(pipe));
4697 }
4698
4699 static void intel_crtc_disable_planes(struct drm_crtc *crtc)
4700 {
4701         struct drm_device *dev = crtc->dev;
4702         struct drm_i915_private *dev_priv = dev->dev_private;
4703         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4704         int pipe = intel_crtc->pipe;
4705
4706         intel_crtc_wait_for_pending_flips(crtc);
4707
4708         if (dev_priv->fbc.crtc == intel_crtc)
4709                 intel_fbc_disable(dev);
4710
4711         hsw_disable_ips(intel_crtc);
4712
4713         intel_crtc_dpms_overlay(intel_crtc, false);
4714         intel_crtc_update_cursor(crtc, false);
4715         intel_disable_sprite_planes(crtc);
4716         intel_disable_primary_hw_plane(crtc->primary, crtc);
4717
4718         /*
4719          * FIXME: Once we grow proper nuclear flip support out of this we need
4720          * to compute the mask of flip planes precisely. For the time being
4721          * consider this a flip to a NULL plane.
4722          */
4723         intel_frontbuffer_flip(dev, INTEL_FRONTBUFFER_ALL_MASK(pipe));
4724 }
4725
4726 static void ironlake_crtc_enable(struct drm_crtc *crtc)
4727 {
4728         struct drm_device *dev = crtc->dev;
4729         struct drm_i915_private *dev_priv = dev->dev_private;
4730         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4731         struct intel_encoder *encoder;
4732         int pipe = intel_crtc->pipe;
4733
4734         WARN_ON(!crtc->state->enable);
4735
4736         if (intel_crtc->active)
4737                 return;
4738
4739         if (intel_crtc->config->has_pch_encoder)
4740                 intel_prepare_shared_dpll(intel_crtc);
4741
4742         if (intel_crtc->config->has_dp_encoder)
4743                 intel_dp_set_m_n(intel_crtc, M1_N1);
4744
4745         intel_set_pipe_timings(intel_crtc);
4746
4747         if (intel_crtc->config->has_pch_encoder) {
4748                 intel_cpu_transcoder_set_m_n(intel_crtc,
4749                                      &intel_crtc->config->fdi_m_n, NULL);
4750         }
4751
4752         ironlake_set_pipeconf(crtc);
4753
4754         intel_crtc->active = true;
4755
4756         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4757         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
4758
4759         for_each_encoder_on_crtc(dev, crtc, encoder)
4760                 if (encoder->pre_enable)
4761                         encoder->pre_enable(encoder);
4762
4763         if (intel_crtc->config->has_pch_encoder) {
4764                 /* Note: FDI PLL enabling _must_ be done before we enable the
4765                  * cpu pipes, hence this is separate from all the other fdi/pch
4766                  * enabling. */
4767                 ironlake_fdi_pll_enable(intel_crtc);
4768         } else {
4769                 assert_fdi_tx_disabled(dev_priv, pipe);
4770                 assert_fdi_rx_disabled(dev_priv, pipe);
4771         }
4772
4773         ironlake_pfit_enable(intel_crtc);
4774
4775         /*
4776          * On ILK+ LUT must be loaded before the pipe is running but with
4777          * clocks enabled
4778          */
4779         intel_crtc_load_lut(crtc);
4780
4781         intel_update_watermarks(crtc);
4782         intel_enable_pipe(intel_crtc);
4783
4784         if (intel_crtc->config->has_pch_encoder)
4785                 ironlake_pch_enable(crtc);
4786
4787         assert_vblank_disabled(crtc);
4788         drm_crtc_vblank_on(crtc);
4789
4790         for_each_encoder_on_crtc(dev, crtc, encoder)
4791                 encoder->enable(encoder);
4792
4793         if (HAS_PCH_CPT(dev))
4794                 cpt_verify_modeset(dev, intel_crtc->pipe);
4795
4796         intel_crtc_enable_planes(crtc);
4797 }
4798
4799 /* IPS only exists on ULT machines and is tied to pipe A. */
4800 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
4801 {
4802         return HAS_IPS(crtc->base.dev) && crtc->pipe == PIPE_A;
4803 }
4804
4805 /*
4806  * This implements the workaround described in the "notes" section of the mode
4807  * set sequence documentation. When going from no pipes or single pipe to
4808  * multiple pipes, and planes are enabled after the pipe, we need to wait at
4809  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
4810  */
4811 static void haswell_mode_set_planes_workaround(struct intel_crtc *crtc)
4812 {
4813         struct drm_device *dev = crtc->base.dev;
4814         struct intel_crtc *crtc_it, *other_active_crtc = NULL;
4815
4816         /* We want to get the other_active_crtc only if there's only 1 other
4817          * active crtc. */
4818         for_each_intel_crtc(dev, crtc_it) {
4819                 if (!crtc_it->active || crtc_it == crtc)
4820                         continue;
4821
4822                 if (other_active_crtc)
4823                         return;
4824
4825                 other_active_crtc = crtc_it;
4826         }
4827         if (!other_active_crtc)
4828                 return;
4829
4830         intel_wait_for_vblank(dev, other_active_crtc->pipe);
4831         intel_wait_for_vblank(dev, other_active_crtc->pipe);
4832 }
4833
4834 static void haswell_crtc_enable(struct drm_crtc *crtc)
4835 {
4836         struct drm_device *dev = crtc->dev;
4837         struct drm_i915_private *dev_priv = dev->dev_private;
4838         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4839         struct intel_encoder *encoder;
4840         int pipe = intel_crtc->pipe;
4841
4842         WARN_ON(!crtc->state->enable);
4843
4844         if (intel_crtc->active)
4845                 return;
4846
4847         if (intel_crtc_to_shared_dpll(intel_crtc))
4848                 intel_enable_shared_dpll(intel_crtc);
4849
4850         if (intel_crtc->config->has_dp_encoder)
4851                 intel_dp_set_m_n(intel_crtc, M1_N1);
4852
4853         intel_set_pipe_timings(intel_crtc);
4854
4855         if (intel_crtc->config->cpu_transcoder != TRANSCODER_EDP) {
4856                 I915_WRITE(PIPE_MULT(intel_crtc->config->cpu_transcoder),
4857                            intel_crtc->config->pixel_multiplier - 1);
4858         }
4859
4860         if (intel_crtc->config->has_pch_encoder) {
4861                 intel_cpu_transcoder_set_m_n(intel_crtc,
4862                                      &intel_crtc->config->fdi_m_n, NULL);
4863         }
4864
4865         haswell_set_pipeconf(crtc);
4866
4867         intel_set_pipe_csc(crtc);
4868
4869         intel_crtc->active = true;
4870
4871         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4872         for_each_encoder_on_crtc(dev, crtc, encoder)
4873                 if (encoder->pre_enable)
4874                         encoder->pre_enable(encoder);
4875
4876         if (intel_crtc->config->has_pch_encoder) {
4877                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4878                                                       true);
4879                 dev_priv->display.fdi_link_train(crtc);
4880         }
4881
4882         intel_ddi_enable_pipe_clock(intel_crtc);
4883
4884         if (INTEL_INFO(dev)->gen == 9)
4885                 skylake_pfit_update(intel_crtc, 1);
4886         else if (INTEL_INFO(dev)->gen < 9)
4887                 ironlake_pfit_enable(intel_crtc);
4888         else
4889                 MISSING_CASE(INTEL_INFO(dev)->gen);
4890
4891         /*
4892          * On ILK+ LUT must be loaded before the pipe is running but with
4893          * clocks enabled
4894          */
4895         intel_crtc_load_lut(crtc);
4896
4897         intel_ddi_set_pipe_settings(crtc);
4898         intel_ddi_enable_transcoder_func(crtc);
4899
4900         intel_update_watermarks(crtc);
4901         intel_enable_pipe(intel_crtc);
4902
4903         if (intel_crtc->config->has_pch_encoder)
4904                 lpt_pch_enable(crtc);
4905
4906         if (intel_crtc->config->dp_encoder_is_mst)
4907                 intel_ddi_set_vc_payload_alloc(crtc, true);
4908
4909         assert_vblank_disabled(crtc);
4910         drm_crtc_vblank_on(crtc);
4911
4912         for_each_encoder_on_crtc(dev, crtc, encoder) {
4913                 encoder->enable(encoder);
4914                 intel_opregion_notify_encoder(encoder, true);
4915         }
4916
4917         /* If we change the relative order between pipe/planes enabling, we need
4918          * to change the workaround. */
4919         haswell_mode_set_planes_workaround(intel_crtc);
4920         intel_crtc_enable_planes(crtc);
4921 }
4922
4923 static void ironlake_pfit_disable(struct intel_crtc *crtc)
4924 {
4925         struct drm_device *dev = crtc->base.dev;
4926         struct drm_i915_private *dev_priv = dev->dev_private;
4927         int pipe = crtc->pipe;
4928
4929         /* To avoid upsetting the power well on haswell only disable the pfit if
4930          * it's in use. The hw state code will make sure we get this right. */
4931         if (crtc->config->pch_pfit.enabled) {
4932                 I915_WRITE(PF_CTL(pipe), 0);
4933                 I915_WRITE(PF_WIN_POS(pipe), 0);
4934                 I915_WRITE(PF_WIN_SZ(pipe), 0);
4935         }
4936 }
4937
4938 static void ironlake_crtc_disable(struct drm_crtc *crtc)
4939 {
4940         struct drm_device *dev = crtc->dev;
4941         struct drm_i915_private *dev_priv = dev->dev_private;
4942         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4943         struct intel_encoder *encoder;
4944         int pipe = intel_crtc->pipe;
4945         u32 reg, temp;
4946
4947         if (!intel_crtc->active)
4948                 return;
4949
4950         intel_crtc_disable_planes(crtc);
4951
4952         for_each_encoder_on_crtc(dev, crtc, encoder)
4953                 encoder->disable(encoder);
4954
4955         drm_crtc_vblank_off(crtc);
4956         assert_vblank_disabled(crtc);
4957
4958         if (intel_crtc->config->has_pch_encoder)
4959                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
4960
4961         intel_disable_pipe(intel_crtc);
4962
4963         ironlake_pfit_disable(intel_crtc);
4964
4965         for_each_encoder_on_crtc(dev, crtc, encoder)
4966                 if (encoder->post_disable)
4967                         encoder->post_disable(encoder);
4968
4969         if (intel_crtc->config->has_pch_encoder) {
4970                 ironlake_fdi_disable(crtc);
4971
4972                 ironlake_disable_pch_transcoder(dev_priv, pipe);
4973
4974                 if (HAS_PCH_CPT(dev)) {
4975                         /* disable TRANS_DP_CTL */
4976                         reg = TRANS_DP_CTL(pipe);
4977                         temp = I915_READ(reg);
4978                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
4979                                   TRANS_DP_PORT_SEL_MASK);
4980                         temp |= TRANS_DP_PORT_SEL_NONE;
4981                         I915_WRITE(reg, temp);
4982
4983                         /* disable DPLL_SEL */
4984                         temp = I915_READ(PCH_DPLL_SEL);
4985                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
4986                         I915_WRITE(PCH_DPLL_SEL, temp);
4987                 }
4988
4989                 /* disable PCH DPLL */
4990                 intel_disable_shared_dpll(intel_crtc);
4991
4992                 ironlake_fdi_pll_disable(intel_crtc);
4993         }
4994
4995         intel_crtc->active = false;
4996         intel_update_watermarks(crtc);
4997
4998         mutex_lock(&dev->struct_mutex);
4999         intel_fbc_update(dev);
5000         mutex_unlock(&dev->struct_mutex);
5001 }
5002
5003 static void haswell_crtc_disable(struct drm_crtc *crtc)
5004 {
5005         struct drm_device *dev = crtc->dev;
5006         struct drm_i915_private *dev_priv = dev->dev_private;
5007         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5008         struct intel_encoder *encoder;
5009         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5010
5011         if (!intel_crtc->active)
5012                 return;
5013
5014         intel_crtc_disable_planes(crtc);
5015
5016         for_each_encoder_on_crtc(dev, crtc, encoder) {
5017                 intel_opregion_notify_encoder(encoder, false);
5018                 encoder->disable(encoder);
5019         }
5020
5021         drm_crtc_vblank_off(crtc);
5022         assert_vblank_disabled(crtc);
5023
5024         if (intel_crtc->config->has_pch_encoder)
5025                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5026                                                       false);
5027         intel_disable_pipe(intel_crtc);
5028
5029         if (intel_crtc->config->dp_encoder_is_mst)
5030                 intel_ddi_set_vc_payload_alloc(crtc, false);
5031
5032         intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
5033
5034         if (INTEL_INFO(dev)->gen == 9)
5035                 skylake_pfit_update(intel_crtc, 0);
5036         else if (INTEL_INFO(dev)->gen < 9)
5037                 ironlake_pfit_disable(intel_crtc);
5038         else
5039                 MISSING_CASE(INTEL_INFO(dev)->gen);
5040
5041         intel_ddi_disable_pipe_clock(intel_crtc);
5042
5043         if (intel_crtc->config->has_pch_encoder) {
5044                 lpt_disable_pch_transcoder(dev_priv);
5045                 intel_ddi_fdi_disable(crtc);
5046         }
5047
5048         for_each_encoder_on_crtc(dev, crtc, encoder)
5049                 if (encoder->post_disable)
5050                         encoder->post_disable(encoder);
5051
5052         intel_crtc->active = false;
5053         intel_update_watermarks(crtc);
5054
5055         mutex_lock(&dev->struct_mutex);
5056         intel_fbc_update(dev);
5057         mutex_unlock(&dev->struct_mutex);
5058
5059         if (intel_crtc_to_shared_dpll(intel_crtc))
5060                 intel_disable_shared_dpll(intel_crtc);
5061 }
5062
5063 static void ironlake_crtc_off(struct drm_crtc *crtc)
5064 {
5065         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5066         intel_put_shared_dpll(intel_crtc);
5067 }
5068
5069
5070 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5071 {
5072         struct drm_device *dev = crtc->base.dev;
5073         struct drm_i915_private *dev_priv = dev->dev_private;
5074         struct intel_crtc_state *pipe_config = crtc->config;
5075
5076         if (!pipe_config->gmch_pfit.control)
5077                 return;
5078
5079         /*
5080          * The panel fitter should only be adjusted whilst the pipe is disabled,
5081          * according to register description and PRM.
5082          */
5083         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5084         assert_pipe_disabled(dev_priv, crtc->pipe);
5085
5086         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5087         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5088
5089         /* Border color in case we don't scale up to the full screen. Black by
5090          * default, change to something else for debugging. */
5091         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5092 }
5093
5094 static enum intel_display_power_domain port_to_power_domain(enum port port)
5095 {
5096         switch (port) {
5097         case PORT_A:
5098                 return POWER_DOMAIN_PORT_DDI_A_4_LANES;
5099         case PORT_B:
5100                 return POWER_DOMAIN_PORT_DDI_B_4_LANES;
5101         case PORT_C:
5102                 return POWER_DOMAIN_PORT_DDI_C_4_LANES;
5103         case PORT_D:
5104                 return POWER_DOMAIN_PORT_DDI_D_4_LANES;
5105         default:
5106                 WARN_ON_ONCE(1);
5107                 return POWER_DOMAIN_PORT_OTHER;
5108         }
5109 }
5110
5111 #define for_each_power_domain(domain, mask)                             \
5112         for ((domain) = 0; (domain) < POWER_DOMAIN_NUM; (domain)++)     \
5113                 if ((1 << (domain)) & (mask))
5114
5115 enum intel_display_power_domain
5116 intel_display_port_power_domain(struct intel_encoder *intel_encoder)
5117 {
5118         struct drm_device *dev = intel_encoder->base.dev;
5119         struct intel_digital_port *intel_dig_port;
5120
5121         switch (intel_encoder->type) {
5122         case INTEL_OUTPUT_UNKNOWN:
5123                 /* Only DDI platforms should ever use this output type */
5124                 WARN_ON_ONCE(!HAS_DDI(dev));
5125         case INTEL_OUTPUT_DISPLAYPORT:
5126         case INTEL_OUTPUT_HDMI:
5127         case INTEL_OUTPUT_EDP:
5128                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5129                 return port_to_power_domain(intel_dig_port->port);
5130         case INTEL_OUTPUT_DP_MST:
5131                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5132                 return port_to_power_domain(intel_dig_port->port);
5133         case INTEL_OUTPUT_ANALOG:
5134                 return POWER_DOMAIN_PORT_CRT;
5135         case INTEL_OUTPUT_DSI:
5136                 return POWER_DOMAIN_PORT_DSI;
5137         default:
5138                 return POWER_DOMAIN_PORT_OTHER;
5139         }
5140 }
5141
5142 static unsigned long get_crtc_power_domains(struct drm_crtc *crtc)
5143 {
5144         struct drm_device *dev = crtc->dev;
5145         struct intel_encoder *intel_encoder;
5146         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5147         enum pipe pipe = intel_crtc->pipe;
5148         unsigned long mask;
5149         enum transcoder transcoder;
5150
5151         transcoder = intel_pipe_to_cpu_transcoder(dev->dev_private, pipe);
5152
5153         mask = BIT(POWER_DOMAIN_PIPE(pipe));
5154         mask |= BIT(POWER_DOMAIN_TRANSCODER(transcoder));
5155         if (intel_crtc->config->pch_pfit.enabled ||
5156             intel_crtc->config->pch_pfit.force_thru)
5157                 mask |= BIT(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5158
5159         for_each_encoder_on_crtc(dev, crtc, intel_encoder)
5160                 mask |= BIT(intel_display_port_power_domain(intel_encoder));
5161
5162         return mask;
5163 }
5164
5165 static void modeset_update_crtc_power_domains(struct drm_atomic_state *state)
5166 {
5167         struct drm_device *dev = state->dev;
5168         struct drm_i915_private *dev_priv = dev->dev_private;
5169         unsigned long pipe_domains[I915_MAX_PIPES] = { 0, };
5170         struct intel_crtc *crtc;
5171
5172         /*
5173          * First get all needed power domains, then put all unneeded, to avoid
5174          * any unnecessary toggling of the power wells.
5175          */
5176         for_each_intel_crtc(dev, crtc) {
5177                 enum intel_display_power_domain domain;
5178
5179                 if (!crtc->base.state->enable)
5180                         continue;
5181
5182                 pipe_domains[crtc->pipe] = get_crtc_power_domains(&crtc->base);
5183
5184                 for_each_power_domain(domain, pipe_domains[crtc->pipe])
5185                         intel_display_power_get(dev_priv, domain);
5186         }
5187
5188         if (dev_priv->display.modeset_global_resources)
5189                 dev_priv->display.modeset_global_resources(state);
5190
5191         for_each_intel_crtc(dev, crtc) {
5192                 enum intel_display_power_domain domain;
5193
5194                 for_each_power_domain(domain, crtc->enabled_power_domains)
5195                         intel_display_power_put(dev_priv, domain);
5196
5197                 crtc->enabled_power_domains = pipe_domains[crtc->pipe];
5198         }
5199
5200         intel_display_set_init_power(dev_priv, false);
5201 }
5202
5203 void broxton_set_cdclk(struct drm_device *dev, int frequency)
5204 {
5205         struct drm_i915_private *dev_priv = dev->dev_private;
5206         uint32_t divider;
5207         uint32_t ratio;
5208         uint32_t current_freq;
5209         int ret;
5210
5211         /* frequency = 19.2MHz * ratio / 2 / div{1,1.5,2,4} */
5212         switch (frequency) {
5213         case 144000:
5214                 divider = BXT_CDCLK_CD2X_DIV_SEL_4;
5215                 ratio = BXT_DE_PLL_RATIO(60);
5216                 break;
5217         case 288000:
5218                 divider = BXT_CDCLK_CD2X_DIV_SEL_2;
5219                 ratio = BXT_DE_PLL_RATIO(60);
5220                 break;
5221         case 384000:
5222                 divider = BXT_CDCLK_CD2X_DIV_SEL_1_5;
5223                 ratio = BXT_DE_PLL_RATIO(60);
5224                 break;
5225         case 576000:
5226                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5227                 ratio = BXT_DE_PLL_RATIO(60);
5228                 break;
5229         case 624000:
5230                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5231                 ratio = BXT_DE_PLL_RATIO(65);
5232                 break;
5233         case 19200:
5234                 /*
5235                  * Bypass frequency with DE PLL disabled. Init ratio, divider
5236                  * to suppress GCC warning.
5237                  */
5238                 ratio = 0;
5239                 divider = 0;
5240                 break;
5241         default:
5242                 DRM_ERROR("unsupported CDCLK freq %d", frequency);
5243
5244                 return;
5245         }
5246
5247         mutex_lock(&dev_priv->rps.hw_lock);
5248         /* Inform power controller of upcoming frequency change */
5249         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5250                                       0x80000000);
5251         mutex_unlock(&dev_priv->rps.hw_lock);
5252
5253         if (ret) {
5254                 DRM_ERROR("PCode CDCLK freq change notify failed (err %d, freq %d)\n",
5255                           ret, frequency);
5256                 return;
5257         }
5258
5259         current_freq = I915_READ(CDCLK_CTL) & CDCLK_FREQ_DECIMAL_MASK;
5260         /* convert from .1 fixpoint MHz with -1MHz offset to kHz */
5261         current_freq = current_freq * 500 + 1000;
5262
5263         /*
5264          * DE PLL has to be disabled when
5265          * - setting to 19.2MHz (bypass, PLL isn't used)
5266          * - before setting to 624MHz (PLL needs toggling)
5267          * - before setting to any frequency from 624MHz (PLL needs toggling)
5268          */
5269         if (frequency == 19200 || frequency == 624000 ||
5270             current_freq == 624000) {
5271                 I915_WRITE(BXT_DE_PLL_ENABLE, ~BXT_DE_PLL_PLL_ENABLE);
5272                 /* Timeout 200us */
5273                 if (wait_for(!(I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_LOCK),
5274                              1))
5275                         DRM_ERROR("timout waiting for DE PLL unlock\n");
5276         }
5277
5278         if (frequency != 19200) {
5279                 uint32_t val;
5280
5281                 val = I915_READ(BXT_DE_PLL_CTL);
5282                 val &= ~BXT_DE_PLL_RATIO_MASK;
5283                 val |= ratio;
5284                 I915_WRITE(BXT_DE_PLL_CTL, val);
5285
5286                 I915_WRITE(BXT_DE_PLL_ENABLE, BXT_DE_PLL_PLL_ENABLE);
5287                 /* Timeout 200us */
5288                 if (wait_for(I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_LOCK, 1))
5289                         DRM_ERROR("timeout waiting for DE PLL lock\n");
5290
5291                 val = I915_READ(CDCLK_CTL);
5292                 val &= ~BXT_CDCLK_CD2X_DIV_SEL_MASK;
5293                 val |= divider;
5294                 /*
5295                  * Disable SSA Precharge when CD clock frequency < 500 MHz,
5296                  * enable otherwise.
5297                  */
5298                 val &= ~BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5299                 if (frequency >= 500000)
5300                         val |= BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5301
5302                 val &= ~CDCLK_FREQ_DECIMAL_MASK;
5303                 /* convert from kHz to .1 fixpoint MHz with -1MHz offset */
5304                 val |= (frequency - 1000) / 500;
5305                 I915_WRITE(CDCLK_CTL, val);
5306         }
5307
5308         mutex_lock(&dev_priv->rps.hw_lock);
5309         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5310                                       DIV_ROUND_UP(frequency, 25000));
5311         mutex_unlock(&dev_priv->rps.hw_lock);
5312
5313         if (ret) {
5314                 DRM_ERROR("PCode CDCLK freq set failed, (err %d, freq %d)\n",
5315                           ret, frequency);
5316                 return;
5317         }
5318
5319         dev_priv->cdclk_freq = frequency;
5320 }
5321
5322 void broxton_init_cdclk(struct drm_device *dev)
5323 {
5324         struct drm_i915_private *dev_priv = dev->dev_private;
5325         uint32_t val;
5326
5327         /*
5328          * NDE_RSTWRN_OPT RST PCH Handshake En must always be 0b on BXT
5329          * or else the reset will hang because there is no PCH to respond.
5330          * Move the handshake programming to initialization sequence.
5331          * Previously was left up to BIOS.
5332          */
5333         val = I915_READ(HSW_NDE_RSTWRN_OPT);
5334         val &= ~RESET_PCH_HANDSHAKE_ENABLE;
5335         I915_WRITE(HSW_NDE_RSTWRN_OPT, val);
5336
5337         /* Enable PG1 for cdclk */
5338         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
5339
5340         /* check if cd clock is enabled */
5341         if (I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_PLL_ENABLE) {
5342                 DRM_DEBUG_KMS("Display already initialized\n");
5343                 return;
5344         }
5345
5346         /*
5347          * FIXME:
5348          * - The initial CDCLK needs to be read from VBT.
5349          *   Need to make this change after VBT has changes for BXT.
5350          * - check if setting the max (or any) cdclk freq is really necessary
5351          *   here, it belongs to modeset time
5352          */
5353         broxton_set_cdclk(dev, 624000);
5354
5355         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) | DBUF_POWER_REQUEST);
5356         udelay(10);
5357
5358         if (!(I915_READ(DBUF_CTL) & DBUF_POWER_STATE))
5359                 DRM_ERROR("DBuf power enable timeout!\n");
5360 }
5361
5362 void broxton_uninit_cdclk(struct drm_device *dev)
5363 {
5364         struct drm_i915_private *dev_priv = dev->dev_private;
5365
5366         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) & ~DBUF_POWER_REQUEST);
5367         udelay(10);
5368
5369         if (I915_READ(DBUF_CTL) & DBUF_POWER_STATE)
5370                 DRM_ERROR("DBuf power disable timeout!\n");
5371
5372         /* Set minimum (bypass) frequency, in effect turning off the DE PLL */
5373         broxton_set_cdclk(dev, 19200);
5374
5375         intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS);
5376 }
5377
5378 /* returns HPLL frequency in kHz */
5379 static int valleyview_get_vco(struct drm_i915_private *dev_priv)
5380 {
5381         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
5382
5383         /* Obtain SKU information */
5384         mutex_lock(&dev_priv->dpio_lock);
5385         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
5386                 CCK_FUSE_HPLL_FREQ_MASK;
5387         mutex_unlock(&dev_priv->dpio_lock);
5388
5389         return vco_freq[hpll_freq] * 1000;
5390 }
5391
5392 static void vlv_update_cdclk(struct drm_device *dev)
5393 {
5394         struct drm_i915_private *dev_priv = dev->dev_private;
5395
5396         dev_priv->cdclk_freq = dev_priv->display.get_display_clock_speed(dev);
5397         DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz\n",
5398                          dev_priv->cdclk_freq);
5399
5400         /*
5401          * Program the gmbus_freq based on the cdclk frequency.
5402          * BSpec erroneously claims we should aim for 4MHz, but
5403          * in fact 1MHz is the correct frequency.
5404          */
5405         I915_WRITE(GMBUSFREQ_VLV, DIV_ROUND_UP(dev_priv->cdclk_freq, 1000));
5406 }
5407
5408 /* Adjust CDclk dividers to allow high res or save power if possible */
5409 static void valleyview_set_cdclk(struct drm_device *dev, int cdclk)
5410 {
5411         struct drm_i915_private *dev_priv = dev->dev_private;
5412         u32 val, cmd;
5413
5414         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5415                                         != dev_priv->cdclk_freq);
5416
5417         if (cdclk >= 320000) /* jump to highest voltage for 400MHz too */
5418                 cmd = 2;
5419         else if (cdclk == 266667)
5420                 cmd = 1;
5421         else
5422                 cmd = 0;
5423
5424         mutex_lock(&dev_priv->rps.hw_lock);
5425         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5426         val &= ~DSPFREQGUAR_MASK;
5427         val |= (cmd << DSPFREQGUAR_SHIFT);
5428         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5429         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5430                       DSPFREQSTAT_MASK) == (cmd << DSPFREQSTAT_SHIFT),
5431                      50)) {
5432                 DRM_ERROR("timed out waiting for CDclk change\n");
5433         }
5434         mutex_unlock(&dev_priv->rps.hw_lock);
5435
5436         if (cdclk == 400000) {
5437                 u32 divider;
5438
5439                 divider = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5440
5441                 mutex_lock(&dev_priv->dpio_lock);
5442                 /* adjust cdclk divider */
5443                 val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
5444                 val &= ~DISPLAY_FREQUENCY_VALUES;
5445                 val |= divider;
5446                 vlv_cck_write(dev_priv, CCK_DISPLAY_CLOCK_CONTROL, val);
5447
5448                 if (wait_for((vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL) &
5449                               DISPLAY_FREQUENCY_STATUS) == (divider << DISPLAY_FREQUENCY_STATUS_SHIFT),
5450                              50))
5451                         DRM_ERROR("timed out waiting for CDclk change\n");
5452                 mutex_unlock(&dev_priv->dpio_lock);
5453         }
5454
5455         mutex_lock(&dev_priv->dpio_lock);
5456         /* adjust self-refresh exit latency value */
5457         val = vlv_bunit_read(dev_priv, BUNIT_REG_BISOC);
5458         val &= ~0x7f;
5459
5460         /*
5461          * For high bandwidth configs, we set a higher latency in the bunit
5462          * so that the core display fetch happens in time to avoid underruns.
5463          */
5464         if (cdclk == 400000)
5465                 val |= 4500 / 250; /* 4.5 usec */
5466         else
5467                 val |= 3000 / 250; /* 3.0 usec */
5468         vlv_bunit_write(dev_priv, BUNIT_REG_BISOC, val);
5469         mutex_unlock(&dev_priv->dpio_lock);
5470
5471         vlv_update_cdclk(dev);
5472 }
5473
5474 static void cherryview_set_cdclk(struct drm_device *dev, int cdclk)
5475 {
5476         struct drm_i915_private *dev_priv = dev->dev_private;
5477         u32 val, cmd;
5478
5479         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5480                                                 != dev_priv->cdclk_freq);
5481
5482         switch (cdclk) {
5483         case 333333:
5484         case 320000:
5485         case 266667:
5486         case 200000:
5487                 break;
5488         default:
5489                 MISSING_CASE(cdclk);
5490                 return;
5491         }
5492
5493         /*
5494          * Specs are full of misinformation, but testing on actual
5495          * hardware has shown that we just need to write the desired
5496          * CCK divider into the Punit register.
5497          */
5498         cmd = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5499
5500         mutex_lock(&dev_priv->rps.hw_lock);
5501         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5502         val &= ~DSPFREQGUAR_MASK_CHV;
5503         val |= (cmd << DSPFREQGUAR_SHIFT_CHV);
5504         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5505         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5506                       DSPFREQSTAT_MASK_CHV) == (cmd << DSPFREQSTAT_SHIFT_CHV),
5507                      50)) {
5508                 DRM_ERROR("timed out waiting for CDclk change\n");
5509         }
5510         mutex_unlock(&dev_priv->rps.hw_lock);
5511
5512         vlv_update_cdclk(dev);
5513 }
5514
5515 static int valleyview_calc_cdclk(struct drm_i915_private *dev_priv,
5516                                  int max_pixclk)
5517 {
5518         int freq_320 = (dev_priv->hpll_freq <<  1) % 320000 != 0 ? 333333 : 320000;
5519         int limit = IS_CHERRYVIEW(dev_priv) ? 95 : 90;
5520
5521         /*
5522          * Really only a few cases to deal with, as only 4 CDclks are supported:
5523          *   200MHz
5524          *   267MHz
5525          *   320/333MHz (depends on HPLL freq)
5526          *   400MHz (VLV only)
5527          * So we check to see whether we're above 90% (VLV) or 95% (CHV)
5528          * of the lower bin and adjust if needed.
5529          *
5530          * We seem to get an unstable or solid color picture at 200MHz.
5531          * Not sure what's wrong. For now use 200MHz only when all pipes
5532          * are off.
5533          */
5534         if (!IS_CHERRYVIEW(dev_priv) &&
5535             max_pixclk > freq_320*limit/100)
5536                 return 400000;
5537         else if (max_pixclk > 266667*limit/100)
5538                 return freq_320;
5539         else if (max_pixclk > 0)
5540                 return 266667;
5541         else
5542                 return 200000;
5543 }
5544
5545 static int broxton_calc_cdclk(struct drm_i915_private *dev_priv,
5546                               int max_pixclk)
5547 {
5548         /*
5549          * FIXME:
5550          * - remove the guardband, it's not needed on BXT
5551          * - set 19.2MHz bypass frequency if there are no active pipes
5552          */
5553         if (max_pixclk > 576000*9/10)
5554                 return 624000;
5555         else if (max_pixclk > 384000*9/10)
5556                 return 576000;
5557         else if (max_pixclk > 288000*9/10)
5558                 return 384000;
5559         else if (max_pixclk > 144000*9/10)
5560                 return 288000;
5561         else
5562                 return 144000;
5563 }
5564
5565 /* compute the max pixel clock for new configuration */
5566 static int intel_mode_max_pixclk(struct drm_atomic_state *state)
5567 {
5568         struct drm_device *dev = state->dev;
5569         struct intel_crtc *intel_crtc;
5570         struct intel_crtc_state *crtc_state;
5571         int max_pixclk = 0;
5572
5573         for_each_intel_crtc(dev, intel_crtc) {
5574                 crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
5575                 if (IS_ERR(crtc_state))
5576                         return PTR_ERR(crtc_state);
5577
5578                 if (!crtc_state->base.enable)
5579                         continue;
5580
5581                 max_pixclk = max(max_pixclk,
5582                                  crtc_state->base.adjusted_mode.crtc_clock);
5583         }
5584
5585         return max_pixclk;
5586 }
5587
5588 static int valleyview_modeset_global_pipes(struct drm_atomic_state *state,
5589                                             unsigned *prepare_pipes)
5590 {
5591         struct drm_i915_private *dev_priv = to_i915(state->dev);
5592         struct intel_crtc *intel_crtc;
5593         int max_pixclk = intel_mode_max_pixclk(state);
5594         int cdclk;
5595
5596         if (max_pixclk < 0)
5597                 return max_pixclk;
5598
5599         if (IS_VALLEYVIEW(dev_priv))
5600                 cdclk = valleyview_calc_cdclk(dev_priv, max_pixclk);
5601         else
5602                 cdclk = broxton_calc_cdclk(dev_priv, max_pixclk);
5603
5604         if (cdclk == dev_priv->cdclk_freq)
5605                 return 0;
5606
5607         /* disable/enable all currently active pipes while we change cdclk */
5608         for_each_intel_crtc(state->dev, intel_crtc)
5609                 if (intel_crtc->base.state->enable)
5610                         *prepare_pipes |= (1 << intel_crtc->pipe);
5611
5612         return 0;
5613 }
5614
5615 static void vlv_program_pfi_credits(struct drm_i915_private *dev_priv)
5616 {
5617         unsigned int credits, default_credits;
5618
5619         if (IS_CHERRYVIEW(dev_priv))
5620                 default_credits = PFI_CREDIT(12);
5621         else
5622                 default_credits = PFI_CREDIT(8);
5623
5624         if (DIV_ROUND_CLOSEST(dev_priv->cdclk_freq, 1000) >= dev_priv->rps.cz_freq) {
5625                 /* CHV suggested value is 31 or 63 */
5626                 if (IS_CHERRYVIEW(dev_priv))
5627                         credits = PFI_CREDIT_31;
5628                 else
5629                         credits = PFI_CREDIT(15);
5630         } else {
5631                 credits = default_credits;
5632         }
5633
5634         /*
5635          * WA - write default credits before re-programming
5636          * FIXME: should we also set the resend bit here?
5637          */
5638         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
5639                    default_credits);
5640
5641         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
5642                    credits | PFI_CREDIT_RESEND);
5643
5644         /*
5645          * FIXME is this guaranteed to clear
5646          * immediately or should we poll for it?
5647          */
5648         WARN_ON(I915_READ(GCI_CONTROL) & PFI_CREDIT_RESEND);
5649 }
5650
5651 static void valleyview_modeset_global_resources(struct drm_atomic_state *state)
5652 {
5653         struct drm_device *dev = state->dev;
5654         struct drm_i915_private *dev_priv = dev->dev_private;
5655         int max_pixclk = intel_mode_max_pixclk(state);
5656         int req_cdclk;
5657
5658         /* The only reason this can fail is if we fail to add the crtc_state
5659          * to the atomic state. But that can't happen since the call to
5660          * intel_mode_max_pixclk() in valleyview_modeset_global_pipes() (which
5661          * can't have failed otherwise the mode set would be aborted) added all
5662          * the states already. */
5663         if (WARN_ON(max_pixclk < 0))
5664                 return;
5665
5666         req_cdclk = valleyview_calc_cdclk(dev_priv, max_pixclk);
5667
5668         if (req_cdclk != dev_priv->cdclk_freq) {
5669                 /*
5670                  * FIXME: We can end up here with all power domains off, yet
5671                  * with a CDCLK frequency other than the minimum. To account
5672                  * for this take the PIPE-A power domain, which covers the HW
5673                  * blocks needed for the following programming. This can be
5674                  * removed once it's guaranteed that we get here either with
5675                  * the minimum CDCLK set, or the required power domains
5676                  * enabled.
5677                  */
5678                 intel_display_power_get(dev_priv, POWER_DOMAIN_PIPE_A);
5679
5680                 if (IS_CHERRYVIEW(dev))
5681                         cherryview_set_cdclk(dev, req_cdclk);
5682                 else
5683                         valleyview_set_cdclk(dev, req_cdclk);
5684
5685                 vlv_program_pfi_credits(dev_priv);
5686
5687                 intel_display_power_put(dev_priv, POWER_DOMAIN_PIPE_A);
5688         }
5689 }
5690
5691 static void valleyview_crtc_enable(struct drm_crtc *crtc)
5692 {
5693         struct drm_device *dev = crtc->dev;
5694         struct drm_i915_private *dev_priv = to_i915(dev);
5695         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5696         struct intel_encoder *encoder;
5697         int pipe = intel_crtc->pipe;
5698         bool is_dsi;
5699
5700         WARN_ON(!crtc->state->enable);
5701
5702         if (intel_crtc->active)
5703                 return;
5704
5705         is_dsi = intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_DSI);
5706
5707         if (!is_dsi) {
5708                 if (IS_CHERRYVIEW(dev))
5709                         chv_prepare_pll(intel_crtc, intel_crtc->config);
5710                 else
5711                         vlv_prepare_pll(intel_crtc, intel_crtc->config);
5712         }
5713
5714         if (intel_crtc->config->has_dp_encoder)
5715                 intel_dp_set_m_n(intel_crtc, M1_N1);
5716
5717         intel_set_pipe_timings(intel_crtc);
5718
5719         if (IS_CHERRYVIEW(dev) && pipe == PIPE_B) {
5720                 struct drm_i915_private *dev_priv = dev->dev_private;
5721
5722                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
5723                 I915_WRITE(CHV_CANVAS(pipe), 0);
5724         }
5725
5726         i9xx_set_pipeconf(intel_crtc);
5727
5728         intel_crtc->active = true;
5729
5730         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5731
5732         for_each_encoder_on_crtc(dev, crtc, encoder)
5733                 if (encoder->pre_pll_enable)
5734                         encoder->pre_pll_enable(encoder);
5735
5736         if (!is_dsi) {
5737                 if (IS_CHERRYVIEW(dev))
5738                         chv_enable_pll(intel_crtc, intel_crtc->config);
5739                 else
5740                         vlv_enable_pll(intel_crtc, intel_crtc->config);
5741         }
5742
5743         for_each_encoder_on_crtc(dev, crtc, encoder)
5744                 if (encoder->pre_enable)
5745                         encoder->pre_enable(encoder);
5746
5747         i9xx_pfit_enable(intel_crtc);
5748
5749         intel_crtc_load_lut(crtc);
5750
5751         intel_update_watermarks(crtc);
5752         intel_enable_pipe(intel_crtc);
5753
5754         assert_vblank_disabled(crtc);
5755         drm_crtc_vblank_on(crtc);
5756
5757         for_each_encoder_on_crtc(dev, crtc, encoder)
5758                 encoder->enable(encoder);
5759
5760         intel_crtc_enable_planes(crtc);
5761
5762         /* Underruns don't raise interrupts, so check manually. */
5763         i9xx_check_fifo_underruns(dev_priv);
5764 }
5765
5766 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
5767 {
5768         struct drm_device *dev = crtc->base.dev;
5769         struct drm_i915_private *dev_priv = dev->dev_private;
5770
5771         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
5772         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
5773 }
5774
5775 static void i9xx_crtc_enable(struct drm_crtc *crtc)
5776 {
5777         struct drm_device *dev = crtc->dev;
5778         struct drm_i915_private *dev_priv = to_i915(dev);
5779         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5780         struct intel_encoder *encoder;
5781         int pipe = intel_crtc->pipe;
5782
5783         WARN_ON(!crtc->state->enable);
5784
5785         if (intel_crtc->active)
5786                 return;
5787
5788         i9xx_set_pll_dividers(intel_crtc);
5789
5790         if (intel_crtc->config->has_dp_encoder)
5791                 intel_dp_set_m_n(intel_crtc, M1_N1);
5792
5793         intel_set_pipe_timings(intel_crtc);
5794
5795         i9xx_set_pipeconf(intel_crtc);
5796
5797         intel_crtc->active = true;
5798
5799         if (!IS_GEN2(dev))
5800                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5801
5802         for_each_encoder_on_crtc(dev, crtc, encoder)
5803                 if (encoder->pre_enable)
5804                         encoder->pre_enable(encoder);
5805
5806         i9xx_enable_pll(intel_crtc);
5807
5808         i9xx_pfit_enable(intel_crtc);
5809
5810         intel_crtc_load_lut(crtc);
5811
5812         intel_update_watermarks(crtc);
5813         intel_enable_pipe(intel_crtc);
5814
5815         assert_vblank_disabled(crtc);
5816         drm_crtc_vblank_on(crtc);
5817
5818         for_each_encoder_on_crtc(dev, crtc, encoder)
5819                 encoder->enable(encoder);
5820
5821         intel_crtc_enable_planes(crtc);
5822
5823         /*
5824          * Gen2 reports pipe underruns whenever all planes are disabled.
5825          * So don't enable underrun reporting before at least some planes
5826          * are enabled.
5827          * FIXME: Need to fix the logic to work when we turn off all planes
5828          * but leave the pipe running.
5829          */
5830         if (IS_GEN2(dev))
5831                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5832
5833         /* Underruns don't raise interrupts, so check manually. */
5834         i9xx_check_fifo_underruns(dev_priv);
5835 }
5836
5837 static void i9xx_pfit_disable(struct intel_crtc *crtc)
5838 {
5839         struct drm_device *dev = crtc->base.dev;
5840         struct drm_i915_private *dev_priv = dev->dev_private;
5841
5842         if (!crtc->config->gmch_pfit.control)
5843                 return;
5844
5845         assert_pipe_disabled(dev_priv, crtc->pipe);
5846
5847         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
5848                          I915_READ(PFIT_CONTROL));
5849         I915_WRITE(PFIT_CONTROL, 0);
5850 }
5851
5852 static void i9xx_crtc_disable(struct drm_crtc *crtc)
5853 {
5854         struct drm_device *dev = crtc->dev;
5855         struct drm_i915_private *dev_priv = dev->dev_private;
5856         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5857         struct intel_encoder *encoder;
5858         int pipe = intel_crtc->pipe;
5859
5860         if (!intel_crtc->active)
5861                 return;
5862
5863         /*
5864          * Gen2 reports pipe underruns whenever all planes are disabled.
5865          * So diasble underrun reporting before all the planes get disabled.
5866          * FIXME: Need to fix the logic to work when we turn off all planes
5867          * but leave the pipe running.
5868          */
5869         if (IS_GEN2(dev))
5870                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5871
5872         /*
5873          * Vblank time updates from the shadow to live plane control register
5874          * are blocked if the memory self-refresh mode is active at that
5875          * moment. So to make sure the plane gets truly disabled, disable
5876          * first the self-refresh mode. The self-refresh enable bit in turn
5877          * will be checked/applied by the HW only at the next frame start
5878          * event which is after the vblank start event, so we need to have a
5879          * wait-for-vblank between disabling the plane and the pipe.
5880          */
5881         intel_set_memory_cxsr(dev_priv, false);
5882         intel_crtc_disable_planes(crtc);
5883
5884         /*
5885          * On gen2 planes are double buffered but the pipe isn't, so we must
5886          * wait for planes to fully turn off before disabling the pipe.
5887          * We also need to wait on all gmch platforms because of the
5888          * self-refresh mode constraint explained above.
5889          */
5890         intel_wait_for_vblank(dev, pipe);
5891
5892         for_each_encoder_on_crtc(dev, crtc, encoder)
5893                 encoder->disable(encoder);
5894
5895         drm_crtc_vblank_off(crtc);
5896         assert_vblank_disabled(crtc);
5897
5898         intel_disable_pipe(intel_crtc);
5899
5900         i9xx_pfit_disable(intel_crtc);
5901
5902         for_each_encoder_on_crtc(dev, crtc, encoder)
5903                 if (encoder->post_disable)
5904                         encoder->post_disable(encoder);
5905
5906         if (!intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_DSI)) {
5907                 if (IS_CHERRYVIEW(dev))
5908                         chv_disable_pll(dev_priv, pipe);
5909                 else if (IS_VALLEYVIEW(dev))
5910                         vlv_disable_pll(dev_priv, pipe);
5911                 else
5912                         i9xx_disable_pll(intel_crtc);
5913         }
5914
5915         if (!IS_GEN2(dev))
5916                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5917
5918         intel_crtc->active = false;
5919         intel_update_watermarks(crtc);
5920
5921         mutex_lock(&dev->struct_mutex);
5922         intel_fbc_update(dev);
5923         mutex_unlock(&dev->struct_mutex);
5924 }
5925
5926 static void i9xx_crtc_off(struct drm_crtc *crtc)
5927 {
5928 }
5929
5930 /* Master function to enable/disable CRTC and corresponding power wells */
5931 void intel_crtc_control(struct drm_crtc *crtc, bool enable)
5932 {
5933         struct drm_device *dev = crtc->dev;
5934         struct drm_i915_private *dev_priv = dev->dev_private;
5935         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5936         enum intel_display_power_domain domain;
5937         unsigned long domains;
5938
5939         if (enable) {
5940                 if (!intel_crtc->active) {
5941                         domains = get_crtc_power_domains(crtc);
5942                         for_each_power_domain(domain, domains)
5943                                 intel_display_power_get(dev_priv, domain);
5944                         intel_crtc->enabled_power_domains = domains;
5945
5946                         dev_priv->display.crtc_enable(crtc);
5947                 }
5948         } else {
5949                 if (intel_crtc->active) {
5950                         dev_priv->display.crtc_disable(crtc);
5951
5952                         domains = intel_crtc->enabled_power_domains;
5953                         for_each_power_domain(domain, domains)
5954                                 intel_display_power_put(dev_priv, domain);
5955                         intel_crtc->enabled_power_domains = 0;
5956                 }
5957         }
5958 }
5959
5960 /**
5961  * Sets the power management mode of the pipe and plane.
5962  */
5963 void intel_crtc_update_dpms(struct drm_crtc *crtc)
5964 {
5965         struct drm_device *dev = crtc->dev;
5966         struct intel_encoder *intel_encoder;
5967         bool enable = false;
5968
5969         for_each_encoder_on_crtc(dev, crtc, intel_encoder)
5970                 enable |= intel_encoder->connectors_active;
5971
5972         intel_crtc_control(crtc, enable);
5973 }
5974
5975 static void intel_crtc_disable(struct drm_crtc *crtc)
5976 {
5977         struct drm_device *dev = crtc->dev;
5978         struct drm_connector *connector;
5979         struct drm_i915_private *dev_priv = dev->dev_private;
5980
5981         /* crtc should still be enabled when we disable it. */
5982         WARN_ON(!crtc->state->enable);
5983
5984         dev_priv->display.crtc_disable(crtc);
5985         dev_priv->display.off(crtc);
5986
5987         drm_plane_helper_disable(crtc->primary);
5988
5989         /* Update computed state. */
5990         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
5991                 if (!connector->encoder || !connector->encoder->crtc)
5992                         continue;
5993
5994                 if (connector->encoder->crtc != crtc)
5995                         continue;
5996
5997                 connector->dpms = DRM_MODE_DPMS_OFF;
5998                 to_intel_encoder(connector->encoder)->connectors_active = false;
5999         }
6000 }
6001
6002 void intel_encoder_destroy(struct drm_encoder *encoder)
6003 {
6004         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6005
6006         drm_encoder_cleanup(encoder);
6007         kfree(intel_encoder);
6008 }
6009
6010 /* Simple dpms helper for encoders with just one connector, no cloning and only
6011  * one kind of off state. It clamps all !ON modes to fully OFF and changes the
6012  * state of the entire output pipe. */
6013 static void intel_encoder_dpms(struct intel_encoder *encoder, int mode)
6014 {
6015         if (mode == DRM_MODE_DPMS_ON) {
6016                 encoder->connectors_active = true;
6017
6018                 intel_crtc_update_dpms(encoder->base.crtc);
6019         } else {
6020                 encoder->connectors_active = false;
6021
6022                 intel_crtc_update_dpms(encoder->base.crtc);
6023         }
6024 }
6025
6026 /* Cross check the actual hw state with our own modeset state tracking (and it's
6027  * internal consistency). */
6028 static void intel_connector_check_state(struct intel_connector *connector)
6029 {
6030         if (connector->get_hw_state(connector)) {
6031                 struct intel_encoder *encoder = connector->encoder;
6032                 struct drm_crtc *crtc;
6033                 bool encoder_enabled;
6034                 enum pipe pipe;
6035
6036                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6037                               connector->base.base.id,
6038                               connector->base.name);
6039
6040                 /* there is no real hw state for MST connectors */
6041                 if (connector->mst_port)
6042                         return;
6043
6044                 I915_STATE_WARN(connector->base.dpms == DRM_MODE_DPMS_OFF,
6045                      "wrong connector dpms state\n");
6046                 I915_STATE_WARN(connector->base.encoder != &encoder->base,
6047                      "active connector not linked to encoder\n");
6048
6049                 if (encoder) {
6050                         I915_STATE_WARN(!encoder->connectors_active,
6051                              "encoder->connectors_active not set\n");
6052
6053                         encoder_enabled = encoder->get_hw_state(encoder, &pipe);
6054                         I915_STATE_WARN(!encoder_enabled, "encoder not enabled\n");
6055                         if (I915_STATE_WARN_ON(!encoder->base.crtc))
6056                                 return;
6057
6058                         crtc = encoder->base.crtc;
6059
6060                         I915_STATE_WARN(!crtc->state->enable,
6061                                         "crtc not enabled\n");
6062                         I915_STATE_WARN(!to_intel_crtc(crtc)->active, "crtc not active\n");
6063                         I915_STATE_WARN(pipe != to_intel_crtc(crtc)->pipe,
6064                              "encoder active on the wrong pipe\n");
6065                 }
6066         }
6067 }
6068
6069 int intel_connector_init(struct intel_connector *connector)
6070 {
6071         struct drm_connector_state *connector_state;
6072
6073         connector_state = kzalloc(sizeof *connector_state, GFP_KERNEL);
6074         if (!connector_state)
6075                 return -ENOMEM;
6076
6077         connector->base.state = connector_state;
6078         return 0;
6079 }
6080
6081 struct intel_connector *intel_connector_alloc(void)
6082 {
6083         struct intel_connector *connector;
6084
6085         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6086         if (!connector)
6087                 return NULL;
6088
6089         if (intel_connector_init(connector) < 0) {
6090                 kfree(connector);
6091                 return NULL;
6092         }
6093
6094         return connector;
6095 }
6096
6097 /* Even simpler default implementation, if there's really no special case to
6098  * consider. */
6099 void intel_connector_dpms(struct drm_connector *connector, int mode)
6100 {
6101         /* All the simple cases only support two dpms states. */
6102         if (mode != DRM_MODE_DPMS_ON)
6103                 mode = DRM_MODE_DPMS_OFF;
6104
6105         if (mode == connector->dpms)
6106                 return;
6107
6108         connector->dpms = mode;
6109
6110         /* Only need to change hw state when actually enabled */
6111         if (connector->encoder)
6112                 intel_encoder_dpms(to_intel_encoder(connector->encoder), mode);
6113
6114         intel_modeset_check_state(connector->dev);
6115 }
6116
6117 /* Simple connector->get_hw_state implementation for encoders that support only
6118  * one connector and no cloning and hence the encoder state determines the state
6119  * of the connector. */
6120 bool intel_connector_get_hw_state(struct intel_connector *connector)
6121 {
6122         enum pipe pipe = 0;
6123         struct intel_encoder *encoder = connector->encoder;
6124
6125         return encoder->get_hw_state(encoder, &pipe);
6126 }
6127
6128 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6129 {
6130         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6131                 return crtc_state->fdi_lanes;
6132
6133         return 0;
6134 }
6135
6136 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6137                                      struct intel_crtc_state *pipe_config)
6138 {
6139         struct drm_atomic_state *state = pipe_config->base.state;
6140         struct intel_crtc *other_crtc;
6141         struct intel_crtc_state *other_crtc_state;
6142
6143         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6144                       pipe_name(pipe), pipe_config->fdi_lanes);
6145         if (pipe_config->fdi_lanes > 4) {
6146                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6147                               pipe_name(pipe), pipe_config->fdi_lanes);
6148                 return -EINVAL;
6149         }
6150
6151         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
6152                 if (pipe_config->fdi_lanes > 2) {
6153                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6154                                       pipe_config->fdi_lanes);
6155                         return -EINVAL;
6156                 } else {
6157                         return 0;
6158                 }
6159         }
6160
6161         if (INTEL_INFO(dev)->num_pipes == 2)
6162                 return 0;
6163
6164         /* Ivybridge 3 pipe is really complicated */
6165         switch (pipe) {
6166         case PIPE_A:
6167                 return 0;
6168         case PIPE_B:
6169                 if (pipe_config->fdi_lanes <= 2)
6170                         return 0;
6171
6172                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_C));
6173                 other_crtc_state =
6174                         intel_atomic_get_crtc_state(state, other_crtc);
6175                 if (IS_ERR(other_crtc_state))
6176                         return PTR_ERR(other_crtc_state);
6177
6178                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6179                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6180                                       pipe_name(pipe), pipe_config->fdi_lanes);
6181                         return -EINVAL;
6182                 }
6183                 return 0;
6184         case PIPE_C:
6185                 if (pipe_config->fdi_lanes > 2) {
6186                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6187                                       pipe_name(pipe), pipe_config->fdi_lanes);
6188                         return -EINVAL;
6189                 }
6190
6191                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_B));
6192                 other_crtc_state =
6193                         intel_atomic_get_crtc_state(state, other_crtc);
6194                 if (IS_ERR(other_crtc_state))
6195                         return PTR_ERR(other_crtc_state);
6196
6197                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6198                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6199                         return -EINVAL;
6200                 }
6201                 return 0;
6202         default:
6203                 BUG();
6204         }
6205 }
6206
6207 #define RETRY 1
6208 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6209                                        struct intel_crtc_state *pipe_config)
6210 {
6211         struct drm_device *dev = intel_crtc->base.dev;
6212         struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6213         int lane, link_bw, fdi_dotclock, ret;
6214         bool needs_recompute = false;
6215
6216 retry:
6217         /* FDI is a binary signal running at ~2.7GHz, encoding
6218          * each output octet as 10 bits. The actual frequency
6219          * is stored as a divider into a 100MHz clock, and the
6220          * mode pixel clock is stored in units of 1KHz.
6221          * Hence the bw of each lane in terms of the mode signal
6222          * is:
6223          */
6224         link_bw = intel_fdi_link_freq(dev) * MHz(100)/KHz(1)/10;
6225
6226         fdi_dotclock = adjusted_mode->crtc_clock;
6227
6228         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6229                                            pipe_config->pipe_bpp);
6230
6231         pipe_config->fdi_lanes = lane;
6232
6233         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6234                                link_bw, &pipe_config->fdi_m_n);
6235
6236         ret = ironlake_check_fdi_lanes(intel_crtc->base.dev,
6237                                        intel_crtc->pipe, pipe_config);
6238         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6239                 pipe_config->pipe_bpp -= 2*3;
6240                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6241                               pipe_config->pipe_bpp);
6242                 needs_recompute = true;
6243                 pipe_config->bw_constrained = true;
6244
6245                 goto retry;
6246         }
6247
6248         if (needs_recompute)
6249                 return RETRY;
6250
6251         return ret;
6252 }
6253
6254 static void hsw_compute_ips_config(struct intel_crtc *crtc,
6255                                    struct intel_crtc_state *pipe_config)
6256 {
6257         pipe_config->ips_enabled = i915.enable_ips &&
6258                                    hsw_crtc_supports_ips(crtc) &&
6259                                    pipe_config->pipe_bpp <= 24;
6260 }
6261
6262 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6263                                      struct intel_crtc_state *pipe_config)
6264 {
6265         struct drm_device *dev = crtc->base.dev;
6266         struct drm_i915_private *dev_priv = dev->dev_private;
6267         struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6268         int ret;
6269
6270         /* FIXME should check pixel clock limits on all platforms */
6271         if (INTEL_INFO(dev)->gen < 4) {
6272                 int clock_limit =
6273                         dev_priv->display.get_display_clock_speed(dev);
6274
6275                 /*
6276                  * Enable pixel doubling when the dot clock
6277                  * is > 90% of the (display) core speed.
6278                  *
6279                  * GDG double wide on either pipe,
6280                  * otherwise pipe A only.
6281                  */
6282                 if ((crtc->pipe == PIPE_A || IS_I915G(dev)) &&
6283                     adjusted_mode->crtc_clock > clock_limit * 9 / 10) {
6284                         clock_limit *= 2;
6285                         pipe_config->double_wide = true;
6286                 }
6287
6288                 if (adjusted_mode->crtc_clock > clock_limit * 9 / 10)
6289                         return -EINVAL;
6290         }
6291
6292         /*
6293          * Pipe horizontal size must be even in:
6294          * - DVO ganged mode
6295          * - LVDS dual channel mode
6296          * - Double wide pipe
6297          */
6298         if ((intel_pipe_will_have_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6299              intel_is_dual_link_lvds(dev)) || pipe_config->double_wide)
6300                 pipe_config->pipe_src_w &= ~1;
6301
6302         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6303          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6304          */
6305         if ((INTEL_INFO(dev)->gen > 4 || IS_G4X(dev)) &&
6306                 adjusted_mode->hsync_start == adjusted_mode->hdisplay)
6307                 return -EINVAL;
6308
6309         if (HAS_IPS(dev))
6310                 hsw_compute_ips_config(crtc, pipe_config);
6311
6312         if (pipe_config->has_pch_encoder)
6313                 return ironlake_fdi_compute_config(crtc, pipe_config);
6314
6315         /* FIXME: remove below call once atomic mode set is place and all crtc
6316          * related checks called from atomic_crtc_check function */
6317         ret = 0;
6318         DRM_DEBUG_KMS("intel_crtc = %p drm_state (pipe_config->base.state) = %p\n",
6319                 crtc, pipe_config->base.state);
6320         ret = intel_atomic_setup_scalers(dev, crtc, pipe_config);
6321
6322         return ret;
6323 }
6324
6325 static int skylake_get_display_clock_speed(struct drm_device *dev)
6326 {
6327         struct drm_i915_private *dev_priv = to_i915(dev);
6328         uint32_t lcpll1 = I915_READ(LCPLL1_CTL);
6329         uint32_t cdctl = I915_READ(CDCLK_CTL);
6330         uint32_t linkrate;
6331
6332         if (!(lcpll1 & LCPLL_PLL_ENABLE)) {
6333                 WARN(1, "LCPLL1 not enabled\n");
6334                 return 24000; /* 24MHz is the cd freq with NSSC ref */
6335         }
6336
6337         if ((cdctl & CDCLK_FREQ_SEL_MASK) == CDCLK_FREQ_540)
6338                 return 540000;
6339
6340         linkrate = (I915_READ(DPLL_CTRL1) &
6341                     DPLL_CRTL1_LINK_RATE_MASK(SKL_DPLL0)) >> 1;
6342
6343         if (linkrate == DPLL_CRTL1_LINK_RATE_2160 ||
6344             linkrate == DPLL_CRTL1_LINK_RATE_1080) {
6345                 /* vco 8640 */
6346                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6347                 case CDCLK_FREQ_450_432:
6348                         return 432000;
6349                 case CDCLK_FREQ_337_308:
6350                         return 308570;
6351                 case CDCLK_FREQ_675_617:
6352                         return 617140;
6353                 default:
6354                         WARN(1, "Unknown cd freq selection\n");
6355                 }
6356         } else {
6357                 /* vco 8100 */
6358                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6359                 case CDCLK_FREQ_450_432:
6360                         return 450000;
6361                 case CDCLK_FREQ_337_308:
6362                         return 337500;
6363                 case CDCLK_FREQ_675_617:
6364                         return 675000;
6365                 default:
6366                         WARN(1, "Unknown cd freq selection\n");
6367                 }
6368         }
6369
6370         /* error case, do as if DPLL0 isn't enabled */
6371         return 24000;
6372 }
6373
6374 static int broadwell_get_display_clock_speed(struct drm_device *dev)
6375 {
6376         struct drm_i915_private *dev_priv = dev->dev_private;
6377         uint32_t lcpll = I915_READ(LCPLL_CTL);
6378         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6379
6380         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6381                 return 800000;
6382         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6383                 return 450000;
6384         else if (freq == LCPLL_CLK_FREQ_450)
6385                 return 450000;
6386         else if (freq == LCPLL_CLK_FREQ_54O_BDW)
6387                 return 540000;
6388         else if (freq == LCPLL_CLK_FREQ_337_5_BDW)
6389                 return 337500;
6390         else
6391                 return 675000;
6392 }
6393
6394 static int haswell_get_display_clock_speed(struct drm_device *dev)
6395 {
6396         struct drm_i915_private *dev_priv = dev->dev_private;
6397         uint32_t lcpll = I915_READ(LCPLL_CTL);
6398         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6399
6400         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6401                 return 800000;
6402         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6403                 return 450000;
6404         else if (freq == LCPLL_CLK_FREQ_450)
6405                 return 450000;
6406         else if (IS_HSW_ULT(dev))
6407                 return 337500;
6408         else
6409                 return 540000;
6410 }
6411
6412 static int valleyview_get_display_clock_speed(struct drm_device *dev)
6413 {
6414         struct drm_i915_private *dev_priv = dev->dev_private;
6415         u32 val;
6416         int divider;
6417
6418         if (dev_priv->hpll_freq == 0)
6419                 dev_priv->hpll_freq = valleyview_get_vco(dev_priv);
6420
6421         mutex_lock(&dev_priv->dpio_lock);
6422         val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
6423         mutex_unlock(&dev_priv->dpio_lock);
6424
6425         divider = val & DISPLAY_FREQUENCY_VALUES;
6426
6427         WARN((val & DISPLAY_FREQUENCY_STATUS) !=
6428              (divider << DISPLAY_FREQUENCY_STATUS_SHIFT),
6429              "cdclk change in progress\n");
6430
6431         return DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, divider + 1);
6432 }
6433
6434 static int ilk_get_display_clock_speed(struct drm_device *dev)
6435 {
6436         return 450000;
6437 }
6438
6439 static int i945_get_display_clock_speed(struct drm_device *dev)
6440 {
6441         return 400000;
6442 }
6443
6444 static int i915_get_display_clock_speed(struct drm_device *dev)
6445 {
6446         return 333333;
6447 }
6448
6449 static int i9xx_misc_get_display_clock_speed(struct drm_device *dev)
6450 {
6451         return 200000;
6452 }
6453
6454 static int pnv_get_display_clock_speed(struct drm_device *dev)
6455 {
6456         u16 gcfgc = 0;
6457
6458         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6459
6460         switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6461         case GC_DISPLAY_CLOCK_267_MHZ_PNV:
6462                 return 266667;
6463         case GC_DISPLAY_CLOCK_333_MHZ_PNV:
6464                 return 333333;
6465         case GC_DISPLAY_CLOCK_444_MHZ_PNV:
6466                 return 444444;
6467         case GC_DISPLAY_CLOCK_200_MHZ_PNV:
6468                 return 200000;
6469         default:
6470                 DRM_ERROR("Unknown pnv display core clock 0x%04x\n", gcfgc);
6471         case GC_DISPLAY_CLOCK_133_MHZ_PNV:
6472                 return 133333;
6473         case GC_DISPLAY_CLOCK_167_MHZ_PNV:
6474                 return 166667;
6475         }
6476 }
6477
6478 static int i915gm_get_display_clock_speed(struct drm_device *dev)
6479 {
6480         u16 gcfgc = 0;
6481
6482         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6483
6484         if (gcfgc & GC_LOW_FREQUENCY_ENABLE)
6485                 return 133333;
6486         else {
6487                 switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6488                 case GC_DISPLAY_CLOCK_333_MHZ:
6489                         return 333333;
6490                 default:
6491                 case GC_DISPLAY_CLOCK_190_200_MHZ:
6492                         return 190000;
6493                 }
6494         }
6495 }
6496
6497 static int i865_get_display_clock_speed(struct drm_device *dev)
6498 {
6499         return 266667;
6500 }
6501
6502 static int i855_get_display_clock_speed(struct drm_device *dev)
6503 {
6504         u16 hpllcc = 0;
6505         /* Assume that the hardware is in the high speed state.  This
6506          * should be the default.
6507          */
6508         switch (hpllcc & GC_CLOCK_CONTROL_MASK) {
6509         case GC_CLOCK_133_200:
6510         case GC_CLOCK_100_200:
6511                 return 200000;
6512         case GC_CLOCK_166_250:
6513                 return 250000;
6514         case GC_CLOCK_100_133:
6515                 return 133333;
6516         }
6517
6518         /* Shouldn't happen */
6519         return 0;
6520 }
6521
6522 static int i830_get_display_clock_speed(struct drm_device *dev)
6523 {
6524         return 133333;
6525 }
6526
6527 static void
6528 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
6529 {
6530         while (*num > DATA_LINK_M_N_MASK ||
6531                *den > DATA_LINK_M_N_MASK) {
6532                 *num >>= 1;
6533                 *den >>= 1;
6534         }
6535 }
6536
6537 static void compute_m_n(unsigned int m, unsigned int n,
6538                         uint32_t *ret_m, uint32_t *ret_n)
6539 {
6540         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
6541         *ret_m = div_u64((uint64_t) m * *ret_n, n);
6542         intel_reduce_m_n_ratio(ret_m, ret_n);
6543 }
6544
6545 void
6546 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
6547                        int pixel_clock, int link_clock,
6548                        struct intel_link_m_n *m_n)
6549 {
6550         m_n->tu = 64;
6551
6552         compute_m_n(bits_per_pixel * pixel_clock,
6553                     link_clock * nlanes * 8,
6554                     &m_n->gmch_m, &m_n->gmch_n);
6555
6556         compute_m_n(pixel_clock, link_clock,
6557                     &m_n->link_m, &m_n->link_n);
6558 }
6559
6560 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
6561 {
6562         if (i915.panel_use_ssc >= 0)
6563                 return i915.panel_use_ssc != 0;
6564         return dev_priv->vbt.lvds_use_ssc
6565                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
6566 }
6567
6568 static int i9xx_get_refclk(const struct intel_crtc_state *crtc_state,
6569                            int num_connectors)
6570 {
6571         struct drm_device *dev = crtc_state->base.crtc->dev;
6572         struct drm_i915_private *dev_priv = dev->dev_private;
6573         int refclk;
6574
6575         WARN_ON(!crtc_state->base.state);
6576
6577         if (IS_VALLEYVIEW(dev)) {
6578                 refclk = 100000;
6579         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6580             intel_panel_use_ssc(dev_priv) && num_connectors < 2) {
6581                 refclk = dev_priv->vbt.lvds_ssc_freq;
6582                 DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
6583         } else if (!IS_GEN2(dev)) {
6584                 refclk = 96000;
6585         } else {
6586                 refclk = 48000;
6587         }
6588
6589         return refclk;
6590 }
6591
6592 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
6593 {
6594         return (1 << dpll->n) << 16 | dpll->m2;
6595 }
6596
6597 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
6598 {
6599         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
6600 }
6601
6602 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
6603                                      struct intel_crtc_state *crtc_state,
6604                                      intel_clock_t *reduced_clock)
6605 {
6606         struct drm_device *dev = crtc->base.dev;
6607         u32 fp, fp2 = 0;
6608
6609         if (IS_PINEVIEW(dev)) {
6610                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
6611                 if (reduced_clock)
6612                         fp2 = pnv_dpll_compute_fp(reduced_clock);
6613         } else {
6614                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
6615                 if (reduced_clock)
6616                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
6617         }
6618
6619         crtc_state->dpll_hw_state.fp0 = fp;
6620
6621         crtc->lowfreq_avail = false;
6622         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6623             reduced_clock) {
6624                 crtc_state->dpll_hw_state.fp1 = fp2;
6625                 crtc->lowfreq_avail = true;
6626         } else {
6627                 crtc_state->dpll_hw_state.fp1 = fp;
6628         }
6629 }
6630
6631 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
6632                 pipe)
6633 {
6634         u32 reg_val;
6635
6636         /*
6637          * PLLB opamp always calibrates to max value of 0x3f, force enable it
6638          * and set it to a reasonable value instead.
6639          */
6640         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6641         reg_val &= 0xffffff00;
6642         reg_val |= 0x00000030;
6643         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6644
6645         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6646         reg_val &= 0x8cffffff;
6647         reg_val = 0x8c000000;
6648         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6649
6650         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6651         reg_val &= 0xffffff00;
6652         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6653
6654         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6655         reg_val &= 0x00ffffff;
6656         reg_val |= 0xb0000000;
6657         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6658 }
6659
6660 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
6661                                          struct intel_link_m_n *m_n)
6662 {
6663         struct drm_device *dev = crtc->base.dev;
6664         struct drm_i915_private *dev_priv = dev->dev_private;
6665         int pipe = crtc->pipe;
6666
6667         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6668         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
6669         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
6670         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
6671 }
6672
6673 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
6674                                          struct intel_link_m_n *m_n,
6675                                          struct intel_link_m_n *m2_n2)
6676 {
6677         struct drm_device *dev = crtc->base.dev;
6678         struct drm_i915_private *dev_priv = dev->dev_private;
6679         int pipe = crtc->pipe;
6680         enum transcoder transcoder = crtc->config->cpu_transcoder;
6681
6682         if (INTEL_INFO(dev)->gen >= 5) {
6683                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
6684                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
6685                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
6686                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
6687                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
6688                  * for gen < 8) and if DRRS is supported (to make sure the
6689                  * registers are not unnecessarily accessed).
6690                  */
6691                 if (m2_n2 && (IS_CHERRYVIEW(dev) || INTEL_INFO(dev)->gen < 8) &&
6692                         crtc->config->has_drrs) {
6693                         I915_WRITE(PIPE_DATA_M2(transcoder),
6694                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
6695                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
6696                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
6697                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
6698                 }
6699         } else {
6700                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6701                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
6702                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
6703                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
6704         }
6705 }
6706
6707 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
6708 {
6709         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
6710
6711         if (m_n == M1_N1) {
6712                 dp_m_n = &crtc->config->dp_m_n;
6713                 dp_m2_n2 = &crtc->config->dp_m2_n2;
6714         } else if (m_n == M2_N2) {
6715
6716                 /*
6717                  * M2_N2 registers are not supported. Hence m2_n2 divider value
6718                  * needs to be programmed into M1_N1.
6719                  */
6720                 dp_m_n = &crtc->config->dp_m2_n2;
6721         } else {
6722                 DRM_ERROR("Unsupported divider value\n");
6723                 return;
6724         }
6725
6726         if (crtc->config->has_pch_encoder)
6727                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
6728         else
6729                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
6730 }
6731
6732 static void vlv_update_pll(struct intel_crtc *crtc,
6733                            struct intel_crtc_state *pipe_config)
6734 {
6735         u32 dpll, dpll_md;
6736
6737         /*
6738          * Enable DPIO clock input. We should never disable the reference
6739          * clock for pipe B, since VGA hotplug / manual detection depends
6740          * on it.
6741          */
6742         dpll = DPLL_EXT_BUFFER_ENABLE_VLV | DPLL_REFA_CLK_ENABLE_VLV |
6743                 DPLL_VGA_MODE_DIS | DPLL_INTEGRATED_CLOCK_VLV;
6744         /* We should never disable this, set it here for state tracking */
6745         if (crtc->pipe == PIPE_B)
6746                 dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6747         dpll |= DPLL_VCO_ENABLE;
6748         pipe_config->dpll_hw_state.dpll = dpll;
6749
6750         dpll_md = (pipe_config->pixel_multiplier - 1)
6751                 << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6752         pipe_config->dpll_hw_state.dpll_md = dpll_md;
6753 }
6754
6755 static void vlv_prepare_pll(struct intel_crtc *crtc,
6756                             const struct intel_crtc_state *pipe_config)
6757 {
6758         struct drm_device *dev = crtc->base.dev;
6759         struct drm_i915_private *dev_priv = dev->dev_private;
6760         int pipe = crtc->pipe;
6761         u32 mdiv;
6762         u32 bestn, bestm1, bestm2, bestp1, bestp2;
6763         u32 coreclk, reg_val;
6764
6765         mutex_lock(&dev_priv->dpio_lock);
6766
6767         bestn = pipe_config->dpll.n;
6768         bestm1 = pipe_config->dpll.m1;
6769         bestm2 = pipe_config->dpll.m2;
6770         bestp1 = pipe_config->dpll.p1;
6771         bestp2 = pipe_config->dpll.p2;
6772
6773         /* See eDP HDMI DPIO driver vbios notes doc */
6774
6775         /* PLL B needs special handling */
6776         if (pipe == PIPE_B)
6777                 vlv_pllb_recal_opamp(dev_priv, pipe);
6778
6779         /* Set up Tx target for periodic Rcomp update */
6780         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
6781
6782         /* Disable target IRef on PLL */
6783         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
6784         reg_val &= 0x00ffffff;
6785         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
6786
6787         /* Disable fast lock */
6788         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
6789
6790         /* Set idtafcrecal before PLL is enabled */
6791         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
6792         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
6793         mdiv |= ((bestn << DPIO_N_SHIFT));
6794         mdiv |= (1 << DPIO_K_SHIFT);
6795
6796         /*
6797          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
6798          * but we don't support that).
6799          * Note: don't use the DAC post divider as it seems unstable.
6800          */
6801         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
6802         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6803
6804         mdiv |= DPIO_ENABLE_CALIBRATION;
6805         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6806
6807         /* Set HBR and RBR LPF coefficients */
6808         if (pipe_config->port_clock == 162000 ||
6809             intel_pipe_has_type(crtc, INTEL_OUTPUT_ANALOG) ||
6810             intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI))
6811                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6812                                  0x009f0003);
6813         else
6814                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6815                                  0x00d0000f);
6816
6817         if (pipe_config->has_dp_encoder) {
6818                 /* Use SSC source */
6819                 if (pipe == PIPE_A)
6820                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6821                                          0x0df40000);
6822                 else
6823                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6824                                          0x0df70000);
6825         } else { /* HDMI or VGA */
6826                 /* Use bend source */
6827                 if (pipe == PIPE_A)
6828                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6829                                          0x0df70000);
6830                 else
6831                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6832                                          0x0df40000);
6833         }
6834
6835         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
6836         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
6837         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DISPLAYPORT) ||
6838             intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP))
6839                 coreclk |= 0x01000000;
6840         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
6841
6842         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
6843         mutex_unlock(&dev_priv->dpio_lock);
6844 }
6845
6846 static void chv_update_pll(struct intel_crtc *crtc,
6847                            struct intel_crtc_state *pipe_config)
6848 {
6849         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLOCK_CHV |
6850                 DPLL_REFA_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS |
6851                 DPLL_VCO_ENABLE;
6852         if (crtc->pipe != PIPE_A)
6853                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6854
6855         pipe_config->dpll_hw_state.dpll_md =
6856                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6857 }
6858
6859 static void chv_prepare_pll(struct intel_crtc *crtc,
6860                             const struct intel_crtc_state *pipe_config)
6861 {
6862         struct drm_device *dev = crtc->base.dev;
6863         struct drm_i915_private *dev_priv = dev->dev_private;
6864         int pipe = crtc->pipe;
6865         int dpll_reg = DPLL(crtc->pipe);
6866         enum dpio_channel port = vlv_pipe_to_channel(pipe);
6867         u32 loopfilter, tribuf_calcntr;
6868         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
6869         u32 dpio_val;
6870         int vco;
6871
6872         bestn = pipe_config->dpll.n;
6873         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
6874         bestm1 = pipe_config->dpll.m1;
6875         bestm2 = pipe_config->dpll.m2 >> 22;
6876         bestp1 = pipe_config->dpll.p1;
6877         bestp2 = pipe_config->dpll.p2;
6878         vco = pipe_config->dpll.vco;
6879         dpio_val = 0;
6880         loopfilter = 0;
6881
6882         /*
6883          * Enable Refclk and SSC
6884          */
6885         I915_WRITE(dpll_reg,
6886                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
6887
6888         mutex_lock(&dev_priv->dpio_lock);
6889
6890         /* p1 and p2 divider */
6891         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
6892                         5 << DPIO_CHV_S1_DIV_SHIFT |
6893                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
6894                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
6895                         1 << DPIO_CHV_K_DIV_SHIFT);
6896
6897         /* Feedback post-divider - m2 */
6898         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
6899
6900         /* Feedback refclk divider - n and m1 */
6901         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
6902                         DPIO_CHV_M1_DIV_BY_2 |
6903                         1 << DPIO_CHV_N_DIV_SHIFT);
6904
6905         /* M2 fraction division */
6906         if (bestm2_frac)
6907                 vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
6908
6909         /* M2 fraction division enable */
6910         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
6911         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
6912         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
6913         if (bestm2_frac)
6914                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
6915         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
6916
6917         /* Program digital lock detect threshold */
6918         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
6919         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
6920                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
6921         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
6922         if (!bestm2_frac)
6923                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
6924         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
6925
6926         /* Loop filter */
6927         if (vco == 5400000) {
6928                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
6929                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
6930                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
6931                 tribuf_calcntr = 0x9;
6932         } else if (vco <= 6200000) {
6933                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
6934                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
6935                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6936                 tribuf_calcntr = 0x9;
6937         } else if (vco <= 6480000) {
6938                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
6939                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
6940                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6941                 tribuf_calcntr = 0x8;
6942         } else {
6943                 /* Not supported. Apply the same limits as in the max case */
6944                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
6945                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
6946                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6947                 tribuf_calcntr = 0;
6948         }
6949         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
6950
6951         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
6952         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
6953         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
6954         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
6955
6956         /* AFC Recal */
6957         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
6958                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
6959                         DPIO_AFC_RECAL);
6960
6961         mutex_unlock(&dev_priv->dpio_lock);
6962 }
6963
6964 /**
6965  * vlv_force_pll_on - forcibly enable just the PLL
6966  * @dev_priv: i915 private structure
6967  * @pipe: pipe PLL to enable
6968  * @dpll: PLL configuration
6969  *
6970  * Enable the PLL for @pipe using the supplied @dpll config. To be used
6971  * in cases where we need the PLL enabled even when @pipe is not going to
6972  * be enabled.
6973  */
6974 void vlv_force_pll_on(struct drm_device *dev, enum pipe pipe,
6975                       const struct dpll *dpll)
6976 {
6977         struct intel_crtc *crtc =
6978                 to_intel_crtc(intel_get_crtc_for_pipe(dev, pipe));
6979         struct intel_crtc_state pipe_config = {
6980                 .base.crtc = &crtc->base,
6981                 .pixel_multiplier = 1,
6982                 .dpll = *dpll,
6983         };
6984
6985         if (IS_CHERRYVIEW(dev)) {
6986                 chv_update_pll(crtc, &pipe_config);
6987                 chv_prepare_pll(crtc, &pipe_config);
6988                 chv_enable_pll(crtc, &pipe_config);
6989         } else {
6990                 vlv_update_pll(crtc, &pipe_config);
6991                 vlv_prepare_pll(crtc, &pipe_config);
6992                 vlv_enable_pll(crtc, &pipe_config);
6993         }
6994 }
6995
6996 /**
6997  * vlv_force_pll_off - forcibly disable just the PLL
6998  * @dev_priv: i915 private structure
6999  * @pipe: pipe PLL to disable
7000  *
7001  * Disable the PLL for @pipe. To be used in cases where we need
7002  * the PLL enabled even when @pipe is not going to be enabled.
7003  */
7004 void vlv_force_pll_off(struct drm_device *dev, enum pipe pipe)
7005 {
7006         if (IS_CHERRYVIEW(dev))
7007                 chv_disable_pll(to_i915(dev), pipe);
7008         else
7009                 vlv_disable_pll(to_i915(dev), pipe);
7010 }
7011
7012 static void i9xx_update_pll(struct intel_crtc *crtc,
7013                             struct intel_crtc_state *crtc_state,
7014                             intel_clock_t *reduced_clock,
7015                             int num_connectors)
7016 {
7017         struct drm_device *dev = crtc->base.dev;
7018         struct drm_i915_private *dev_priv = dev->dev_private;
7019         u32 dpll;
7020         bool is_sdvo;
7021         struct dpll *clock = &crtc_state->dpll;
7022
7023         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7024
7025         is_sdvo = intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7026                 intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_HDMI);
7027
7028         dpll = DPLL_VGA_MODE_DIS;
7029
7030         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
7031                 dpll |= DPLLB_MODE_LVDS;
7032         else
7033                 dpll |= DPLLB_MODE_DAC_SERIAL;
7034
7035         if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
7036                 dpll |= (crtc_state->pixel_multiplier - 1)
7037                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7038         }
7039
7040         if (is_sdvo)
7041                 dpll |= DPLL_SDVO_HIGH_SPEED;
7042
7043         if (crtc_state->has_dp_encoder)
7044                 dpll |= DPLL_SDVO_HIGH_SPEED;
7045
7046         /* compute bitmask from p1 value */
7047         if (IS_PINEVIEW(dev))
7048                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7049         else {
7050                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7051                 if (IS_G4X(dev) && reduced_clock)
7052                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7053         }
7054         switch (clock->p2) {
7055         case 5:
7056                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7057                 break;
7058         case 7:
7059                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7060                 break;
7061         case 10:
7062                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7063                 break;
7064         case 14:
7065                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7066                 break;
7067         }
7068         if (INTEL_INFO(dev)->gen >= 4)
7069                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7070
7071         if (crtc_state->sdvo_tv_clock)
7072                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7073         else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7074                  intel_panel_use_ssc(dev_priv) && num_connectors < 2)
7075                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7076         else
7077                 dpll |= PLL_REF_INPUT_DREFCLK;
7078
7079         dpll |= DPLL_VCO_ENABLE;
7080         crtc_state->dpll_hw_state.dpll = dpll;
7081
7082         if (INTEL_INFO(dev)->gen >= 4) {
7083                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7084                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7085                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7086         }
7087 }
7088
7089 static void i8xx_update_pll(struct intel_crtc *crtc,
7090                             struct intel_crtc_state *crtc_state,
7091                             intel_clock_t *reduced_clock,
7092                             int num_connectors)
7093 {
7094         struct drm_device *dev = crtc->base.dev;
7095         struct drm_i915_private *dev_priv = dev->dev_private;
7096         u32 dpll;
7097         struct dpll *clock = &crtc_state->dpll;
7098
7099         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7100
7101         dpll = DPLL_VGA_MODE_DIS;
7102
7103         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7104                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7105         } else {
7106                 if (clock->p1 == 2)
7107                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7108                 else
7109                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7110                 if (clock->p2 == 4)
7111                         dpll |= PLL_P2_DIVIDE_BY_4;
7112         }
7113
7114         if (!IS_I830(dev) && intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_DVO))
7115                 dpll |= DPLL_DVO_2X_MODE;
7116
7117         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7118                  intel_panel_use_ssc(dev_priv) && num_connectors < 2)
7119                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7120         else
7121                 dpll |= PLL_REF_INPUT_DREFCLK;
7122
7123         dpll |= DPLL_VCO_ENABLE;
7124         crtc_state->dpll_hw_state.dpll = dpll;
7125 }
7126
7127 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
7128 {
7129         struct drm_device *dev = intel_crtc->base.dev;
7130         struct drm_i915_private *dev_priv = dev->dev_private;
7131         enum pipe pipe = intel_crtc->pipe;
7132         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
7133         struct drm_display_mode *adjusted_mode =
7134                 &intel_crtc->config->base.adjusted_mode;
7135         uint32_t crtc_vtotal, crtc_vblank_end;
7136         int vsyncshift = 0;
7137
7138         /* We need to be careful not to changed the adjusted mode, for otherwise
7139          * the hw state checker will get angry at the mismatch. */
7140         crtc_vtotal = adjusted_mode->crtc_vtotal;
7141         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7142
7143         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7144                 /* the chip adds 2 halflines automatically */
7145                 crtc_vtotal -= 1;
7146                 crtc_vblank_end -= 1;
7147
7148                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
7149                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7150                 else
7151                         vsyncshift = adjusted_mode->crtc_hsync_start -
7152                                 adjusted_mode->crtc_htotal / 2;
7153                 if (vsyncshift < 0)
7154                         vsyncshift += adjusted_mode->crtc_htotal;
7155         }
7156
7157         if (INTEL_INFO(dev)->gen > 3)
7158                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7159
7160         I915_WRITE(HTOTAL(cpu_transcoder),
7161                    (adjusted_mode->crtc_hdisplay - 1) |
7162                    ((adjusted_mode->crtc_htotal - 1) << 16));
7163         I915_WRITE(HBLANK(cpu_transcoder),
7164                    (adjusted_mode->crtc_hblank_start - 1) |
7165                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7166         I915_WRITE(HSYNC(cpu_transcoder),
7167                    (adjusted_mode->crtc_hsync_start - 1) |
7168                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7169
7170         I915_WRITE(VTOTAL(cpu_transcoder),
7171                    (adjusted_mode->crtc_vdisplay - 1) |
7172                    ((crtc_vtotal - 1) << 16));
7173         I915_WRITE(VBLANK(cpu_transcoder),
7174                    (adjusted_mode->crtc_vblank_start - 1) |
7175                    ((crtc_vblank_end - 1) << 16));
7176         I915_WRITE(VSYNC(cpu_transcoder),
7177                    (adjusted_mode->crtc_vsync_start - 1) |
7178                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7179
7180         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7181          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7182          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7183          * bits. */
7184         if (IS_HASWELL(dev) && cpu_transcoder == TRANSCODER_EDP &&
7185             (pipe == PIPE_B || pipe == PIPE_C))
7186                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7187
7188         /* pipesrc controls the size that is scaled from, which should
7189          * always be the user's requested size.
7190          */
7191         I915_WRITE(PIPESRC(pipe),
7192                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
7193                    (intel_crtc->config->pipe_src_h - 1));
7194 }
7195
7196 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7197                                    struct intel_crtc_state *pipe_config)
7198 {
7199         struct drm_device *dev = crtc->base.dev;
7200         struct drm_i915_private *dev_priv = dev->dev_private;
7201         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7202         uint32_t tmp;
7203
7204         tmp = I915_READ(HTOTAL(cpu_transcoder));
7205         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7206         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7207         tmp = I915_READ(HBLANK(cpu_transcoder));
7208         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7209         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7210         tmp = I915_READ(HSYNC(cpu_transcoder));
7211         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7212         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7213
7214         tmp = I915_READ(VTOTAL(cpu_transcoder));
7215         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7216         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7217         tmp = I915_READ(VBLANK(cpu_transcoder));
7218         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7219         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7220         tmp = I915_READ(VSYNC(cpu_transcoder));
7221         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7222         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7223
7224         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7225                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7226                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7227                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7228         }
7229
7230         tmp = I915_READ(PIPESRC(crtc->pipe));
7231         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7232         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7233
7234         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7235         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7236 }
7237
7238 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7239                                  struct intel_crtc_state *pipe_config)
7240 {
7241         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7242         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7243         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7244         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7245
7246         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7247         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7248         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7249         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7250
7251         mode->flags = pipe_config->base.adjusted_mode.flags;
7252
7253         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7254         mode->flags |= pipe_config->base.adjusted_mode.flags;
7255 }
7256
7257 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
7258 {
7259         struct drm_device *dev = intel_crtc->base.dev;
7260         struct drm_i915_private *dev_priv = dev->dev_private;
7261         uint32_t pipeconf;
7262
7263         pipeconf = 0;
7264
7265         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
7266             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
7267                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
7268
7269         if (intel_crtc->config->double_wide)
7270                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7271
7272         /* only g4x and later have fancy bpc/dither controls */
7273         if (IS_G4X(dev) || IS_VALLEYVIEW(dev)) {
7274                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7275                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
7276                         pipeconf |= PIPECONF_DITHER_EN |
7277                                     PIPECONF_DITHER_TYPE_SP;
7278
7279                 switch (intel_crtc->config->pipe_bpp) {
7280                 case 18:
7281                         pipeconf |= PIPECONF_6BPC;
7282                         break;
7283                 case 24:
7284                         pipeconf |= PIPECONF_8BPC;
7285                         break;
7286                 case 30:
7287                         pipeconf |= PIPECONF_10BPC;
7288                         break;
7289                 default:
7290                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7291                         BUG();
7292                 }
7293         }
7294
7295         if (HAS_PIPE_CXSR(dev)) {
7296                 if (intel_crtc->lowfreq_avail) {
7297                         DRM_DEBUG_KMS("enabling CxSR downclocking\n");
7298                         pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
7299                 } else {
7300                         DRM_DEBUG_KMS("disabling CxSR downclocking\n");
7301                 }
7302         }
7303
7304         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7305                 if (INTEL_INFO(dev)->gen < 4 ||
7306                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
7307                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7308                 else
7309                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7310         } else
7311                 pipeconf |= PIPECONF_PROGRESSIVE;
7312
7313         if (IS_VALLEYVIEW(dev) && intel_crtc->config->limited_color_range)
7314                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7315
7316         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
7317         POSTING_READ(PIPECONF(intel_crtc->pipe));
7318 }
7319
7320 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7321                                    struct intel_crtc_state *crtc_state)
7322 {
7323         struct drm_device *dev = crtc->base.dev;
7324         struct drm_i915_private *dev_priv = dev->dev_private;
7325         int refclk, num_connectors = 0;
7326         intel_clock_t clock, reduced_clock;
7327         bool ok, has_reduced_clock = false;
7328         bool is_lvds = false, is_dsi = false;
7329         struct intel_encoder *encoder;
7330         const intel_limit_t *limit;
7331         struct drm_atomic_state *state = crtc_state->base.state;
7332         struct drm_connector_state *connector_state;
7333         int i;
7334
7335         for (i = 0; i < state->num_connector; i++) {
7336                 if (!state->connectors[i])
7337                         continue;
7338
7339                 connector_state = state->connector_states[i];
7340                 if (connector_state->crtc != &crtc->base)
7341                         continue;
7342
7343                 encoder = to_intel_encoder(connector_state->best_encoder);
7344
7345                 switch (encoder->type) {
7346                 case INTEL_OUTPUT_LVDS:
7347                         is_lvds = true;
7348                         break;
7349                 case INTEL_OUTPUT_DSI:
7350                         is_dsi = true;
7351                         break;
7352                 default:
7353                         break;
7354                 }
7355
7356                 num_connectors++;
7357         }
7358
7359         if (is_dsi)
7360                 return 0;
7361
7362         if (!crtc_state->clock_set) {
7363                 refclk = i9xx_get_refclk(crtc_state, num_connectors);
7364
7365                 /*
7366                  * Returns a set of divisors for the desired target clock with
7367                  * the given refclk, or FALSE.  The returned values represent
7368                  * the clock equation: reflck * (5 * (m1 + 2) + (m2 + 2)) / (n +
7369                  * 2) / p1 / p2.
7370                  */
7371                 limit = intel_limit(crtc_state, refclk);
7372                 ok = dev_priv->display.find_dpll(limit, crtc_state,
7373                                                  crtc_state->port_clock,
7374                                                  refclk, NULL, &clock);
7375                 if (!ok) {
7376                         DRM_ERROR("Couldn't find PLL settings for mode!\n");
7377                         return -EINVAL;
7378                 }
7379
7380                 if (is_lvds && dev_priv->lvds_downclock_avail) {
7381                         /*
7382                          * Ensure we match the reduced clock's P to the target
7383                          * clock.  If the clocks don't match, we can't switch
7384                          * the display clock by using the FP0/FP1. In such case
7385                          * we will disable the LVDS downclock feature.
7386                          */
7387                         has_reduced_clock =
7388                                 dev_priv->display.find_dpll(limit, crtc_state,
7389                                                             dev_priv->lvds_downclock,
7390                                                             refclk, &clock,
7391                                                             &reduced_clock);
7392                 }
7393                 /* Compat-code for transition, will disappear. */
7394                 crtc_state->dpll.n = clock.n;
7395                 crtc_state->dpll.m1 = clock.m1;
7396                 crtc_state->dpll.m2 = clock.m2;
7397                 crtc_state->dpll.p1 = clock.p1;
7398                 crtc_state->dpll.p2 = clock.p2;
7399         }
7400
7401         if (IS_GEN2(dev)) {
7402                 i8xx_update_pll(crtc, crtc_state,
7403                                 has_reduced_clock ? &reduced_clock : NULL,
7404                                 num_connectors);
7405         } else if (IS_CHERRYVIEW(dev)) {
7406                 chv_update_pll(crtc, crtc_state);
7407         } else if (IS_VALLEYVIEW(dev)) {
7408                 vlv_update_pll(crtc, crtc_state);
7409         } else {
7410                 i9xx_update_pll(crtc, crtc_state,
7411                                 has_reduced_clock ? &reduced_clock : NULL,
7412                                 num_connectors);
7413         }
7414
7415         return 0;
7416 }
7417
7418 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
7419                                  struct intel_crtc_state *pipe_config)
7420 {
7421         struct drm_device *dev = crtc->base.dev;
7422         struct drm_i915_private *dev_priv = dev->dev_private;
7423         uint32_t tmp;
7424
7425         if (INTEL_INFO(dev)->gen <= 3 && (IS_I830(dev) || !IS_MOBILE(dev)))
7426                 return;
7427
7428         tmp = I915_READ(PFIT_CONTROL);
7429         if (!(tmp & PFIT_ENABLE))
7430                 return;
7431
7432         /* Check whether the pfit is attached to our pipe. */
7433         if (INTEL_INFO(dev)->gen < 4) {
7434                 if (crtc->pipe != PIPE_B)
7435                         return;
7436         } else {
7437                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
7438                         return;
7439         }
7440
7441         pipe_config->gmch_pfit.control = tmp;
7442         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
7443         if (INTEL_INFO(dev)->gen < 5)
7444                 pipe_config->gmch_pfit.lvds_border_bits =
7445                         I915_READ(LVDS) & LVDS_BORDER_ENABLE;
7446 }
7447
7448 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
7449                                struct intel_crtc_state *pipe_config)
7450 {
7451         struct drm_device *dev = crtc->base.dev;
7452         struct drm_i915_private *dev_priv = dev->dev_private;
7453         int pipe = pipe_config->cpu_transcoder;
7454         intel_clock_t clock;
7455         u32 mdiv;
7456         int refclk = 100000;
7457
7458         /* In case of MIPI DPLL will not even be used */
7459         if (!(pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE))
7460                 return;
7461
7462         mutex_lock(&dev_priv->dpio_lock);
7463         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
7464         mutex_unlock(&dev_priv->dpio_lock);
7465
7466         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
7467         clock.m2 = mdiv & DPIO_M2DIV_MASK;
7468         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
7469         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
7470         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
7471
7472         vlv_clock(refclk, &clock);
7473
7474         /* clock.dot is the fast clock */
7475         pipe_config->port_clock = clock.dot / 5;
7476 }
7477
7478 static void
7479 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
7480                               struct intel_initial_plane_config *plane_config)
7481 {
7482         struct drm_device *dev = crtc->base.dev;
7483         struct drm_i915_private *dev_priv = dev->dev_private;
7484         u32 val, base, offset;
7485         int pipe = crtc->pipe, plane = crtc->plane;
7486         int fourcc, pixel_format;
7487         unsigned int aligned_height;
7488         struct drm_framebuffer *fb;
7489         struct intel_framebuffer *intel_fb;
7490
7491         val = I915_READ(DSPCNTR(plane));
7492         if (!(val & DISPLAY_PLANE_ENABLE))
7493                 return;
7494
7495         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
7496         if (!intel_fb) {
7497                 DRM_DEBUG_KMS("failed to alloc fb\n");
7498                 return;
7499         }
7500
7501         fb = &intel_fb->base;
7502
7503         if (INTEL_INFO(dev)->gen >= 4) {
7504                 if (val & DISPPLANE_TILED) {
7505                         plane_config->tiling = I915_TILING_X;
7506                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
7507                 }
7508         }
7509
7510         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
7511         fourcc = i9xx_format_to_fourcc(pixel_format);
7512         fb->pixel_format = fourcc;
7513         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
7514
7515         if (INTEL_INFO(dev)->gen >= 4) {
7516                 if (plane_config->tiling)
7517                         offset = I915_READ(DSPTILEOFF(plane));
7518                 else
7519                         offset = I915_READ(DSPLINOFF(plane));
7520                 base = I915_READ(DSPSURF(plane)) & 0xfffff000;
7521         } else {
7522                 base = I915_READ(DSPADDR(plane));
7523         }
7524         plane_config->base = base;
7525
7526         val = I915_READ(PIPESRC(pipe));
7527         fb->width = ((val >> 16) & 0xfff) + 1;
7528         fb->height = ((val >> 0) & 0xfff) + 1;
7529
7530         val = I915_READ(DSPSTRIDE(pipe));
7531         fb->pitches[0] = val & 0xffffffc0;
7532
7533         aligned_height = intel_fb_align_height(dev, fb->height,
7534                                                fb->pixel_format,
7535                                                fb->modifier[0]);
7536
7537         plane_config->size = fb->pitches[0] * aligned_height;
7538
7539         DRM_DEBUG_KMS("pipe/plane %c/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
7540                       pipe_name(pipe), plane, fb->width, fb->height,
7541                       fb->bits_per_pixel, base, fb->pitches[0],
7542                       plane_config->size);
7543
7544         plane_config->fb = intel_fb;
7545 }
7546
7547 static void chv_crtc_clock_get(struct intel_crtc *crtc,
7548                                struct intel_crtc_state *pipe_config)
7549 {
7550         struct drm_device *dev = crtc->base.dev;
7551         struct drm_i915_private *dev_priv = dev->dev_private;
7552         int pipe = pipe_config->cpu_transcoder;
7553         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7554         intel_clock_t clock;
7555         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2;
7556         int refclk = 100000;
7557
7558         mutex_lock(&dev_priv->dpio_lock);
7559         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
7560         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
7561         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
7562         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
7563         mutex_unlock(&dev_priv->dpio_lock);
7564
7565         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
7566         clock.m2 = ((pll_dw0 & 0xff) << 22) | (pll_dw2 & 0x3fffff);
7567         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
7568         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
7569         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
7570
7571         chv_clock(refclk, &clock);
7572
7573         /* clock.dot is the fast clock */
7574         pipe_config->port_clock = clock.dot / 5;
7575 }
7576
7577 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
7578                                  struct intel_crtc_state *pipe_config)
7579 {
7580         struct drm_device *dev = crtc->base.dev;
7581         struct drm_i915_private *dev_priv = dev->dev_private;
7582         uint32_t tmp;
7583
7584         if (!intel_display_power_is_enabled(dev_priv,
7585                                             POWER_DOMAIN_PIPE(crtc->pipe)))
7586                 return false;
7587
7588         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
7589         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
7590
7591         tmp = I915_READ(PIPECONF(crtc->pipe));
7592         if (!(tmp & PIPECONF_ENABLE))
7593                 return false;
7594
7595         if (IS_G4X(dev) || IS_VALLEYVIEW(dev)) {
7596                 switch (tmp & PIPECONF_BPC_MASK) {
7597                 case PIPECONF_6BPC:
7598                         pipe_config->pipe_bpp = 18;
7599                         break;
7600                 case PIPECONF_8BPC:
7601                         pipe_config->pipe_bpp = 24;
7602                         break;
7603                 case PIPECONF_10BPC:
7604                         pipe_config->pipe_bpp = 30;
7605                         break;
7606                 default:
7607                         break;
7608                 }
7609         }
7610
7611         if (IS_VALLEYVIEW(dev) && (tmp & PIPECONF_COLOR_RANGE_SELECT))
7612                 pipe_config->limited_color_range = true;
7613
7614         if (INTEL_INFO(dev)->gen < 4)
7615                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
7616
7617         intel_get_pipe_timings(crtc, pipe_config);
7618
7619         i9xx_get_pfit_config(crtc, pipe_config);
7620
7621         if (INTEL_INFO(dev)->gen >= 4) {
7622                 tmp = I915_READ(DPLL_MD(crtc->pipe));
7623                 pipe_config->pixel_multiplier =
7624                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
7625                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
7626                 pipe_config->dpll_hw_state.dpll_md = tmp;
7627         } else if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
7628                 tmp = I915_READ(DPLL(crtc->pipe));
7629                 pipe_config->pixel_multiplier =
7630                         ((tmp & SDVO_MULTIPLIER_MASK)
7631                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
7632         } else {
7633                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
7634                  * port and will be fixed up in the encoder->get_config
7635                  * function. */
7636                 pipe_config->pixel_multiplier = 1;
7637         }
7638         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
7639         if (!IS_VALLEYVIEW(dev)) {
7640                 /*
7641                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
7642                  * on 830. Filter it out here so that we don't
7643                  * report errors due to that.
7644                  */
7645                 if (IS_I830(dev))
7646                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
7647
7648                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
7649                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
7650         } else {
7651                 /* Mask out read-only status bits. */
7652                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
7653                                                      DPLL_PORTC_READY_MASK |
7654                                                      DPLL_PORTB_READY_MASK);
7655         }
7656
7657         if (IS_CHERRYVIEW(dev))
7658                 chv_crtc_clock_get(crtc, pipe_config);
7659         else if (IS_VALLEYVIEW(dev))
7660                 vlv_crtc_clock_get(crtc, pipe_config);
7661         else
7662                 i9xx_crtc_clock_get(crtc, pipe_config);
7663
7664         return true;
7665 }
7666
7667 static void ironlake_init_pch_refclk(struct drm_device *dev)
7668 {
7669         struct drm_i915_private *dev_priv = dev->dev_private;
7670         struct intel_encoder *encoder;
7671         u32 val, final;
7672         bool has_lvds = false;
7673         bool has_cpu_edp = false;
7674         bool has_panel = false;
7675         bool has_ck505 = false;
7676         bool can_ssc = false;
7677
7678         /* We need to take the global config into account */
7679         for_each_intel_encoder(dev, encoder) {
7680                 switch (encoder->type) {
7681                 case INTEL_OUTPUT_LVDS:
7682                         has_panel = true;
7683                         has_lvds = true;
7684                         break;
7685                 case INTEL_OUTPUT_EDP:
7686                         has_panel = true;
7687                         if (enc_to_dig_port(&encoder->base)->port == PORT_A)
7688                                 has_cpu_edp = true;
7689                         break;
7690                 default:
7691                         break;
7692                 }
7693         }
7694
7695         if (HAS_PCH_IBX(dev)) {
7696                 has_ck505 = dev_priv->vbt.display_clock_mode;
7697                 can_ssc = has_ck505;
7698         } else {
7699                 has_ck505 = false;
7700                 can_ssc = true;
7701         }
7702
7703         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d\n",
7704                       has_panel, has_lvds, has_ck505);
7705
7706         /* Ironlake: try to setup display ref clock before DPLL
7707          * enabling. This is only under driver's control after
7708          * PCH B stepping, previous chipset stepping should be
7709          * ignoring this setting.
7710          */
7711         val = I915_READ(PCH_DREF_CONTROL);
7712
7713         /* As we must carefully and slowly disable/enable each source in turn,
7714          * compute the final state we want first and check if we need to
7715          * make any changes at all.
7716          */
7717         final = val;
7718         final &= ~DREF_NONSPREAD_SOURCE_MASK;
7719         if (has_ck505)
7720                 final |= DREF_NONSPREAD_CK505_ENABLE;
7721         else
7722                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
7723
7724         final &= ~DREF_SSC_SOURCE_MASK;
7725         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7726         final &= ~DREF_SSC1_ENABLE;
7727
7728         if (has_panel) {
7729                 final |= DREF_SSC_SOURCE_ENABLE;
7730
7731                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
7732                         final |= DREF_SSC1_ENABLE;
7733
7734                 if (has_cpu_edp) {
7735                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
7736                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
7737                         else
7738                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
7739                 } else
7740                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7741         } else {
7742                 final |= DREF_SSC_SOURCE_DISABLE;
7743                 final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7744         }
7745
7746         if (final == val)
7747                 return;
7748
7749         /* Always enable nonspread source */
7750         val &= ~DREF_NONSPREAD_SOURCE_MASK;
7751
7752         if (has_ck505)
7753                 val |= DREF_NONSPREAD_CK505_ENABLE;
7754         else
7755                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
7756
7757         if (has_panel) {
7758                 val &= ~DREF_SSC_SOURCE_MASK;
7759                 val |= DREF_SSC_SOURCE_ENABLE;
7760
7761                 /* SSC must be turned on before enabling the CPU output  */
7762                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
7763                         DRM_DEBUG_KMS("Using SSC on panel\n");
7764                         val |= DREF_SSC1_ENABLE;
7765                 } else
7766                         val &= ~DREF_SSC1_ENABLE;
7767
7768                 /* Get SSC going before enabling the outputs */
7769                 I915_WRITE(PCH_DREF_CONTROL, val);
7770                 POSTING_READ(PCH_DREF_CONTROL);
7771                 udelay(200);
7772
7773                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7774
7775                 /* Enable CPU source on CPU attached eDP */
7776                 if (has_cpu_edp) {
7777                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
7778                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
7779                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
7780                         } else
7781                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
7782                 } else
7783                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7784
7785                 I915_WRITE(PCH_DREF_CONTROL, val);
7786                 POSTING_READ(PCH_DREF_CONTROL);
7787                 udelay(200);
7788         } else {
7789                 DRM_DEBUG_KMS("Disabling SSC entirely\n");
7790
7791                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7792
7793                 /* Turn off CPU output */
7794                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7795
7796                 I915_WRITE(PCH_DREF_CONTROL, val);
7797                 POSTING_READ(PCH_DREF_CONTROL);
7798                 udelay(200);
7799
7800                 /* Turn off the SSC source */
7801                 val &= ~DREF_SSC_SOURCE_MASK;
7802                 val |= DREF_SSC_SOURCE_DISABLE;
7803
7804                 /* Turn off SSC1 */
7805                 val &= ~DREF_SSC1_ENABLE;
7806
7807                 I915_WRITE(PCH_DREF_CONTROL, val);
7808                 POSTING_READ(PCH_DREF_CONTROL);
7809                 udelay(200);
7810         }
7811
7812         BUG_ON(val != final);
7813 }
7814
7815 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
7816 {
7817         uint32_t tmp;
7818
7819         tmp = I915_READ(SOUTH_CHICKEN2);
7820         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
7821         I915_WRITE(SOUTH_CHICKEN2, tmp);
7822
7823         if (wait_for_atomic_us(I915_READ(SOUTH_CHICKEN2) &
7824                                FDI_MPHY_IOSFSB_RESET_STATUS, 100))
7825                 DRM_ERROR("FDI mPHY reset assert timeout\n");
7826
7827         tmp = I915_READ(SOUTH_CHICKEN2);
7828         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
7829         I915_WRITE(SOUTH_CHICKEN2, tmp);
7830
7831         if (wait_for_atomic_us((I915_READ(SOUTH_CHICKEN2) &
7832                                 FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
7833                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
7834 }
7835
7836 /* WaMPhyProgramming:hsw */
7837 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
7838 {
7839         uint32_t tmp;
7840
7841         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
7842         tmp &= ~(0xFF << 24);
7843         tmp |= (0x12 << 24);
7844         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
7845
7846         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
7847         tmp |= (1 << 11);
7848         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
7849
7850         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
7851         tmp |= (1 << 11);
7852         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
7853
7854         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
7855         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
7856         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
7857
7858         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
7859         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
7860         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
7861
7862         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
7863         tmp &= ~(7 << 13);
7864         tmp |= (5 << 13);
7865         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
7866
7867         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
7868         tmp &= ~(7 << 13);
7869         tmp |= (5 << 13);
7870         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
7871
7872         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
7873         tmp &= ~0xFF;
7874         tmp |= 0x1C;
7875         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
7876
7877         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
7878         tmp &= ~0xFF;
7879         tmp |= 0x1C;
7880         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
7881
7882         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
7883         tmp &= ~(0xFF << 16);
7884         tmp |= (0x1C << 16);
7885         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
7886
7887         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
7888         tmp &= ~(0xFF << 16);
7889         tmp |= (0x1C << 16);
7890         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
7891
7892         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
7893         tmp |= (1 << 27);
7894         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
7895
7896         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
7897         tmp |= (1 << 27);
7898         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
7899
7900         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
7901         tmp &= ~(0xF << 28);
7902         tmp |= (4 << 28);
7903         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
7904
7905         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
7906         tmp &= ~(0xF << 28);
7907         tmp |= (4 << 28);
7908         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
7909 }
7910
7911 /* Implements 3 different sequences from BSpec chapter "Display iCLK
7912  * Programming" based on the parameters passed:
7913  * - Sequence to enable CLKOUT_DP
7914  * - Sequence to enable CLKOUT_DP without spread
7915  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
7916  */
7917 static void lpt_enable_clkout_dp(struct drm_device *dev, bool with_spread,
7918                                  bool with_fdi)
7919 {
7920         struct drm_i915_private *dev_priv = dev->dev_private;
7921         uint32_t reg, tmp;
7922
7923         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
7924                 with_spread = true;
7925         if (WARN(dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE &&
7926                  with_fdi, "LP PCH doesn't have FDI\n"))
7927                 with_fdi = false;
7928
7929         mutex_lock(&dev_priv->dpio_lock);
7930
7931         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
7932         tmp &= ~SBI_SSCCTL_DISABLE;
7933         tmp |= SBI_SSCCTL_PATHALT;
7934         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
7935
7936         udelay(24);
7937
7938         if (with_spread) {
7939                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
7940                 tmp &= ~SBI_SSCCTL_PATHALT;
7941                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
7942
7943                 if (with_fdi) {
7944                         lpt_reset_fdi_mphy(dev_priv);
7945                         lpt_program_fdi_mphy(dev_priv);
7946                 }
7947         }
7948
7949         reg = (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) ?
7950                SBI_GEN0 : SBI_DBUFF0;
7951         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
7952         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
7953         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
7954
7955         mutex_unlock(&dev_priv->dpio_lock);
7956 }
7957
7958 /* Sequence to disable CLKOUT_DP */
7959 static void lpt_disable_clkout_dp(struct drm_device *dev)
7960 {
7961         struct drm_i915_private *dev_priv = dev->dev_private;
7962         uint32_t reg, tmp;
7963
7964         mutex_lock(&dev_priv->dpio_lock);
7965
7966         reg = (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) ?
7967                SBI_GEN0 : SBI_DBUFF0;
7968         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
7969         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
7970         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
7971
7972         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
7973         if (!(tmp & SBI_SSCCTL_DISABLE)) {
7974                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
7975                         tmp |= SBI_SSCCTL_PATHALT;
7976                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
7977                         udelay(32);
7978                 }
7979                 tmp |= SBI_SSCCTL_DISABLE;
7980                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
7981         }
7982
7983         mutex_unlock(&dev_priv->dpio_lock);
7984 }
7985
7986 static void lpt_init_pch_refclk(struct drm_device *dev)
7987 {
7988         struct intel_encoder *encoder;
7989         bool has_vga = false;
7990
7991         for_each_intel_encoder(dev, encoder) {
7992                 switch (encoder->type) {
7993                 case INTEL_OUTPUT_ANALOG:
7994                         has_vga = true;
7995                         break;
7996                 default:
7997                         break;
7998                 }
7999         }
8000
8001         if (has_vga)
8002                 lpt_enable_clkout_dp(dev, true, true);
8003         else
8004                 lpt_disable_clkout_dp(dev);
8005 }
8006
8007 /*
8008  * Initialize reference clocks when the driver loads
8009  */
8010 void intel_init_pch_refclk(struct drm_device *dev)
8011 {
8012         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
8013                 ironlake_init_pch_refclk(dev);
8014         else if (HAS_PCH_LPT(dev))
8015                 lpt_init_pch_refclk(dev);
8016 }
8017
8018 static int ironlake_get_refclk(struct intel_crtc_state *crtc_state)
8019 {
8020         struct drm_device *dev = crtc_state->base.crtc->dev;
8021         struct drm_i915_private *dev_priv = dev->dev_private;
8022         struct drm_atomic_state *state = crtc_state->base.state;
8023         struct drm_connector_state *connector_state;
8024         struct intel_encoder *encoder;
8025         int num_connectors = 0, i;
8026         bool is_lvds = false;
8027
8028         for (i = 0; i < state->num_connector; i++) {
8029                 if (!state->connectors[i])
8030                         continue;
8031
8032                 connector_state = state->connector_states[i];
8033                 if (connector_state->crtc != crtc_state->base.crtc)
8034                         continue;
8035
8036                 encoder = to_intel_encoder(connector_state->best_encoder);
8037
8038                 switch (encoder->type) {
8039                 case INTEL_OUTPUT_LVDS:
8040                         is_lvds = true;
8041                         break;
8042                 default:
8043                         break;
8044                 }
8045                 num_connectors++;
8046         }
8047
8048         if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2) {
8049                 DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8050                               dev_priv->vbt.lvds_ssc_freq);
8051                 return dev_priv->vbt.lvds_ssc_freq;
8052         }
8053
8054         return 120000;
8055 }
8056
8057 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
8058 {
8059         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
8060         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8061         int pipe = intel_crtc->pipe;
8062         uint32_t val;
8063
8064         val = 0;
8065
8066         switch (intel_crtc->config->pipe_bpp) {
8067         case 18:
8068                 val |= PIPECONF_6BPC;
8069                 break;
8070         case 24:
8071                 val |= PIPECONF_8BPC;
8072                 break;
8073         case 30:
8074                 val |= PIPECONF_10BPC;
8075                 break;
8076         case 36:
8077                 val |= PIPECONF_12BPC;
8078                 break;
8079         default:
8080                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8081                 BUG();
8082         }
8083
8084         if (intel_crtc->config->dither)
8085                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8086
8087         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8088                 val |= PIPECONF_INTERLACED_ILK;
8089         else
8090                 val |= PIPECONF_PROGRESSIVE;
8091
8092         if (intel_crtc->config->limited_color_range)
8093                 val |= PIPECONF_COLOR_RANGE_SELECT;
8094
8095         I915_WRITE(PIPECONF(pipe), val);
8096         POSTING_READ(PIPECONF(pipe));
8097 }
8098
8099 /*
8100  * Set up the pipe CSC unit.
8101  *
8102  * Currently only full range RGB to limited range RGB conversion
8103  * is supported, but eventually this should handle various
8104  * RGB<->YCbCr scenarios as well.
8105  */
8106 static void intel_set_pipe_csc(struct drm_crtc *crtc)
8107 {
8108         struct drm_device *dev = crtc->dev;
8109         struct drm_i915_private *dev_priv = dev->dev_private;
8110         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8111         int pipe = intel_crtc->pipe;
8112         uint16_t coeff = 0x7800; /* 1.0 */
8113
8114         /*
8115          * TODO: Check what kind of values actually come out of the pipe
8116          * with these coeff/postoff values and adjust to get the best
8117          * accuracy. Perhaps we even need to take the bpc value into
8118          * consideration.
8119          */
8120
8121         if (intel_crtc->config->limited_color_range)
8122                 coeff = ((235 - 16) * (1 << 12) / 255) & 0xff8; /* 0.xxx... */
8123
8124         /*
8125          * GY/GU and RY/RU should be the other way around according
8126          * to BSpec, but reality doesn't agree. Just set them up in
8127          * a way that results in the correct picture.
8128          */
8129         I915_WRITE(PIPE_CSC_COEFF_RY_GY(pipe), coeff << 16);
8130         I915_WRITE(PIPE_CSC_COEFF_BY(pipe), 0);
8131
8132         I915_WRITE(PIPE_CSC_COEFF_RU_GU(pipe), coeff);
8133         I915_WRITE(PIPE_CSC_COEFF_BU(pipe), 0);
8134
8135         I915_WRITE(PIPE_CSC_COEFF_RV_GV(pipe), 0);
8136         I915_WRITE(PIPE_CSC_COEFF_BV(pipe), coeff << 16);
8137
8138         I915_WRITE(PIPE_CSC_PREOFF_HI(pipe), 0);
8139         I915_WRITE(PIPE_CSC_PREOFF_ME(pipe), 0);
8140         I915_WRITE(PIPE_CSC_PREOFF_LO(pipe), 0);
8141
8142         if (INTEL_INFO(dev)->gen > 6) {
8143                 uint16_t postoff = 0;
8144
8145                 if (intel_crtc->config->limited_color_range)
8146                         postoff = (16 * (1 << 12) / 255) & 0x1fff;
8147
8148                 I915_WRITE(PIPE_CSC_POSTOFF_HI(pipe), postoff);
8149                 I915_WRITE(PIPE_CSC_POSTOFF_ME(pipe), postoff);
8150                 I915_WRITE(PIPE_CSC_POSTOFF_LO(pipe), postoff);
8151
8152                 I915_WRITE(PIPE_CSC_MODE(pipe), 0);
8153         } else {
8154                 uint32_t mode = CSC_MODE_YUV_TO_RGB;
8155
8156                 if (intel_crtc->config->limited_color_range)
8157                         mode |= CSC_BLACK_SCREEN_OFFSET;
8158
8159                 I915_WRITE(PIPE_CSC_MODE(pipe), mode);
8160         }
8161 }
8162
8163 static void haswell_set_pipeconf(struct drm_crtc *crtc)
8164 {
8165         struct drm_device *dev = crtc->dev;
8166         struct drm_i915_private *dev_priv = dev->dev_private;
8167         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8168         enum pipe pipe = intel_crtc->pipe;
8169         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8170         uint32_t val;
8171
8172         val = 0;
8173
8174         if (IS_HASWELL(dev) && intel_crtc->config->dither)
8175                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8176
8177         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8178                 val |= PIPECONF_INTERLACED_ILK;
8179         else
8180                 val |= PIPECONF_PROGRESSIVE;
8181
8182         I915_WRITE(PIPECONF(cpu_transcoder), val);
8183         POSTING_READ(PIPECONF(cpu_transcoder));
8184
8185         I915_WRITE(GAMMA_MODE(intel_crtc->pipe), GAMMA_MODE_MODE_8BIT);
8186         POSTING_READ(GAMMA_MODE(intel_crtc->pipe));
8187
8188         if (IS_BROADWELL(dev) || INTEL_INFO(dev)->gen >= 9) {
8189                 val = 0;
8190
8191                 switch (intel_crtc->config->pipe_bpp) {
8192                 case 18:
8193                         val |= PIPEMISC_DITHER_6_BPC;
8194                         break;
8195                 case 24:
8196                         val |= PIPEMISC_DITHER_8_BPC;
8197                         break;
8198                 case 30:
8199                         val |= PIPEMISC_DITHER_10_BPC;
8200                         break;
8201                 case 36:
8202                         val |= PIPEMISC_DITHER_12_BPC;
8203                         break;
8204                 default:
8205                         /* Case prevented by pipe_config_set_bpp. */
8206                         BUG();
8207                 }
8208
8209                 if (intel_crtc->config->dither)
8210                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8211
8212                 I915_WRITE(PIPEMISC(pipe), val);
8213         }
8214 }
8215
8216 static bool ironlake_compute_clocks(struct drm_crtc *crtc,
8217                                     struct intel_crtc_state *crtc_state,
8218                                     intel_clock_t *clock,
8219                                     bool *has_reduced_clock,
8220                                     intel_clock_t *reduced_clock)
8221 {
8222         struct drm_device *dev = crtc->dev;
8223         struct drm_i915_private *dev_priv = dev->dev_private;
8224         int refclk;
8225         const intel_limit_t *limit;
8226         bool ret, is_lvds = false;
8227
8228         is_lvds = intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS);
8229
8230         refclk = ironlake_get_refclk(crtc_state);
8231
8232         /*
8233          * Returns a set of divisors for the desired target clock with the given
8234          * refclk, or FALSE.  The returned values represent the clock equation:
8235          * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
8236          */
8237         limit = intel_limit(crtc_state, refclk);
8238         ret = dev_priv->display.find_dpll(limit, crtc_state,
8239                                           crtc_state->port_clock,
8240                                           refclk, NULL, clock);
8241         if (!ret)
8242                 return false;
8243
8244         if (is_lvds && dev_priv->lvds_downclock_avail) {
8245                 /*
8246                  * Ensure we match the reduced clock's P to the target clock.
8247                  * If the clocks don't match, we can't switch the display clock
8248                  * by using the FP0/FP1. In such case we will disable the LVDS
8249                  * downclock feature.
8250                 */
8251                 *has_reduced_clock =
8252                         dev_priv->display.find_dpll(limit, crtc_state,
8253                                                     dev_priv->lvds_downclock,
8254                                                     refclk, clock,
8255                                                     reduced_clock);
8256         }
8257
8258         return true;
8259 }
8260
8261 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8262 {
8263         /*
8264          * Account for spread spectrum to avoid
8265          * oversubscribing the link. Max center spread
8266          * is 2.5%; use 5% for safety's sake.
8267          */
8268         u32 bps = target_clock * bpp * 21 / 20;
8269         return DIV_ROUND_UP(bps, link_bw * 8);
8270 }
8271
8272 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8273 {
8274         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8275 }
8276
8277 static uint32_t ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8278                                       struct intel_crtc_state *crtc_state,
8279                                       u32 *fp,
8280                                       intel_clock_t *reduced_clock, u32 *fp2)
8281 {
8282         struct drm_crtc *crtc = &intel_crtc->base;
8283         struct drm_device *dev = crtc->dev;
8284         struct drm_i915_private *dev_priv = dev->dev_private;
8285         struct drm_atomic_state *state = crtc_state->base.state;
8286         struct drm_connector_state *connector_state;
8287         struct intel_encoder *encoder;
8288         uint32_t dpll;
8289         int factor, num_connectors = 0, i;
8290         bool is_lvds = false, is_sdvo = false;
8291
8292         for (i = 0; i < state->num_connector; i++) {
8293                 if (!state->connectors[i])
8294                         continue;
8295
8296                 connector_state = state->connector_states[i];
8297                 if (connector_state->crtc != crtc_state->base.crtc)
8298                         continue;
8299
8300                 encoder = to_intel_encoder(connector_state->best_encoder);
8301
8302                 switch (encoder->type) {
8303                 case INTEL_OUTPUT_LVDS:
8304                         is_lvds = true;
8305                         break;
8306                 case INTEL_OUTPUT_SDVO:
8307                 case INTEL_OUTPUT_HDMI:
8308                         is_sdvo = true;
8309                         break;
8310                 default:
8311                         break;
8312                 }
8313
8314                 num_connectors++;
8315         }
8316
8317         /* Enable autotuning of the PLL clock (if permissible) */
8318         factor = 21;
8319         if (is_lvds) {
8320                 if ((intel_panel_use_ssc(dev_priv) &&
8321                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8322                     (HAS_PCH_IBX(dev) && intel_is_dual_link_lvds(dev)))
8323                         factor = 25;
8324         } else if (crtc_state->sdvo_tv_clock)
8325                 factor = 20;
8326
8327         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8328                 *fp |= FP_CB_TUNE;
8329
8330         if (fp2 && (reduced_clock->m < factor * reduced_clock->n))
8331                 *fp2 |= FP_CB_TUNE;
8332
8333         dpll = 0;
8334
8335         if (is_lvds)
8336                 dpll |= DPLLB_MODE_LVDS;
8337         else
8338                 dpll |= DPLLB_MODE_DAC_SERIAL;
8339
8340         dpll |= (crtc_state->pixel_multiplier - 1)
8341                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8342
8343         if (is_sdvo)
8344                 dpll |= DPLL_SDVO_HIGH_SPEED;
8345         if (crtc_state->has_dp_encoder)
8346                 dpll |= DPLL_SDVO_HIGH_SPEED;
8347
8348         /* compute bitmask from p1 value */
8349         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8350         /* also FPA1 */
8351         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8352
8353         switch (crtc_state->dpll.p2) {
8354         case 5:
8355                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8356                 break;
8357         case 7:
8358                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8359                 break;
8360         case 10:
8361                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8362                 break;
8363         case 14:
8364                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8365                 break;
8366         }
8367
8368         if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2)
8369                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8370         else
8371                 dpll |= PLL_REF_INPUT_DREFCLK;
8372
8373         return dpll | DPLL_VCO_ENABLE;
8374 }
8375
8376 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
8377                                        struct intel_crtc_state *crtc_state)
8378 {
8379         struct drm_device *dev = crtc->base.dev;
8380         intel_clock_t clock, reduced_clock;
8381         u32 dpll = 0, fp = 0, fp2 = 0;
8382         bool ok, has_reduced_clock = false;
8383         bool is_lvds = false;
8384         struct intel_shared_dpll *pll;
8385
8386         is_lvds = intel_pipe_has_type(crtc, INTEL_OUTPUT_LVDS);
8387
8388         WARN(!(HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev)),
8389              "Unexpected PCH type %d\n", INTEL_PCH_TYPE(dev));
8390
8391         ok = ironlake_compute_clocks(&crtc->base, crtc_state, &clock,
8392                                      &has_reduced_clock, &reduced_clock);
8393         if (!ok && !crtc_state->clock_set) {
8394                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8395                 return -EINVAL;
8396         }
8397         /* Compat-code for transition, will disappear. */
8398         if (!crtc_state->clock_set) {
8399                 crtc_state->dpll.n = clock.n;
8400                 crtc_state->dpll.m1 = clock.m1;
8401                 crtc_state->dpll.m2 = clock.m2;
8402                 crtc_state->dpll.p1 = clock.p1;
8403                 crtc_state->dpll.p2 = clock.p2;
8404         }
8405
8406         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
8407         if (crtc_state->has_pch_encoder) {
8408                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8409                 if (has_reduced_clock)
8410                         fp2 = i9xx_dpll_compute_fp(&reduced_clock);
8411
8412                 dpll = ironlake_compute_dpll(crtc, crtc_state,
8413                                              &fp, &reduced_clock,
8414                                              has_reduced_clock ? &fp2 : NULL);
8415
8416                 crtc_state->dpll_hw_state.dpll = dpll;
8417                 crtc_state->dpll_hw_state.fp0 = fp;
8418                 if (has_reduced_clock)
8419                         crtc_state->dpll_hw_state.fp1 = fp2;
8420                 else
8421                         crtc_state->dpll_hw_state.fp1 = fp;
8422
8423                 pll = intel_get_shared_dpll(crtc, crtc_state);
8424                 if (pll == NULL) {
8425                         DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
8426                                          pipe_name(crtc->pipe));
8427                         return -EINVAL;
8428                 }
8429         }
8430
8431         if (is_lvds && has_reduced_clock)
8432                 crtc->lowfreq_avail = true;
8433         else
8434                 crtc->lowfreq_avail = false;
8435
8436         return 0;
8437 }
8438
8439 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
8440                                          struct intel_link_m_n *m_n)
8441 {
8442         struct drm_device *dev = crtc->base.dev;
8443         struct drm_i915_private *dev_priv = dev->dev_private;
8444         enum pipe pipe = crtc->pipe;
8445
8446         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
8447         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
8448         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
8449                 & ~TU_SIZE_MASK;
8450         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
8451         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
8452                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8453 }
8454
8455 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
8456                                          enum transcoder transcoder,
8457                                          struct intel_link_m_n *m_n,
8458                                          struct intel_link_m_n *m2_n2)
8459 {
8460         struct drm_device *dev = crtc->base.dev;
8461         struct drm_i915_private *dev_priv = dev->dev_private;
8462         enum pipe pipe = crtc->pipe;
8463
8464         if (INTEL_INFO(dev)->gen >= 5) {
8465                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
8466                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
8467                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
8468                         & ~TU_SIZE_MASK;
8469                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
8470                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
8471                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8472                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
8473                  * gen < 8) and if DRRS is supported (to make sure the
8474                  * registers are not unnecessarily read).
8475                  */
8476                 if (m2_n2 && INTEL_INFO(dev)->gen < 8 &&
8477                         crtc->config->has_drrs) {
8478                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
8479                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
8480                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
8481                                         & ~TU_SIZE_MASK;
8482                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
8483                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
8484                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8485                 }
8486         } else {
8487                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
8488                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
8489                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
8490                         & ~TU_SIZE_MASK;
8491                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
8492                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
8493                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8494         }
8495 }
8496
8497 void intel_dp_get_m_n(struct intel_crtc *crtc,
8498                       struct intel_crtc_state *pipe_config)
8499 {
8500         if (pipe_config->has_pch_encoder)
8501                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
8502         else
8503                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8504                                              &pipe_config->dp_m_n,
8505                                              &pipe_config->dp_m2_n2);
8506 }
8507
8508 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
8509                                         struct intel_crtc_state *pipe_config)
8510 {
8511         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8512                                      &pipe_config->fdi_m_n, NULL);
8513 }
8514
8515 static void skylake_get_pfit_config(struct intel_crtc *crtc,
8516                                     struct intel_crtc_state *pipe_config)
8517 {
8518         struct drm_device *dev = crtc->base.dev;
8519         struct drm_i915_private *dev_priv = dev->dev_private;
8520         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
8521         uint32_t ps_ctrl = 0;
8522         int id = -1;
8523         int i;
8524
8525         /* find scaler attached to this pipe */
8526         for (i = 0; i < crtc->num_scalers; i++) {
8527                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
8528                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
8529                         id = i;
8530                         pipe_config->pch_pfit.enabled = true;
8531                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
8532                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
8533                         break;
8534                 }
8535         }
8536
8537         scaler_state->scaler_id = id;
8538         if (id >= 0) {
8539                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
8540         } else {
8541                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
8542         }
8543 }
8544
8545 static void
8546 skylake_get_initial_plane_config(struct intel_crtc *crtc,
8547                                  struct intel_initial_plane_config *plane_config)
8548 {
8549         struct drm_device *dev = crtc->base.dev;
8550         struct drm_i915_private *dev_priv = dev->dev_private;
8551         u32 val, base, offset, stride_mult, tiling;
8552         int pipe = crtc->pipe;
8553         int fourcc, pixel_format;
8554         unsigned int aligned_height;
8555         struct drm_framebuffer *fb;
8556         struct intel_framebuffer *intel_fb;
8557
8558         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8559         if (!intel_fb) {
8560                 DRM_DEBUG_KMS("failed to alloc fb\n");
8561                 return;
8562         }
8563
8564         fb = &intel_fb->base;
8565
8566         val = I915_READ(PLANE_CTL(pipe, 0));
8567         if (!(val & PLANE_CTL_ENABLE))
8568                 goto error;
8569
8570         pixel_format = val & PLANE_CTL_FORMAT_MASK;
8571         fourcc = skl_format_to_fourcc(pixel_format,
8572                                       val & PLANE_CTL_ORDER_RGBX,
8573                                       val & PLANE_CTL_ALPHA_MASK);
8574         fb->pixel_format = fourcc;
8575         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
8576
8577         tiling = val & PLANE_CTL_TILED_MASK;
8578         switch (tiling) {
8579         case PLANE_CTL_TILED_LINEAR:
8580                 fb->modifier[0] = DRM_FORMAT_MOD_NONE;
8581                 break;
8582         case PLANE_CTL_TILED_X:
8583                 plane_config->tiling = I915_TILING_X;
8584                 fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
8585                 break;
8586         case PLANE_CTL_TILED_Y:
8587                 fb->modifier[0] = I915_FORMAT_MOD_Y_TILED;
8588                 break;
8589         case PLANE_CTL_TILED_YF:
8590                 fb->modifier[0] = I915_FORMAT_MOD_Yf_TILED;
8591                 break;
8592         default:
8593                 MISSING_CASE(tiling);
8594                 goto error;
8595         }
8596
8597         base = I915_READ(PLANE_SURF(pipe, 0)) & 0xfffff000;
8598         plane_config->base = base;
8599
8600         offset = I915_READ(PLANE_OFFSET(pipe, 0));
8601
8602         val = I915_READ(PLANE_SIZE(pipe, 0));
8603         fb->height = ((val >> 16) & 0xfff) + 1;
8604         fb->width = ((val >> 0) & 0x1fff) + 1;
8605
8606         val = I915_READ(PLANE_STRIDE(pipe, 0));
8607         stride_mult = intel_fb_stride_alignment(dev, fb->modifier[0],
8608                                                 fb->pixel_format);
8609         fb->pitches[0] = (val & 0x3ff) * stride_mult;
8610
8611         aligned_height = intel_fb_align_height(dev, fb->height,
8612                                                fb->pixel_format,
8613                                                fb->modifier[0]);
8614
8615         plane_config->size = fb->pitches[0] * aligned_height;
8616
8617         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8618                       pipe_name(pipe), fb->width, fb->height,
8619                       fb->bits_per_pixel, base, fb->pitches[0],
8620                       plane_config->size);
8621
8622         plane_config->fb = intel_fb;
8623         return;
8624
8625 error:
8626         kfree(fb);
8627 }
8628
8629 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
8630                                      struct intel_crtc_state *pipe_config)
8631 {
8632         struct drm_device *dev = crtc->base.dev;
8633         struct drm_i915_private *dev_priv = dev->dev_private;
8634         uint32_t tmp;
8635
8636         tmp = I915_READ(PF_CTL(crtc->pipe));
8637
8638         if (tmp & PF_ENABLE) {
8639                 pipe_config->pch_pfit.enabled = true;
8640                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
8641                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
8642
8643                 /* We currently do not free assignements of panel fitters on
8644                  * ivb/hsw (since we don't use the higher upscaling modes which
8645                  * differentiates them) so just WARN about this case for now. */
8646                 if (IS_GEN7(dev)) {
8647                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
8648                                 PF_PIPE_SEL_IVB(crtc->pipe));
8649                 }
8650         }
8651 }
8652
8653 static void
8654 ironlake_get_initial_plane_config(struct intel_crtc *crtc,
8655                                   struct intel_initial_plane_config *plane_config)
8656 {
8657         struct drm_device *dev = crtc->base.dev;
8658         struct drm_i915_private *dev_priv = dev->dev_private;
8659         u32 val, base, offset;
8660         int pipe = crtc->pipe;
8661         int fourcc, pixel_format;
8662         unsigned int aligned_height;
8663         struct drm_framebuffer *fb;
8664         struct intel_framebuffer *intel_fb;
8665
8666         val = I915_READ(DSPCNTR(pipe));
8667         if (!(val & DISPLAY_PLANE_ENABLE))
8668                 return;
8669
8670         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8671         if (!intel_fb) {
8672                 DRM_DEBUG_KMS("failed to alloc fb\n");
8673                 return;
8674         }
8675
8676         fb = &intel_fb->base;
8677
8678         if (INTEL_INFO(dev)->gen >= 4) {
8679                 if (val & DISPPLANE_TILED) {
8680                         plane_config->tiling = I915_TILING_X;
8681                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
8682                 }
8683         }
8684
8685         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
8686         fourcc = i9xx_format_to_fourcc(pixel_format);
8687         fb->pixel_format = fourcc;
8688         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
8689
8690         base = I915_READ(DSPSURF(pipe)) & 0xfffff000;
8691         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
8692                 offset = I915_READ(DSPOFFSET(pipe));
8693         } else {
8694                 if (plane_config->tiling)
8695                         offset = I915_READ(DSPTILEOFF(pipe));
8696                 else
8697                         offset = I915_READ(DSPLINOFF(pipe));
8698         }
8699         plane_config->base = base;
8700
8701         val = I915_READ(PIPESRC(pipe));
8702         fb->width = ((val >> 16) & 0xfff) + 1;
8703         fb->height = ((val >> 0) & 0xfff) + 1;
8704
8705         val = I915_READ(DSPSTRIDE(pipe));
8706         fb->pitches[0] = val & 0xffffffc0;
8707
8708         aligned_height = intel_fb_align_height(dev, fb->height,
8709                                                fb->pixel_format,
8710                                                fb->modifier[0]);
8711
8712         plane_config->size = fb->pitches[0] * aligned_height;
8713
8714         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8715                       pipe_name(pipe), fb->width, fb->height,
8716                       fb->bits_per_pixel, base, fb->pitches[0],
8717                       plane_config->size);
8718
8719         plane_config->fb = intel_fb;
8720 }
8721
8722 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
8723                                      struct intel_crtc_state *pipe_config)
8724 {
8725         struct drm_device *dev = crtc->base.dev;
8726         struct drm_i915_private *dev_priv = dev->dev_private;
8727         uint32_t tmp;
8728
8729         if (!intel_display_power_is_enabled(dev_priv,
8730                                             POWER_DOMAIN_PIPE(crtc->pipe)))
8731                 return false;
8732
8733         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8734         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
8735
8736         tmp = I915_READ(PIPECONF(crtc->pipe));
8737         if (!(tmp & PIPECONF_ENABLE))
8738                 return false;
8739
8740         switch (tmp & PIPECONF_BPC_MASK) {
8741         case PIPECONF_6BPC:
8742                 pipe_config->pipe_bpp = 18;
8743                 break;
8744         case PIPECONF_8BPC:
8745                 pipe_config->pipe_bpp = 24;
8746                 break;
8747         case PIPECONF_10BPC:
8748                 pipe_config->pipe_bpp = 30;
8749                 break;
8750         case PIPECONF_12BPC:
8751                 pipe_config->pipe_bpp = 36;
8752                 break;
8753         default:
8754                 break;
8755         }
8756
8757         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
8758                 pipe_config->limited_color_range = true;
8759
8760         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
8761                 struct intel_shared_dpll *pll;
8762
8763                 pipe_config->has_pch_encoder = true;
8764
8765                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
8766                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
8767                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
8768
8769                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
8770
8771                 if (HAS_PCH_IBX(dev_priv->dev)) {
8772                         pipe_config->shared_dpll =
8773                                 (enum intel_dpll_id) crtc->pipe;
8774                 } else {
8775                         tmp = I915_READ(PCH_DPLL_SEL);
8776                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
8777                                 pipe_config->shared_dpll = DPLL_ID_PCH_PLL_B;
8778                         else
8779                                 pipe_config->shared_dpll = DPLL_ID_PCH_PLL_A;
8780                 }
8781
8782                 pll = &dev_priv->shared_dplls[pipe_config->shared_dpll];
8783
8784                 WARN_ON(!pll->get_hw_state(dev_priv, pll,
8785                                            &pipe_config->dpll_hw_state));
8786
8787                 tmp = pipe_config->dpll_hw_state.dpll;
8788                 pipe_config->pixel_multiplier =
8789                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
8790                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
8791
8792                 ironlake_pch_clock_get(crtc, pipe_config);
8793         } else {
8794                 pipe_config->pixel_multiplier = 1;
8795         }
8796
8797         intel_get_pipe_timings(crtc, pipe_config);
8798
8799         ironlake_get_pfit_config(crtc, pipe_config);
8800
8801         return true;
8802 }
8803
8804 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
8805 {
8806         struct drm_device *dev = dev_priv->dev;
8807         struct intel_crtc *crtc;
8808
8809         for_each_intel_crtc(dev, crtc)
8810                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
8811                      pipe_name(crtc->pipe));
8812
8813         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_DRIVER), "Power well on\n");
8814         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
8815         I915_STATE_WARN(I915_READ(WRPLL_CTL1) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
8816         I915_STATE_WARN(I915_READ(WRPLL_CTL2) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
8817         I915_STATE_WARN(I915_READ(PCH_PP_STATUS) & PP_ON, "Panel power on\n");
8818         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
8819              "CPU PWM1 enabled\n");
8820         if (IS_HASWELL(dev))
8821                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
8822                      "CPU PWM2 enabled\n");
8823         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
8824              "PCH PWM1 enabled\n");
8825         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
8826              "Utility pin enabled\n");
8827         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
8828
8829         /*
8830          * In theory we can still leave IRQs enabled, as long as only the HPD
8831          * interrupts remain enabled. We used to check for that, but since it's
8832          * gen-specific and since we only disable LCPLL after we fully disable
8833          * the interrupts, the check below should be enough.
8834          */
8835         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
8836 }
8837
8838 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
8839 {
8840         struct drm_device *dev = dev_priv->dev;
8841
8842         if (IS_HASWELL(dev))
8843                 return I915_READ(D_COMP_HSW);
8844         else
8845                 return I915_READ(D_COMP_BDW);
8846 }
8847
8848 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
8849 {
8850         struct drm_device *dev = dev_priv->dev;
8851
8852         if (IS_HASWELL(dev)) {
8853                 mutex_lock(&dev_priv->rps.hw_lock);
8854                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
8855                                             val))
8856                         DRM_ERROR("Failed to write to D_COMP\n");
8857                 mutex_unlock(&dev_priv->rps.hw_lock);
8858         } else {
8859                 I915_WRITE(D_COMP_BDW, val);
8860                 POSTING_READ(D_COMP_BDW);
8861         }
8862 }
8863
8864 /*
8865  * This function implements pieces of two sequences from BSpec:
8866  * - Sequence for display software to disable LCPLL
8867  * - Sequence for display software to allow package C8+
8868  * The steps implemented here are just the steps that actually touch the LCPLL
8869  * register. Callers should take care of disabling all the display engine
8870  * functions, doing the mode unset, fixing interrupts, etc.
8871  */
8872 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
8873                               bool switch_to_fclk, bool allow_power_down)
8874 {
8875         uint32_t val;
8876
8877         assert_can_disable_lcpll(dev_priv);
8878
8879         val = I915_READ(LCPLL_CTL);
8880
8881         if (switch_to_fclk) {
8882                 val |= LCPLL_CD_SOURCE_FCLK;
8883                 I915_WRITE(LCPLL_CTL, val);
8884
8885                 if (wait_for_atomic_us(I915_READ(LCPLL_CTL) &
8886                                        LCPLL_CD_SOURCE_FCLK_DONE, 1))
8887                         DRM_ERROR("Switching to FCLK failed\n");
8888
8889                 val = I915_READ(LCPLL_CTL);
8890         }
8891
8892         val |= LCPLL_PLL_DISABLE;
8893         I915_WRITE(LCPLL_CTL, val);
8894         POSTING_READ(LCPLL_CTL);
8895
8896         if (wait_for((I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK) == 0, 1))
8897                 DRM_ERROR("LCPLL still locked\n");
8898
8899         val = hsw_read_dcomp(dev_priv);
8900         val |= D_COMP_COMP_DISABLE;
8901         hsw_write_dcomp(dev_priv, val);
8902         ndelay(100);
8903
8904         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
8905                      1))
8906                 DRM_ERROR("D_COMP RCOMP still in progress\n");
8907
8908         if (allow_power_down) {
8909                 val = I915_READ(LCPLL_CTL);
8910                 val |= LCPLL_POWER_DOWN_ALLOW;
8911                 I915_WRITE(LCPLL_CTL, val);
8912                 POSTING_READ(LCPLL_CTL);
8913         }
8914 }
8915
8916 /*
8917  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
8918  * source.
8919  */
8920 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
8921 {
8922         uint32_t val;
8923
8924         val = I915_READ(LCPLL_CTL);
8925
8926         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
8927                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
8928                 return;
8929
8930         /*
8931          * Make sure we're not on PC8 state before disabling PC8, otherwise
8932          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
8933          */
8934         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
8935
8936         if (val & LCPLL_POWER_DOWN_ALLOW) {
8937                 val &= ~LCPLL_POWER_DOWN_ALLOW;
8938                 I915_WRITE(LCPLL_CTL, val);
8939                 POSTING_READ(LCPLL_CTL);
8940         }
8941
8942         val = hsw_read_dcomp(dev_priv);
8943         val |= D_COMP_COMP_FORCE;
8944         val &= ~D_COMP_COMP_DISABLE;
8945         hsw_write_dcomp(dev_priv, val);
8946
8947         val = I915_READ(LCPLL_CTL);
8948         val &= ~LCPLL_PLL_DISABLE;
8949         I915_WRITE(LCPLL_CTL, val);
8950
8951         if (wait_for(I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK, 5))
8952                 DRM_ERROR("LCPLL not locked yet\n");
8953
8954         if (val & LCPLL_CD_SOURCE_FCLK) {
8955                 val = I915_READ(LCPLL_CTL);
8956                 val &= ~LCPLL_CD_SOURCE_FCLK;
8957                 I915_WRITE(LCPLL_CTL, val);
8958
8959                 if (wait_for_atomic_us((I915_READ(LCPLL_CTL) &
8960                                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
8961                         DRM_ERROR("Switching back to LCPLL failed\n");
8962         }
8963
8964         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
8965 }
8966
8967 /*
8968  * Package states C8 and deeper are really deep PC states that can only be
8969  * reached when all the devices on the system allow it, so even if the graphics
8970  * device allows PC8+, it doesn't mean the system will actually get to these
8971  * states. Our driver only allows PC8+ when going into runtime PM.
8972  *
8973  * The requirements for PC8+ are that all the outputs are disabled, the power
8974  * well is disabled and most interrupts are disabled, and these are also
8975  * requirements for runtime PM. When these conditions are met, we manually do
8976  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
8977  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
8978  * hang the machine.
8979  *
8980  * When we really reach PC8 or deeper states (not just when we allow it) we lose
8981  * the state of some registers, so when we come back from PC8+ we need to
8982  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
8983  * need to take care of the registers kept by RC6. Notice that this happens even
8984  * if we don't put the device in PCI D3 state (which is what currently happens
8985  * because of the runtime PM support).
8986  *
8987  * For more, read "Display Sequences for Package C8" on the hardware
8988  * documentation.
8989  */
8990 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
8991 {
8992         struct drm_device *dev = dev_priv->dev;
8993         uint32_t val;
8994
8995         DRM_DEBUG_KMS("Enabling package C8+\n");
8996
8997         if (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) {
8998                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
8999                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
9000                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9001         }
9002
9003         lpt_disable_clkout_dp(dev);
9004         hsw_disable_lcpll(dev_priv, true, true);
9005 }
9006
9007 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
9008 {
9009         struct drm_device *dev = dev_priv->dev;
9010         uint32_t val;
9011
9012         DRM_DEBUG_KMS("Disabling package C8+\n");
9013
9014         hsw_restore_lcpll(dev_priv);
9015         lpt_init_pch_refclk(dev);
9016
9017         if (dev_priv->pch_id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) {
9018                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9019                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
9020                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9021         }
9022
9023         intel_prepare_ddi(dev);
9024 }
9025
9026 static void broxton_modeset_global_resources(struct drm_atomic_state *state)
9027 {
9028         struct drm_device *dev = state->dev;
9029         struct drm_i915_private *dev_priv = dev->dev_private;
9030         int max_pixclk = intel_mode_max_pixclk(state);
9031         int req_cdclk;
9032
9033         /* see the comment in valleyview_modeset_global_resources */
9034         if (WARN_ON(max_pixclk < 0))
9035                 return;
9036
9037         req_cdclk = broxton_calc_cdclk(dev_priv, max_pixclk);
9038
9039         if (req_cdclk != dev_priv->cdclk_freq)
9040                 broxton_set_cdclk(dev, req_cdclk);
9041 }
9042
9043 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9044                                       struct intel_crtc_state *crtc_state)
9045 {
9046         if (!intel_ddi_pll_select(crtc, crtc_state))
9047                 return -EINVAL;
9048
9049         crtc->lowfreq_avail = false;
9050
9051         return 0;
9052 }
9053
9054 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9055                                 enum port port,
9056                                 struct intel_crtc_state *pipe_config)
9057 {
9058         u32 temp, dpll_ctl1;
9059
9060         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9061         pipe_config->ddi_pll_sel = temp >> (port * 3 + 1);
9062
9063         switch (pipe_config->ddi_pll_sel) {
9064         case SKL_DPLL0:
9065                 /*
9066                  * On SKL the eDP DPLL (DPLL0 as we don't use SSC) is not part
9067                  * of the shared DPLL framework and thus needs to be read out
9068                  * separately
9069                  */
9070                 dpll_ctl1 = I915_READ(DPLL_CTRL1);
9071                 pipe_config->dpll_hw_state.ctrl1 = dpll_ctl1 & 0x3f;
9072                 break;
9073         case SKL_DPLL1:
9074                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL1;
9075                 break;
9076         case SKL_DPLL2:
9077                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL2;
9078                 break;
9079         case SKL_DPLL3:
9080                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL3;
9081                 break;
9082         }
9083 }
9084
9085 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9086                                 enum port port,
9087                                 struct intel_crtc_state *pipe_config)
9088 {
9089         pipe_config->ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9090
9091         switch (pipe_config->ddi_pll_sel) {
9092         case PORT_CLK_SEL_WRPLL1:
9093                 pipe_config->shared_dpll = DPLL_ID_WRPLL1;
9094                 break;
9095         case PORT_CLK_SEL_WRPLL2:
9096                 pipe_config->shared_dpll = DPLL_ID_WRPLL2;
9097                 break;
9098         }
9099 }
9100
9101 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9102                                        struct intel_crtc_state *pipe_config)
9103 {
9104         struct drm_device *dev = crtc->base.dev;
9105         struct drm_i915_private *dev_priv = dev->dev_private;
9106         struct intel_shared_dpll *pll;
9107         enum port port;
9108         uint32_t tmp;
9109
9110         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9111
9112         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9113
9114         if (IS_SKYLAKE(dev))
9115                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
9116         else
9117                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
9118
9119         if (pipe_config->shared_dpll >= 0) {
9120                 pll = &dev_priv->shared_dplls[pipe_config->shared_dpll];
9121
9122                 WARN_ON(!pll->get_hw_state(dev_priv, pll,
9123                                            &pipe_config->dpll_hw_state));
9124         }
9125
9126         /*
9127          * Haswell has only FDI/PCH transcoder A. It is which is connected to
9128          * DDI E. So just check whether this pipe is wired to DDI E and whether
9129          * the PCH transcoder is on.
9130          */
9131         if (INTEL_INFO(dev)->gen < 9 &&
9132             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
9133                 pipe_config->has_pch_encoder = true;
9134
9135                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
9136                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9137                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9138
9139                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9140         }
9141 }
9142
9143 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
9144                                     struct intel_crtc_state *pipe_config)
9145 {
9146         struct drm_device *dev = crtc->base.dev;
9147         struct drm_i915_private *dev_priv = dev->dev_private;
9148         enum intel_display_power_domain pfit_domain;
9149         uint32_t tmp;
9150
9151         if (!intel_display_power_is_enabled(dev_priv,
9152                                          POWER_DOMAIN_PIPE(crtc->pipe)))
9153                 return false;
9154
9155         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9156         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
9157
9158         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
9159         if (tmp & TRANS_DDI_FUNC_ENABLE) {
9160                 enum pipe trans_edp_pipe;
9161                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9162                 default:
9163                         WARN(1, "unknown pipe linked to edp transcoder\n");
9164                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9165                 case TRANS_DDI_EDP_INPUT_A_ON:
9166                         trans_edp_pipe = PIPE_A;
9167                         break;
9168                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
9169                         trans_edp_pipe = PIPE_B;
9170                         break;
9171                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
9172                         trans_edp_pipe = PIPE_C;
9173                         break;
9174                 }
9175
9176                 if (trans_edp_pipe == crtc->pipe)
9177                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
9178         }
9179
9180         if (!intel_display_power_is_enabled(dev_priv,
9181                         POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder)))
9182                 return false;
9183
9184         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
9185         if (!(tmp & PIPECONF_ENABLE))
9186                 return false;
9187
9188         haswell_get_ddi_port_state(crtc, pipe_config);
9189
9190         intel_get_pipe_timings(crtc, pipe_config);
9191
9192         if (INTEL_INFO(dev)->gen >= 9) {
9193                 skl_init_scalers(dev, crtc, pipe_config);
9194         }
9195
9196         pfit_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
9197         if (intel_display_power_is_enabled(dev_priv, pfit_domain)) {
9198                 if (INTEL_INFO(dev)->gen == 9)
9199                         skylake_get_pfit_config(crtc, pipe_config);
9200                 else if (INTEL_INFO(dev)->gen < 9)
9201                         ironlake_get_pfit_config(crtc, pipe_config);
9202                 else
9203                         MISSING_CASE(INTEL_INFO(dev)->gen);
9204
9205         } else {
9206                 pipe_config->scaler_state.scaler_id = -1;
9207                 pipe_config->scaler_state.scaler_users &= ~(1 << SKL_CRTC_INDEX);
9208         }
9209
9210         if (IS_HASWELL(dev))
9211                 pipe_config->ips_enabled = hsw_crtc_supports_ips(crtc) &&
9212                         (I915_READ(IPS_CTL) & IPS_ENABLE);
9213
9214         if (pipe_config->cpu_transcoder != TRANSCODER_EDP) {
9215                 pipe_config->pixel_multiplier =
9216                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
9217         } else {
9218                 pipe_config->pixel_multiplier = 1;
9219         }
9220
9221         return true;
9222 }
9223
9224 static void i845_update_cursor(struct drm_crtc *crtc, u32 base)
9225 {
9226         struct drm_device *dev = crtc->dev;
9227         struct drm_i915_private *dev_priv = dev->dev_private;
9228         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9229         uint32_t cntl = 0, size = 0;
9230
9231         if (base) {
9232                 unsigned int width = intel_crtc->base.cursor->state->crtc_w;
9233                 unsigned int height = intel_crtc->base.cursor->state->crtc_h;
9234                 unsigned int stride = roundup_pow_of_two(width) * 4;
9235
9236                 switch (stride) {
9237                 default:
9238                         WARN_ONCE(1, "Invalid cursor width/stride, width=%u, stride=%u\n",
9239                                   width, stride);
9240                         stride = 256;
9241                         /* fallthrough */
9242                 case 256:
9243                 case 512:
9244                 case 1024:
9245                 case 2048:
9246                         break;
9247                 }
9248
9249                 cntl |= CURSOR_ENABLE |
9250                         CURSOR_GAMMA_ENABLE |
9251                         CURSOR_FORMAT_ARGB |
9252                         CURSOR_STRIDE(stride);
9253
9254                 size = (height << 12) | width;
9255         }
9256
9257         if (intel_crtc->cursor_cntl != 0 &&
9258             (intel_crtc->cursor_base != base ||
9259              intel_crtc->cursor_size != size ||
9260              intel_crtc->cursor_cntl != cntl)) {
9261                 /* On these chipsets we can only modify the base/size/stride
9262                  * whilst the cursor is disabled.
9263                  */
9264                 I915_WRITE(_CURACNTR, 0);
9265                 POSTING_READ(_CURACNTR);
9266                 intel_crtc->cursor_cntl = 0;
9267         }
9268
9269         if (intel_crtc->cursor_base != base) {
9270                 I915_WRITE(_CURABASE, base);
9271                 intel_crtc->cursor_base = base;
9272         }
9273
9274         if (intel_crtc->cursor_size != size) {
9275                 I915_WRITE(CURSIZE, size);
9276                 intel_crtc->cursor_size = size;
9277         }
9278
9279         if (intel_crtc->cursor_cntl != cntl) {
9280                 I915_WRITE(_CURACNTR, cntl);
9281                 POSTING_READ(_CURACNTR);
9282                 intel_crtc->cursor_cntl = cntl;
9283         }
9284 }
9285
9286 static void i9xx_update_cursor(struct drm_crtc *crtc, u32 base)
9287 {
9288         struct drm_device *dev = crtc->dev;
9289         struct drm_i915_private *dev_priv = dev->dev_private;
9290         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9291         int pipe = intel_crtc->pipe;
9292         uint32_t cntl;
9293
9294         cntl = 0;
9295         if (base) {
9296                 cntl = MCURSOR_GAMMA_ENABLE;
9297                 switch (intel_crtc->base.cursor->state->crtc_w) {
9298                         case 64:
9299                                 cntl |= CURSOR_MODE_64_ARGB_AX;
9300                                 break;
9301                         case 128:
9302                                 cntl |= CURSOR_MODE_128_ARGB_AX;
9303                                 break;
9304                         case 256:
9305                                 cntl |= CURSOR_MODE_256_ARGB_AX;
9306                                 break;
9307                         default:
9308                                 MISSING_CASE(intel_crtc->base.cursor->state->crtc_w);
9309                                 return;
9310                 }
9311                 cntl |= pipe << 28; /* Connect to correct pipe */
9312
9313                 if (IS_HASWELL(dev) || IS_BROADWELL(dev))
9314                         cntl |= CURSOR_PIPE_CSC_ENABLE;
9315         }
9316
9317         if (crtc->cursor->state->rotation == BIT(DRM_ROTATE_180))
9318                 cntl |= CURSOR_ROTATE_180;
9319
9320         if (intel_crtc->cursor_cntl != cntl) {
9321                 I915_WRITE(CURCNTR(pipe), cntl);
9322                 POSTING_READ(CURCNTR(pipe));
9323                 intel_crtc->cursor_cntl = cntl;
9324         }
9325
9326         /* and commit changes on next vblank */
9327         I915_WRITE(CURBASE(pipe), base);
9328         POSTING_READ(CURBASE(pipe));
9329
9330         intel_crtc->cursor_base = base;
9331 }
9332
9333 /* If no-part of the cursor is visible on the framebuffer, then the GPU may hang... */
9334 static void intel_crtc_update_cursor(struct drm_crtc *crtc,
9335                                      bool on)
9336 {
9337         struct drm_device *dev = crtc->dev;
9338         struct drm_i915_private *dev_priv = dev->dev_private;
9339         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9340         int pipe = intel_crtc->pipe;
9341         int x = crtc->cursor_x;
9342         int y = crtc->cursor_y;
9343         u32 base = 0, pos = 0;
9344
9345         if (on)
9346                 base = intel_crtc->cursor_addr;
9347
9348         if (x >= intel_crtc->config->pipe_src_w)
9349                 base = 0;
9350
9351         if (y >= intel_crtc->config->pipe_src_h)
9352                 base = 0;
9353
9354         if (x < 0) {
9355                 if (x + intel_crtc->base.cursor->state->crtc_w <= 0)
9356                         base = 0;
9357
9358                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
9359                 x = -x;
9360         }
9361         pos |= x << CURSOR_X_SHIFT;
9362
9363         if (y < 0) {
9364                 if (y + intel_crtc->base.cursor->state->crtc_h <= 0)
9365                         base = 0;
9366
9367                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
9368                 y = -y;
9369         }
9370         pos |= y << CURSOR_Y_SHIFT;
9371
9372         if (base == 0 && intel_crtc->cursor_base == 0)
9373                 return;
9374
9375         I915_WRITE(CURPOS(pipe), pos);
9376
9377         /* ILK+ do this automagically */
9378         if (HAS_GMCH_DISPLAY(dev) &&
9379             crtc->cursor->state->rotation == BIT(DRM_ROTATE_180)) {
9380                 base += (intel_crtc->base.cursor->state->crtc_h *
9381                         intel_crtc->base.cursor->state->crtc_w - 1) * 4;
9382         }
9383
9384         if (IS_845G(dev) || IS_I865G(dev))
9385                 i845_update_cursor(crtc, base);
9386         else
9387                 i9xx_update_cursor(crtc, base);
9388 }
9389
9390 static bool cursor_size_ok(struct drm_device *dev,
9391                            uint32_t width, uint32_t height)
9392 {
9393         if (width == 0 || height == 0)
9394                 return false;
9395
9396         /*
9397          * 845g/865g are special in that they are only limited by
9398          * the width of their cursors, the height is arbitrary up to
9399          * the precision of the register. Everything else requires
9400          * square cursors, limited to a few power-of-two sizes.
9401          */
9402         if (IS_845G(dev) || IS_I865G(dev)) {
9403                 if ((width & 63) != 0)
9404                         return false;
9405
9406                 if (width > (IS_845G(dev) ? 64 : 512))
9407                         return false;
9408
9409                 if (height > 1023)
9410                         return false;
9411         } else {
9412                 switch (width | height) {
9413                 case 256:
9414                 case 128:
9415                         if (IS_GEN2(dev))
9416                                 return false;
9417                 case 64:
9418                         break;
9419                 default:
9420                         return false;
9421                 }
9422         }
9423
9424         return true;
9425 }
9426
9427 static void intel_crtc_gamma_set(struct drm_crtc *crtc, u16 *red, u16 *green,
9428                                  u16 *blue, uint32_t start, uint32_t size)
9429 {
9430         int end = (start + size > 256) ? 256 : start + size, i;
9431         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9432
9433         for (i = start; i < end; i++) {
9434                 intel_crtc->lut_r[i] = red[i] >> 8;
9435                 intel_crtc->lut_g[i] = green[i] >> 8;
9436                 intel_crtc->lut_b[i] = blue[i] >> 8;
9437         }
9438
9439         intel_crtc_load_lut(crtc);
9440 }
9441
9442 /* VESA 640x480x72Hz mode to set on the pipe */
9443 static struct drm_display_mode load_detect_mode = {
9444         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
9445                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
9446 };
9447
9448 struct drm_framebuffer *
9449 __intel_framebuffer_create(struct drm_device *dev,
9450                            struct drm_mode_fb_cmd2 *mode_cmd,
9451                            struct drm_i915_gem_object *obj)
9452 {
9453         struct intel_framebuffer *intel_fb;
9454         int ret;
9455
9456         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9457         if (!intel_fb) {
9458                 drm_gem_object_unreference(&obj->base);
9459                 return ERR_PTR(-ENOMEM);
9460         }
9461
9462         ret = intel_framebuffer_init(dev, intel_fb, mode_cmd, obj);
9463         if (ret)
9464                 goto err;
9465
9466         return &intel_fb->base;
9467 err:
9468         drm_gem_object_unreference(&obj->base);
9469         kfree(intel_fb);
9470
9471         return ERR_PTR(ret);
9472 }
9473
9474 static struct drm_framebuffer *
9475 intel_framebuffer_create(struct drm_device *dev,
9476                          struct drm_mode_fb_cmd2 *mode_cmd,
9477                          struct drm_i915_gem_object *obj)
9478 {
9479         struct drm_framebuffer *fb;
9480         int ret;
9481
9482         ret = i915_mutex_lock_interruptible(dev);
9483         if (ret)
9484                 return ERR_PTR(ret);
9485         fb = __intel_framebuffer_create(dev, mode_cmd, obj);
9486         mutex_unlock(&dev->struct_mutex);
9487
9488         return fb;
9489 }
9490
9491 static u32
9492 intel_framebuffer_pitch_for_width(int width, int bpp)
9493 {
9494         u32 pitch = DIV_ROUND_UP(width * bpp, 8);
9495         return ALIGN(pitch, 64);
9496 }
9497
9498 static u32
9499 intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
9500 {
9501         u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
9502         return PAGE_ALIGN(pitch * mode->vdisplay);
9503 }
9504
9505 static struct drm_framebuffer *
9506 intel_framebuffer_create_for_mode(struct drm_device *dev,
9507                                   struct drm_display_mode *mode,
9508                                   int depth, int bpp)
9509 {
9510         struct drm_i915_gem_object *obj;
9511         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
9512
9513         obj = i915_gem_alloc_object(dev,
9514                                     intel_framebuffer_size_for_mode(mode, bpp));
9515         if (obj == NULL)
9516                 return ERR_PTR(-ENOMEM);
9517
9518         mode_cmd.width = mode->hdisplay;
9519         mode_cmd.height = mode->vdisplay;
9520         mode_cmd.pitches[0] = intel_framebuffer_pitch_for_width(mode_cmd.width,
9521                                                                 bpp);
9522         mode_cmd.pixel_format = drm_mode_legacy_fb_format(bpp, depth);
9523
9524         return intel_framebuffer_create(dev, &mode_cmd, obj);
9525 }
9526
9527 static struct drm_framebuffer *
9528 mode_fits_in_fbdev(struct drm_device *dev,
9529                    struct drm_display_mode *mode)
9530 {
9531 #ifdef CONFIG_DRM_I915_FBDEV
9532         struct drm_i915_private *dev_priv = dev->dev_private;
9533         struct drm_i915_gem_object *obj;
9534         struct drm_framebuffer *fb;
9535
9536         if (!dev_priv->fbdev)
9537                 return NULL;
9538
9539         if (!dev_priv->fbdev->fb)
9540                 return NULL;
9541
9542         obj = dev_priv->fbdev->fb->obj;
9543         BUG_ON(!obj);
9544
9545         fb = &dev_priv->fbdev->fb->base;
9546         if (fb->pitches[0] < intel_framebuffer_pitch_for_width(mode->hdisplay,
9547                                                                fb->bits_per_pixel))
9548                 return NULL;
9549
9550         if (obj->base.size < mode->vdisplay * fb->pitches[0])
9551                 return NULL;
9552
9553         return fb;
9554 #else
9555         return NULL;
9556 #endif
9557 }
9558
9559 bool intel_get_load_detect_pipe(struct drm_connector *connector,
9560                                 struct drm_display_mode *mode,
9561                                 struct intel_load_detect_pipe *old,
9562                                 struct drm_modeset_acquire_ctx *ctx)
9563 {
9564         struct intel_crtc *intel_crtc;
9565         struct intel_encoder *intel_encoder =
9566                 intel_attached_encoder(connector);
9567         struct drm_crtc *possible_crtc;
9568         struct drm_encoder *encoder = &intel_encoder->base;
9569         struct drm_crtc *crtc = NULL;
9570         struct drm_device *dev = encoder->dev;
9571         struct drm_framebuffer *fb;
9572         struct drm_mode_config *config = &dev->mode_config;
9573         struct drm_atomic_state *state = NULL;
9574         struct drm_connector_state *connector_state;
9575         int ret, i = -1;
9576
9577         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
9578                       connector->base.id, connector->name,
9579                       encoder->base.id, encoder->name);
9580
9581 retry:
9582         ret = drm_modeset_lock(&config->connection_mutex, ctx);
9583         if (ret)
9584                 goto fail_unlock;
9585
9586         /*
9587          * Algorithm gets a little messy:
9588          *
9589          *   - if the connector already has an assigned crtc, use it (but make
9590          *     sure it's on first)
9591          *
9592          *   - try to find the first unused crtc that can drive this connector,
9593          *     and use that if we find one
9594          */
9595
9596         /* See if we already have a CRTC for this connector */
9597         if (encoder->crtc) {
9598                 crtc = encoder->crtc;
9599
9600                 ret = drm_modeset_lock(&crtc->mutex, ctx);
9601                 if (ret)
9602                         goto fail_unlock;
9603                 ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
9604                 if (ret)
9605                         goto fail_unlock;
9606
9607                 old->dpms_mode = connector->dpms;
9608                 old->load_detect_temp = false;
9609
9610                 /* Make sure the crtc and connector are running */
9611                 if (connector->dpms != DRM_MODE_DPMS_ON)
9612                         connector->funcs->dpms(connector, DRM_MODE_DPMS_ON);
9613
9614                 return true;
9615         }
9616
9617         /* Find an unused one (if possible) */
9618         for_each_crtc(dev, possible_crtc) {
9619                 i++;
9620                 if (!(encoder->possible_crtcs & (1 << i)))
9621                         continue;
9622                 if (possible_crtc->state->enable)
9623                         continue;
9624                 /* This can occur when applying the pipe A quirk on resume. */
9625                 if (to_intel_crtc(possible_crtc)->new_enabled)
9626                         continue;
9627
9628                 crtc = possible_crtc;
9629                 break;
9630         }
9631
9632         /*
9633          * If we didn't find an unused CRTC, don't use any.
9634          */
9635         if (!crtc) {
9636                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
9637                 goto fail_unlock;
9638         }
9639
9640         ret = drm_modeset_lock(&crtc->mutex, ctx);
9641         if (ret)
9642                 goto fail_unlock;
9643         ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
9644         if (ret)
9645                 goto fail_unlock;
9646         intel_encoder->new_crtc = to_intel_crtc(crtc);
9647         to_intel_connector(connector)->new_encoder = intel_encoder;
9648
9649         intel_crtc = to_intel_crtc(crtc);
9650         intel_crtc->new_enabled = true;
9651         old->dpms_mode = connector->dpms;
9652         old->load_detect_temp = true;
9653         old->release_fb = NULL;
9654
9655         state = drm_atomic_state_alloc(dev);
9656         if (!state)
9657                 return false;
9658
9659         state->acquire_ctx = ctx;
9660
9661         connector_state = drm_atomic_get_connector_state(state, connector);
9662         if (IS_ERR(connector_state)) {
9663                 ret = PTR_ERR(connector_state);
9664                 goto fail;
9665         }
9666
9667         connector_state->crtc = crtc;
9668         connector_state->best_encoder = &intel_encoder->base;
9669
9670         if (!mode)
9671                 mode = &load_detect_mode;
9672
9673         /* We need a framebuffer large enough to accommodate all accesses
9674          * that the plane may generate whilst we perform load detection.
9675          * We can not rely on the fbcon either being present (we get called
9676          * during its initialisation to detect all boot displays, or it may
9677          * not even exist) or that it is large enough to satisfy the
9678          * requested mode.
9679          */
9680         fb = mode_fits_in_fbdev(dev, mode);
9681         if (fb == NULL) {
9682                 DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
9683                 fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
9684                 old->release_fb = fb;
9685         } else
9686                 DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
9687         if (IS_ERR(fb)) {
9688                 DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
9689                 goto fail;
9690         }
9691
9692         if (intel_set_mode(crtc, mode, 0, 0, fb, state)) {
9693                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
9694                 if (old->release_fb)
9695                         old->release_fb->funcs->destroy(old->release_fb);
9696                 goto fail;
9697         }
9698         crtc->primary->crtc = crtc;
9699
9700         /* let the connector get through one full cycle before testing */
9701         intel_wait_for_vblank(dev, intel_crtc->pipe);
9702         return true;
9703
9704  fail:
9705         intel_crtc->new_enabled = crtc->state->enable;
9706 fail_unlock:
9707         if (state) {
9708                 drm_atomic_state_free(state);
9709                 state = NULL;
9710         }
9711
9712         if (ret == -EDEADLK) {
9713                 drm_modeset_backoff(ctx);
9714                 goto retry;
9715         }
9716
9717         return false;
9718 }
9719
9720 void intel_release_load_detect_pipe(struct drm_connector *connector,
9721                                     struct intel_load_detect_pipe *old,
9722                                     struct drm_modeset_acquire_ctx *ctx)
9723 {
9724         struct drm_device *dev = connector->dev;
9725         struct intel_encoder *intel_encoder =
9726                 intel_attached_encoder(connector);
9727         struct drm_encoder *encoder = &intel_encoder->base;
9728         struct drm_crtc *crtc = encoder->crtc;
9729         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9730         struct drm_atomic_state *state;
9731         struct drm_connector_state *connector_state;
9732
9733         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
9734                       connector->base.id, connector->name,
9735                       encoder->base.id, encoder->name);
9736
9737         if (old->load_detect_temp) {
9738                 state = drm_atomic_state_alloc(dev);
9739                 if (!state)
9740                         goto fail;
9741
9742                 state->acquire_ctx = ctx;
9743
9744                 connector_state = drm_atomic_get_connector_state(state, connector);
9745                 if (IS_ERR(connector_state))
9746                         goto fail;
9747
9748                 to_intel_connector(connector)->new_encoder = NULL;
9749                 intel_encoder->new_crtc = NULL;
9750                 intel_crtc->new_enabled = false;
9751
9752                 connector_state->best_encoder = NULL;
9753                 connector_state->crtc = NULL;
9754
9755                 intel_set_mode(crtc, NULL, 0, 0, NULL, state);
9756
9757                 drm_atomic_state_free(state);
9758
9759                 if (old->release_fb) {
9760                         drm_framebuffer_unregister_private(old->release_fb);
9761                         drm_framebuffer_unreference(old->release_fb);
9762                 }
9763
9764                 return;
9765         }
9766
9767         /* Switch crtc and encoder back off if necessary */
9768         if (old->dpms_mode != DRM_MODE_DPMS_ON)
9769                 connector->funcs->dpms(connector, old->dpms_mode);
9770
9771         return;
9772 fail:
9773         DRM_DEBUG_KMS("Couldn't release load detect pipe.\n");
9774         drm_atomic_state_free(state);
9775 }
9776
9777 static int i9xx_pll_refclk(struct drm_device *dev,
9778                            const struct intel_crtc_state *pipe_config)
9779 {
9780         struct drm_i915_private *dev_priv = dev->dev_private;
9781         u32 dpll = pipe_config->dpll_hw_state.dpll;
9782
9783         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
9784                 return dev_priv->vbt.lvds_ssc_freq;
9785         else if (HAS_PCH_SPLIT(dev))
9786                 return 120000;
9787         else if (!IS_GEN2(dev))
9788                 return 96000;
9789         else
9790                 return 48000;
9791 }
9792
9793 /* Returns the clock of the currently programmed mode of the given pipe. */
9794 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
9795                                 struct intel_crtc_state *pipe_config)
9796 {
9797         struct drm_device *dev = crtc->base.dev;
9798         struct drm_i915_private *dev_priv = dev->dev_private;
9799         int pipe = pipe_config->cpu_transcoder;
9800         u32 dpll = pipe_config->dpll_hw_state.dpll;
9801         u32 fp;
9802         intel_clock_t clock;
9803         int refclk = i9xx_pll_refclk(dev, pipe_config);
9804
9805         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
9806                 fp = pipe_config->dpll_hw_state.fp0;
9807         else
9808                 fp = pipe_config->dpll_hw_state.fp1;
9809
9810         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
9811         if (IS_PINEVIEW(dev)) {
9812                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
9813                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
9814         } else {
9815                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
9816                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
9817         }
9818
9819         if (!IS_GEN2(dev)) {
9820                 if (IS_PINEVIEW(dev))
9821                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
9822                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
9823                 else
9824                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
9825                                DPLL_FPA01_P1_POST_DIV_SHIFT);
9826
9827                 switch (dpll & DPLL_MODE_MASK) {
9828                 case DPLLB_MODE_DAC_SERIAL:
9829                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
9830                                 5 : 10;
9831                         break;
9832                 case DPLLB_MODE_LVDS:
9833                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
9834                                 7 : 14;
9835                         break;
9836                 default:
9837                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
9838                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
9839                         return;
9840                 }
9841
9842                 if (IS_PINEVIEW(dev))
9843                         pineview_clock(refclk, &clock);
9844                 else
9845                         i9xx_clock(refclk, &clock);
9846         } else {
9847                 u32 lvds = IS_I830(dev) ? 0 : I915_READ(LVDS);
9848                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
9849
9850                 if (is_lvds) {
9851                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
9852                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
9853
9854                         if (lvds & LVDS_CLKB_POWER_UP)
9855                                 clock.p2 = 7;
9856                         else
9857                                 clock.p2 = 14;
9858                 } else {
9859                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
9860                                 clock.p1 = 2;
9861                         else {
9862                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
9863                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
9864                         }
9865                         if (dpll & PLL_P2_DIVIDE_BY_4)
9866                                 clock.p2 = 4;
9867                         else
9868                                 clock.p2 = 2;
9869                 }
9870
9871                 i9xx_clock(refclk, &clock);
9872         }
9873
9874         /*
9875          * This value includes pixel_multiplier. We will use
9876          * port_clock to compute adjusted_mode.crtc_clock in the
9877          * encoder's get_config() function.
9878          */
9879         pipe_config->port_clock = clock.dot;
9880 }
9881
9882 int intel_dotclock_calculate(int link_freq,
9883                              const struct intel_link_m_n *m_n)
9884 {
9885         /*
9886          * The calculation for the data clock is:
9887          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
9888          * But we want to avoid losing precison if possible, so:
9889          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
9890          *
9891          * and the link clock is simpler:
9892          * link_clock = (m * link_clock) / n
9893          */
9894
9895         if (!m_n->link_n)
9896                 return 0;
9897
9898         return div_u64((u64)m_n->link_m * link_freq, m_n->link_n);
9899 }
9900
9901 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
9902                                    struct intel_crtc_state *pipe_config)
9903 {
9904         struct drm_device *dev = crtc->base.dev;
9905
9906         /* read out port_clock from the DPLL */
9907         i9xx_crtc_clock_get(crtc, pipe_config);
9908
9909         /*
9910          * This value does not include pixel_multiplier.
9911          * We will check that port_clock and adjusted_mode.crtc_clock
9912          * agree once we know their relationship in the encoder's
9913          * get_config() function.
9914          */
9915         pipe_config->base.adjusted_mode.crtc_clock =
9916                 intel_dotclock_calculate(intel_fdi_link_freq(dev) * 10000,
9917                                          &pipe_config->fdi_m_n);
9918 }
9919
9920 /** Returns the currently programmed mode of the given pipe. */
9921 struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
9922                                              struct drm_crtc *crtc)
9923 {
9924         struct drm_i915_private *dev_priv = dev->dev_private;
9925         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9926         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
9927         struct drm_display_mode *mode;
9928         struct intel_crtc_state pipe_config;
9929         int htot = I915_READ(HTOTAL(cpu_transcoder));
9930         int hsync = I915_READ(HSYNC(cpu_transcoder));
9931         int vtot = I915_READ(VTOTAL(cpu_transcoder));
9932         int vsync = I915_READ(VSYNC(cpu_transcoder));
9933         enum pipe pipe = intel_crtc->pipe;
9934
9935         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
9936         if (!mode)
9937                 return NULL;
9938
9939         /*
9940          * Construct a pipe_config sufficient for getting the clock info
9941          * back out of crtc_clock_get.
9942          *
9943          * Note, if LVDS ever uses a non-1 pixel multiplier, we'll need
9944          * to use a real value here instead.
9945          */
9946         pipe_config.cpu_transcoder = (enum transcoder) pipe;
9947         pipe_config.pixel_multiplier = 1;
9948         pipe_config.dpll_hw_state.dpll = I915_READ(DPLL(pipe));
9949         pipe_config.dpll_hw_state.fp0 = I915_READ(FP0(pipe));
9950         pipe_config.dpll_hw_state.fp1 = I915_READ(FP1(pipe));
9951         i9xx_crtc_clock_get(intel_crtc, &pipe_config);
9952
9953         mode->clock = pipe_config.port_clock / pipe_config.pixel_multiplier;
9954         mode->hdisplay = (htot & 0xffff) + 1;
9955         mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
9956         mode->hsync_start = (hsync & 0xffff) + 1;
9957         mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
9958         mode->vdisplay = (vtot & 0xffff) + 1;
9959         mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
9960         mode->vsync_start = (vsync & 0xffff) + 1;
9961         mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
9962
9963         drm_mode_set_name(mode);
9964
9965         return mode;
9966 }
9967
9968 static void intel_decrease_pllclock(struct drm_crtc *crtc)
9969 {
9970         struct drm_device *dev = crtc->dev;
9971         struct drm_i915_private *dev_priv = dev->dev_private;
9972         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
9973
9974         if (!HAS_GMCH_DISPLAY(dev))
9975                 return;
9976
9977         if (!dev_priv->lvds_downclock_avail)
9978                 return;
9979
9980         /*
9981          * Since this is called by a timer, we should never get here in
9982          * the manual case.
9983          */
9984         if (!HAS_PIPE_CXSR(dev) && intel_crtc->lowfreq_avail) {
9985                 int pipe = intel_crtc->pipe;
9986                 int dpll_reg = DPLL(pipe);
9987                 int dpll;
9988
9989                 DRM_DEBUG_DRIVER("downclocking LVDS\n");
9990
9991                 assert_panel_unlocked(dev_priv, pipe);
9992
9993                 dpll = I915_READ(dpll_reg);
9994                 dpll |= DISPLAY_RATE_SELECT_FPA1;
9995                 I915_WRITE(dpll_reg, dpll);
9996                 intel_wait_for_vblank(dev, pipe);
9997                 dpll = I915_READ(dpll_reg);
9998                 if (!(dpll & DISPLAY_RATE_SELECT_FPA1))
9999                         DRM_DEBUG_DRIVER("failed to downclock LVDS!\n");
10000         }
10001
10002 }
10003
10004 void intel_mark_busy(struct drm_device *dev)
10005 {
10006         struct drm_i915_private *dev_priv = dev->dev_private;
10007
10008         if (dev_priv->mm.busy)
10009                 return;
10010
10011         intel_runtime_pm_get(dev_priv);
10012         i915_update_gfx_val(dev_priv);
10013         if (INTEL_INFO(dev)->gen >= 6)
10014                 gen6_rps_busy(dev_priv);
10015         dev_priv->mm.busy = true;
10016 }
10017
10018 void intel_mark_idle(struct drm_device *dev)
10019 {
10020         struct drm_i915_private *dev_priv = dev->dev_private;
10021         struct drm_crtc *crtc;
10022
10023         if (!dev_priv->mm.busy)
10024                 return;
10025
10026         dev_priv->mm.busy = false;
10027
10028         for_each_crtc(dev, crtc) {
10029                 if (!crtc->primary->fb)
10030                         continue;
10031
10032                 intel_decrease_pllclock(crtc);
10033         }
10034
10035         if (INTEL_INFO(dev)->gen >= 6)
10036                 gen6_rps_idle(dev->dev_private);
10037
10038         intel_runtime_pm_put(dev_priv);
10039 }
10040
10041 static void intel_crtc_set_state(struct intel_crtc *crtc,
10042                                  struct intel_crtc_state *crtc_state)
10043 {
10044         kfree(crtc->config);
10045         crtc->config = crtc_state;
10046         crtc->base.state = &crtc_state->base;
10047 }
10048
10049 static void intel_crtc_destroy(struct drm_crtc *crtc)
10050 {
10051         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10052         struct drm_device *dev = crtc->dev;
10053         struct intel_unpin_work *work;
10054
10055         spin_lock_irq(&dev->event_lock);
10056         work = intel_crtc->unpin_work;
10057         intel_crtc->unpin_work = NULL;
10058         spin_unlock_irq(&dev->event_lock);
10059
10060         if (work) {
10061                 cancel_work_sync(&work->work);
10062                 kfree(work);
10063         }
10064
10065         intel_crtc_set_state(intel_crtc, NULL);
10066         drm_crtc_cleanup(crtc);
10067
10068         kfree(intel_crtc);
10069 }
10070
10071 static void intel_unpin_work_fn(struct work_struct *__work)
10072 {
10073         struct intel_unpin_work *work =
10074                 container_of(__work, struct intel_unpin_work, work);
10075         struct drm_device *dev = work->crtc->dev;
10076         enum pipe pipe = to_intel_crtc(work->crtc)->pipe;
10077
10078         mutex_lock(&dev->struct_mutex);
10079         intel_unpin_fb_obj(work->old_fb, work->crtc->primary->state);
10080         drm_gem_object_unreference(&work->pending_flip_obj->base);
10081
10082         intel_fbc_update(dev);
10083
10084         if (work->flip_queued_req)
10085                 i915_gem_request_assign(&work->flip_queued_req, NULL);
10086         mutex_unlock(&dev->struct_mutex);
10087
10088         intel_frontbuffer_flip_complete(dev, INTEL_FRONTBUFFER_PRIMARY(pipe));
10089         drm_framebuffer_unreference(work->old_fb);
10090
10091         BUG_ON(atomic_read(&to_intel_crtc(work->crtc)->unpin_work_count) == 0);
10092         atomic_dec(&to_intel_crtc(work->crtc)->unpin_work_count);
10093
10094         kfree(work);
10095 }
10096
10097 static void do_intel_finish_page_flip(struct drm_device *dev,
10098                                       struct drm_crtc *crtc)
10099 {
10100         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10101         struct intel_unpin_work *work;
10102         unsigned long flags;
10103
10104         /* Ignore early vblank irqs */
10105         if (intel_crtc == NULL)
10106                 return;
10107
10108         /*
10109          * This is called both by irq handlers and the reset code (to complete
10110          * lost pageflips) so needs the full irqsave spinlocks.
10111          */
10112         spin_lock_irqsave(&dev->event_lock, flags);
10113         work = intel_crtc->unpin_work;
10114
10115         /* Ensure we don't miss a work->pending update ... */
10116         smp_rmb();
10117
10118         if (work == NULL || atomic_read(&work->pending) < INTEL_FLIP_COMPLETE) {
10119                 spin_unlock_irqrestore(&dev->event_lock, flags);
10120                 return;
10121         }
10122
10123         page_flip_completed(intel_crtc);
10124
10125         spin_unlock_irqrestore(&dev->event_lock, flags);
10126 }
10127
10128 void intel_finish_page_flip(struct drm_device *dev, int pipe)
10129 {
10130         struct drm_i915_private *dev_priv = dev->dev_private;
10131         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
10132
10133         do_intel_finish_page_flip(dev, crtc);
10134 }
10135
10136 void intel_finish_page_flip_plane(struct drm_device *dev, int plane)
10137 {
10138         struct drm_i915_private *dev_priv = dev->dev_private;
10139         struct drm_crtc *crtc = dev_priv->plane_to_crtc_mapping[plane];
10140
10141         do_intel_finish_page_flip(dev, crtc);
10142 }
10143
10144 /* Is 'a' after or equal to 'b'? */
10145 static bool g4x_flip_count_after_eq(u32 a, u32 b)
10146 {
10147         return !((a - b) & 0x80000000);
10148 }
10149
10150 static bool page_flip_finished(struct intel_crtc *crtc)
10151 {
10152         struct drm_device *dev = crtc->base.dev;
10153         struct drm_i915_private *dev_priv = dev->dev_private;
10154
10155         if (i915_reset_in_progress(&dev_priv->gpu_error) ||
10156             crtc->reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
10157                 return true;
10158
10159         /*
10160          * The relevant registers doen't exist on pre-ctg.
10161          * As the flip done interrupt doesn't trigger for mmio
10162          * flips on gmch platforms, a flip count check isn't
10163          * really needed there. But since ctg has the registers,
10164          * include it in the check anyway.
10165          */
10166         if (INTEL_INFO(dev)->gen < 5 && !IS_G4X(dev))
10167                 return true;
10168
10169         /*
10170          * A DSPSURFLIVE check isn't enough in case the mmio and CS flips
10171          * used the same base address. In that case the mmio flip might
10172          * have completed, but the CS hasn't even executed the flip yet.
10173          *
10174          * A flip count check isn't enough as the CS might have updated
10175          * the base address just after start of vblank, but before we
10176          * managed to process the interrupt. This means we'd complete the
10177          * CS flip too soon.
10178          *
10179          * Combining both checks should get us a good enough result. It may
10180          * still happen that the CS flip has been executed, but has not
10181          * yet actually completed. But in case the base address is the same
10182          * anyway, we don't really care.
10183          */
10184         return (I915_READ(DSPSURFLIVE(crtc->plane)) & ~0xfff) ==
10185                 crtc->unpin_work->gtt_offset &&
10186                 g4x_flip_count_after_eq(I915_READ(PIPE_FLIPCOUNT_GM45(crtc->pipe)),
10187                                     crtc->unpin_work->flip_count);
10188 }
10189
10190 void intel_prepare_page_flip(struct drm_device *dev, int plane)
10191 {
10192         struct drm_i915_private *dev_priv = dev->dev_private;
10193         struct intel_crtc *intel_crtc =
10194                 to_intel_crtc(dev_priv->plane_to_crtc_mapping[plane]);
10195         unsigned long flags;
10196
10197
10198         /*
10199          * This is called both by irq handlers and the reset code (to complete
10200          * lost pageflips) so needs the full irqsave spinlocks.
10201          *
10202          * NB: An MMIO update of the plane base pointer will also
10203          * generate a page-flip completion irq, i.e. every modeset
10204          * is also accompanied by a spurious intel_prepare_page_flip().
10205          */
10206         spin_lock_irqsave(&dev->event_lock, flags);
10207         if (intel_crtc->unpin_work && page_flip_finished(intel_crtc))
10208                 atomic_inc_not_zero(&intel_crtc->unpin_work->pending);
10209         spin_unlock_irqrestore(&dev->event_lock, flags);
10210 }
10211
10212 static inline void intel_mark_page_flip_active(struct intel_crtc *intel_crtc)
10213 {
10214         /* Ensure that the work item is consistent when activating it ... */
10215         smp_wmb();
10216         atomic_set(&intel_crtc->unpin_work->pending, INTEL_FLIP_PENDING);
10217         /* and that it is marked active as soon as the irq could fire. */
10218         smp_wmb();
10219 }
10220
10221 static int intel_gen2_queue_flip(struct drm_device *dev,
10222                                  struct drm_crtc *crtc,
10223                                  struct drm_framebuffer *fb,
10224                                  struct drm_i915_gem_object *obj,
10225                                  struct intel_engine_cs *ring,
10226                                  uint32_t flags)
10227 {
10228         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10229         u32 flip_mask;
10230         int ret;
10231
10232         ret = intel_ring_begin(ring, 6);
10233         if (ret)
10234                 return ret;
10235
10236         /* Can't queue multiple flips, so wait for the previous
10237          * one to finish before executing the next.
10238          */
10239         if (intel_crtc->plane)
10240                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
10241         else
10242                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
10243         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
10244         intel_ring_emit(ring, MI_NOOP);
10245         intel_ring_emit(ring, MI_DISPLAY_FLIP |
10246                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
10247         intel_ring_emit(ring, fb->pitches[0]);
10248         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
10249         intel_ring_emit(ring, 0); /* aux display base address, unused */
10250
10251         intel_mark_page_flip_active(intel_crtc);
10252         __intel_ring_advance(ring);
10253         return 0;
10254 }
10255
10256 static int intel_gen3_queue_flip(struct drm_device *dev,
10257                                  struct drm_crtc *crtc,
10258                                  struct drm_framebuffer *fb,
10259                                  struct drm_i915_gem_object *obj,
10260                                  struct intel_engine_cs *ring,
10261                                  uint32_t flags)
10262 {
10263         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10264         u32 flip_mask;
10265         int ret;
10266
10267         ret = intel_ring_begin(ring, 6);
10268         if (ret)
10269                 return ret;
10270
10271         if (intel_crtc->plane)
10272                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
10273         else
10274                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
10275         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
10276         intel_ring_emit(ring, MI_NOOP);
10277         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 |
10278                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
10279         intel_ring_emit(ring, fb->pitches[0]);
10280         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
10281         intel_ring_emit(ring, MI_NOOP);
10282
10283         intel_mark_page_flip_active(intel_crtc);
10284         __intel_ring_advance(ring);
10285         return 0;
10286 }
10287
10288 static int intel_gen4_queue_flip(struct drm_device *dev,
10289                                  struct drm_crtc *crtc,
10290                                  struct drm_framebuffer *fb,
10291                                  struct drm_i915_gem_object *obj,
10292                                  struct intel_engine_cs *ring,
10293                                  uint32_t flags)
10294 {
10295         struct drm_i915_private *dev_priv = dev->dev_private;
10296         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10297         uint32_t pf, pipesrc;
10298         int ret;
10299
10300         ret = intel_ring_begin(ring, 4);
10301         if (ret)
10302                 return ret;
10303
10304         /* i965+ uses the linear or tiled offsets from the
10305          * Display Registers (which do not change across a page-flip)
10306          * so we need only reprogram the base address.
10307          */
10308         intel_ring_emit(ring, MI_DISPLAY_FLIP |
10309                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
10310         intel_ring_emit(ring, fb->pitches[0]);
10311         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset |
10312                         obj->tiling_mode);
10313
10314         /* XXX Enabling the panel-fitter across page-flip is so far
10315          * untested on non-native modes, so ignore it for now.
10316          * pf = I915_READ(pipe == 0 ? PFA_CTL_1 : PFB_CTL_1) & PF_ENABLE;
10317          */
10318         pf = 0;
10319         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
10320         intel_ring_emit(ring, pf | pipesrc);
10321
10322         intel_mark_page_flip_active(intel_crtc);
10323         __intel_ring_advance(ring);
10324         return 0;
10325 }
10326
10327 static int intel_gen6_queue_flip(struct drm_device *dev,
10328                                  struct drm_crtc *crtc,
10329                                  struct drm_framebuffer *fb,
10330                                  struct drm_i915_gem_object *obj,
10331                                  struct intel_engine_cs *ring,
10332                                  uint32_t flags)
10333 {
10334         struct drm_i915_private *dev_priv = dev->dev_private;
10335         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10336         uint32_t pf, pipesrc;
10337         int ret;
10338
10339         ret = intel_ring_begin(ring, 4);
10340         if (ret)
10341                 return ret;
10342
10343         intel_ring_emit(ring, MI_DISPLAY_FLIP |
10344                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
10345         intel_ring_emit(ring, fb->pitches[0] | obj->tiling_mode);
10346         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
10347
10348         /* Contrary to the suggestions in the documentation,
10349          * "Enable Panel Fitter" does not seem to be required when page
10350          * flipping with a non-native mode, and worse causes a normal
10351          * modeset to fail.
10352          * pf = I915_READ(PF_CTL(intel_crtc->pipe)) & PF_ENABLE;
10353          */
10354         pf = 0;
10355         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
10356         intel_ring_emit(ring, pf | pipesrc);
10357
10358         intel_mark_page_flip_active(intel_crtc);
10359         __intel_ring_advance(ring);
10360         return 0;
10361 }
10362
10363 static int intel_gen7_queue_flip(struct drm_device *dev,
10364                                  struct drm_crtc *crtc,
10365                                  struct drm_framebuffer *fb,
10366                                  struct drm_i915_gem_object *obj,
10367                                  struct intel_engine_cs *ring,
10368                                  uint32_t flags)
10369 {
10370         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10371         uint32_t plane_bit = 0;
10372         int len, ret;
10373
10374         switch (intel_crtc->plane) {
10375         case PLANE_A:
10376                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_A;
10377                 break;
10378         case PLANE_B:
10379                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_B;
10380                 break;
10381         case PLANE_C:
10382                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_C;
10383                 break;
10384         default:
10385                 WARN_ONCE(1, "unknown plane in flip command\n");
10386                 return -ENODEV;
10387         }
10388
10389         len = 4;
10390         if (ring->id == RCS) {
10391                 len += 6;
10392                 /*
10393                  * On Gen 8, SRM is now taking an extra dword to accommodate
10394                  * 48bits addresses, and we need a NOOP for the batch size to
10395                  * stay even.
10396                  */
10397                 if (IS_GEN8(dev))
10398                         len += 2;
10399         }
10400
10401         /*
10402          * BSpec MI_DISPLAY_FLIP for IVB:
10403          * "The full packet must be contained within the same cache line."
10404          *
10405          * Currently the LRI+SRM+MI_DISPLAY_FLIP all fit within the same
10406          * cacheline, if we ever start emitting more commands before
10407          * the MI_DISPLAY_FLIP we may need to first emit everything else,
10408          * then do the cacheline alignment, and finally emit the
10409          * MI_DISPLAY_FLIP.
10410          */
10411         ret = intel_ring_cacheline_align(ring);
10412         if (ret)
10413                 return ret;
10414
10415         ret = intel_ring_begin(ring, len);
10416         if (ret)
10417                 return ret;
10418
10419         /* Unmask the flip-done completion message. Note that the bspec says that
10420          * we should do this for both the BCS and RCS, and that we must not unmask
10421          * more than one flip event at any time (or ensure that one flip message
10422          * can be sent by waiting for flip-done prior to queueing new flips).
10423          * Experimentation says that BCS works despite DERRMR masking all
10424          * flip-done completion events and that unmasking all planes at once
10425          * for the RCS also doesn't appear to drop events. Setting the DERRMR
10426          * to zero does lead to lockups within MI_DISPLAY_FLIP.
10427          */
10428         if (ring->id == RCS) {
10429                 intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
10430                 intel_ring_emit(ring, DERRMR);
10431                 intel_ring_emit(ring, ~(DERRMR_PIPEA_PRI_FLIP_DONE |
10432                                         DERRMR_PIPEB_PRI_FLIP_DONE |
10433                                         DERRMR_PIPEC_PRI_FLIP_DONE));
10434                 if (IS_GEN8(dev))
10435                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM_GEN8(1) |
10436                                               MI_SRM_LRM_GLOBAL_GTT);
10437                 else
10438                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM(1) |
10439                                               MI_SRM_LRM_GLOBAL_GTT);
10440                 intel_ring_emit(ring, DERRMR);
10441                 intel_ring_emit(ring, ring->scratch.gtt_offset + 256);
10442                 if (IS_GEN8(dev)) {
10443                         intel_ring_emit(ring, 0);
10444                         intel_ring_emit(ring, MI_NOOP);
10445                 }
10446         }
10447
10448         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 | plane_bit);
10449         intel_ring_emit(ring, (fb->pitches[0] | obj->tiling_mode));
10450         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
10451         intel_ring_emit(ring, (MI_NOOP));
10452
10453         intel_mark_page_flip_active(intel_crtc);
10454         __intel_ring_advance(ring);
10455         return 0;
10456 }
10457
10458 static bool use_mmio_flip(struct intel_engine_cs *ring,
10459                           struct drm_i915_gem_object *obj)
10460 {
10461         /*
10462          * This is not being used for older platforms, because
10463          * non-availability of flip done interrupt forces us to use
10464          * CS flips. Older platforms derive flip done using some clever
10465          * tricks involving the flip_pending status bits and vblank irqs.
10466          * So using MMIO flips there would disrupt this mechanism.
10467          */
10468
10469         if (ring == NULL)
10470                 return true;
10471
10472         if (INTEL_INFO(ring->dev)->gen < 5)
10473                 return false;
10474
10475         if (i915.use_mmio_flip < 0)
10476                 return false;
10477         else if (i915.use_mmio_flip > 0)
10478                 return true;
10479         else if (i915.enable_execlists)
10480                 return true;
10481         else
10482                 return ring != i915_gem_request_get_ring(obj->last_read_req);
10483 }
10484
10485 static void skl_do_mmio_flip(struct intel_crtc *intel_crtc)
10486 {
10487         struct drm_device *dev = intel_crtc->base.dev;
10488         struct drm_i915_private *dev_priv = dev->dev_private;
10489         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
10490         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
10491         struct drm_i915_gem_object *obj = intel_fb->obj;
10492         const enum pipe pipe = intel_crtc->pipe;
10493         u32 ctl, stride;
10494
10495         ctl = I915_READ(PLANE_CTL(pipe, 0));
10496         ctl &= ~PLANE_CTL_TILED_MASK;
10497         if (obj->tiling_mode == I915_TILING_X)
10498                 ctl |= PLANE_CTL_TILED_X;
10499
10500         /*
10501          * The stride is either expressed as a multiple of 64 bytes chunks for
10502          * linear buffers or in number of tiles for tiled buffers.
10503          */
10504         stride = fb->pitches[0] >> 6;
10505         if (obj->tiling_mode == I915_TILING_X)
10506                 stride = fb->pitches[0] >> 9; /* X tiles are 512 bytes wide */
10507
10508         /*
10509          * Both PLANE_CTL and PLANE_STRIDE are not updated on vblank but on
10510          * PLANE_SURF updates, the update is then guaranteed to be atomic.
10511          */
10512         I915_WRITE(PLANE_CTL(pipe, 0), ctl);
10513         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
10514
10515         I915_WRITE(PLANE_SURF(pipe, 0), intel_crtc->unpin_work->gtt_offset);
10516         POSTING_READ(PLANE_SURF(pipe, 0));
10517 }
10518
10519 static void ilk_do_mmio_flip(struct intel_crtc *intel_crtc)
10520 {
10521         struct drm_device *dev = intel_crtc->base.dev;
10522         struct drm_i915_private *dev_priv = dev->dev_private;
10523         struct intel_framebuffer *intel_fb =
10524                 to_intel_framebuffer(intel_crtc->base.primary->fb);
10525         struct drm_i915_gem_object *obj = intel_fb->obj;
10526         u32 dspcntr;
10527         u32 reg;
10528
10529         reg = DSPCNTR(intel_crtc->plane);
10530         dspcntr = I915_READ(reg);
10531
10532         if (obj->tiling_mode != I915_TILING_NONE)
10533                 dspcntr |= DISPPLANE_TILED;
10534         else
10535                 dspcntr &= ~DISPPLANE_TILED;
10536
10537         I915_WRITE(reg, dspcntr);
10538
10539         I915_WRITE(DSPSURF(intel_crtc->plane),
10540                    intel_crtc->unpin_work->gtt_offset);
10541         POSTING_READ(DSPSURF(intel_crtc->plane));
10542
10543 }
10544
10545 /*
10546  * XXX: This is the temporary way to update the plane registers until we get
10547  * around to using the usual plane update functions for MMIO flips
10548  */
10549 static void intel_do_mmio_flip(struct intel_crtc *intel_crtc)
10550 {
10551         struct drm_device *dev = intel_crtc->base.dev;
10552         bool atomic_update;
10553         u32 start_vbl_count;
10554
10555         intel_mark_page_flip_active(intel_crtc);
10556
10557         atomic_update = intel_pipe_update_start(intel_crtc, &start_vbl_count);
10558
10559         if (INTEL_INFO(dev)->gen >= 9)
10560                 skl_do_mmio_flip(intel_crtc);
10561         else
10562                 /* use_mmio_flip() retricts MMIO flips to ilk+ */
10563                 ilk_do_mmio_flip(intel_crtc);
10564
10565         if (atomic_update)
10566                 intel_pipe_update_end(intel_crtc, start_vbl_count);
10567 }
10568
10569 static void intel_mmio_flip_work_func(struct work_struct *work)
10570 {
10571         struct intel_crtc *crtc =
10572                 container_of(work, struct intel_crtc, mmio_flip.work);
10573         struct intel_mmio_flip *mmio_flip;
10574
10575         mmio_flip = &crtc->mmio_flip;
10576         if (mmio_flip->req)
10577                 WARN_ON(__i915_wait_request(mmio_flip->req,
10578                                             crtc->reset_counter,
10579                                             false, NULL, NULL) != 0);
10580
10581         intel_do_mmio_flip(crtc);
10582         if (mmio_flip->req) {
10583                 mutex_lock(&crtc->base.dev->struct_mutex);
10584                 i915_gem_request_assign(&mmio_flip->req, NULL);
10585                 mutex_unlock(&crtc->base.dev->struct_mutex);
10586         }
10587 }
10588
10589 static int intel_queue_mmio_flip(struct drm_device *dev,
10590                                  struct drm_crtc *crtc,
10591                                  struct drm_framebuffer *fb,
10592                                  struct drm_i915_gem_object *obj,
10593                                  struct intel_engine_cs *ring,
10594                                  uint32_t flags)
10595 {
10596         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10597
10598         i915_gem_request_assign(&intel_crtc->mmio_flip.req,
10599                                 obj->last_write_req);
10600
10601         schedule_work(&intel_crtc->mmio_flip.work);
10602
10603         return 0;
10604 }
10605
10606 static int intel_default_queue_flip(struct drm_device *dev,
10607                                     struct drm_crtc *crtc,
10608                                     struct drm_framebuffer *fb,
10609                                     struct drm_i915_gem_object *obj,
10610                                     struct intel_engine_cs *ring,
10611                                     uint32_t flags)
10612 {
10613         return -ENODEV;
10614 }
10615
10616 static bool __intel_pageflip_stall_check(struct drm_device *dev,
10617                                          struct drm_crtc *crtc)
10618 {
10619         struct drm_i915_private *dev_priv = dev->dev_private;
10620         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10621         struct intel_unpin_work *work = intel_crtc->unpin_work;
10622         u32 addr;
10623
10624         if (atomic_read(&work->pending) >= INTEL_FLIP_COMPLETE)
10625                 return true;
10626
10627         if (!work->enable_stall_check)
10628                 return false;
10629
10630         if (work->flip_ready_vblank == 0) {
10631                 if (work->flip_queued_req &&
10632                     !i915_gem_request_completed(work->flip_queued_req, true))
10633                         return false;
10634
10635                 work->flip_ready_vblank = drm_crtc_vblank_count(crtc);
10636         }
10637
10638         if (drm_crtc_vblank_count(crtc) - work->flip_ready_vblank < 3)
10639                 return false;
10640
10641         /* Potential stall - if we see that the flip has happened,
10642          * assume a missed interrupt. */
10643         if (INTEL_INFO(dev)->gen >= 4)
10644                 addr = I915_HI_DISPBASE(I915_READ(DSPSURF(intel_crtc->plane)));
10645         else
10646                 addr = I915_READ(DSPADDR(intel_crtc->plane));
10647
10648         /* There is a potential issue here with a false positive after a flip
10649          * to the same address. We could address this by checking for a
10650          * non-incrementing frame counter.
10651          */
10652         return addr == work->gtt_offset;
10653 }
10654
10655 void intel_check_page_flip(struct drm_device *dev, int pipe)
10656 {
10657         struct drm_i915_private *dev_priv = dev->dev_private;
10658         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
10659         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10660         struct intel_unpin_work *work;
10661
10662         WARN_ON(!in_interrupt());
10663
10664         if (crtc == NULL)
10665                 return;
10666
10667         spin_lock(&dev->event_lock);
10668         work = intel_crtc->unpin_work;
10669         if (work != NULL && __intel_pageflip_stall_check(dev, crtc)) {
10670                 WARN_ONCE(1, "Kicking stuck page flip: queued at %d, now %d\n",
10671                          work->flip_queued_vblank, drm_vblank_count(dev, pipe));
10672                 page_flip_completed(intel_crtc);
10673                 work = NULL;
10674         }
10675         if (work != NULL &&
10676             drm_vblank_count(dev, pipe) - work->flip_queued_vblank > 1)
10677                 intel_queue_rps_boost_for_request(dev, work->flip_queued_req);
10678         spin_unlock(&dev->event_lock);
10679 }
10680
10681 static int intel_crtc_page_flip(struct drm_crtc *crtc,
10682                                 struct drm_framebuffer *fb,
10683                                 struct drm_pending_vblank_event *event,
10684                                 uint32_t page_flip_flags)
10685 {
10686         struct drm_device *dev = crtc->dev;
10687         struct drm_i915_private *dev_priv = dev->dev_private;
10688         struct drm_framebuffer *old_fb = crtc->primary->fb;
10689         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
10690         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10691         struct drm_plane *primary = crtc->primary;
10692         enum pipe pipe = intel_crtc->pipe;
10693         struct intel_unpin_work *work;
10694         struct intel_engine_cs *ring;
10695         bool mmio_flip;
10696         int ret;
10697
10698         /*
10699          * drm_mode_page_flip_ioctl() should already catch this, but double
10700          * check to be safe.  In the future we may enable pageflipping from
10701          * a disabled primary plane.
10702          */
10703         if (WARN_ON(intel_fb_obj(old_fb) == NULL))
10704                 return -EBUSY;
10705
10706         /* Can't change pixel format via MI display flips. */
10707         if (fb->pixel_format != crtc->primary->fb->pixel_format)
10708                 return -EINVAL;
10709
10710         /*
10711          * TILEOFF/LINOFF registers can't be changed via MI display flips.
10712          * Note that pitch changes could also affect these register.
10713          */
10714         if (INTEL_INFO(dev)->gen > 3 &&
10715             (fb->offsets[0] != crtc->primary->fb->offsets[0] ||
10716              fb->pitches[0] != crtc->primary->fb->pitches[0]))
10717                 return -EINVAL;
10718
10719         if (i915_terminally_wedged(&dev_priv->gpu_error))
10720                 goto out_hang;
10721
10722         work = kzalloc(sizeof(*work), GFP_KERNEL);
10723         if (work == NULL)
10724                 return -ENOMEM;
10725
10726         work->event = event;
10727         work->crtc = crtc;
10728         work->old_fb = old_fb;
10729         INIT_WORK(&work->work, intel_unpin_work_fn);
10730
10731         ret = drm_crtc_vblank_get(crtc);
10732         if (ret)
10733                 goto free_work;
10734
10735         /* We borrow the event spin lock for protecting unpin_work */
10736         spin_lock_irq(&dev->event_lock);
10737         if (intel_crtc->unpin_work) {
10738                 /* Before declaring the flip queue wedged, check if
10739                  * the hardware completed the operation behind our backs.
10740                  */
10741                 if (__intel_pageflip_stall_check(dev, crtc)) {
10742                         DRM_DEBUG_DRIVER("flip queue: previous flip completed, continuing\n");
10743                         page_flip_completed(intel_crtc);
10744                 } else {
10745                         DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
10746                         spin_unlock_irq(&dev->event_lock);
10747
10748                         drm_crtc_vblank_put(crtc);
10749                         kfree(work);
10750                         return -EBUSY;
10751                 }
10752         }
10753         intel_crtc->unpin_work = work;
10754         spin_unlock_irq(&dev->event_lock);
10755
10756         if (atomic_read(&intel_crtc->unpin_work_count) >= 2)
10757                 flush_workqueue(dev_priv->wq);
10758
10759         /* Reference the objects for the scheduled work. */
10760         drm_framebuffer_reference(work->old_fb);
10761         drm_gem_object_reference(&obj->base);
10762
10763         crtc->primary->fb = fb;
10764         update_state_fb(crtc->primary);
10765
10766         work->pending_flip_obj = obj;
10767
10768         ret = i915_mutex_lock_interruptible(dev);
10769         if (ret)
10770                 goto cleanup;
10771
10772         atomic_inc(&intel_crtc->unpin_work_count);
10773         intel_crtc->reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
10774
10775         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
10776                 work->flip_count = I915_READ(PIPE_FLIPCOUNT_GM45(pipe)) + 1;
10777
10778         if (IS_VALLEYVIEW(dev)) {
10779                 ring = &dev_priv->ring[BCS];
10780                 if (obj->tiling_mode != intel_fb_obj(work->old_fb)->tiling_mode)
10781                         /* vlv: DISPLAY_FLIP fails to change tiling */
10782                         ring = NULL;
10783         } else if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev)) {
10784                 ring = &dev_priv->ring[BCS];
10785         } else if (INTEL_INFO(dev)->gen >= 7) {
10786                 ring = i915_gem_request_get_ring(obj->last_read_req);
10787                 if (ring == NULL || ring->id != RCS)
10788                         ring = &dev_priv->ring[BCS];
10789         } else {
10790                 ring = &dev_priv->ring[RCS];
10791         }
10792
10793         mmio_flip = use_mmio_flip(ring, obj);
10794
10795         /* When using CS flips, we want to emit semaphores between rings.
10796          * However, when using mmio flips we will create a task to do the
10797          * synchronisation, so all we want here is to pin the framebuffer
10798          * into the display plane and skip any waits.
10799          */
10800         ret = intel_pin_and_fence_fb_obj(crtc->primary, fb,
10801                                          crtc->primary->state,
10802                                          mmio_flip ? i915_gem_request_get_ring(obj->last_read_req) : ring);
10803         if (ret)
10804                 goto cleanup_pending;
10805
10806         work->gtt_offset = intel_plane_obj_offset(to_intel_plane(primary), obj)
10807                                                   + intel_crtc->dspaddr_offset;
10808
10809         if (mmio_flip) {
10810                 ret = intel_queue_mmio_flip(dev, crtc, fb, obj, ring,
10811                                             page_flip_flags);
10812                 if (ret)
10813                         goto cleanup_unpin;
10814
10815                 i915_gem_request_assign(&work->flip_queued_req,
10816                                         obj->last_write_req);
10817         } else {
10818                 ret = dev_priv->display.queue_flip(dev, crtc, fb, obj, ring,
10819                                                    page_flip_flags);
10820                 if (ret)
10821                         goto cleanup_unpin;
10822
10823                 i915_gem_request_assign(&work->flip_queued_req,
10824                                         intel_ring_get_request(ring));
10825         }
10826
10827         work->flip_queued_vblank = drm_crtc_vblank_count(crtc);
10828         work->enable_stall_check = true;
10829
10830         i915_gem_track_fb(intel_fb_obj(work->old_fb), obj,
10831                           INTEL_FRONTBUFFER_PRIMARY(pipe));
10832
10833         intel_fbc_disable(dev);
10834         intel_frontbuffer_flip_prepare(dev, INTEL_FRONTBUFFER_PRIMARY(pipe));
10835         mutex_unlock(&dev->struct_mutex);
10836
10837         trace_i915_flip_request(intel_crtc->plane, obj);
10838
10839         return 0;
10840
10841 cleanup_unpin:
10842         intel_unpin_fb_obj(fb, crtc->primary->state);
10843 cleanup_pending:
10844         atomic_dec(&intel_crtc->unpin_work_count);
10845         mutex_unlock(&dev->struct_mutex);
10846 cleanup:
10847         crtc->primary->fb = old_fb;
10848         update_state_fb(crtc->primary);
10849
10850         drm_gem_object_unreference_unlocked(&obj->base);
10851         drm_framebuffer_unreference(work->old_fb);
10852
10853         spin_lock_irq(&dev->event_lock);
10854         intel_crtc->unpin_work = NULL;
10855         spin_unlock_irq(&dev->event_lock);
10856
10857         drm_crtc_vblank_put(crtc);
10858 free_work:
10859         kfree(work);
10860
10861         if (ret == -EIO) {
10862 out_hang:
10863                 ret = intel_plane_restore(primary);
10864                 if (ret == 0 && event) {
10865                         spin_lock_irq(&dev->event_lock);
10866                         drm_send_vblank_event(dev, pipe, event);
10867                         spin_unlock_irq(&dev->event_lock);
10868                 }
10869         }
10870         return ret;
10871 }
10872
10873 static struct drm_crtc_helper_funcs intel_helper_funcs = {
10874         .mode_set_base_atomic = intel_pipe_set_base_atomic,
10875         .load_lut = intel_crtc_load_lut,
10876         .atomic_begin = intel_begin_crtc_commit,
10877         .atomic_flush = intel_finish_crtc_commit,
10878 };
10879
10880 /**
10881  * intel_modeset_update_staged_output_state
10882  *
10883  * Updates the staged output configuration state, e.g. after we've read out the
10884  * current hw state.
10885  */
10886 static void intel_modeset_update_staged_output_state(struct drm_device *dev)
10887 {
10888         struct intel_crtc *crtc;
10889         struct intel_encoder *encoder;
10890         struct intel_connector *connector;
10891
10892         for_each_intel_connector(dev, connector) {
10893                 connector->new_encoder =
10894                         to_intel_encoder(connector->base.encoder);
10895         }
10896
10897         for_each_intel_encoder(dev, encoder) {
10898                 encoder->new_crtc =
10899                         to_intel_crtc(encoder->base.crtc);
10900         }
10901
10902         for_each_intel_crtc(dev, crtc) {
10903                 crtc->new_enabled = crtc->base.state->enable;
10904         }
10905 }
10906
10907 /* Transitional helper to copy current connector/encoder state to
10908  * connector->state. This is needed so that code that is partially
10909  * converted to atomic does the right thing.
10910  */
10911 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
10912 {
10913         struct intel_connector *connector;
10914
10915         for_each_intel_connector(dev, connector) {
10916                 if (connector->base.encoder) {
10917                         connector->base.state->best_encoder =
10918                                 connector->base.encoder;
10919                         connector->base.state->crtc =
10920                                 connector->base.encoder->crtc;
10921                 } else {
10922                         connector->base.state->best_encoder = NULL;
10923                         connector->base.state->crtc = NULL;
10924                 }
10925         }
10926 }
10927
10928 /**
10929  * intel_modeset_commit_output_state
10930  *
10931  * This function copies the stage display pipe configuration to the real one.
10932  */
10933 static void intel_modeset_commit_output_state(struct drm_device *dev)
10934 {
10935         struct intel_crtc *crtc;
10936         struct intel_encoder *encoder;
10937         struct intel_connector *connector;
10938
10939         for_each_intel_connector(dev, connector) {
10940                 connector->base.encoder = &connector->new_encoder->base;
10941         }
10942
10943         for_each_intel_encoder(dev, encoder) {
10944                 encoder->base.crtc = &encoder->new_crtc->base;
10945         }
10946
10947         for_each_intel_crtc(dev, crtc) {
10948                 crtc->base.state->enable = crtc->new_enabled;
10949                 crtc->base.enabled = crtc->new_enabled;
10950         }
10951
10952         intel_modeset_update_connector_atomic_state(dev);
10953 }
10954
10955 static void
10956 connected_sink_compute_bpp(struct intel_connector *connector,
10957                            struct intel_crtc_state *pipe_config)
10958 {
10959         int bpp = pipe_config->pipe_bpp;
10960
10961         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
10962                 connector->base.base.id,
10963                 connector->base.name);
10964
10965         /* Don't use an invalid EDID bpc value */
10966         if (connector->base.display_info.bpc &&
10967             connector->base.display_info.bpc * 3 < bpp) {
10968                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
10969                               bpp, connector->base.display_info.bpc*3);
10970                 pipe_config->pipe_bpp = connector->base.display_info.bpc*3;
10971         }
10972
10973         /* Clamp bpp to 8 on screens without EDID 1.4 */
10974         if (connector->base.display_info.bpc == 0 && bpp > 24) {
10975                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
10976                               bpp);
10977                 pipe_config->pipe_bpp = 24;
10978         }
10979 }
10980
10981 static int
10982 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
10983                           struct intel_crtc_state *pipe_config)
10984 {
10985         struct drm_device *dev = crtc->base.dev;
10986         struct drm_atomic_state *state;
10987         struct intel_connector *connector;
10988         int bpp, i;
10989
10990         if ((IS_G4X(dev) || IS_VALLEYVIEW(dev)))
10991                 bpp = 10*3;
10992         else if (INTEL_INFO(dev)->gen >= 5)
10993                 bpp = 12*3;
10994         else
10995                 bpp = 8*3;
10996
10997
10998         pipe_config->pipe_bpp = bpp;
10999
11000         state = pipe_config->base.state;
11001
11002         /* Clamp display bpp to EDID value */
11003         for (i = 0; i < state->num_connector; i++) {
11004                 if (!state->connectors[i])
11005                         continue;
11006
11007                 connector = to_intel_connector(state->connectors[i]);
11008                 if (state->connector_states[i]->crtc != &crtc->base)
11009                         continue;
11010
11011                 connected_sink_compute_bpp(connector, pipe_config);
11012         }
11013
11014         return bpp;
11015 }
11016
11017 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
11018 {
11019         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
11020                         "type: 0x%x flags: 0x%x\n",
11021                 mode->crtc_clock,
11022                 mode->crtc_hdisplay, mode->crtc_hsync_start,
11023                 mode->crtc_hsync_end, mode->crtc_htotal,
11024                 mode->crtc_vdisplay, mode->crtc_vsync_start,
11025                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
11026 }
11027
11028 static void intel_dump_pipe_config(struct intel_crtc *crtc,
11029                                    struct intel_crtc_state *pipe_config,
11030                                    const char *context)
11031 {
11032         struct drm_device *dev = crtc->base.dev;
11033         struct drm_plane *plane;
11034         struct intel_plane *intel_plane;
11035         struct intel_plane_state *state;
11036         struct drm_framebuffer *fb;
11037
11038         DRM_DEBUG_KMS("[CRTC:%d]%s config %p for pipe %c\n", crtc->base.base.id,
11039                       context, pipe_config, pipe_name(crtc->pipe));
11040
11041         DRM_DEBUG_KMS("cpu_transcoder: %c\n", transcoder_name(pipe_config->cpu_transcoder));
11042         DRM_DEBUG_KMS("pipe bpp: %i, dithering: %i\n",
11043                       pipe_config->pipe_bpp, pipe_config->dither);
11044         DRM_DEBUG_KMS("fdi/pch: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
11045                       pipe_config->has_pch_encoder,
11046                       pipe_config->fdi_lanes,
11047                       pipe_config->fdi_m_n.gmch_m, pipe_config->fdi_m_n.gmch_n,
11048                       pipe_config->fdi_m_n.link_m, pipe_config->fdi_m_n.link_n,
11049                       pipe_config->fdi_m_n.tu);
11050         DRM_DEBUG_KMS("dp: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
11051                       pipe_config->has_dp_encoder,
11052                       pipe_config->dp_m_n.gmch_m, pipe_config->dp_m_n.gmch_n,
11053                       pipe_config->dp_m_n.link_m, pipe_config->dp_m_n.link_n,
11054                       pipe_config->dp_m_n.tu);
11055
11056         DRM_DEBUG_KMS("dp: %i, gmch_m2: %u, gmch_n2: %u, link_m2: %u, link_n2: %u, tu2: %u\n",
11057                       pipe_config->has_dp_encoder,
11058                       pipe_config->dp_m2_n2.gmch_m,
11059                       pipe_config->dp_m2_n2.gmch_n,
11060                       pipe_config->dp_m2_n2.link_m,
11061                       pipe_config->dp_m2_n2.link_n,
11062                       pipe_config->dp_m2_n2.tu);
11063
11064         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
11065                       pipe_config->has_audio,
11066                       pipe_config->has_infoframe);
11067
11068         DRM_DEBUG_KMS("requested mode:\n");
11069         drm_mode_debug_printmodeline(&pipe_config->base.mode);
11070         DRM_DEBUG_KMS("adjusted mode:\n");
11071         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
11072         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
11073         DRM_DEBUG_KMS("port clock: %d\n", pipe_config->port_clock);
11074         DRM_DEBUG_KMS("pipe src size: %dx%d\n",
11075                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
11076         DRM_DEBUG_KMS("num_scalers: %d\n", crtc->num_scalers);
11077         DRM_DEBUG_KMS("scaler_users: 0x%x\n", pipe_config->scaler_state.scaler_users);
11078         DRM_DEBUG_KMS("scaler id: %d\n", pipe_config->scaler_state.scaler_id);
11079         DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
11080                       pipe_config->gmch_pfit.control,
11081                       pipe_config->gmch_pfit.pgm_ratios,
11082                       pipe_config->gmch_pfit.lvds_border_bits);
11083         DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
11084                       pipe_config->pch_pfit.pos,
11085                       pipe_config->pch_pfit.size,
11086                       pipe_config->pch_pfit.enabled ? "enabled" : "disabled");
11087         DRM_DEBUG_KMS("ips: %i\n", pipe_config->ips_enabled);
11088         DRM_DEBUG_KMS("double wide: %i\n", pipe_config->double_wide);
11089
11090         DRM_DEBUG_KMS("planes on this crtc\n");
11091         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
11092                 intel_plane = to_intel_plane(plane);
11093                 if (intel_plane->pipe != crtc->pipe)
11094                         continue;
11095
11096                 state = to_intel_plane_state(plane->state);
11097                 fb = state->base.fb;
11098                 if (!fb) {
11099                         DRM_DEBUG_KMS("%s PLANE:%d plane: %u.%u idx: %d "
11100                                 "disabled, scaler_id = %d\n",
11101                                 plane->type == DRM_PLANE_TYPE_CURSOR ? "CURSOR" : "STANDARD",
11102                                 plane->base.id, intel_plane->pipe,
11103                                 (crtc->base.primary == plane) ? 0 : intel_plane->plane + 1,
11104                                 drm_plane_index(plane), state->scaler_id);
11105                         continue;
11106                 }
11107
11108                 DRM_DEBUG_KMS("%s PLANE:%d plane: %u.%u idx: %d enabled",
11109                         plane->type == DRM_PLANE_TYPE_CURSOR ? "CURSOR" : "STANDARD",
11110                         plane->base.id, intel_plane->pipe,
11111                         crtc->base.primary == plane ? 0 : intel_plane->plane + 1,
11112                         drm_plane_index(plane));
11113                 DRM_DEBUG_KMS("\tFB:%d, fb = %ux%u format = 0x%x",
11114                         fb->base.id, fb->width, fb->height, fb->pixel_format);
11115                 DRM_DEBUG_KMS("\tscaler:%d src (%u, %u) %ux%u dst (%u, %u) %ux%u\n",
11116                         state->scaler_id,
11117                         state->src.x1 >> 16, state->src.y1 >> 16,
11118                         drm_rect_width(&state->src) >> 16,
11119                         drm_rect_height(&state->src) >> 16,
11120                         state->dst.x1, state->dst.y1,
11121                         drm_rect_width(&state->dst), drm_rect_height(&state->dst));
11122         }
11123 }
11124
11125 static bool encoders_cloneable(const struct intel_encoder *a,
11126                                const struct intel_encoder *b)
11127 {
11128         /* masks could be asymmetric, so check both ways */
11129         return a == b || (a->cloneable & (1 << b->type) &&
11130                           b->cloneable & (1 << a->type));
11131 }
11132
11133 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
11134                                          struct intel_crtc *crtc,
11135                                          struct intel_encoder *encoder)
11136 {
11137         struct intel_encoder *source_encoder;
11138         struct drm_connector_state *connector_state;
11139         int i;
11140
11141         for (i = 0; i < state->num_connector; i++) {
11142                 if (!state->connectors[i])
11143                         continue;
11144
11145                 connector_state = state->connector_states[i];
11146                 if (connector_state->crtc != &crtc->base)
11147                         continue;
11148
11149                 source_encoder =
11150                         to_intel_encoder(connector_state->best_encoder);
11151                 if (!encoders_cloneable(encoder, source_encoder))
11152                         return false;
11153         }
11154
11155         return true;
11156 }
11157
11158 static bool check_encoder_cloning(struct drm_atomic_state *state,
11159                                   struct intel_crtc *crtc)
11160 {
11161         struct intel_encoder *encoder;
11162         struct drm_connector_state *connector_state;
11163         int i;
11164
11165         for (i = 0; i < state->num_connector; i++) {
11166                 if (!state->connectors[i])
11167                         continue;
11168
11169                 connector_state = state->connector_states[i];
11170                 if (connector_state->crtc != &crtc->base)
11171                         continue;
11172
11173                 encoder = to_intel_encoder(connector_state->best_encoder);
11174                 if (!check_single_encoder_cloning(state, crtc, encoder))
11175                         return false;
11176         }
11177
11178         return true;
11179 }
11180
11181 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
11182 {
11183         struct drm_device *dev = state->dev;
11184         struct intel_encoder *encoder;
11185         struct drm_connector_state *connector_state;
11186         unsigned int used_ports = 0;
11187         int i;
11188
11189         /*
11190          * Walk the connector list instead of the encoder
11191          * list to detect the problem on ddi platforms
11192          * where there's just one encoder per digital port.
11193          */
11194         for (i = 0; i < state->num_connector; i++) {
11195                 if (!state->connectors[i])
11196                         continue;
11197
11198                 connector_state = state->connector_states[i];
11199                 if (!connector_state->best_encoder)
11200                         continue;
11201
11202                 encoder = to_intel_encoder(connector_state->best_encoder);
11203
11204                 WARN_ON(!connector_state->crtc);
11205
11206                 switch (encoder->type) {
11207                         unsigned int port_mask;
11208                 case INTEL_OUTPUT_UNKNOWN:
11209                         if (WARN_ON(!HAS_DDI(dev)))
11210                                 break;
11211                 case INTEL_OUTPUT_DISPLAYPORT:
11212                 case INTEL_OUTPUT_HDMI:
11213                 case INTEL_OUTPUT_EDP:
11214                         port_mask = 1 << enc_to_dig_port(&encoder->base)->port;
11215
11216                         /* the same port mustn't appear more than once */
11217                         if (used_ports & port_mask)
11218                                 return false;
11219
11220                         used_ports |= port_mask;
11221                 default:
11222                         break;
11223                 }
11224         }
11225
11226         return true;
11227 }
11228
11229 static void
11230 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
11231 {
11232         struct drm_crtc_state tmp_state;
11233         struct intel_crtc_scaler_state scaler_state;
11234
11235         /* Clear only the intel specific part of the crtc state excluding scalers */
11236         tmp_state = crtc_state->base;
11237         scaler_state = crtc_state->scaler_state;
11238         memset(crtc_state, 0, sizeof *crtc_state);
11239         crtc_state->base = tmp_state;
11240         crtc_state->scaler_state = scaler_state;
11241 }
11242
11243 static struct intel_crtc_state *
11244 intel_modeset_pipe_config(struct drm_crtc *crtc,
11245                           struct drm_display_mode *mode,
11246                           struct drm_atomic_state *state)
11247 {
11248         struct intel_encoder *encoder;
11249         struct intel_connector *connector;
11250         struct drm_connector_state *connector_state;
11251         struct intel_crtc_state *pipe_config;
11252         int base_bpp, ret = -EINVAL;
11253         int i;
11254         bool retry = true;
11255
11256         if (!check_encoder_cloning(state, to_intel_crtc(crtc))) {
11257                 DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
11258                 return ERR_PTR(-EINVAL);
11259         }
11260
11261         if (!check_digital_port_conflicts(state)) {
11262                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
11263                 return ERR_PTR(-EINVAL);
11264         }
11265
11266         pipe_config = intel_atomic_get_crtc_state(state, to_intel_crtc(crtc));
11267         if (IS_ERR(pipe_config))
11268                 return pipe_config;
11269
11270         clear_intel_crtc_state(pipe_config);
11271
11272         pipe_config->base.crtc = crtc;
11273         drm_mode_copy(&pipe_config->base.adjusted_mode, mode);
11274         drm_mode_copy(&pipe_config->base.mode, mode);
11275
11276         pipe_config->cpu_transcoder =
11277                 (enum transcoder) to_intel_crtc(crtc)->pipe;
11278         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
11279
11280         /*
11281          * Sanitize sync polarity flags based on requested ones. If neither
11282          * positive or negative polarity is requested, treat this as meaning
11283          * negative polarity.
11284          */
11285         if (!(pipe_config->base.adjusted_mode.flags &
11286               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
11287                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
11288
11289         if (!(pipe_config->base.adjusted_mode.flags &
11290               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
11291                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
11292
11293         /* Compute a starting value for pipe_config->pipe_bpp taking the source
11294          * plane pixel format and any sink constraints into account. Returns the
11295          * source plane bpp so that dithering can be selected on mismatches
11296          * after encoders and crtc also have had their say. */
11297         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
11298                                              pipe_config);
11299         if (base_bpp < 0)
11300                 goto fail;
11301
11302         /*
11303          * Determine the real pipe dimensions. Note that stereo modes can
11304          * increase the actual pipe size due to the frame doubling and
11305          * insertion of additional space for blanks between the frame. This
11306          * is stored in the crtc timings. We use the requested mode to do this
11307          * computation to clearly distinguish it from the adjusted mode, which
11308          * can be changed by the connectors in the below retry loop.
11309          */
11310         drm_crtc_get_hv_timing(&pipe_config->base.mode,
11311                                &pipe_config->pipe_src_w,
11312                                &pipe_config->pipe_src_h);
11313
11314 encoder_retry:
11315         /* Ensure the port clock defaults are reset when retrying. */
11316         pipe_config->port_clock = 0;
11317         pipe_config->pixel_multiplier = 1;
11318
11319         /* Fill in default crtc timings, allow encoders to overwrite them. */
11320         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
11321                               CRTC_STEREO_DOUBLE);
11322
11323         /* Pass our mode to the connectors and the CRTC to give them a chance to
11324          * adjust it according to limitations or connector properties, and also
11325          * a chance to reject the mode entirely.
11326          */
11327         for (i = 0; i < state->num_connector; i++) {
11328                 connector = to_intel_connector(state->connectors[i]);
11329                 if (!connector)
11330                         continue;
11331
11332                 connector_state = state->connector_states[i];
11333                 if (connector_state->crtc != crtc)
11334                         continue;
11335
11336                 encoder = to_intel_encoder(connector_state->best_encoder);
11337
11338                 if (!(encoder->compute_config(encoder, pipe_config))) {
11339                         DRM_DEBUG_KMS("Encoder config failure\n");
11340                         goto fail;
11341                 }
11342         }
11343
11344         /* Set default port clock if not overwritten by the encoder. Needs to be
11345          * done afterwards in case the encoder adjusts the mode. */
11346         if (!pipe_config->port_clock)
11347                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
11348                         * pipe_config->pixel_multiplier;
11349
11350         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
11351         if (ret < 0) {
11352                 DRM_DEBUG_KMS("CRTC fixup failed\n");
11353                 goto fail;
11354         }
11355
11356         if (ret == RETRY) {
11357                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
11358                         ret = -EINVAL;
11359                         goto fail;
11360                 }
11361
11362                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
11363                 retry = false;
11364                 goto encoder_retry;
11365         }
11366
11367         pipe_config->dither = pipe_config->pipe_bpp != base_bpp;
11368         DRM_DEBUG_KMS("plane bpp: %i, pipe bpp: %i, dithering: %i\n",
11369                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
11370
11371         return pipe_config;
11372 fail:
11373         return ERR_PTR(ret);
11374 }
11375
11376 /* Computes which crtcs are affected and sets the relevant bits in the mask. For
11377  * simplicity we use the crtc's pipe number (because it's easier to obtain). */
11378 static void
11379 intel_modeset_affected_pipes(struct drm_crtc *crtc, unsigned *modeset_pipes,
11380                              unsigned *prepare_pipes, unsigned *disable_pipes)
11381 {
11382         struct intel_crtc *intel_crtc;
11383         struct drm_device *dev = crtc->dev;
11384         struct intel_encoder *encoder;
11385         struct intel_connector *connector;
11386         struct drm_crtc *tmp_crtc;
11387
11388         *disable_pipes = *modeset_pipes = *prepare_pipes = 0;
11389
11390         /* Check which crtcs have changed outputs connected to them, these need
11391          * to be part of the prepare_pipes mask. We don't (yet) support global
11392          * modeset across multiple crtcs, so modeset_pipes will only have one
11393          * bit set at most. */
11394         for_each_intel_connector(dev, connector) {
11395                 if (connector->base.encoder == &connector->new_encoder->base)
11396                         continue;
11397
11398                 if (connector->base.encoder) {
11399                         tmp_crtc = connector->base.encoder->crtc;
11400
11401                         *prepare_pipes |= 1 << to_intel_crtc(tmp_crtc)->pipe;
11402                 }
11403
11404                 if (connector->new_encoder)
11405                         *prepare_pipes |=
11406                                 1 << connector->new_encoder->new_crtc->pipe;
11407         }
11408
11409         for_each_intel_encoder(dev, encoder) {
11410                 if (encoder->base.crtc == &encoder->new_crtc->base)
11411                         continue;
11412
11413                 if (encoder->base.crtc) {
11414                         tmp_crtc = encoder->base.crtc;
11415
11416                         *prepare_pipes |= 1 << to_intel_crtc(tmp_crtc)->pipe;
11417                 }
11418
11419                 if (encoder->new_crtc)
11420                         *prepare_pipes |= 1 << encoder->new_crtc->pipe;
11421         }
11422
11423         /* Check for pipes that will be enabled/disabled ... */
11424         for_each_intel_crtc(dev, intel_crtc) {
11425                 if (intel_crtc->base.state->enable == intel_crtc->new_enabled)
11426                         continue;
11427
11428                 if (!intel_crtc->new_enabled)
11429                         *disable_pipes |= 1 << intel_crtc->pipe;
11430                 else
11431                         *prepare_pipes |= 1 << intel_crtc->pipe;
11432         }
11433
11434
11435         /* set_mode is also used to update properties on life display pipes. */
11436         intel_crtc = to_intel_crtc(crtc);
11437         if (intel_crtc->new_enabled)
11438                 *prepare_pipes |= 1 << intel_crtc->pipe;
11439
11440         /*
11441          * For simplicity do a full modeset on any pipe where the output routing
11442          * changed. We could be more clever, but that would require us to be
11443          * more careful with calling the relevant encoder->mode_set functions.
11444          */
11445         if (*prepare_pipes)
11446                 *modeset_pipes = *prepare_pipes;
11447
11448         /* ... and mask these out. */
11449         *modeset_pipes &= ~(*disable_pipes);
11450         *prepare_pipes &= ~(*disable_pipes);
11451
11452         /*
11453          * HACK: We don't (yet) fully support global modesets. intel_set_config
11454          * obies this rule, but the modeset restore mode of
11455          * intel_modeset_setup_hw_state does not.
11456          */
11457         *modeset_pipes &= 1 << intel_crtc->pipe;
11458         *prepare_pipes &= 1 << intel_crtc->pipe;
11459
11460         DRM_DEBUG_KMS("set mode pipe masks: modeset: %x, prepare: %x, disable: %x\n",
11461                       *modeset_pipes, *prepare_pipes, *disable_pipes);
11462 }
11463
11464 static bool intel_crtc_in_use(struct drm_crtc *crtc)
11465 {
11466         struct drm_encoder *encoder;
11467         struct drm_device *dev = crtc->dev;
11468
11469         list_for_each_entry(encoder, &dev->mode_config.encoder_list, head)
11470                 if (encoder->crtc == crtc)
11471                         return true;
11472
11473         return false;
11474 }
11475
11476 static void
11477 intel_modeset_update_state(struct drm_device *dev, unsigned prepare_pipes)
11478 {
11479         struct drm_i915_private *dev_priv = dev->dev_private;
11480         struct intel_encoder *intel_encoder;
11481         struct intel_crtc *intel_crtc;
11482         struct drm_connector *connector;
11483
11484         intel_shared_dpll_commit(dev_priv);
11485
11486         for_each_intel_encoder(dev, intel_encoder) {
11487                 if (!intel_encoder->base.crtc)
11488                         continue;
11489
11490                 intel_crtc = to_intel_crtc(intel_encoder->base.crtc);
11491
11492                 if (prepare_pipes & (1 << intel_crtc->pipe))
11493                         intel_encoder->connectors_active = false;
11494         }
11495
11496         intel_modeset_commit_output_state(dev);
11497
11498         /* Double check state. */
11499         for_each_intel_crtc(dev, intel_crtc) {
11500                 WARN_ON(intel_crtc->base.state->enable != intel_crtc_in_use(&intel_crtc->base));
11501         }
11502
11503         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
11504                 if (!connector->encoder || !connector->encoder->crtc)
11505                         continue;
11506
11507                 intel_crtc = to_intel_crtc(connector->encoder->crtc);
11508
11509                 if (prepare_pipes & (1 << intel_crtc->pipe)) {
11510                         struct drm_property *dpms_property =
11511                                 dev->mode_config.dpms_property;
11512
11513                         connector->dpms = DRM_MODE_DPMS_ON;
11514                         drm_object_property_set_value(&connector->base,
11515                                                          dpms_property,
11516                                                          DRM_MODE_DPMS_ON);
11517
11518                         intel_encoder = to_intel_encoder(connector->encoder);
11519                         intel_encoder->connectors_active = true;
11520                 }
11521         }
11522
11523 }
11524
11525 static bool intel_fuzzy_clock_check(int clock1, int clock2)
11526 {
11527         int diff;
11528
11529         if (clock1 == clock2)
11530                 return true;
11531
11532         if (!clock1 || !clock2)
11533                 return false;
11534
11535         diff = abs(clock1 - clock2);
11536
11537         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
11538                 return true;
11539
11540         return false;
11541 }
11542
11543 #define for_each_intel_crtc_masked(dev, mask, intel_crtc) \
11544         list_for_each_entry((intel_crtc), \
11545                             &(dev)->mode_config.crtc_list, \
11546                             base.head) \
11547                 if (mask & (1 <<(intel_crtc)->pipe))
11548
11549 static bool
11550 intel_pipe_config_compare(struct drm_device *dev,
11551                           struct intel_crtc_state *current_config,
11552                           struct intel_crtc_state *pipe_config)
11553 {
11554 #define PIPE_CONF_CHECK_X(name) \
11555         if (current_config->name != pipe_config->name) { \
11556                 DRM_ERROR("mismatch in " #name " " \
11557                           "(expected 0x%08x, found 0x%08x)\n", \
11558                           current_config->name, \
11559                           pipe_config->name); \
11560                 return false; \
11561         }
11562
11563 #define PIPE_CONF_CHECK_I(name) \
11564         if (current_config->name != pipe_config->name) { \
11565                 DRM_ERROR("mismatch in " #name " " \
11566                           "(expected %i, found %i)\n", \
11567                           current_config->name, \
11568                           pipe_config->name); \
11569                 return false; \
11570         }
11571
11572 /* This is required for BDW+ where there is only one set of registers for
11573  * switching between high and low RR.
11574  * This macro can be used whenever a comparison has to be made between one
11575  * hw state and multiple sw state variables.
11576  */
11577 #define PIPE_CONF_CHECK_I_ALT(name, alt_name) \
11578         if ((current_config->name != pipe_config->name) && \
11579                 (current_config->alt_name != pipe_config->name)) { \
11580                         DRM_ERROR("mismatch in " #name " " \
11581                                   "(expected %i or %i, found %i)\n", \
11582                                   current_config->name, \
11583                                   current_config->alt_name, \
11584                                   pipe_config->name); \
11585                         return false; \
11586         }
11587
11588 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
11589         if ((current_config->name ^ pipe_config->name) & (mask)) { \
11590                 DRM_ERROR("mismatch in " #name "(" #mask ") "      \
11591                           "(expected %i, found %i)\n", \
11592                           current_config->name & (mask), \
11593                           pipe_config->name & (mask)); \
11594                 return false; \
11595         }
11596
11597 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
11598         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
11599                 DRM_ERROR("mismatch in " #name " " \
11600                           "(expected %i, found %i)\n", \
11601                           current_config->name, \
11602                           pipe_config->name); \
11603                 return false; \
11604         }
11605
11606 #define PIPE_CONF_QUIRK(quirk)  \
11607         ((current_config->quirks | pipe_config->quirks) & (quirk))
11608
11609         PIPE_CONF_CHECK_I(cpu_transcoder);
11610
11611         PIPE_CONF_CHECK_I(has_pch_encoder);
11612         PIPE_CONF_CHECK_I(fdi_lanes);
11613         PIPE_CONF_CHECK_I(fdi_m_n.gmch_m);
11614         PIPE_CONF_CHECK_I(fdi_m_n.gmch_n);
11615         PIPE_CONF_CHECK_I(fdi_m_n.link_m);
11616         PIPE_CONF_CHECK_I(fdi_m_n.link_n);
11617         PIPE_CONF_CHECK_I(fdi_m_n.tu);
11618
11619         PIPE_CONF_CHECK_I(has_dp_encoder);
11620
11621         if (INTEL_INFO(dev)->gen < 8) {
11622                 PIPE_CONF_CHECK_I(dp_m_n.gmch_m);
11623                 PIPE_CONF_CHECK_I(dp_m_n.gmch_n);
11624                 PIPE_CONF_CHECK_I(dp_m_n.link_m);
11625                 PIPE_CONF_CHECK_I(dp_m_n.link_n);
11626                 PIPE_CONF_CHECK_I(dp_m_n.tu);
11627
11628                 if (current_config->has_drrs) {
11629                         PIPE_CONF_CHECK_I(dp_m2_n2.gmch_m);
11630                         PIPE_CONF_CHECK_I(dp_m2_n2.gmch_n);
11631                         PIPE_CONF_CHECK_I(dp_m2_n2.link_m);
11632                         PIPE_CONF_CHECK_I(dp_m2_n2.link_n);
11633                         PIPE_CONF_CHECK_I(dp_m2_n2.tu);
11634                 }
11635         } else {
11636                 PIPE_CONF_CHECK_I_ALT(dp_m_n.gmch_m, dp_m2_n2.gmch_m);
11637                 PIPE_CONF_CHECK_I_ALT(dp_m_n.gmch_n, dp_m2_n2.gmch_n);
11638                 PIPE_CONF_CHECK_I_ALT(dp_m_n.link_m, dp_m2_n2.link_m);
11639                 PIPE_CONF_CHECK_I_ALT(dp_m_n.link_n, dp_m2_n2.link_n);
11640                 PIPE_CONF_CHECK_I_ALT(dp_m_n.tu, dp_m2_n2.tu);
11641         }
11642
11643         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
11644         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
11645         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
11646         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
11647         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
11648         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
11649
11650         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
11651         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
11652         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
11653         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
11654         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
11655         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
11656
11657         PIPE_CONF_CHECK_I(pixel_multiplier);
11658         PIPE_CONF_CHECK_I(has_hdmi_sink);
11659         if ((INTEL_INFO(dev)->gen < 8 && !IS_HASWELL(dev)) ||
11660             IS_VALLEYVIEW(dev))
11661                 PIPE_CONF_CHECK_I(limited_color_range);
11662         PIPE_CONF_CHECK_I(has_infoframe);
11663
11664         PIPE_CONF_CHECK_I(has_audio);
11665
11666         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11667                               DRM_MODE_FLAG_INTERLACE);
11668
11669         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
11670                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11671                                       DRM_MODE_FLAG_PHSYNC);
11672                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11673                                       DRM_MODE_FLAG_NHSYNC);
11674                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11675                                       DRM_MODE_FLAG_PVSYNC);
11676                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11677                                       DRM_MODE_FLAG_NVSYNC);
11678         }
11679
11680         PIPE_CONF_CHECK_I(pipe_src_w);
11681         PIPE_CONF_CHECK_I(pipe_src_h);
11682
11683         /*
11684          * FIXME: BIOS likes to set up a cloned config with lvds+external
11685          * screen. Since we don't yet re-compute the pipe config when moving
11686          * just the lvds port away to another pipe the sw tracking won't match.
11687          *
11688          * Proper atomic modesets with recomputed global state will fix this.
11689          * Until then just don't check gmch state for inherited modes.
11690          */
11691         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_INHERITED_MODE)) {
11692                 PIPE_CONF_CHECK_I(gmch_pfit.control);
11693                 /* pfit ratios are autocomputed by the hw on gen4+ */
11694                 if (INTEL_INFO(dev)->gen < 4)
11695                         PIPE_CONF_CHECK_I(gmch_pfit.pgm_ratios);
11696                 PIPE_CONF_CHECK_I(gmch_pfit.lvds_border_bits);
11697         }
11698
11699         PIPE_CONF_CHECK_I(pch_pfit.enabled);
11700         if (current_config->pch_pfit.enabled) {
11701                 PIPE_CONF_CHECK_I(pch_pfit.pos);
11702                 PIPE_CONF_CHECK_I(pch_pfit.size);
11703         }
11704
11705         PIPE_CONF_CHECK_I(scaler_state.scaler_id);
11706
11707         /* BDW+ don't expose a synchronous way to read the state */
11708         if (IS_HASWELL(dev))
11709                 PIPE_CONF_CHECK_I(ips_enabled);
11710
11711         PIPE_CONF_CHECK_I(double_wide);
11712
11713         PIPE_CONF_CHECK_X(ddi_pll_sel);
11714
11715         PIPE_CONF_CHECK_I(shared_dpll);
11716         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
11717         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
11718         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
11719         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
11720         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
11721         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
11722         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
11723         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
11724
11725         if (IS_G4X(dev) || INTEL_INFO(dev)->gen >= 5)
11726                 PIPE_CONF_CHECK_I(pipe_bpp);
11727
11728         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
11729         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
11730
11731 #undef PIPE_CONF_CHECK_X
11732 #undef PIPE_CONF_CHECK_I
11733 #undef PIPE_CONF_CHECK_I_ALT
11734 #undef PIPE_CONF_CHECK_FLAGS
11735 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
11736 #undef PIPE_CONF_QUIRK
11737
11738         return true;
11739 }
11740
11741 static void check_wm_state(struct drm_device *dev)
11742 {
11743         struct drm_i915_private *dev_priv = dev->dev_private;
11744         struct skl_ddb_allocation hw_ddb, *sw_ddb;
11745         struct intel_crtc *intel_crtc;
11746         int plane;
11747
11748         if (INTEL_INFO(dev)->gen < 9)
11749                 return;
11750
11751         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
11752         sw_ddb = &dev_priv->wm.skl_hw.ddb;
11753
11754         for_each_intel_crtc(dev, intel_crtc) {
11755                 struct skl_ddb_entry *hw_entry, *sw_entry;
11756                 const enum pipe pipe = intel_crtc->pipe;
11757
11758                 if (!intel_crtc->active)
11759                         continue;
11760
11761                 /* planes */
11762                 for_each_plane(dev_priv, pipe, plane) {
11763                         hw_entry = &hw_ddb.plane[pipe][plane];
11764                         sw_entry = &sw_ddb->plane[pipe][plane];
11765
11766                         if (skl_ddb_entry_equal(hw_entry, sw_entry))
11767                                 continue;
11768
11769                         DRM_ERROR("mismatch in DDB state pipe %c plane %d "
11770                                   "(expected (%u,%u), found (%u,%u))\n",
11771                                   pipe_name(pipe), plane + 1,
11772                                   sw_entry->start, sw_entry->end,
11773                                   hw_entry->start, hw_entry->end);
11774                 }
11775
11776                 /* cursor */
11777                 hw_entry = &hw_ddb.cursor[pipe];
11778                 sw_entry = &sw_ddb->cursor[pipe];
11779
11780                 if (skl_ddb_entry_equal(hw_entry, sw_entry))
11781                         continue;
11782
11783                 DRM_ERROR("mismatch in DDB state pipe %c cursor "
11784                           "(expected (%u,%u), found (%u,%u))\n",
11785                           pipe_name(pipe),
11786                           sw_entry->start, sw_entry->end,
11787                           hw_entry->start, hw_entry->end);
11788         }
11789 }
11790
11791 static void
11792 check_connector_state(struct drm_device *dev)
11793 {
11794         struct intel_connector *connector;
11795
11796         for_each_intel_connector(dev, connector) {
11797                 /* This also checks the encoder/connector hw state with the
11798                  * ->get_hw_state callbacks. */
11799                 intel_connector_check_state(connector);
11800
11801                 I915_STATE_WARN(&connector->new_encoder->base != connector->base.encoder,
11802                      "connector's staged encoder doesn't match current encoder\n");
11803         }
11804 }
11805
11806 static void
11807 check_encoder_state(struct drm_device *dev)
11808 {
11809         struct intel_encoder *encoder;
11810         struct intel_connector *connector;
11811
11812         for_each_intel_encoder(dev, encoder) {
11813                 bool enabled = false;
11814                 bool active = false;
11815                 enum pipe pipe, tracked_pipe;
11816
11817                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
11818                               encoder->base.base.id,
11819                               encoder->base.name);
11820
11821                 I915_STATE_WARN(&encoder->new_crtc->base != encoder->base.crtc,
11822                      "encoder's stage crtc doesn't match current crtc\n");
11823                 I915_STATE_WARN(encoder->connectors_active && !encoder->base.crtc,
11824                      "encoder's active_connectors set, but no crtc\n");
11825
11826                 for_each_intel_connector(dev, connector) {
11827                         if (connector->base.encoder != &encoder->base)
11828                                 continue;
11829                         enabled = true;
11830                         if (connector->base.dpms != DRM_MODE_DPMS_OFF)
11831                                 active = true;
11832                 }
11833                 /*
11834                  * for MST connectors if we unplug the connector is gone
11835                  * away but the encoder is still connected to a crtc
11836                  * until a modeset happens in response to the hotplug.
11837                  */
11838                 if (!enabled && encoder->base.encoder_type == DRM_MODE_ENCODER_DPMST)
11839                         continue;
11840
11841                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
11842                      "encoder's enabled state mismatch "
11843                      "(expected %i, found %i)\n",
11844                      !!encoder->base.crtc, enabled);
11845                 I915_STATE_WARN(active && !encoder->base.crtc,
11846                      "active encoder with no crtc\n");
11847
11848                 I915_STATE_WARN(encoder->connectors_active != active,
11849                      "encoder's computed active state doesn't match tracked active state "
11850                      "(expected %i, found %i)\n", active, encoder->connectors_active);
11851
11852                 active = encoder->get_hw_state(encoder, &pipe);
11853                 I915_STATE_WARN(active != encoder->connectors_active,
11854                      "encoder's hw state doesn't match sw tracking "
11855                      "(expected %i, found %i)\n",
11856                      encoder->connectors_active, active);
11857
11858                 if (!encoder->base.crtc)
11859                         continue;
11860
11861                 tracked_pipe = to_intel_crtc(encoder->base.crtc)->pipe;
11862                 I915_STATE_WARN(active && pipe != tracked_pipe,
11863                      "active encoder's pipe doesn't match"
11864                      "(expected %i, found %i)\n",
11865                      tracked_pipe, pipe);
11866
11867         }
11868 }
11869
11870 static void
11871 check_crtc_state(struct drm_device *dev)
11872 {
11873         struct drm_i915_private *dev_priv = dev->dev_private;
11874         struct intel_crtc *crtc;
11875         struct intel_encoder *encoder;
11876         struct intel_crtc_state pipe_config;
11877
11878         for_each_intel_crtc(dev, crtc) {
11879                 bool enabled = false;
11880                 bool active = false;
11881
11882                 memset(&pipe_config, 0, sizeof(pipe_config));
11883
11884                 DRM_DEBUG_KMS("[CRTC:%d]\n",
11885                               crtc->base.base.id);
11886
11887                 I915_STATE_WARN(crtc->active && !crtc->base.state->enable,
11888                      "active crtc, but not enabled in sw tracking\n");
11889
11890                 for_each_intel_encoder(dev, encoder) {
11891                         if (encoder->base.crtc != &crtc->base)
11892                                 continue;
11893                         enabled = true;
11894                         if (encoder->connectors_active)
11895                                 active = true;
11896                 }
11897
11898                 I915_STATE_WARN(active != crtc->active,
11899                      "crtc's computed active state doesn't match tracked active state "
11900                      "(expected %i, found %i)\n", active, crtc->active);
11901                 I915_STATE_WARN(enabled != crtc->base.state->enable,
11902                      "crtc's computed enabled state doesn't match tracked enabled state "
11903                      "(expected %i, found %i)\n", enabled,
11904                                 crtc->base.state->enable);
11905
11906                 active = dev_priv->display.get_pipe_config(crtc,
11907                                                            &pipe_config);
11908
11909                 /* hw state is inconsistent with the pipe quirk */
11910                 if ((crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
11911                     (crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
11912                         active = crtc->active;
11913
11914                 for_each_intel_encoder(dev, encoder) {
11915                         enum pipe pipe;
11916                         if (encoder->base.crtc != &crtc->base)
11917                                 continue;
11918                         if (encoder->get_hw_state(encoder, &pipe))
11919                                 encoder->get_config(encoder, &pipe_config);
11920                 }
11921
11922                 I915_STATE_WARN(crtc->active != active,
11923                      "crtc active state doesn't match with hw state "
11924                      "(expected %i, found %i)\n", crtc->active, active);
11925
11926                 if (active &&
11927                     !intel_pipe_config_compare(dev, crtc->config, &pipe_config)) {
11928                         I915_STATE_WARN(1, "pipe state doesn't match!\n");
11929                         intel_dump_pipe_config(crtc, &pipe_config,
11930                                                "[hw state]");
11931                         intel_dump_pipe_config(crtc, crtc->config,
11932                                                "[sw state]");
11933                 }
11934         }
11935 }
11936
11937 static void
11938 check_shared_dpll_state(struct drm_device *dev)
11939 {
11940         struct drm_i915_private *dev_priv = dev->dev_private;
11941         struct intel_crtc *crtc;
11942         struct intel_dpll_hw_state dpll_hw_state;
11943         int i;
11944
11945         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
11946                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
11947                 int enabled_crtcs = 0, active_crtcs = 0;
11948                 bool active;
11949
11950                 memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
11951
11952                 DRM_DEBUG_KMS("%s\n", pll->name);
11953
11954                 active = pll->get_hw_state(dev_priv, pll, &dpll_hw_state);
11955
11956                 I915_STATE_WARN(pll->active > hweight32(pll->config.crtc_mask),
11957                      "more active pll users than references: %i vs %i\n",
11958                      pll->active, hweight32(pll->config.crtc_mask));
11959                 I915_STATE_WARN(pll->active && !pll->on,
11960                      "pll in active use but not on in sw tracking\n");
11961                 I915_STATE_WARN(pll->on && !pll->active,
11962                      "pll in on but not on in use in sw tracking\n");
11963                 I915_STATE_WARN(pll->on != active,
11964                      "pll on state mismatch (expected %i, found %i)\n",
11965                      pll->on, active);
11966
11967                 for_each_intel_crtc(dev, crtc) {
11968                         if (crtc->base.state->enable && intel_crtc_to_shared_dpll(crtc) == pll)
11969                                 enabled_crtcs++;
11970                         if (crtc->active && intel_crtc_to_shared_dpll(crtc) == pll)
11971                                 active_crtcs++;
11972                 }
11973                 I915_STATE_WARN(pll->active != active_crtcs,
11974                      "pll active crtcs mismatch (expected %i, found %i)\n",
11975                      pll->active, active_crtcs);
11976                 I915_STATE_WARN(hweight32(pll->config.crtc_mask) != enabled_crtcs,
11977                      "pll enabled crtcs mismatch (expected %i, found %i)\n",
11978                      hweight32(pll->config.crtc_mask), enabled_crtcs);
11979
11980                 I915_STATE_WARN(pll->on && memcmp(&pll->config.hw_state, &dpll_hw_state,
11981                                        sizeof(dpll_hw_state)),
11982                      "pll hw state mismatch\n");
11983         }
11984 }
11985
11986 void
11987 intel_modeset_check_state(struct drm_device *dev)
11988 {
11989         check_wm_state(dev);
11990         check_connector_state(dev);
11991         check_encoder_state(dev);
11992         check_crtc_state(dev);
11993         check_shared_dpll_state(dev);
11994 }
11995
11996 void ironlake_check_encoder_dotclock(const struct intel_crtc_state *pipe_config,
11997                                      int dotclock)
11998 {
11999         /*
12000          * FDI already provided one idea for the dotclock.
12001          * Yell if the encoder disagrees.
12002          */
12003         WARN(!intel_fuzzy_clock_check(pipe_config->base.adjusted_mode.crtc_clock, dotclock),
12004              "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
12005              pipe_config->base.adjusted_mode.crtc_clock, dotclock);
12006 }
12007
12008 static void update_scanline_offset(struct intel_crtc *crtc)
12009 {
12010         struct drm_device *dev = crtc->base.dev;
12011
12012         /*
12013          * The scanline counter increments at the leading edge of hsync.
12014          *
12015          * On most platforms it starts counting from vtotal-1 on the
12016          * first active line. That means the scanline counter value is
12017          * always one less than what we would expect. Ie. just after
12018          * start of vblank, which also occurs at start of hsync (on the
12019          * last active line), the scanline counter will read vblank_start-1.
12020          *
12021          * On gen2 the scanline counter starts counting from 1 instead
12022          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
12023          * to keep the value positive), instead of adding one.
12024          *
12025          * On HSW+ the behaviour of the scanline counter depends on the output
12026          * type. For DP ports it behaves like most other platforms, but on HDMI
12027          * there's an extra 1 line difference. So we need to add two instead of
12028          * one to the value.
12029          */
12030         if (IS_GEN2(dev)) {
12031                 const struct drm_display_mode *mode = &crtc->config->base.adjusted_mode;
12032                 int vtotal;
12033
12034                 vtotal = mode->crtc_vtotal;
12035                 if (mode->flags & DRM_MODE_FLAG_INTERLACE)
12036                         vtotal /= 2;
12037
12038                 crtc->scanline_offset = vtotal - 1;
12039         } else if (HAS_DDI(dev) &&
12040                    intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI)) {
12041                 crtc->scanline_offset = 2;
12042         } else
12043                 crtc->scanline_offset = 1;
12044 }
12045
12046 static struct intel_crtc_state *
12047 intel_modeset_compute_config(struct drm_crtc *crtc,
12048                              struct drm_display_mode *mode,
12049                              struct drm_atomic_state *state,
12050                              unsigned *modeset_pipes,
12051                              unsigned *prepare_pipes,
12052                              unsigned *disable_pipes)
12053 {
12054         struct drm_device *dev = crtc->dev;
12055         struct intel_crtc_state *pipe_config = NULL;
12056         struct intel_crtc *intel_crtc;
12057         int ret = 0;
12058
12059         ret = drm_atomic_add_affected_connectors(state, crtc);
12060         if (ret)
12061                 return ERR_PTR(ret);
12062
12063         intel_modeset_affected_pipes(crtc, modeset_pipes,
12064                                      prepare_pipes, disable_pipes);
12065
12066         for_each_intel_crtc_masked(dev, *disable_pipes, intel_crtc) {
12067                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
12068                 if (IS_ERR(pipe_config))
12069                         return pipe_config;
12070
12071                 pipe_config->base.enable = false;
12072         }
12073
12074         /*
12075          * Note this needs changes when we start tracking multiple modes
12076          * and crtcs.  At that point we'll need to compute the whole config
12077          * (i.e. one pipe_config for each crtc) rather than just the one
12078          * for this crtc.
12079          */
12080         for_each_intel_crtc_masked(dev, *modeset_pipes, intel_crtc) {
12081                 /* FIXME: For now we still expect modeset_pipes has at most
12082                  * one bit set. */
12083                 if (WARN_ON(&intel_crtc->base != crtc))
12084                         continue;
12085
12086                 pipe_config = intel_modeset_pipe_config(crtc, mode, state);
12087                 if (IS_ERR(pipe_config))
12088                         return pipe_config;
12089
12090                 pipe_config->base.enable = true;
12091
12092                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
12093                                        "[modeset]");
12094         }
12095
12096         return intel_atomic_get_crtc_state(state, to_intel_crtc(crtc));;
12097 }
12098
12099 static int __intel_set_mode_setup_plls(struct drm_atomic_state *state,
12100                                        unsigned modeset_pipes,
12101                                        unsigned disable_pipes)
12102 {
12103         struct drm_device *dev = state->dev;
12104         struct drm_i915_private *dev_priv = to_i915(dev);
12105         unsigned clear_pipes = modeset_pipes | disable_pipes;
12106         struct intel_crtc *intel_crtc;
12107         int ret = 0;
12108
12109         if (!dev_priv->display.crtc_compute_clock)
12110                 return 0;
12111
12112         ret = intel_shared_dpll_start_config(dev_priv, clear_pipes);
12113         if (ret)
12114                 goto done;
12115
12116         for_each_intel_crtc_masked(dev, modeset_pipes, intel_crtc) {
12117                 struct intel_crtc_state *crtc_state =
12118                         intel_atomic_get_crtc_state(state, intel_crtc);
12119
12120                 /* Modeset pipes should have a new state by now */
12121                 if (WARN_ON(IS_ERR(crtc_state)))
12122                         continue;
12123
12124                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
12125                                                            crtc_state);
12126                 if (ret) {
12127                         intel_shared_dpll_abort_config(dev_priv);
12128                         goto done;
12129                 }
12130         }
12131
12132 done:
12133         return ret;
12134 }
12135
12136 static int __intel_set_mode(struct drm_crtc *crtc,
12137                             struct drm_display_mode *mode,
12138                             int x, int y, struct drm_framebuffer *fb,
12139                             struct intel_crtc_state *pipe_config,
12140                             unsigned modeset_pipes,
12141                             unsigned prepare_pipes,
12142                             unsigned disable_pipes)
12143 {
12144         struct drm_device *dev = crtc->dev;
12145         struct drm_i915_private *dev_priv = dev->dev_private;
12146         struct drm_display_mode *saved_mode;
12147         struct drm_atomic_state *state = pipe_config->base.state;
12148         struct intel_crtc_state *crtc_state_copy = NULL;
12149         struct intel_crtc *intel_crtc;
12150         int ret = 0;
12151
12152         saved_mode = kmalloc(sizeof(*saved_mode), GFP_KERNEL);
12153         if (!saved_mode)
12154                 return -ENOMEM;
12155
12156         crtc_state_copy = kmalloc(sizeof(*crtc_state_copy), GFP_KERNEL);
12157         if (!crtc_state_copy) {
12158                 ret = -ENOMEM;
12159                 goto done;
12160         }
12161
12162         *saved_mode = crtc->mode;
12163
12164         /*
12165          * See if the config requires any additional preparation, e.g.
12166          * to adjust global state with pipes off.  We need to do this
12167          * here so we can get the modeset_pipe updated config for the new
12168          * mode set on this crtc.  For other crtcs we need to use the
12169          * adjusted_mode bits in the crtc directly.
12170          */
12171         if (IS_VALLEYVIEW(dev) || IS_BROXTON(dev)) {
12172                 ret = valleyview_modeset_global_pipes(state, &prepare_pipes);
12173                 if (ret)
12174                         goto done;
12175
12176                 /* may have added more to prepare_pipes than we should */
12177                 prepare_pipes &= ~disable_pipes;
12178         }
12179
12180         ret = __intel_set_mode_setup_plls(state, modeset_pipes, disable_pipes);
12181         if (ret)
12182                 goto done;
12183
12184         for_each_intel_crtc_masked(dev, disable_pipes, intel_crtc)
12185                 intel_crtc_disable(&intel_crtc->base);
12186
12187         for_each_intel_crtc_masked(dev, prepare_pipes, intel_crtc) {
12188                 if (intel_crtc->base.state->enable)
12189                         dev_priv->display.crtc_disable(&intel_crtc->base);
12190         }
12191
12192         /* crtc->mode is already used by the ->mode_set callbacks, hence we need
12193          * to set it here already despite that we pass it down the callchain.
12194          *
12195          * Note we'll need to fix this up when we start tracking multiple
12196          * pipes; here we assume a single modeset_pipe and only track the
12197          * single crtc and mode.
12198          */
12199         if (modeset_pipes) {
12200                 crtc->mode = *mode;
12201                 /* mode_set/enable/disable functions rely on a correct pipe
12202                  * config. */
12203                 intel_crtc_set_state(to_intel_crtc(crtc), pipe_config);
12204
12205                 /*
12206                  * Calculate and store various constants which
12207                  * are later needed by vblank and swap-completion
12208                  * timestamping. They are derived from true hwmode.
12209                  */
12210                 drm_calc_timestamping_constants(crtc,
12211                                                 &pipe_config->base.adjusted_mode);
12212         }
12213
12214         /* Only after disabling all output pipelines that will be changed can we
12215          * update the the output configuration. */
12216         intel_modeset_update_state(dev, prepare_pipes);
12217
12218         modeset_update_crtc_power_domains(state);
12219
12220         for_each_intel_crtc_masked(dev, modeset_pipes, intel_crtc) {
12221                 struct drm_plane *primary = intel_crtc->base.primary;
12222                 int vdisplay, hdisplay;
12223
12224                 drm_crtc_get_hv_timing(mode, &hdisplay, &vdisplay);
12225                 ret = drm_plane_helper_update(primary, &intel_crtc->base,
12226                                               fb, 0, 0,
12227                                               hdisplay, vdisplay,
12228                                               x << 16, y << 16,
12229                                               hdisplay << 16, vdisplay << 16);
12230         }
12231
12232         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
12233         for_each_intel_crtc_masked(dev, prepare_pipes, intel_crtc) {
12234                 update_scanline_offset(intel_crtc);
12235
12236                 dev_priv->display.crtc_enable(&intel_crtc->base);
12237         }
12238
12239         /* FIXME: add subpixel order */
12240 done:
12241         if (ret && crtc->state->enable)
12242                 crtc->mode = *saved_mode;
12243
12244         if (ret == 0 && pipe_config) {
12245                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12246
12247                 /* The pipe_config will be freed with the atomic state, so
12248                  * make a copy. */
12249                 memcpy(crtc_state_copy, intel_crtc->config,
12250                        sizeof *crtc_state_copy);
12251                 intel_crtc->config = crtc_state_copy;
12252                 intel_crtc->base.state = &crtc_state_copy->base;
12253         } else {
12254                 kfree(crtc_state_copy);
12255         }
12256
12257         kfree(saved_mode);
12258         return ret;
12259 }
12260
12261 static int intel_set_mode_pipes(struct drm_crtc *crtc,
12262                                 struct drm_display_mode *mode,
12263                                 int x, int y, struct drm_framebuffer *fb,
12264                                 struct intel_crtc_state *pipe_config,
12265                                 unsigned modeset_pipes,
12266                                 unsigned prepare_pipes,
12267                                 unsigned disable_pipes)
12268 {
12269         int ret;
12270
12271         ret = __intel_set_mode(crtc, mode, x, y, fb, pipe_config, modeset_pipes,
12272                                prepare_pipes, disable_pipes);
12273
12274         if (ret == 0)
12275                 intel_modeset_check_state(crtc->dev);
12276
12277         return ret;
12278 }
12279
12280 static int intel_set_mode(struct drm_crtc *crtc,
12281                           struct drm_display_mode *mode,
12282                           int x, int y, struct drm_framebuffer *fb,
12283                           struct drm_atomic_state *state)
12284 {
12285         struct intel_crtc_state *pipe_config;
12286         unsigned modeset_pipes, prepare_pipes, disable_pipes;
12287         int ret = 0;
12288
12289         pipe_config = intel_modeset_compute_config(crtc, mode, state,
12290                                                    &modeset_pipes,
12291                                                    &prepare_pipes,
12292                                                    &disable_pipes);
12293
12294         if (IS_ERR(pipe_config)) {
12295                 ret = PTR_ERR(pipe_config);
12296                 goto out;
12297         }
12298
12299         ret = intel_set_mode_pipes(crtc, mode, x, y, fb, pipe_config,
12300                                    modeset_pipes, prepare_pipes,
12301                                    disable_pipes);
12302         if (ret)
12303                 goto out;
12304
12305 out:
12306         return ret;
12307 }
12308
12309 void intel_crtc_restore_mode(struct drm_crtc *crtc)
12310 {
12311         struct drm_device *dev = crtc->dev;
12312         struct drm_atomic_state *state;
12313         struct intel_encoder *encoder;
12314         struct intel_connector *connector;
12315         struct drm_connector_state *connector_state;
12316
12317         state = drm_atomic_state_alloc(dev);
12318         if (!state) {
12319                 DRM_DEBUG_KMS("[CRTC:%d] mode restore failed, out of memory",
12320                               crtc->base.id);
12321                 return;
12322         }
12323
12324         state->acquire_ctx = dev->mode_config.acquire_ctx;
12325
12326         /* The force restore path in the HW readout code relies on the staged
12327          * config still keeping the user requested config while the actual
12328          * state has been overwritten by the configuration read from HW. We
12329          * need to copy the staged config to the atomic state, otherwise the
12330          * mode set will just reapply the state the HW is already in. */
12331         for_each_intel_encoder(dev, encoder) {
12332                 if (&encoder->new_crtc->base != crtc)
12333                         continue;
12334
12335                 for_each_intel_connector(dev, connector) {
12336                         if (connector->new_encoder != encoder)
12337                                 continue;
12338
12339                         connector_state = drm_atomic_get_connector_state(state, &connector->base);
12340                         if (IS_ERR(connector_state)) {
12341                                 DRM_DEBUG_KMS("Failed to add [CONNECTOR:%d:%s] to state: %ld\n",
12342                                               connector->base.base.id,
12343                                               connector->base.name,
12344                                               PTR_ERR(connector_state));
12345                                 continue;
12346                         }
12347
12348                         connector_state->crtc = crtc;
12349                         connector_state->best_encoder = &encoder->base;
12350                 }
12351         }
12352
12353         intel_set_mode(crtc, &crtc->mode, crtc->x, crtc->y, crtc->primary->fb,
12354                        state);
12355
12356         drm_atomic_state_free(state);
12357 }
12358
12359 #undef for_each_intel_crtc_masked
12360
12361 static void intel_set_config_free(struct intel_set_config *config)
12362 {
12363         if (!config)
12364                 return;
12365
12366         kfree(config->save_connector_encoders);
12367         kfree(config->save_encoder_crtcs);
12368         kfree(config->save_crtc_enabled);
12369         kfree(config);
12370 }
12371
12372 static int intel_set_config_save_state(struct drm_device *dev,
12373                                        struct intel_set_config *config)
12374 {
12375         struct drm_crtc *crtc;
12376         struct drm_encoder *encoder;
12377         struct drm_connector *connector;
12378         int count;
12379
12380         config->save_crtc_enabled =
12381                 kcalloc(dev->mode_config.num_crtc,
12382                         sizeof(bool), GFP_KERNEL);
12383         if (!config->save_crtc_enabled)
12384                 return -ENOMEM;
12385
12386         config->save_encoder_crtcs =
12387                 kcalloc(dev->mode_config.num_encoder,
12388                         sizeof(struct drm_crtc *), GFP_KERNEL);
12389         if (!config->save_encoder_crtcs)
12390                 return -ENOMEM;
12391
12392         config->save_connector_encoders =
12393                 kcalloc(dev->mode_config.num_connector,
12394                         sizeof(struct drm_encoder *), GFP_KERNEL);
12395         if (!config->save_connector_encoders)
12396                 return -ENOMEM;
12397
12398         /* Copy data. Note that driver private data is not affected.
12399          * Should anything bad happen only the expected state is
12400          * restored, not the drivers personal bookkeeping.
12401          */
12402         count = 0;
12403         for_each_crtc(dev, crtc) {
12404                 config->save_crtc_enabled[count++] = crtc->state->enable;
12405         }
12406
12407         count = 0;
12408         list_for_each_entry(encoder, &dev->mode_config.encoder_list, head) {
12409                 config->save_encoder_crtcs[count++] = encoder->crtc;
12410         }
12411
12412         count = 0;
12413         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
12414                 config->save_connector_encoders[count++] = connector->encoder;
12415         }
12416
12417         return 0;
12418 }
12419
12420 static void intel_set_config_restore_state(struct drm_device *dev,
12421                                            struct intel_set_config *config)
12422 {
12423         struct intel_crtc *crtc;
12424         struct intel_encoder *encoder;
12425         struct intel_connector *connector;
12426         int count;
12427
12428         count = 0;
12429         for_each_intel_crtc(dev, crtc) {
12430                 crtc->new_enabled = config->save_crtc_enabled[count++];
12431         }
12432
12433         count = 0;
12434         for_each_intel_encoder(dev, encoder) {
12435                 encoder->new_crtc =
12436                         to_intel_crtc(config->save_encoder_crtcs[count++]);
12437         }
12438
12439         count = 0;
12440         for_each_intel_connector(dev, connector) {
12441                 connector->new_encoder =
12442                         to_intel_encoder(config->save_connector_encoders[count++]);
12443         }
12444 }
12445
12446 static bool
12447 is_crtc_connector_off(struct drm_mode_set *set)
12448 {
12449         int i;
12450
12451         if (set->num_connectors == 0)
12452                 return false;
12453
12454         if (WARN_ON(set->connectors == NULL))
12455                 return false;
12456
12457         for (i = 0; i < set->num_connectors; i++)
12458                 if (set->connectors[i]->encoder &&
12459                     set->connectors[i]->encoder->crtc == set->crtc &&
12460                     set->connectors[i]->dpms != DRM_MODE_DPMS_ON)
12461                         return true;
12462
12463         return false;
12464 }
12465
12466 static void
12467 intel_set_config_compute_mode_changes(struct drm_mode_set *set,
12468                                       struct intel_set_config *config)
12469 {
12470
12471         /* We should be able to check here if the fb has the same properties
12472          * and then just flip_or_move it */
12473         if (is_crtc_connector_off(set)) {
12474                 config->mode_changed = true;
12475         } else if (set->crtc->primary->fb != set->fb) {
12476                 /*
12477                  * If we have no fb, we can only flip as long as the crtc is
12478                  * active, otherwise we need a full mode set.  The crtc may
12479                  * be active if we've only disabled the primary plane, or
12480                  * in fastboot situations.
12481                  */
12482                 if (set->crtc->primary->fb == NULL) {
12483                         struct intel_crtc *intel_crtc =
12484                                 to_intel_crtc(set->crtc);
12485
12486                         if (intel_crtc->active) {
12487                                 DRM_DEBUG_KMS("crtc has no fb, will flip\n");
12488                                 config->fb_changed = true;
12489                         } else {
12490                                 DRM_DEBUG_KMS("inactive crtc, full mode set\n");
12491                                 config->mode_changed = true;
12492                         }
12493                 } else if (set->fb == NULL) {
12494                         config->mode_changed = true;
12495                 } else if (set->fb->pixel_format !=
12496                            set->crtc->primary->fb->pixel_format) {
12497                         config->mode_changed = true;
12498                 } else {
12499                         config->fb_changed = true;
12500                 }
12501         }
12502
12503         if (set->fb && (set->x != set->crtc->x || set->y != set->crtc->y))
12504                 config->fb_changed = true;
12505
12506         if (set->mode && !drm_mode_equal(set->mode, &set->crtc->mode)) {
12507                 DRM_DEBUG_KMS("modes are different, full mode set\n");
12508                 drm_mode_debug_printmodeline(&set->crtc->mode);
12509                 drm_mode_debug_printmodeline(set->mode);
12510                 config->mode_changed = true;
12511         }
12512
12513         DRM_DEBUG_KMS("computed changes for [CRTC:%d], mode_changed=%d, fb_changed=%d\n",
12514                         set->crtc->base.id, config->mode_changed, config->fb_changed);
12515 }
12516
12517 static int
12518 intel_modeset_stage_output_state(struct drm_device *dev,
12519                                  struct drm_mode_set *set,
12520                                  struct intel_set_config *config,
12521                                  struct drm_atomic_state *state)
12522 {
12523         struct intel_connector *connector;
12524         struct drm_connector_state *connector_state;
12525         struct intel_encoder *encoder;
12526         struct intel_crtc *crtc;
12527         int ro;
12528
12529         /* The upper layers ensure that we either disable a crtc or have a list
12530          * of connectors. For paranoia, double-check this. */
12531         WARN_ON(!set->fb && (set->num_connectors != 0));
12532         WARN_ON(set->fb && (set->num_connectors == 0));
12533
12534         for_each_intel_connector(dev, connector) {
12535                 /* Otherwise traverse passed in connector list and get encoders
12536                  * for them. */
12537                 for (ro = 0; ro < set->num_connectors; ro++) {
12538                         if (set->connectors[ro] == &connector->base) {
12539                                 connector->new_encoder = intel_find_encoder(connector, to_intel_crtc(set->crtc)->pipe);
12540                                 break;
12541                         }
12542                 }
12543
12544                 /* If we disable the crtc, disable all its connectors. Also, if
12545                  * the connector is on the changing crtc but not on the new
12546                  * connector list, disable it. */
12547                 if ((!set->fb || ro == set->num_connectors) &&
12548                     connector->base.encoder &&
12549                     connector->base.encoder->crtc == set->crtc) {
12550                         connector->new_encoder = NULL;
12551
12552                         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] to [NOCRTC]\n",
12553                                 connector->base.base.id,
12554                                 connector->base.name);
12555                 }
12556
12557
12558                 if (&connector->new_encoder->base != connector->base.encoder) {
12559                         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] encoder changed, full mode switch\n",
12560                                       connector->base.base.id,
12561                                       connector->base.name);
12562                         config->mode_changed = true;
12563                 }
12564         }
12565         /* connector->new_encoder is now updated for all connectors. */
12566
12567         /* Update crtc of enabled connectors. */
12568         for_each_intel_connector(dev, connector) {
12569                 struct drm_crtc *new_crtc;
12570
12571                 if (!connector->new_encoder)
12572                         continue;
12573
12574                 new_crtc = connector->new_encoder->base.crtc;
12575
12576                 for (ro = 0; ro < set->num_connectors; ro++) {
12577                         if (set->connectors[ro] == &connector->base)
12578                                 new_crtc = set->crtc;
12579                 }
12580
12581                 /* Make sure the new CRTC will work with the encoder */
12582                 if (!drm_encoder_crtc_ok(&connector->new_encoder->base,
12583                                          new_crtc)) {
12584                         return -EINVAL;
12585                 }
12586                 connector->new_encoder->new_crtc = to_intel_crtc(new_crtc);
12587
12588                 connector_state =
12589                         drm_atomic_get_connector_state(state, &connector->base);
12590                 if (IS_ERR(connector_state))
12591                         return PTR_ERR(connector_state);
12592
12593                 connector_state->crtc = new_crtc;
12594                 connector_state->best_encoder = &connector->new_encoder->base;
12595
12596                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] to [CRTC:%d]\n",
12597                         connector->base.base.id,
12598                         connector->base.name,
12599                         new_crtc->base.id);
12600         }
12601
12602         /* Check for any encoders that needs to be disabled. */
12603         for_each_intel_encoder(dev, encoder) {
12604                 int num_connectors = 0;
12605                 for_each_intel_connector(dev, connector) {
12606                         if (connector->new_encoder == encoder) {
12607                                 WARN_ON(!connector->new_encoder->new_crtc);
12608                                 num_connectors++;
12609                         }
12610                 }
12611
12612                 if (num_connectors == 0)
12613                         encoder->new_crtc = NULL;
12614                 else if (num_connectors > 1)
12615                         return -EINVAL;
12616
12617                 /* Only now check for crtc changes so we don't miss encoders
12618                  * that will be disabled. */
12619                 if (&encoder->new_crtc->base != encoder->base.crtc) {
12620                         DRM_DEBUG_KMS("[ENCODER:%d:%s] crtc changed, full mode switch\n",
12621                                       encoder->base.base.id,
12622                                       encoder->base.name);
12623                         config->mode_changed = true;
12624                 }
12625         }
12626         /* Now we've also updated encoder->new_crtc for all encoders. */
12627         for_each_intel_connector(dev, connector) {
12628                 connector_state =
12629                         drm_atomic_get_connector_state(state, &connector->base);
12630                 if (IS_ERR(connector_state))
12631                         return PTR_ERR(connector_state);
12632
12633                 if (connector->new_encoder) {
12634                         if (connector->new_encoder != connector->encoder)
12635                                 connector->encoder = connector->new_encoder;
12636                 } else {
12637                         connector_state->crtc = NULL;
12638                         connector_state->best_encoder = NULL;
12639                 }
12640         }
12641         for_each_intel_crtc(dev, crtc) {
12642                 crtc->new_enabled = false;
12643
12644                 for_each_intel_encoder(dev, encoder) {
12645                         if (encoder->new_crtc == crtc) {
12646                                 crtc->new_enabled = true;
12647                                 break;
12648                         }
12649                 }
12650
12651                 if (crtc->new_enabled != crtc->base.state->enable) {
12652                         DRM_DEBUG_KMS("[CRTC:%d] %sabled, full mode switch\n",
12653                                       crtc->base.base.id,
12654                                       crtc->new_enabled ? "en" : "dis");
12655                         config->mode_changed = true;
12656                 }
12657         }
12658
12659         return 0;
12660 }
12661
12662 static void disable_crtc_nofb(struct intel_crtc *crtc)
12663 {
12664         struct drm_device *dev = crtc->base.dev;
12665         struct intel_encoder *encoder;
12666         struct intel_connector *connector;
12667
12668         DRM_DEBUG_KMS("Trying to restore without FB -> disabling pipe %c\n",
12669                       pipe_name(crtc->pipe));
12670
12671         for_each_intel_connector(dev, connector) {
12672                 if (connector->new_encoder &&
12673                     connector->new_encoder->new_crtc == crtc)
12674                         connector->new_encoder = NULL;
12675         }
12676
12677         for_each_intel_encoder(dev, encoder) {
12678                 if (encoder->new_crtc == crtc)
12679                         encoder->new_crtc = NULL;
12680         }
12681
12682         crtc->new_enabled = false;
12683 }
12684
12685 static int intel_crtc_set_config(struct drm_mode_set *set)
12686 {
12687         struct drm_device *dev;
12688         struct drm_mode_set save_set;
12689         struct drm_atomic_state *state = NULL;
12690         struct intel_set_config *config;
12691         struct intel_crtc_state *pipe_config;
12692         unsigned modeset_pipes, prepare_pipes, disable_pipes;
12693         int ret;
12694
12695         BUG_ON(!set);
12696         BUG_ON(!set->crtc);
12697         BUG_ON(!set->crtc->helper_private);
12698
12699         /* Enforce sane interface api - has been abused by the fb helper. */
12700         BUG_ON(!set->mode && set->fb);
12701         BUG_ON(set->fb && set->num_connectors == 0);
12702
12703         if (set->fb) {
12704                 DRM_DEBUG_KMS("[CRTC:%d] [FB:%d] #connectors=%d (x y) (%i %i)\n",
12705                                 set->crtc->base.id, set->fb->base.id,
12706                                 (int)set->num_connectors, set->x, set->y);
12707         } else {
12708                 DRM_DEBUG_KMS("[CRTC:%d] [NOFB]\n", set->crtc->base.id);
12709         }
12710
12711         dev = set->crtc->dev;
12712
12713         ret = -ENOMEM;
12714         config = kzalloc(sizeof(*config), GFP_KERNEL);
12715         if (!config)
12716                 goto out_config;
12717
12718         ret = intel_set_config_save_state(dev, config);
12719         if (ret)
12720                 goto out_config;
12721
12722         save_set.crtc = set->crtc;
12723         save_set.mode = &set->crtc->mode;
12724         save_set.x = set->crtc->x;
12725         save_set.y = set->crtc->y;
12726         save_set.fb = set->crtc->primary->fb;
12727
12728         /* Compute whether we need a full modeset, only an fb base update or no
12729          * change at all. In the future we might also check whether only the
12730          * mode changed, e.g. for LVDS where we only change the panel fitter in
12731          * such cases. */
12732         intel_set_config_compute_mode_changes(set, config);
12733
12734         state = drm_atomic_state_alloc(dev);
12735         if (!state) {
12736                 ret = -ENOMEM;
12737                 goto out_config;
12738         }
12739
12740         state->acquire_ctx = dev->mode_config.acquire_ctx;
12741
12742         ret = intel_modeset_stage_output_state(dev, set, config, state);
12743         if (ret)
12744                 goto fail;
12745
12746         pipe_config = intel_modeset_compute_config(set->crtc, set->mode,
12747                                                    state,
12748                                                    &modeset_pipes,
12749                                                    &prepare_pipes,
12750                                                    &disable_pipes);
12751         if (IS_ERR(pipe_config)) {
12752                 ret = PTR_ERR(pipe_config);
12753                 goto fail;
12754         } else if (pipe_config) {
12755                 if (pipe_config->has_audio !=
12756                     to_intel_crtc(set->crtc)->config->has_audio)
12757                         config->mode_changed = true;
12758
12759                 /*
12760                  * Note we have an issue here with infoframes: current code
12761                  * only updates them on the full mode set path per hw
12762                  * requirements.  So here we should be checking for any
12763                  * required changes and forcing a mode set.
12764                  */
12765         }
12766
12767         intel_update_pipe_size(to_intel_crtc(set->crtc));
12768
12769         if (config->mode_changed) {
12770                 ret = intel_set_mode_pipes(set->crtc, set->mode,
12771                                            set->x, set->y, set->fb, pipe_config,
12772                                            modeset_pipes, prepare_pipes,
12773                                            disable_pipes);
12774         } else if (config->fb_changed) {
12775                 struct intel_crtc *intel_crtc = to_intel_crtc(set->crtc);
12776                 struct drm_plane *primary = set->crtc->primary;
12777                 int vdisplay, hdisplay;
12778
12779                 drm_crtc_get_hv_timing(set->mode, &hdisplay, &vdisplay);
12780                 ret = drm_plane_helper_update(primary, set->crtc, set->fb,
12781                                               0, 0, hdisplay, vdisplay,
12782                                               set->x << 16, set->y << 16,
12783                                               hdisplay << 16, vdisplay << 16);
12784
12785                 /*
12786                  * We need to make sure the primary plane is re-enabled if it
12787                  * has previously been turned off.
12788                  */
12789                 if (!intel_crtc->primary_enabled && ret == 0) {
12790                         WARN_ON(!intel_crtc->active);
12791                         intel_enable_primary_hw_plane(set->crtc->primary, set->crtc);
12792                 }
12793
12794                 /*
12795                  * In the fastboot case this may be our only check of the
12796                  * state after boot.  It would be better to only do it on
12797                  * the first update, but we don't have a nice way of doing that
12798                  * (and really, set_config isn't used much for high freq page
12799                  * flipping, so increasing its cost here shouldn't be a big
12800                  * deal).
12801                  */
12802                 if (i915.fastboot && ret == 0)
12803                         intel_modeset_check_state(set->crtc->dev);
12804         }
12805
12806         if (ret) {
12807                 DRM_DEBUG_KMS("failed to set mode on [CRTC:%d], err = %d\n",
12808                               set->crtc->base.id, ret);
12809 fail:
12810                 intel_set_config_restore_state(dev, config);
12811
12812                 drm_atomic_state_clear(state);
12813
12814                 /*
12815                  * HACK: if the pipe was on, but we didn't have a framebuffer,
12816                  * force the pipe off to avoid oopsing in the modeset code
12817                  * due to fb==NULL. This should only happen during boot since
12818                  * we don't yet reconstruct the FB from the hardware state.
12819                  */
12820                 if (to_intel_crtc(save_set.crtc)->new_enabled && !save_set.fb)
12821                         disable_crtc_nofb(to_intel_crtc(save_set.crtc));
12822
12823                 /* Try to restore the config */
12824                 if (config->mode_changed &&
12825                     intel_set_mode(save_set.crtc, save_set.mode,
12826                                    save_set.x, save_set.y, save_set.fb,
12827                                    state))
12828                         DRM_ERROR("failed to restore config after modeset failure\n");
12829         }
12830
12831 out_config:
12832         if (state)
12833                 drm_atomic_state_free(state);
12834
12835         intel_set_config_free(config);
12836         return ret;
12837 }
12838
12839 static const struct drm_crtc_funcs intel_crtc_funcs = {
12840         .gamma_set = intel_crtc_gamma_set,
12841         .set_config = intel_crtc_set_config,
12842         .destroy = intel_crtc_destroy,
12843         .page_flip = intel_crtc_page_flip,
12844         .atomic_duplicate_state = intel_crtc_duplicate_state,
12845         .atomic_destroy_state = intel_crtc_destroy_state,
12846 };
12847
12848 static bool ibx_pch_dpll_get_hw_state(struct drm_i915_private *dev_priv,
12849                                       struct intel_shared_dpll *pll,
12850                                       struct intel_dpll_hw_state *hw_state)
12851 {
12852         uint32_t val;
12853
12854         if (!intel_display_power_is_enabled(dev_priv, POWER_DOMAIN_PLLS))
12855                 return false;
12856
12857         val = I915_READ(PCH_DPLL(pll->id));
12858         hw_state->dpll = val;
12859         hw_state->fp0 = I915_READ(PCH_FP0(pll->id));
12860         hw_state->fp1 = I915_READ(PCH_FP1(pll->id));
12861
12862         return val & DPLL_VCO_ENABLE;
12863 }
12864
12865 static void ibx_pch_dpll_mode_set(struct drm_i915_private *dev_priv,
12866                                   struct intel_shared_dpll *pll)
12867 {
12868         I915_WRITE(PCH_FP0(pll->id), pll->config.hw_state.fp0);
12869         I915_WRITE(PCH_FP1(pll->id), pll->config.hw_state.fp1);
12870 }
12871
12872 static void ibx_pch_dpll_enable(struct drm_i915_private *dev_priv,
12873                                 struct intel_shared_dpll *pll)
12874 {
12875         /* PCH refclock must be enabled first */
12876         ibx_assert_pch_refclk_enabled(dev_priv);
12877
12878         I915_WRITE(PCH_DPLL(pll->id), pll->config.hw_state.dpll);
12879
12880         /* Wait for the clocks to stabilize. */
12881         POSTING_READ(PCH_DPLL(pll->id));
12882         udelay(150);
12883
12884         /* The pixel multiplier can only be updated once the
12885          * DPLL is enabled and the clocks are stable.
12886          *
12887          * So write it again.
12888          */
12889         I915_WRITE(PCH_DPLL(pll->id), pll->config.hw_state.dpll);
12890         POSTING_READ(PCH_DPLL(pll->id));
12891         udelay(200);
12892 }
12893
12894 static void ibx_pch_dpll_disable(struct drm_i915_private *dev_priv,
12895                                  struct intel_shared_dpll *pll)
12896 {
12897         struct drm_device *dev = dev_priv->dev;
12898         struct intel_crtc *crtc;
12899
12900         /* Make sure no transcoder isn't still depending on us. */
12901         for_each_intel_crtc(dev, crtc) {
12902                 if (intel_crtc_to_shared_dpll(crtc) == pll)
12903                         assert_pch_transcoder_disabled(dev_priv, crtc->pipe);
12904         }
12905
12906         I915_WRITE(PCH_DPLL(pll->id), 0);
12907         POSTING_READ(PCH_DPLL(pll->id));
12908         udelay(200);
12909 }
12910
12911 static char *ibx_pch_dpll_names[] = {
12912         "PCH DPLL A",
12913         "PCH DPLL B",
12914 };
12915
12916 static void ibx_pch_dpll_init(struct drm_device *dev)
12917 {
12918         struct drm_i915_private *dev_priv = dev->dev_private;
12919         int i;
12920
12921         dev_priv->num_shared_dpll = 2;
12922
12923         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
12924                 dev_priv->shared_dplls[i].id = i;
12925                 dev_priv->shared_dplls[i].name = ibx_pch_dpll_names[i];
12926                 dev_priv->shared_dplls[i].mode_set = ibx_pch_dpll_mode_set;
12927                 dev_priv->shared_dplls[i].enable = ibx_pch_dpll_enable;
12928                 dev_priv->shared_dplls[i].disable = ibx_pch_dpll_disable;
12929                 dev_priv->shared_dplls[i].get_hw_state =
12930                         ibx_pch_dpll_get_hw_state;
12931         }
12932 }
12933
12934 static void intel_shared_dpll_init(struct drm_device *dev)
12935 {
12936         struct drm_i915_private *dev_priv = dev->dev_private;
12937
12938         if (HAS_DDI(dev))
12939                 intel_ddi_pll_init(dev);
12940         else if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
12941                 ibx_pch_dpll_init(dev);
12942         else
12943                 dev_priv->num_shared_dpll = 0;
12944
12945         BUG_ON(dev_priv->num_shared_dpll > I915_NUM_PLLS);
12946 }
12947
12948 /**
12949  * intel_wm_need_update - Check whether watermarks need updating
12950  * @plane: drm plane
12951  * @state: new plane state
12952  *
12953  * Check current plane state versus the new one to determine whether
12954  * watermarks need to be recalculated.
12955  *
12956  * Returns true or false.
12957  */
12958 bool intel_wm_need_update(struct drm_plane *plane,
12959                           struct drm_plane_state *state)
12960 {
12961         /* Update watermarks on tiling changes. */
12962         if (!plane->state->fb || !state->fb ||
12963             plane->state->fb->modifier[0] != state->fb->modifier[0] ||
12964             plane->state->rotation != state->rotation)
12965                 return true;
12966
12967         return false;
12968 }
12969
12970 /**
12971  * intel_prepare_plane_fb - Prepare fb for usage on plane
12972  * @plane: drm plane to prepare for
12973  * @fb: framebuffer to prepare for presentation
12974  *
12975  * Prepares a framebuffer for usage on a display plane.  Generally this
12976  * involves pinning the underlying object and updating the frontbuffer tracking
12977  * bits.  Some older platforms need special physical address handling for
12978  * cursor planes.
12979  *
12980  * Returns 0 on success, negative error code on failure.
12981  */
12982 int
12983 intel_prepare_plane_fb(struct drm_plane *plane,
12984                        struct drm_framebuffer *fb,
12985                        const struct drm_plane_state *new_state)
12986 {
12987         struct drm_device *dev = plane->dev;
12988         struct intel_plane *intel_plane = to_intel_plane(plane);
12989         enum pipe pipe = intel_plane->pipe;
12990         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
12991         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->fb);
12992         unsigned frontbuffer_bits = 0;
12993         int ret = 0;
12994
12995         if (!obj)
12996                 return 0;
12997
12998         switch (plane->type) {
12999         case DRM_PLANE_TYPE_PRIMARY:
13000                 frontbuffer_bits = INTEL_FRONTBUFFER_PRIMARY(pipe);
13001                 break;
13002         case DRM_PLANE_TYPE_CURSOR:
13003                 frontbuffer_bits = INTEL_FRONTBUFFER_CURSOR(pipe);
13004                 break;
13005         case DRM_PLANE_TYPE_OVERLAY:
13006                 frontbuffer_bits = INTEL_FRONTBUFFER_SPRITE(pipe);
13007                 break;
13008         }
13009
13010         mutex_lock(&dev->struct_mutex);
13011
13012         if (plane->type == DRM_PLANE_TYPE_CURSOR &&
13013             INTEL_INFO(dev)->cursor_needs_physical) {
13014                 int align = IS_I830(dev) ? 16 * 1024 : 256;
13015                 ret = i915_gem_object_attach_phys(obj, align);
13016                 if (ret)
13017                         DRM_DEBUG_KMS("failed to attach phys object\n");
13018         } else {
13019                 ret = intel_pin_and_fence_fb_obj(plane, fb, new_state, NULL);
13020         }
13021
13022         if (ret == 0)
13023                 i915_gem_track_fb(old_obj, obj, frontbuffer_bits);
13024
13025         mutex_unlock(&dev->struct_mutex);
13026
13027         return ret;
13028 }
13029
13030 /**
13031  * intel_cleanup_plane_fb - Cleans up an fb after plane use
13032  * @plane: drm plane to clean up for
13033  * @fb: old framebuffer that was on plane
13034  *
13035  * Cleans up a framebuffer that has just been removed from a plane.
13036  */
13037 void
13038 intel_cleanup_plane_fb(struct drm_plane *plane,
13039                        struct drm_framebuffer *fb,
13040                        const struct drm_plane_state *old_state)
13041 {
13042         struct drm_device *dev = plane->dev;
13043         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13044
13045         if (WARN_ON(!obj))
13046                 return;
13047
13048         if (plane->type != DRM_PLANE_TYPE_CURSOR ||
13049             !INTEL_INFO(dev)->cursor_needs_physical) {
13050                 mutex_lock(&dev->struct_mutex);
13051                 intel_unpin_fb_obj(fb, old_state);
13052                 mutex_unlock(&dev->struct_mutex);
13053         }
13054 }
13055
13056 static int
13057 intel_check_primary_plane(struct drm_plane *plane,
13058                           struct intel_plane_state *state)
13059 {
13060         struct drm_device *dev = plane->dev;
13061         struct drm_i915_private *dev_priv = dev->dev_private;
13062         struct drm_crtc *crtc = state->base.crtc;
13063         struct intel_crtc *intel_crtc;
13064         struct drm_framebuffer *fb = state->base.fb;
13065         struct drm_rect *dest = &state->dst;
13066         struct drm_rect *src = &state->src;
13067         const struct drm_rect *clip = &state->clip;
13068         bool can_position = false;
13069         int ret;
13070
13071         crtc = crtc ? crtc : plane->crtc;
13072         intel_crtc = to_intel_crtc(crtc);
13073
13074         if (INTEL_INFO(dev)->gen >= 9)
13075                 can_position = true;
13076
13077         ret = drm_plane_helper_check_update(plane, crtc, fb,
13078                                             src, dest, clip,
13079                                             DRM_PLANE_HELPER_NO_SCALING,
13080                                             DRM_PLANE_HELPER_NO_SCALING,
13081                                             can_position, true,
13082                                             &state->visible);
13083         if (ret)
13084                 return ret;
13085
13086         if (intel_crtc->active) {
13087                 intel_crtc->atomic.wait_for_flips = true;
13088
13089                 /*
13090                  * FBC does not work on some platforms for rotated
13091                  * planes, so disable it when rotation is not 0 and
13092                  * update it when rotation is set back to 0.
13093                  *
13094                  * FIXME: This is redundant with the fbc update done in
13095                  * the primary plane enable function except that that
13096                  * one is done too late. We eventually need to unify
13097                  * this.
13098                  */
13099                 if (intel_crtc->primary_enabled &&
13100                     INTEL_INFO(dev)->gen <= 4 && !IS_G4X(dev) &&
13101                     dev_priv->fbc.crtc == intel_crtc &&
13102                     state->base.rotation != BIT(DRM_ROTATE_0)) {
13103                         intel_crtc->atomic.disable_fbc = true;
13104                 }
13105
13106                 if (state->visible) {
13107                         /*
13108                          * BDW signals flip done immediately if the plane
13109                          * is disabled, even if the plane enable is already
13110                          * armed to occur at the next vblank :(
13111                          */
13112                         if (IS_BROADWELL(dev) && !intel_crtc->primary_enabled)
13113                                 intel_crtc->atomic.wait_vblank = true;
13114                 }
13115
13116                 intel_crtc->atomic.fb_bits |=
13117                         INTEL_FRONTBUFFER_PRIMARY(intel_crtc->pipe);
13118
13119                 intel_crtc->atomic.update_fbc = true;
13120
13121                 if (intel_wm_need_update(plane, &state->base))
13122                         intel_crtc->atomic.update_wm = true;
13123         }
13124
13125         return 0;
13126 }
13127
13128 static void
13129 intel_commit_primary_plane(struct drm_plane *plane,
13130                            struct intel_plane_state *state)
13131 {
13132         struct drm_crtc *crtc = state->base.crtc;
13133         struct drm_framebuffer *fb = state->base.fb;
13134         struct drm_device *dev = plane->dev;
13135         struct drm_i915_private *dev_priv = dev->dev_private;
13136         struct intel_crtc *intel_crtc;
13137         struct drm_rect *src = &state->src;
13138
13139         crtc = crtc ? crtc : plane->crtc;
13140         intel_crtc = to_intel_crtc(crtc);
13141
13142         plane->fb = fb;
13143         crtc->x = src->x1 >> 16;
13144         crtc->y = src->y1 >> 16;
13145
13146         if (intel_crtc->active) {
13147                 if (state->visible) {
13148                         /* FIXME: kill this fastboot hack */
13149                         intel_update_pipe_size(intel_crtc);
13150
13151                         intel_crtc->primary_enabled = true;
13152
13153                         dev_priv->display.update_primary_plane(crtc, plane->fb,
13154                                         crtc->x, crtc->y);
13155                 } else {
13156                         /*
13157                          * If clipping results in a non-visible primary plane,
13158                          * we'll disable the primary plane.  Note that this is
13159                          * a bit different than what happens if userspace
13160                          * explicitly disables the plane by passing fb=0
13161                          * because plane->fb still gets set and pinned.
13162                          */
13163                         intel_disable_primary_hw_plane(plane, crtc);
13164                 }
13165         }
13166 }
13167
13168 static void intel_begin_crtc_commit(struct drm_crtc *crtc)
13169 {
13170         struct drm_device *dev = crtc->dev;
13171         struct drm_i915_private *dev_priv = dev->dev_private;
13172         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13173         struct intel_plane *intel_plane;
13174         struct drm_plane *p;
13175         unsigned fb_bits = 0;
13176
13177         /* Track fb's for any planes being disabled */
13178         list_for_each_entry(p, &dev->mode_config.plane_list, head) {
13179                 intel_plane = to_intel_plane(p);
13180
13181                 if (intel_crtc->atomic.disabled_planes &
13182                     (1 << drm_plane_index(p))) {
13183                         switch (p->type) {
13184                         case DRM_PLANE_TYPE_PRIMARY:
13185                                 fb_bits = INTEL_FRONTBUFFER_PRIMARY(intel_plane->pipe);
13186                                 break;
13187                         case DRM_PLANE_TYPE_CURSOR:
13188                                 fb_bits = INTEL_FRONTBUFFER_CURSOR(intel_plane->pipe);
13189                                 break;
13190                         case DRM_PLANE_TYPE_OVERLAY:
13191                                 fb_bits = INTEL_FRONTBUFFER_SPRITE(intel_plane->pipe);
13192                                 break;
13193                         }
13194
13195                         mutex_lock(&dev->struct_mutex);
13196                         i915_gem_track_fb(intel_fb_obj(p->fb), NULL, fb_bits);
13197                         mutex_unlock(&dev->struct_mutex);
13198                 }
13199         }
13200
13201         if (intel_crtc->atomic.wait_for_flips)
13202                 intel_crtc_wait_for_pending_flips(crtc);
13203
13204         if (intel_crtc->atomic.disable_fbc)
13205                 intel_fbc_disable(dev);
13206
13207         if (intel_crtc->atomic.pre_disable_primary)
13208                 intel_pre_disable_primary(crtc);
13209
13210         if (intel_crtc->atomic.update_wm)
13211                 intel_update_watermarks(crtc);
13212
13213         intel_runtime_pm_get(dev_priv);
13214
13215         /* Perform vblank evasion around commit operation */
13216         if (intel_crtc->active)
13217                 intel_crtc->atomic.evade =
13218                         intel_pipe_update_start(intel_crtc,
13219                                                 &intel_crtc->atomic.start_vbl_count);
13220 }
13221
13222 static void intel_finish_crtc_commit(struct drm_crtc *crtc)
13223 {
13224         struct drm_device *dev = crtc->dev;
13225         struct drm_i915_private *dev_priv = dev->dev_private;
13226         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13227         struct drm_plane *p;
13228
13229         if (intel_crtc->atomic.evade)
13230                 intel_pipe_update_end(intel_crtc,
13231                                       intel_crtc->atomic.start_vbl_count);
13232
13233         intel_runtime_pm_put(dev_priv);
13234
13235         if (intel_crtc->atomic.wait_vblank)
13236                 intel_wait_for_vblank(dev, intel_crtc->pipe);
13237
13238         intel_frontbuffer_flip(dev, intel_crtc->atomic.fb_bits);
13239
13240         if (intel_crtc->atomic.update_fbc) {
13241                 mutex_lock(&dev->struct_mutex);
13242                 intel_fbc_update(dev);
13243                 mutex_unlock(&dev->struct_mutex);
13244         }
13245
13246         if (intel_crtc->atomic.post_enable_primary)
13247                 intel_post_enable_primary(crtc);
13248
13249         drm_for_each_legacy_plane(p, &dev->mode_config.plane_list)
13250                 if (intel_crtc->atomic.update_sprite_watermarks & drm_plane_index(p))
13251                         intel_update_sprite_watermarks(p, crtc, 0, 0, 0,
13252                                                        false, false);
13253
13254         memset(&intel_crtc->atomic, 0, sizeof(intel_crtc->atomic));
13255 }
13256
13257 /**
13258  * intel_plane_destroy - destroy a plane
13259  * @plane: plane to destroy
13260  *
13261  * Common destruction function for all types of planes (primary, cursor,
13262  * sprite).
13263  */
13264 void intel_plane_destroy(struct drm_plane *plane)
13265 {
13266         struct intel_plane *intel_plane = to_intel_plane(plane);
13267         drm_plane_cleanup(plane);
13268         kfree(intel_plane);
13269 }
13270
13271 const struct drm_plane_funcs intel_plane_funcs = {
13272         .update_plane = drm_atomic_helper_update_plane,
13273         .disable_plane = drm_atomic_helper_disable_plane,
13274         .destroy = intel_plane_destroy,
13275         .set_property = drm_atomic_helper_plane_set_property,
13276         .atomic_get_property = intel_plane_atomic_get_property,
13277         .atomic_set_property = intel_plane_atomic_set_property,
13278         .atomic_duplicate_state = intel_plane_duplicate_state,
13279         .atomic_destroy_state = intel_plane_destroy_state,
13280
13281 };
13282
13283 static struct drm_plane *intel_primary_plane_create(struct drm_device *dev,
13284                                                     int pipe)
13285 {
13286         struct intel_plane *primary;
13287         struct intel_plane_state *state;
13288         const uint32_t *intel_primary_formats;
13289         int num_formats;
13290
13291         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
13292         if (primary == NULL)
13293                 return NULL;
13294
13295         state = intel_create_plane_state(&primary->base);
13296         if (!state) {
13297                 kfree(primary);
13298                 return NULL;
13299         }
13300         primary->base.state = &state->base;
13301
13302         primary->can_scale = false;
13303         primary->max_downscale = 1;
13304         state->scaler_id = -1;
13305         primary->pipe = pipe;
13306         primary->plane = pipe;
13307         primary->check_plane = intel_check_primary_plane;
13308         primary->commit_plane = intel_commit_primary_plane;
13309         primary->ckey.flags = I915_SET_COLORKEY_NONE;
13310         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4)
13311                 primary->plane = !pipe;
13312
13313         if (INTEL_INFO(dev)->gen <= 3) {
13314                 intel_primary_formats = intel_primary_formats_gen2;
13315                 num_formats = ARRAY_SIZE(intel_primary_formats_gen2);
13316         } else {
13317                 intel_primary_formats = intel_primary_formats_gen4;
13318                 num_formats = ARRAY_SIZE(intel_primary_formats_gen4);
13319         }
13320
13321         drm_universal_plane_init(dev, &primary->base, 0,
13322                                  &intel_plane_funcs,
13323                                  intel_primary_formats, num_formats,
13324                                  DRM_PLANE_TYPE_PRIMARY);
13325
13326         if (INTEL_INFO(dev)->gen >= 4)
13327                 intel_create_rotation_property(dev, primary);
13328
13329         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
13330
13331         return &primary->base;
13332 }
13333
13334 void intel_create_rotation_property(struct drm_device *dev, struct intel_plane *plane)
13335 {
13336         if (!dev->mode_config.rotation_property) {
13337                 unsigned long flags = BIT(DRM_ROTATE_0) |
13338                         BIT(DRM_ROTATE_180);
13339
13340                 if (INTEL_INFO(dev)->gen >= 9)
13341                         flags |= BIT(DRM_ROTATE_90) | BIT(DRM_ROTATE_270);
13342
13343                 dev->mode_config.rotation_property =
13344                         drm_mode_create_rotation_property(dev, flags);
13345         }
13346         if (dev->mode_config.rotation_property)
13347                 drm_object_attach_property(&plane->base.base,
13348                                 dev->mode_config.rotation_property,
13349                                 plane->base.state->rotation);
13350 }
13351
13352 static int
13353 intel_check_cursor_plane(struct drm_plane *plane,
13354                          struct intel_plane_state *state)
13355 {
13356         struct drm_crtc *crtc = state->base.crtc;
13357         struct drm_device *dev = plane->dev;
13358         struct drm_framebuffer *fb = state->base.fb;
13359         struct drm_rect *dest = &state->dst;
13360         struct drm_rect *src = &state->src;
13361         const struct drm_rect *clip = &state->clip;
13362         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13363         struct intel_crtc *intel_crtc;
13364         unsigned stride;
13365         int ret;
13366
13367         crtc = crtc ? crtc : plane->crtc;
13368         intel_crtc = to_intel_crtc(crtc);
13369
13370         ret = drm_plane_helper_check_update(plane, crtc, fb,
13371                                             src, dest, clip,
13372                                             DRM_PLANE_HELPER_NO_SCALING,
13373                                             DRM_PLANE_HELPER_NO_SCALING,
13374                                             true, true, &state->visible);
13375         if (ret)
13376                 return ret;
13377
13378
13379         /* if we want to turn off the cursor ignore width and height */
13380         if (!obj)
13381                 goto finish;
13382
13383         /* Check for which cursor types we support */
13384         if (!cursor_size_ok(dev, state->base.crtc_w, state->base.crtc_h)) {
13385                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
13386                           state->base.crtc_w, state->base.crtc_h);
13387                 return -EINVAL;
13388         }
13389
13390         stride = roundup_pow_of_two(state->base.crtc_w) * 4;
13391         if (obj->base.size < stride * state->base.crtc_h) {
13392                 DRM_DEBUG_KMS("buffer is too small\n");
13393                 return -ENOMEM;
13394         }
13395
13396         if (fb->modifier[0] != DRM_FORMAT_MOD_NONE) {
13397                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
13398                 ret = -EINVAL;
13399         }
13400
13401 finish:
13402         if (intel_crtc->active) {
13403                 if (plane->state->crtc_w != state->base.crtc_w)
13404                         intel_crtc->atomic.update_wm = true;
13405
13406                 intel_crtc->atomic.fb_bits |=
13407                         INTEL_FRONTBUFFER_CURSOR(intel_crtc->pipe);
13408         }
13409
13410         return ret;
13411 }
13412
13413 static void
13414 intel_commit_cursor_plane(struct drm_plane *plane,
13415                           struct intel_plane_state *state)
13416 {
13417         struct drm_crtc *crtc = state->base.crtc;
13418         struct drm_device *dev = plane->dev;
13419         struct intel_crtc *intel_crtc;
13420         struct drm_i915_gem_object *obj = intel_fb_obj(state->base.fb);
13421         uint32_t addr;
13422
13423         crtc = crtc ? crtc : plane->crtc;
13424         intel_crtc = to_intel_crtc(crtc);
13425
13426         plane->fb = state->base.fb;
13427         crtc->cursor_x = state->base.crtc_x;
13428         crtc->cursor_y = state->base.crtc_y;
13429
13430         if (intel_crtc->cursor_bo == obj)
13431                 goto update;
13432
13433         if (!obj)
13434                 addr = 0;
13435         else if (!INTEL_INFO(dev)->cursor_needs_physical)
13436                 addr = i915_gem_obj_ggtt_offset(obj);
13437         else
13438                 addr = obj->phys_handle->busaddr;
13439
13440         intel_crtc->cursor_addr = addr;
13441         intel_crtc->cursor_bo = obj;
13442 update:
13443
13444         if (intel_crtc->active)
13445                 intel_crtc_update_cursor(crtc, state->visible);
13446 }
13447
13448 static struct drm_plane *intel_cursor_plane_create(struct drm_device *dev,
13449                                                    int pipe)
13450 {
13451         struct intel_plane *cursor;
13452         struct intel_plane_state *state;
13453
13454         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
13455         if (cursor == NULL)
13456                 return NULL;
13457
13458         state = intel_create_plane_state(&cursor->base);
13459         if (!state) {
13460                 kfree(cursor);
13461                 return NULL;
13462         }
13463         cursor->base.state = &state->base;
13464
13465         cursor->can_scale = false;
13466         cursor->max_downscale = 1;
13467         cursor->pipe = pipe;
13468         cursor->plane = pipe;
13469         state->scaler_id = -1;
13470         cursor->check_plane = intel_check_cursor_plane;
13471         cursor->commit_plane = intel_commit_cursor_plane;
13472
13473         drm_universal_plane_init(dev, &cursor->base, 0,
13474                                  &intel_plane_funcs,
13475                                  intel_cursor_formats,
13476                                  ARRAY_SIZE(intel_cursor_formats),
13477                                  DRM_PLANE_TYPE_CURSOR);
13478
13479         if (INTEL_INFO(dev)->gen >= 4) {
13480                 if (!dev->mode_config.rotation_property)
13481                         dev->mode_config.rotation_property =
13482                                 drm_mode_create_rotation_property(dev,
13483                                                         BIT(DRM_ROTATE_0) |
13484                                                         BIT(DRM_ROTATE_180));
13485                 if (dev->mode_config.rotation_property)
13486                         drm_object_attach_property(&cursor->base.base,
13487                                 dev->mode_config.rotation_property,
13488                                 state->base.rotation);
13489         }
13490
13491         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
13492
13493         return &cursor->base;
13494 }
13495
13496 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
13497         struct intel_crtc_state *crtc_state)
13498 {
13499         int i;
13500         struct intel_scaler *intel_scaler;
13501         struct intel_crtc_scaler_state *scaler_state = &crtc_state->scaler_state;
13502
13503         for (i = 0; i < intel_crtc->num_scalers; i++) {
13504                 intel_scaler = &scaler_state->scalers[i];
13505                 intel_scaler->in_use = 0;
13506                 intel_scaler->id = i;
13507
13508                 intel_scaler->mode = PS_SCALER_MODE_DYN;
13509         }
13510
13511         scaler_state->scaler_id = -1;
13512 }
13513
13514 static void intel_crtc_init(struct drm_device *dev, int pipe)
13515 {
13516         struct drm_i915_private *dev_priv = dev->dev_private;
13517         struct intel_crtc *intel_crtc;
13518         struct intel_crtc_state *crtc_state = NULL;
13519         struct drm_plane *primary = NULL;
13520         struct drm_plane *cursor = NULL;
13521         int i, ret;
13522
13523         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
13524         if (intel_crtc == NULL)
13525                 return;
13526
13527         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
13528         if (!crtc_state)
13529                 goto fail;
13530         intel_crtc_set_state(intel_crtc, crtc_state);
13531         crtc_state->base.crtc = &intel_crtc->base;
13532
13533         /* initialize shared scalers */
13534         if (INTEL_INFO(dev)->gen >= 9) {
13535                 if (pipe == PIPE_C)
13536                         intel_crtc->num_scalers = 1;
13537                 else
13538                         intel_crtc->num_scalers = SKL_NUM_SCALERS;
13539
13540                 skl_init_scalers(dev, intel_crtc, crtc_state);
13541         }
13542
13543         primary = intel_primary_plane_create(dev, pipe);
13544         if (!primary)
13545                 goto fail;
13546
13547         cursor = intel_cursor_plane_create(dev, pipe);
13548         if (!cursor)
13549                 goto fail;
13550
13551         ret = drm_crtc_init_with_planes(dev, &intel_crtc->base, primary,
13552                                         cursor, &intel_crtc_funcs);
13553         if (ret)
13554                 goto fail;
13555
13556         drm_mode_crtc_set_gamma_size(&intel_crtc->base, 256);
13557         for (i = 0; i < 256; i++) {
13558                 intel_crtc->lut_r[i] = i;
13559                 intel_crtc->lut_g[i] = i;
13560                 intel_crtc->lut_b[i] = i;
13561         }
13562
13563         /*
13564          * On gen2/3 only plane A can do fbc, but the panel fitter and lvds port
13565          * is hooked to pipe B. Hence we want plane A feeding pipe B.
13566          */
13567         intel_crtc->pipe = pipe;
13568         intel_crtc->plane = pipe;
13569         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4) {
13570                 DRM_DEBUG_KMS("swapping pipes & planes for FBC\n");
13571                 intel_crtc->plane = !pipe;
13572         }
13573
13574         intel_crtc->cursor_base = ~0;
13575         intel_crtc->cursor_cntl = ~0;
13576         intel_crtc->cursor_size = ~0;
13577
13578         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
13579                dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
13580         dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = &intel_crtc->base;
13581         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = &intel_crtc->base;
13582
13583         INIT_WORK(&intel_crtc->mmio_flip.work, intel_mmio_flip_work_func);
13584
13585         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
13586
13587         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
13588         return;
13589
13590 fail:
13591         if (primary)
13592                 drm_plane_cleanup(primary);
13593         if (cursor)
13594                 drm_plane_cleanup(cursor);
13595         kfree(crtc_state);
13596         kfree(intel_crtc);
13597 }
13598
13599 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
13600 {
13601         struct drm_encoder *encoder = connector->base.encoder;
13602         struct drm_device *dev = connector->base.dev;
13603
13604         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
13605
13606         if (!encoder || WARN_ON(!encoder->crtc))
13607                 return INVALID_PIPE;
13608
13609         return to_intel_crtc(encoder->crtc)->pipe;
13610 }
13611
13612 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
13613                                 struct drm_file *file)
13614 {
13615         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
13616         struct drm_crtc *drmmode_crtc;
13617         struct intel_crtc *crtc;
13618
13619         drmmode_crtc = drm_crtc_find(dev, pipe_from_crtc_id->crtc_id);
13620
13621         if (!drmmode_crtc) {
13622                 DRM_ERROR("no such CRTC id\n");
13623                 return -ENOENT;
13624         }
13625
13626         crtc = to_intel_crtc(drmmode_crtc);
13627         pipe_from_crtc_id->pipe = crtc->pipe;
13628
13629         return 0;
13630 }
13631
13632 static int intel_encoder_clones(struct intel_encoder *encoder)
13633 {
13634         struct drm_device *dev = encoder->base.dev;
13635         struct intel_encoder *source_encoder;
13636         int index_mask = 0;
13637         int entry = 0;
13638
13639         for_each_intel_encoder(dev, source_encoder) {
13640                 if (encoders_cloneable(encoder, source_encoder))
13641                         index_mask |= (1 << entry);
13642
13643                 entry++;
13644         }
13645
13646         return index_mask;
13647 }
13648
13649 static bool has_edp_a(struct drm_device *dev)
13650 {
13651         struct drm_i915_private *dev_priv = dev->dev_private;
13652
13653         if (!IS_MOBILE(dev))
13654                 return false;
13655
13656         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
13657                 return false;
13658
13659         if (IS_GEN5(dev) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
13660                 return false;
13661
13662         return true;
13663 }
13664
13665 static bool intel_crt_present(struct drm_device *dev)
13666 {
13667         struct drm_i915_private *dev_priv = dev->dev_private;
13668
13669         if (INTEL_INFO(dev)->gen >= 9)
13670                 return false;
13671
13672         if (IS_HSW_ULT(dev) || IS_BDW_ULT(dev))
13673                 return false;
13674
13675         if (IS_CHERRYVIEW(dev))
13676                 return false;
13677
13678         if (IS_VALLEYVIEW(dev) && !dev_priv->vbt.int_crt_support)
13679                 return false;
13680
13681         return true;
13682 }
13683
13684 static void intel_setup_outputs(struct drm_device *dev)
13685 {
13686         struct drm_i915_private *dev_priv = dev->dev_private;
13687         struct intel_encoder *encoder;
13688         bool dpd_is_edp = false;
13689
13690         intel_lvds_init(dev);
13691
13692         if (intel_crt_present(dev))
13693                 intel_crt_init(dev);
13694
13695         if (IS_BROXTON(dev)) {
13696                 /*
13697                  * FIXME: Broxton doesn't support port detection via the
13698                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
13699                  * detect the ports.
13700                  */
13701                 intel_ddi_init(dev, PORT_A);
13702                 intel_ddi_init(dev, PORT_B);
13703                 intel_ddi_init(dev, PORT_C);
13704         } else if (HAS_DDI(dev)) {
13705                 int found;
13706
13707                 /*
13708                  * Haswell uses DDI functions to detect digital outputs.
13709                  * On SKL pre-D0 the strap isn't connected, so we assume
13710                  * it's there.
13711                  */
13712                 found = I915_READ(DDI_BUF_CTL_A) & DDI_INIT_DISPLAY_DETECTED;
13713                 /* WaIgnoreDDIAStrap: skl */
13714                 if (found ||
13715                     (IS_SKYLAKE(dev) && INTEL_REVID(dev) < SKL_REVID_D0))
13716                         intel_ddi_init(dev, PORT_A);
13717
13718                 /* DDI B, C and D detection is indicated by the SFUSE_STRAP
13719                  * register */
13720                 found = I915_READ(SFUSE_STRAP);
13721
13722                 if (found & SFUSE_STRAP_DDIB_DETECTED)
13723                         intel_ddi_init(dev, PORT_B);
13724                 if (found & SFUSE_STRAP_DDIC_DETECTED)
13725                         intel_ddi_init(dev, PORT_C);
13726                 if (found & SFUSE_STRAP_DDID_DETECTED)
13727                         intel_ddi_init(dev, PORT_D);
13728         } else if (HAS_PCH_SPLIT(dev)) {
13729                 int found;
13730                 dpd_is_edp = intel_dp_is_edp(dev, PORT_D);
13731
13732                 if (has_edp_a(dev))
13733                         intel_dp_init(dev, DP_A, PORT_A);
13734
13735                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
13736                         /* PCH SDVOB multiplex with HDMIB */
13737                         found = intel_sdvo_init(dev, PCH_SDVOB, true);
13738                         if (!found)
13739                                 intel_hdmi_init(dev, PCH_HDMIB, PORT_B);
13740                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
13741                                 intel_dp_init(dev, PCH_DP_B, PORT_B);
13742                 }
13743
13744                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
13745                         intel_hdmi_init(dev, PCH_HDMIC, PORT_C);
13746
13747                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
13748                         intel_hdmi_init(dev, PCH_HDMID, PORT_D);
13749
13750                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
13751                         intel_dp_init(dev, PCH_DP_C, PORT_C);
13752
13753                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
13754                         intel_dp_init(dev, PCH_DP_D, PORT_D);
13755         } else if (IS_VALLEYVIEW(dev)) {
13756                 /*
13757                  * The DP_DETECTED bit is the latched state of the DDC
13758                  * SDA pin at boot. However since eDP doesn't require DDC
13759                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
13760                  * eDP ports may have been muxed to an alternate function.
13761                  * Thus we can't rely on the DP_DETECTED bit alone to detect
13762                  * eDP ports. Consult the VBT as well as DP_DETECTED to
13763                  * detect eDP ports.
13764                  */
13765                 if (I915_READ(VLV_DISPLAY_BASE + GEN4_HDMIB) & SDVO_DETECTED &&
13766                     !intel_dp_is_edp(dev, PORT_B))
13767                         intel_hdmi_init(dev, VLV_DISPLAY_BASE + GEN4_HDMIB,
13768                                         PORT_B);
13769                 if (I915_READ(VLV_DISPLAY_BASE + DP_B) & DP_DETECTED ||
13770                     intel_dp_is_edp(dev, PORT_B))
13771                         intel_dp_init(dev, VLV_DISPLAY_BASE + DP_B, PORT_B);
13772
13773                 if (I915_READ(VLV_DISPLAY_BASE + GEN4_HDMIC) & SDVO_DETECTED &&
13774                     !intel_dp_is_edp(dev, PORT_C))
13775                         intel_hdmi_init(dev, VLV_DISPLAY_BASE + GEN4_HDMIC,
13776                                         PORT_C);
13777                 if (I915_READ(VLV_DISPLAY_BASE + DP_C) & DP_DETECTED ||
13778                     intel_dp_is_edp(dev, PORT_C))
13779                         intel_dp_init(dev, VLV_DISPLAY_BASE + DP_C, PORT_C);
13780
13781                 if (IS_CHERRYVIEW(dev)) {
13782                         if (I915_READ(VLV_DISPLAY_BASE + CHV_HDMID) & SDVO_DETECTED)
13783                                 intel_hdmi_init(dev, VLV_DISPLAY_BASE + CHV_HDMID,
13784                                                 PORT_D);
13785                         /* eDP not supported on port D, so don't check VBT */
13786                         if (I915_READ(VLV_DISPLAY_BASE + DP_D) & DP_DETECTED)
13787                                 intel_dp_init(dev, VLV_DISPLAY_BASE + DP_D, PORT_D);
13788                 }
13789
13790                 intel_dsi_init(dev);
13791         } else if (SUPPORTS_DIGITAL_OUTPUTS(dev)) {
13792                 bool found = false;
13793
13794                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
13795                         DRM_DEBUG_KMS("probing SDVOB\n");
13796                         found = intel_sdvo_init(dev, GEN3_SDVOB, true);
13797                         if (!found && SUPPORTS_INTEGRATED_HDMI(dev)) {
13798                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
13799                                 intel_hdmi_init(dev, GEN4_HDMIB, PORT_B);
13800                         }
13801
13802                         if (!found && SUPPORTS_INTEGRATED_DP(dev))
13803                                 intel_dp_init(dev, DP_B, PORT_B);
13804                 }
13805
13806                 /* Before G4X SDVOC doesn't have its own detect register */
13807
13808                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
13809                         DRM_DEBUG_KMS("probing SDVOC\n");
13810                         found = intel_sdvo_init(dev, GEN3_SDVOC, false);
13811                 }
13812
13813                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
13814
13815                         if (SUPPORTS_INTEGRATED_HDMI(dev)) {
13816                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
13817                                 intel_hdmi_init(dev, GEN4_HDMIC, PORT_C);
13818                         }
13819                         if (SUPPORTS_INTEGRATED_DP(dev))
13820                                 intel_dp_init(dev, DP_C, PORT_C);
13821                 }
13822
13823                 if (SUPPORTS_INTEGRATED_DP(dev) &&
13824                     (I915_READ(DP_D) & DP_DETECTED))
13825                         intel_dp_init(dev, DP_D, PORT_D);
13826         } else if (IS_GEN2(dev))
13827                 intel_dvo_init(dev);
13828
13829         if (SUPPORTS_TV(dev))
13830                 intel_tv_init(dev);
13831
13832         intel_psr_init(dev);
13833
13834         for_each_intel_encoder(dev, encoder) {
13835                 encoder->base.possible_crtcs = encoder->crtc_mask;
13836                 encoder->base.possible_clones =
13837                         intel_encoder_clones(encoder);
13838         }
13839
13840         intel_init_pch_refclk(dev);
13841
13842         drm_helper_move_panel_connectors_to_head(dev);
13843 }
13844
13845 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
13846 {
13847         struct drm_device *dev = fb->dev;
13848         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
13849
13850         drm_framebuffer_cleanup(fb);
13851         mutex_lock(&dev->struct_mutex);
13852         WARN_ON(!intel_fb->obj->framebuffer_references--);
13853         drm_gem_object_unreference(&intel_fb->obj->base);
13854         mutex_unlock(&dev->struct_mutex);
13855         kfree(intel_fb);
13856 }
13857
13858 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
13859                                                 struct drm_file *file,
13860                                                 unsigned int *handle)
13861 {
13862         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
13863         struct drm_i915_gem_object *obj = intel_fb->obj;
13864
13865         return drm_gem_handle_create(file, &obj->base, handle);
13866 }
13867
13868 static const struct drm_framebuffer_funcs intel_fb_funcs = {
13869         .destroy = intel_user_framebuffer_destroy,
13870         .create_handle = intel_user_framebuffer_create_handle,
13871 };
13872
13873 static
13874 u32 intel_fb_pitch_limit(struct drm_device *dev, uint64_t fb_modifier,
13875                          uint32_t pixel_format)
13876 {
13877         u32 gen = INTEL_INFO(dev)->gen;
13878
13879         if (gen >= 9) {
13880                 /* "The stride in bytes must not exceed the of the size of 8K
13881                  *  pixels and 32K bytes."
13882                  */
13883                  return min(8192*drm_format_plane_cpp(pixel_format, 0), 32768);
13884         } else if (gen >= 5 && !IS_VALLEYVIEW(dev)) {
13885                 return 32*1024;
13886         } else if (gen >= 4) {
13887                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
13888                         return 16*1024;
13889                 else
13890                         return 32*1024;
13891         } else if (gen >= 3) {
13892                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
13893                         return 8*1024;
13894                 else
13895                         return 16*1024;
13896         } else {
13897                 /* XXX DSPC is limited to 4k tiled */
13898                 return 8*1024;
13899         }
13900 }
13901
13902 static int intel_framebuffer_init(struct drm_device *dev,
13903                                   struct intel_framebuffer *intel_fb,
13904                                   struct drm_mode_fb_cmd2 *mode_cmd,
13905                                   struct drm_i915_gem_object *obj)
13906 {
13907         unsigned int aligned_height;
13908         int ret;
13909         u32 pitch_limit, stride_alignment;
13910
13911         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
13912
13913         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
13914                 /* Enforce that fb modifier and tiling mode match, but only for
13915                  * X-tiled. This is needed for FBC. */
13916                 if (!!(obj->tiling_mode == I915_TILING_X) !=
13917                     !!(mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED)) {
13918                         DRM_DEBUG("tiling_mode doesn't match fb modifier\n");
13919                         return -EINVAL;
13920                 }
13921         } else {
13922                 if (obj->tiling_mode == I915_TILING_X)
13923                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
13924                 else if (obj->tiling_mode == I915_TILING_Y) {
13925                         DRM_DEBUG("No Y tiling for legacy addfb\n");
13926                         return -EINVAL;
13927                 }
13928         }
13929
13930         /* Passed in modifier sanity checking. */
13931         switch (mode_cmd->modifier[0]) {
13932         case I915_FORMAT_MOD_Y_TILED:
13933         case I915_FORMAT_MOD_Yf_TILED:
13934                 if (INTEL_INFO(dev)->gen < 9) {
13935                         DRM_DEBUG("Unsupported tiling 0x%llx!\n",
13936                                   mode_cmd->modifier[0]);
13937                         return -EINVAL;
13938                 }
13939         case DRM_FORMAT_MOD_NONE:
13940         case I915_FORMAT_MOD_X_TILED:
13941                 break;
13942         default:
13943                 DRM_DEBUG("Unsupported fb modifier 0x%llx!\n",
13944                           mode_cmd->modifier[0]);
13945                 return -EINVAL;
13946         }
13947
13948         stride_alignment = intel_fb_stride_alignment(dev, mode_cmd->modifier[0],
13949                                                      mode_cmd->pixel_format);
13950         if (mode_cmd->pitches[0] & (stride_alignment - 1)) {
13951                 DRM_DEBUG("pitch (%d) must be at least %u byte aligned\n",
13952                           mode_cmd->pitches[0], stride_alignment);
13953                 return -EINVAL;
13954         }
13955
13956         pitch_limit = intel_fb_pitch_limit(dev, mode_cmd->modifier[0],
13957                                            mode_cmd->pixel_format);
13958         if (mode_cmd->pitches[0] > pitch_limit) {
13959                 DRM_DEBUG("%s pitch (%u) must be at less than %d\n",
13960                           mode_cmd->modifier[0] != DRM_FORMAT_MOD_NONE ?
13961                           "tiled" : "linear",
13962                           mode_cmd->pitches[0], pitch_limit);
13963                 return -EINVAL;
13964         }
13965
13966         if (mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED &&
13967             mode_cmd->pitches[0] != obj->stride) {
13968                 DRM_DEBUG("pitch (%d) must match tiling stride (%d)\n",
13969                           mode_cmd->pitches[0], obj->stride);
13970                 return -EINVAL;
13971         }
13972
13973         /* Reject formats not supported by any plane early. */
13974         switch (mode_cmd->pixel_format) {
13975         case DRM_FORMAT_C8:
13976         case DRM_FORMAT_RGB565:
13977         case DRM_FORMAT_XRGB8888:
13978         case DRM_FORMAT_ARGB8888:
13979                 break;
13980         case DRM_FORMAT_XRGB1555:
13981         case DRM_FORMAT_ARGB1555:
13982                 if (INTEL_INFO(dev)->gen > 3) {
13983                         DRM_DEBUG("unsupported pixel format: %s\n",
13984                                   drm_get_format_name(mode_cmd->pixel_format));
13985                         return -EINVAL;
13986                 }
13987                 break;
13988         case DRM_FORMAT_XBGR8888:
13989         case DRM_FORMAT_ABGR8888:
13990         case DRM_FORMAT_XRGB2101010:
13991         case DRM_FORMAT_ARGB2101010:
13992         case DRM_FORMAT_XBGR2101010:
13993         case DRM_FORMAT_ABGR2101010:
13994                 if (INTEL_INFO(dev)->gen < 4) {
13995                         DRM_DEBUG("unsupported pixel format: %s\n",
13996                                   drm_get_format_name(mode_cmd->pixel_format));
13997                         return -EINVAL;
13998                 }
13999                 break;
14000         case DRM_FORMAT_YUYV:
14001         case DRM_FORMAT_UYVY:
14002         case DRM_FORMAT_YVYU:
14003         case DRM_FORMAT_VYUY:
14004                 if (INTEL_INFO(dev)->gen < 5) {
14005                         DRM_DEBUG("unsupported pixel format: %s\n",
14006                                   drm_get_format_name(mode_cmd->pixel_format));
14007                         return -EINVAL;
14008                 }
14009                 break;
14010         default:
14011                 DRM_DEBUG("unsupported pixel format: %s\n",
14012                           drm_get_format_name(mode_cmd->pixel_format));
14013                 return -EINVAL;
14014         }
14015
14016         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14017         if (mode_cmd->offsets[0] != 0)
14018                 return -EINVAL;
14019
14020         aligned_height = intel_fb_align_height(dev, mode_cmd->height,
14021                                                mode_cmd->pixel_format,
14022                                                mode_cmd->modifier[0]);
14023         /* FIXME drm helper for size checks (especially planar formats)? */
14024         if (obj->base.size < aligned_height * mode_cmd->pitches[0])
14025                 return -EINVAL;
14026
14027         drm_helper_mode_fill_fb_struct(&intel_fb->base, mode_cmd);
14028         intel_fb->obj = obj;
14029         intel_fb->obj->framebuffer_references++;
14030
14031         ret = drm_framebuffer_init(dev, &intel_fb->base, &intel_fb_funcs);
14032         if (ret) {
14033                 DRM_ERROR("framebuffer init failed %d\n", ret);
14034                 return ret;
14035         }
14036
14037         return 0;
14038 }
14039
14040 static struct drm_framebuffer *
14041 intel_user_framebuffer_create(struct drm_device *dev,
14042                               struct drm_file *filp,
14043                               struct drm_mode_fb_cmd2 *mode_cmd)
14044 {
14045         struct drm_i915_gem_object *obj;
14046
14047         obj = to_intel_bo(drm_gem_object_lookup(dev, filp,
14048                                                 mode_cmd->handles[0]));
14049         if (&obj->base == NULL)
14050                 return ERR_PTR(-ENOENT);
14051
14052         return intel_framebuffer_create(dev, mode_cmd, obj);
14053 }
14054
14055 #ifndef CONFIG_DRM_I915_FBDEV
14056 static inline void intel_fbdev_output_poll_changed(struct drm_device *dev)
14057 {
14058 }
14059 #endif
14060
14061 static const struct drm_mode_config_funcs intel_mode_funcs = {
14062         .fb_create = intel_user_framebuffer_create,
14063         .output_poll_changed = intel_fbdev_output_poll_changed,
14064         .atomic_check = intel_atomic_check,
14065         .atomic_commit = intel_atomic_commit,
14066 };
14067
14068 /* Set up chip specific display functions */
14069 static void intel_init_display(struct drm_device *dev)
14070 {
14071         struct drm_i915_private *dev_priv = dev->dev_private;
14072
14073         if (HAS_PCH_SPLIT(dev) || IS_G4X(dev))
14074                 dev_priv->display.find_dpll = g4x_find_best_dpll;
14075         else if (IS_CHERRYVIEW(dev))
14076                 dev_priv->display.find_dpll = chv_find_best_dpll;
14077         else if (IS_VALLEYVIEW(dev))
14078                 dev_priv->display.find_dpll = vlv_find_best_dpll;
14079         else if (IS_PINEVIEW(dev))
14080                 dev_priv->display.find_dpll = pnv_find_best_dpll;
14081         else
14082                 dev_priv->display.find_dpll = i9xx_find_best_dpll;
14083
14084         if (INTEL_INFO(dev)->gen >= 9) {
14085                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14086                 dev_priv->display.get_initial_plane_config =
14087                         skylake_get_initial_plane_config;
14088                 dev_priv->display.crtc_compute_clock =
14089                         haswell_crtc_compute_clock;
14090                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14091                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14092                 dev_priv->display.off = ironlake_crtc_off;
14093                 dev_priv->display.update_primary_plane =
14094                         skylake_update_primary_plane;
14095         } else if (HAS_DDI(dev)) {
14096                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14097                 dev_priv->display.get_initial_plane_config =
14098                         ironlake_get_initial_plane_config;
14099                 dev_priv->display.crtc_compute_clock =
14100                         haswell_crtc_compute_clock;
14101                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14102                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14103                 dev_priv->display.off = ironlake_crtc_off;
14104                 dev_priv->display.update_primary_plane =
14105                         ironlake_update_primary_plane;
14106         } else if (HAS_PCH_SPLIT(dev)) {
14107                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
14108                 dev_priv->display.get_initial_plane_config =
14109                         ironlake_get_initial_plane_config;
14110                 dev_priv->display.crtc_compute_clock =
14111                         ironlake_crtc_compute_clock;
14112                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
14113                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
14114                 dev_priv->display.off = ironlake_crtc_off;
14115                 dev_priv->display.update_primary_plane =
14116                         ironlake_update_primary_plane;
14117         } else if (IS_VALLEYVIEW(dev)) {
14118                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14119                 dev_priv->display.get_initial_plane_config =
14120                         i9xx_get_initial_plane_config;
14121                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14122                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14123                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14124                 dev_priv->display.off = i9xx_crtc_off;
14125                 dev_priv->display.update_primary_plane =
14126                         i9xx_update_primary_plane;
14127         } else {
14128                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14129                 dev_priv->display.get_initial_plane_config =
14130                         i9xx_get_initial_plane_config;
14131                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14132                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14133                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14134                 dev_priv->display.off = i9xx_crtc_off;
14135                 dev_priv->display.update_primary_plane =
14136                         i9xx_update_primary_plane;
14137         }
14138
14139         /* Returns the core display clock speed */
14140         if (IS_SKYLAKE(dev))
14141                 dev_priv->display.get_display_clock_speed =
14142                         skylake_get_display_clock_speed;
14143         else if (IS_BROADWELL(dev))
14144                 dev_priv->display.get_display_clock_speed =
14145                         broadwell_get_display_clock_speed;
14146         else if (IS_HASWELL(dev))
14147                 dev_priv->display.get_display_clock_speed =
14148                         haswell_get_display_clock_speed;
14149         else if (IS_VALLEYVIEW(dev))
14150                 dev_priv->display.get_display_clock_speed =
14151                         valleyview_get_display_clock_speed;
14152         else if (IS_GEN5(dev))
14153                 dev_priv->display.get_display_clock_speed =
14154                         ilk_get_display_clock_speed;
14155         else if (IS_I945G(dev) || IS_BROADWATER(dev) ||
14156                  IS_GEN6(dev) || IS_IVYBRIDGE(dev) || (IS_G33(dev) && !IS_PINEVIEW_M(dev)))
14157                 dev_priv->display.get_display_clock_speed =
14158                         i945_get_display_clock_speed;
14159         else if (IS_I915G(dev))
14160                 dev_priv->display.get_display_clock_speed =
14161                         i915_get_display_clock_speed;
14162         else if (IS_I945GM(dev) || IS_845G(dev))
14163                 dev_priv->display.get_display_clock_speed =
14164                         i9xx_misc_get_display_clock_speed;
14165         else if (IS_PINEVIEW(dev))
14166                 dev_priv->display.get_display_clock_speed =
14167                         pnv_get_display_clock_speed;
14168         else if (IS_I915GM(dev))
14169                 dev_priv->display.get_display_clock_speed =
14170                         i915gm_get_display_clock_speed;
14171         else if (IS_I865G(dev))
14172                 dev_priv->display.get_display_clock_speed =
14173                         i865_get_display_clock_speed;
14174         else if (IS_I85X(dev))
14175                 dev_priv->display.get_display_clock_speed =
14176                         i855_get_display_clock_speed;
14177         else /* 852, 830 */
14178                 dev_priv->display.get_display_clock_speed =
14179                         i830_get_display_clock_speed;
14180
14181         if (IS_GEN5(dev)) {
14182                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
14183         } else if (IS_GEN6(dev)) {
14184                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
14185         } else if (IS_IVYBRIDGE(dev)) {
14186                 /* FIXME: detect B0+ stepping and use auto training */
14187                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
14188         } else if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
14189                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
14190         } else if (IS_VALLEYVIEW(dev)) {
14191                 dev_priv->display.modeset_global_resources =
14192                         valleyview_modeset_global_resources;
14193         } else if (IS_BROXTON(dev)) {
14194                 dev_priv->display.modeset_global_resources =
14195                         broxton_modeset_global_resources;
14196         }
14197
14198         switch (INTEL_INFO(dev)->gen) {
14199         case 2:
14200                 dev_priv->display.queue_flip = intel_gen2_queue_flip;
14201                 break;
14202
14203         case 3:
14204                 dev_priv->display.queue_flip = intel_gen3_queue_flip;
14205                 break;
14206
14207         case 4:
14208         case 5:
14209                 dev_priv->display.queue_flip = intel_gen4_queue_flip;
14210                 break;
14211
14212         case 6:
14213                 dev_priv->display.queue_flip = intel_gen6_queue_flip;
14214                 break;
14215         case 7:
14216         case 8: /* FIXME(BDW): Check that the gen8 RCS flip works. */
14217                 dev_priv->display.queue_flip = intel_gen7_queue_flip;
14218                 break;
14219         case 9:
14220                 /* Drop through - unsupported since execlist only. */
14221         default:
14222                 /* Default just returns -ENODEV to indicate unsupported */
14223                 dev_priv->display.queue_flip = intel_default_queue_flip;
14224         }
14225
14226         intel_panel_init_backlight_funcs(dev);
14227
14228         mutex_init(&dev_priv->pps_mutex);
14229 }
14230
14231 /*
14232  * Some BIOSes insist on assuming the GPU's pipe A is enabled at suspend,
14233  * resume, or other times.  This quirk makes sure that's the case for
14234  * affected systems.
14235  */
14236 static void quirk_pipea_force(struct drm_device *dev)
14237 {
14238         struct drm_i915_private *dev_priv = dev->dev_private;
14239
14240         dev_priv->quirks |= QUIRK_PIPEA_FORCE;
14241         DRM_INFO("applying pipe a force quirk\n");
14242 }
14243
14244 static void quirk_pipeb_force(struct drm_device *dev)
14245 {
14246         struct drm_i915_private *dev_priv = dev->dev_private;
14247
14248         dev_priv->quirks |= QUIRK_PIPEB_FORCE;
14249         DRM_INFO("applying pipe b force quirk\n");
14250 }
14251
14252 /*
14253  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
14254  */
14255 static void quirk_ssc_force_disable(struct drm_device *dev)
14256 {
14257         struct drm_i915_private *dev_priv = dev->dev_private;
14258         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
14259         DRM_INFO("applying lvds SSC disable quirk\n");
14260 }
14261
14262 /*
14263  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
14264  * brightness value
14265  */
14266 static void quirk_invert_brightness(struct drm_device *dev)
14267 {
14268         struct drm_i915_private *dev_priv = dev->dev_private;
14269         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
14270         DRM_INFO("applying inverted panel brightness quirk\n");
14271 }
14272
14273 /* Some VBT's incorrectly indicate no backlight is present */
14274 static void quirk_backlight_present(struct drm_device *dev)
14275 {
14276         struct drm_i915_private *dev_priv = dev->dev_private;
14277         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
14278         DRM_INFO("applying backlight present quirk\n");
14279 }
14280
14281 struct intel_quirk {
14282         int device;
14283         int subsystem_vendor;
14284         int subsystem_device;
14285         void (*hook)(struct drm_device *dev);
14286 };
14287
14288 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
14289 struct intel_dmi_quirk {
14290         void (*hook)(struct drm_device *dev);
14291         const struct dmi_system_id (*dmi_id_list)[];
14292 };
14293
14294 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
14295 {
14296         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
14297         return 1;
14298 }
14299
14300 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
14301         {
14302                 .dmi_id_list = &(const struct dmi_system_id[]) {
14303                         {
14304                                 .callback = intel_dmi_reverse_brightness,
14305                                 .ident = "NCR Corporation",
14306                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
14307                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
14308                                 },
14309                         },
14310                         { }  /* terminating entry */
14311                 },
14312                 .hook = quirk_invert_brightness,
14313         },
14314 };
14315
14316 static struct intel_quirk intel_quirks[] = {
14317         /* HP Mini needs pipe A force quirk (LP: #322104) */
14318         { 0x27ae, 0x103c, 0x361a, quirk_pipea_force },
14319
14320         /* Toshiba Protege R-205, S-209 needs pipe A force quirk */
14321         { 0x2592, 0x1179, 0x0001, quirk_pipea_force },
14322
14323         /* ThinkPad T60 needs pipe A force quirk (bug #16494) */
14324         { 0x2782, 0x17aa, 0x201a, quirk_pipea_force },
14325
14326         /* 830 needs to leave pipe A & dpll A up */
14327         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipea_force },
14328
14329         /* 830 needs to leave pipe B & dpll B up */
14330         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipeb_force },
14331
14332         /* Lenovo U160 cannot use SSC on LVDS */
14333         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
14334
14335         /* Sony Vaio Y cannot use SSC on LVDS */
14336         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
14337
14338         /* Acer Aspire 5734Z must invert backlight brightness */
14339         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
14340
14341         /* Acer/eMachines G725 */
14342         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
14343
14344         /* Acer/eMachines e725 */
14345         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
14346
14347         /* Acer/Packard Bell NCL20 */
14348         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
14349
14350         /* Acer Aspire 4736Z */
14351         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
14352
14353         /* Acer Aspire 5336 */
14354         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
14355
14356         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
14357         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
14358
14359         /* Acer C720 Chromebook (Core i3 4005U) */
14360         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
14361
14362         /* Apple Macbook 2,1 (Core 2 T7400) */
14363         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
14364
14365         /* Toshiba CB35 Chromebook (Celeron 2955U) */
14366         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
14367
14368         /* HP Chromebook 14 (Celeron 2955U) */
14369         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
14370
14371         /* Dell Chromebook 11 */
14372         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
14373 };
14374
14375 static void intel_init_quirks(struct drm_device *dev)
14376 {
14377         struct pci_dev *d = dev->pdev;
14378         int i;
14379
14380         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
14381                 struct intel_quirk *q = &intel_quirks[i];
14382
14383                 if (d->device == q->device &&
14384                     (d->subsystem_vendor == q->subsystem_vendor ||
14385                      q->subsystem_vendor == PCI_ANY_ID) &&
14386                     (d->subsystem_device == q->subsystem_device ||
14387                      q->subsystem_device == PCI_ANY_ID))
14388                         q->hook(dev);
14389         }
14390         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
14391                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
14392                         intel_dmi_quirks[i].hook(dev);
14393         }
14394 }
14395
14396 /* Disable the VGA plane that we never use */
14397 static void i915_disable_vga(struct drm_device *dev)
14398 {
14399         struct drm_i915_private *dev_priv = dev->dev_private;
14400         u8 sr1;
14401         u32 vga_reg = i915_vgacntrl_reg(dev);
14402
14403         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
14404         vga_get_uninterruptible(dev->pdev, VGA_RSRC_LEGACY_IO);
14405         outb(SR01, VGA_SR_INDEX);
14406         sr1 = inb(VGA_SR_DATA);
14407         outb(sr1 | 1<<5, VGA_SR_DATA);
14408         vga_put(dev->pdev, VGA_RSRC_LEGACY_IO);
14409         udelay(300);
14410
14411         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
14412         POSTING_READ(vga_reg);
14413 }
14414
14415 void intel_modeset_init_hw(struct drm_device *dev)
14416 {
14417         intel_prepare_ddi(dev);
14418
14419         if (IS_VALLEYVIEW(dev))
14420                 vlv_update_cdclk(dev);
14421
14422         intel_init_clock_gating(dev);
14423
14424         intel_enable_gt_powersave(dev);
14425 }
14426
14427 void intel_modeset_init(struct drm_device *dev)
14428 {
14429         struct drm_i915_private *dev_priv = dev->dev_private;
14430         int sprite, ret;
14431         enum pipe pipe;
14432         struct intel_crtc *crtc;
14433
14434         drm_mode_config_init(dev);
14435
14436         dev->mode_config.min_width = 0;
14437         dev->mode_config.min_height = 0;
14438
14439         dev->mode_config.preferred_depth = 24;
14440         dev->mode_config.prefer_shadow = 1;
14441
14442         dev->mode_config.allow_fb_modifiers = true;
14443
14444         dev->mode_config.funcs = &intel_mode_funcs;
14445
14446         intel_init_quirks(dev);
14447
14448         intel_init_pm(dev);
14449
14450         if (INTEL_INFO(dev)->num_pipes == 0)
14451                 return;
14452
14453         intel_init_display(dev);
14454         intel_init_audio(dev);
14455
14456         if (IS_GEN2(dev)) {
14457                 dev->mode_config.max_width = 2048;
14458                 dev->mode_config.max_height = 2048;
14459         } else if (IS_GEN3(dev)) {
14460                 dev->mode_config.max_width = 4096;
14461                 dev->mode_config.max_height = 4096;
14462         } else {
14463                 dev->mode_config.max_width = 8192;
14464                 dev->mode_config.max_height = 8192;
14465         }
14466
14467         if (IS_845G(dev) || IS_I865G(dev)) {
14468                 dev->mode_config.cursor_width = IS_845G(dev) ? 64 : 512;
14469                 dev->mode_config.cursor_height = 1023;
14470         } else if (IS_GEN2(dev)) {
14471                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
14472                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
14473         } else {
14474                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
14475                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
14476         }
14477
14478         dev->mode_config.fb_base = dev_priv->gtt.mappable_base;
14479
14480         DRM_DEBUG_KMS("%d display pipe%s available.\n",
14481                       INTEL_INFO(dev)->num_pipes,
14482                       INTEL_INFO(dev)->num_pipes > 1 ? "s" : "");
14483
14484         for_each_pipe(dev_priv, pipe) {
14485                 intel_crtc_init(dev, pipe);
14486                 for_each_sprite(dev_priv, pipe, sprite) {
14487                         ret = intel_plane_init(dev, pipe, sprite);
14488                         if (ret)
14489                                 DRM_DEBUG_KMS("pipe %c sprite %c init failed: %d\n",
14490                                               pipe_name(pipe), sprite_name(pipe, sprite), ret);
14491                 }
14492         }
14493
14494         intel_init_dpio(dev);
14495
14496         intel_shared_dpll_init(dev);
14497
14498         /* Just disable it once at startup */
14499         i915_disable_vga(dev);
14500         intel_setup_outputs(dev);
14501
14502         /* Just in case the BIOS is doing something questionable. */
14503         intel_fbc_disable(dev);
14504
14505         drm_modeset_lock_all(dev);
14506         intel_modeset_setup_hw_state(dev, false);
14507         drm_modeset_unlock_all(dev);
14508
14509         for_each_intel_crtc(dev, crtc) {
14510                 if (!crtc->active)
14511                         continue;
14512
14513                 /*
14514                  * Note that reserving the BIOS fb up front prevents us
14515                  * from stuffing other stolen allocations like the ring
14516                  * on top.  This prevents some ugliness at boot time, and
14517                  * can even allow for smooth boot transitions if the BIOS
14518                  * fb is large enough for the active pipe configuration.
14519                  */
14520                 if (dev_priv->display.get_initial_plane_config) {
14521                         dev_priv->display.get_initial_plane_config(crtc,
14522                                                            &crtc->plane_config);
14523                         /*
14524                          * If the fb is shared between multiple heads, we'll
14525                          * just get the first one.
14526                          */
14527                         intel_find_initial_plane_obj(crtc, &crtc->plane_config);
14528                 }
14529         }
14530 }
14531
14532 static void intel_enable_pipe_a(struct drm_device *dev)
14533 {
14534         struct intel_connector *connector;
14535         struct drm_connector *crt = NULL;
14536         struct intel_load_detect_pipe load_detect_temp;
14537         struct drm_modeset_acquire_ctx *ctx = dev->mode_config.acquire_ctx;
14538
14539         /* We can't just switch on the pipe A, we need to set things up with a
14540          * proper mode and output configuration. As a gross hack, enable pipe A
14541          * by enabling the load detect pipe once. */
14542         for_each_intel_connector(dev, connector) {
14543                 if (connector->encoder->type == INTEL_OUTPUT_ANALOG) {
14544                         crt = &connector->base;
14545                         break;
14546                 }
14547         }
14548
14549         if (!crt)
14550                 return;
14551
14552         if (intel_get_load_detect_pipe(crt, NULL, &load_detect_temp, ctx))
14553                 intel_release_load_detect_pipe(crt, &load_detect_temp, ctx);
14554 }
14555
14556 static bool
14557 intel_check_plane_mapping(struct intel_crtc *crtc)
14558 {
14559         struct drm_device *dev = crtc->base.dev;
14560         struct drm_i915_private *dev_priv = dev->dev_private;
14561         u32 reg, val;
14562
14563         if (INTEL_INFO(dev)->num_pipes == 1)
14564                 return true;
14565
14566         reg = DSPCNTR(!crtc->plane);
14567         val = I915_READ(reg);
14568
14569         if ((val & DISPLAY_PLANE_ENABLE) &&
14570             (!!(val & DISPPLANE_SEL_PIPE_MASK) == crtc->pipe))
14571                 return false;
14572
14573         return true;
14574 }
14575
14576 static void intel_sanitize_crtc(struct intel_crtc *crtc)
14577 {
14578         struct drm_device *dev = crtc->base.dev;
14579         struct drm_i915_private *dev_priv = dev->dev_private;
14580         u32 reg;
14581
14582         /* Clear any frame start delays used for debugging left by the BIOS */
14583         reg = PIPECONF(crtc->config->cpu_transcoder);
14584         I915_WRITE(reg, I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
14585
14586         /* restore vblank interrupts to correct state */
14587         drm_crtc_vblank_reset(&crtc->base);
14588         if (crtc->active) {
14589                 update_scanline_offset(crtc);
14590                 drm_crtc_vblank_on(&crtc->base);
14591         }
14592
14593         /* We need to sanitize the plane -> pipe mapping first because this will
14594          * disable the crtc (and hence change the state) if it is wrong. Note
14595          * that gen4+ has a fixed plane -> pipe mapping.  */
14596         if (INTEL_INFO(dev)->gen < 4 && !intel_check_plane_mapping(crtc)) {
14597                 struct intel_connector *connector;
14598                 bool plane;
14599
14600                 DRM_DEBUG_KMS("[CRTC:%d] wrong plane connection detected!\n",
14601                               crtc->base.base.id);
14602
14603                 /* Pipe has the wrong plane attached and the plane is active.
14604                  * Temporarily change the plane mapping and disable everything
14605                  * ...  */
14606                 plane = crtc->plane;
14607                 crtc->plane = !plane;
14608                 crtc->primary_enabled = true;
14609                 dev_priv->display.crtc_disable(&crtc->base);
14610                 crtc->plane = plane;
14611
14612                 /* ... and break all links. */
14613                 for_each_intel_connector(dev, connector) {
14614                         if (connector->encoder->base.crtc != &crtc->base)
14615                                 continue;
14616
14617                         connector->base.dpms = DRM_MODE_DPMS_OFF;
14618                         connector->base.encoder = NULL;
14619                 }
14620                 /* multiple connectors may have the same encoder:
14621                  *  handle them and break crtc link separately */
14622                 for_each_intel_connector(dev, connector)
14623                         if (connector->encoder->base.crtc == &crtc->base) {
14624                                 connector->encoder->base.crtc = NULL;
14625                                 connector->encoder->connectors_active = false;
14626                         }
14627
14628                 WARN_ON(crtc->active);
14629                 crtc->base.state->enable = false;
14630                 crtc->base.enabled = false;
14631         }
14632
14633         if (dev_priv->quirks & QUIRK_PIPEA_FORCE &&
14634             crtc->pipe == PIPE_A && !crtc->active) {
14635                 /* BIOS forgot to enable pipe A, this mostly happens after
14636                  * resume. Force-enable the pipe to fix this, the update_dpms
14637                  * call below we restore the pipe to the right state, but leave
14638                  * the required bits on. */
14639                 intel_enable_pipe_a(dev);
14640         }
14641
14642         /* Adjust the state of the output pipe according to whether we
14643          * have active connectors/encoders. */
14644         intel_crtc_update_dpms(&crtc->base);
14645
14646         if (crtc->active != crtc->base.state->enable) {
14647                 struct intel_encoder *encoder;
14648
14649                 /* This can happen either due to bugs in the get_hw_state
14650                  * functions or because the pipe is force-enabled due to the
14651                  * pipe A quirk. */
14652                 DRM_DEBUG_KMS("[CRTC:%d] hw state adjusted, was %s, now %s\n",
14653                               crtc->base.base.id,
14654                               crtc->base.state->enable ? "enabled" : "disabled",
14655                               crtc->active ? "enabled" : "disabled");
14656
14657                 crtc->base.state->enable = crtc->active;
14658                 crtc->base.enabled = crtc->active;
14659
14660                 /* Because we only establish the connector -> encoder ->
14661                  * crtc links if something is active, this means the
14662                  * crtc is now deactivated. Break the links. connector
14663                  * -> encoder links are only establish when things are
14664                  *  actually up, hence no need to break them. */
14665                 WARN_ON(crtc->active);
14666
14667                 for_each_encoder_on_crtc(dev, &crtc->base, encoder) {
14668                         WARN_ON(encoder->connectors_active);
14669                         encoder->base.crtc = NULL;
14670                 }
14671         }
14672
14673         if (crtc->active || HAS_GMCH_DISPLAY(dev)) {
14674                 /*
14675                  * We start out with underrun reporting disabled to avoid races.
14676                  * For correct bookkeeping mark this on active crtcs.
14677                  *
14678                  * Also on gmch platforms we dont have any hardware bits to
14679                  * disable the underrun reporting. Which means we need to start
14680                  * out with underrun reporting disabled also on inactive pipes,
14681                  * since otherwise we'll complain about the garbage we read when
14682                  * e.g. coming up after runtime pm.
14683                  *
14684                  * No protection against concurrent access is required - at
14685                  * worst a fifo underrun happens which also sets this to false.
14686                  */
14687                 crtc->cpu_fifo_underrun_disabled = true;
14688                 crtc->pch_fifo_underrun_disabled = true;
14689         }
14690 }
14691
14692 static void intel_sanitize_encoder(struct intel_encoder *encoder)
14693 {
14694         struct intel_connector *connector;
14695         struct drm_device *dev = encoder->base.dev;
14696
14697         /* We need to check both for a crtc link (meaning that the
14698          * encoder is active and trying to read from a pipe) and the
14699          * pipe itself being active. */
14700         bool has_active_crtc = encoder->base.crtc &&
14701                 to_intel_crtc(encoder->base.crtc)->active;
14702
14703         if (encoder->connectors_active && !has_active_crtc) {
14704                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
14705                               encoder->base.base.id,
14706                               encoder->base.name);
14707
14708                 /* Connector is active, but has no active pipe. This is
14709                  * fallout from our resume register restoring. Disable
14710                  * the encoder manually again. */
14711                 if (encoder->base.crtc) {
14712                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
14713                                       encoder->base.base.id,
14714                                       encoder->base.name);
14715                         encoder->disable(encoder);
14716                         if (encoder->post_disable)
14717                                 encoder->post_disable(encoder);
14718                 }
14719                 encoder->base.crtc = NULL;
14720                 encoder->connectors_active = false;
14721
14722                 /* Inconsistent output/port/pipe state happens presumably due to
14723                  * a bug in one of the get_hw_state functions. Or someplace else
14724                  * in our code, like the register restore mess on resume. Clamp
14725                  * things to off as a safer default. */
14726                 for_each_intel_connector(dev, connector) {
14727                         if (connector->encoder != encoder)
14728                                 continue;
14729                         connector->base.dpms = DRM_MODE_DPMS_OFF;
14730                         connector->base.encoder = NULL;
14731                 }
14732         }
14733         /* Enabled encoders without active connectors will be fixed in
14734          * the crtc fixup. */
14735 }
14736
14737 void i915_redisable_vga_power_on(struct drm_device *dev)
14738 {
14739         struct drm_i915_private *dev_priv = dev->dev_private;
14740         u32 vga_reg = i915_vgacntrl_reg(dev);
14741
14742         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
14743                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
14744                 i915_disable_vga(dev);
14745         }
14746 }
14747
14748 void i915_redisable_vga(struct drm_device *dev)
14749 {
14750         struct drm_i915_private *dev_priv = dev->dev_private;
14751
14752         /* This function can be called both from intel_modeset_setup_hw_state or
14753          * at a very early point in our resume sequence, where the power well
14754          * structures are not yet restored. Since this function is at a very
14755          * paranoid "someone might have enabled VGA while we were not looking"
14756          * level, just check if the power well is enabled instead of trying to
14757          * follow the "don't touch the power well if we don't need it" policy
14758          * the rest of the driver uses. */
14759         if (!intel_display_power_is_enabled(dev_priv, POWER_DOMAIN_VGA))
14760                 return;
14761
14762         i915_redisable_vga_power_on(dev);
14763 }
14764
14765 static bool primary_get_hw_state(struct intel_crtc *crtc)
14766 {
14767         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
14768
14769         if (!crtc->active)
14770                 return false;
14771
14772         return I915_READ(DSPCNTR(crtc->plane)) & DISPLAY_PLANE_ENABLE;
14773 }
14774
14775 static void intel_modeset_readout_hw_state(struct drm_device *dev)
14776 {
14777         struct drm_i915_private *dev_priv = dev->dev_private;
14778         enum pipe pipe;
14779         struct intel_crtc *crtc;
14780         struct intel_encoder *encoder;
14781         struct intel_connector *connector;
14782         int i;
14783
14784         for_each_intel_crtc(dev, crtc) {
14785                 memset(crtc->config, 0, sizeof(*crtc->config));
14786
14787                 crtc->config->quirks |= PIPE_CONFIG_QUIRK_INHERITED_MODE;
14788
14789                 crtc->active = dev_priv->display.get_pipe_config(crtc,
14790                                                                  crtc->config);
14791
14792                 crtc->base.state->enable = crtc->active;
14793                 crtc->base.enabled = crtc->active;
14794                 crtc->primary_enabled = primary_get_hw_state(crtc);
14795
14796                 DRM_DEBUG_KMS("[CRTC:%d] hw state readout: %s\n",
14797                               crtc->base.base.id,
14798                               crtc->active ? "enabled" : "disabled");
14799         }
14800
14801         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
14802                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
14803
14804                 pll->on = pll->get_hw_state(dev_priv, pll,
14805                                             &pll->config.hw_state);
14806                 pll->active = 0;
14807                 pll->config.crtc_mask = 0;
14808                 for_each_intel_crtc(dev, crtc) {
14809                         if (crtc->active && intel_crtc_to_shared_dpll(crtc) == pll) {
14810                                 pll->active++;
14811                                 pll->config.crtc_mask |= 1 << crtc->pipe;
14812                         }
14813                 }
14814
14815                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
14816                               pll->name, pll->config.crtc_mask, pll->on);
14817
14818                 if (pll->config.crtc_mask)
14819                         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
14820         }
14821
14822         for_each_intel_encoder(dev, encoder) {
14823                 pipe = 0;
14824
14825                 if (encoder->get_hw_state(encoder, &pipe)) {
14826                         crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
14827                         encoder->base.crtc = &crtc->base;
14828                         encoder->get_config(encoder, crtc->config);
14829                 } else {
14830                         encoder->base.crtc = NULL;
14831                 }
14832
14833                 encoder->connectors_active = false;
14834                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
14835                               encoder->base.base.id,
14836                               encoder->base.name,
14837                               encoder->base.crtc ? "enabled" : "disabled",
14838                               pipe_name(pipe));
14839         }
14840
14841         for_each_intel_connector(dev, connector) {
14842                 if (connector->get_hw_state(connector)) {
14843                         connector->base.dpms = DRM_MODE_DPMS_ON;
14844                         connector->encoder->connectors_active = true;
14845                         connector->base.encoder = &connector->encoder->base;
14846                 } else {
14847                         connector->base.dpms = DRM_MODE_DPMS_OFF;
14848                         connector->base.encoder = NULL;
14849                 }
14850                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
14851                               connector->base.base.id,
14852                               connector->base.name,
14853                               connector->base.encoder ? "enabled" : "disabled");
14854         }
14855 }
14856
14857 /* Scan out the current hw modeset state, sanitizes it and maps it into the drm
14858  * and i915 state tracking structures. */
14859 void intel_modeset_setup_hw_state(struct drm_device *dev,
14860                                   bool force_restore)
14861 {
14862         struct drm_i915_private *dev_priv = dev->dev_private;
14863         enum pipe pipe;
14864         struct intel_crtc *crtc;
14865         struct intel_encoder *encoder;
14866         int i;
14867
14868         intel_modeset_readout_hw_state(dev);
14869
14870         /*
14871          * Now that we have the config, copy it to each CRTC struct
14872          * Note that this could go away if we move to using crtc_config
14873          * checking everywhere.
14874          */
14875         for_each_intel_crtc(dev, crtc) {
14876                 if (crtc->active && i915.fastboot) {
14877                         intel_mode_from_pipe_config(&crtc->base.mode,
14878                                                     crtc->config);
14879                         DRM_DEBUG_KMS("[CRTC:%d] found active mode: ",
14880                                       crtc->base.base.id);
14881                         drm_mode_debug_printmodeline(&crtc->base.mode);
14882                 }
14883         }
14884
14885         /* HW state is read out, now we need to sanitize this mess. */
14886         for_each_intel_encoder(dev, encoder) {
14887                 intel_sanitize_encoder(encoder);
14888         }
14889
14890         for_each_pipe(dev_priv, pipe) {
14891                 crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
14892                 intel_sanitize_crtc(crtc);
14893                 intel_dump_pipe_config(crtc, crtc->config,
14894                                        "[setup_hw_state]");
14895         }
14896
14897         intel_modeset_update_connector_atomic_state(dev);
14898
14899         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
14900                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
14901
14902                 if (!pll->on || pll->active)
14903                         continue;
14904
14905                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
14906
14907                 pll->disable(dev_priv, pll);
14908                 pll->on = false;
14909         }
14910
14911         if (IS_GEN9(dev))
14912                 skl_wm_get_hw_state(dev);
14913         else if (HAS_PCH_SPLIT(dev))
14914                 ilk_wm_get_hw_state(dev);
14915
14916         if (force_restore) {
14917                 i915_redisable_vga(dev);
14918
14919                 /*
14920                  * We need to use raw interfaces for restoring state to avoid
14921                  * checking (bogus) intermediate states.
14922                  */
14923                 for_each_pipe(dev_priv, pipe) {
14924                         struct drm_crtc *crtc =
14925                                 dev_priv->pipe_to_crtc_mapping[pipe];
14926
14927                         intel_crtc_restore_mode(crtc);
14928                 }
14929         } else {
14930                 intel_modeset_update_staged_output_state(dev);
14931         }
14932
14933         intel_modeset_check_state(dev);
14934 }
14935
14936 void intel_modeset_gem_init(struct drm_device *dev)
14937 {
14938         struct drm_i915_private *dev_priv = dev->dev_private;
14939         struct drm_crtc *c;
14940         struct drm_i915_gem_object *obj;
14941
14942         mutex_lock(&dev->struct_mutex);
14943         intel_init_gt_powersave(dev);
14944         mutex_unlock(&dev->struct_mutex);
14945
14946         /*
14947          * There may be no VBT; and if the BIOS enabled SSC we can
14948          * just keep using it to avoid unnecessary flicker.  Whereas if the
14949          * BIOS isn't using it, don't assume it will work even if the VBT
14950          * indicates as much.
14951          */
14952         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
14953                 dev_priv->vbt.lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
14954                                                 DREF_SSC1_ENABLE);
14955
14956         intel_modeset_init_hw(dev);
14957
14958         intel_setup_overlay(dev);
14959
14960         /*
14961          * Make sure any fbs we allocated at startup are properly
14962          * pinned & fenced.  When we do the allocation it's too early
14963          * for this.
14964          */
14965         mutex_lock(&dev->struct_mutex);
14966         for_each_crtc(dev, c) {
14967                 obj = intel_fb_obj(c->primary->fb);
14968                 if (obj == NULL)
14969                         continue;
14970
14971                 if (intel_pin_and_fence_fb_obj(c->primary,
14972                                                c->primary->fb,
14973                                                c->primary->state,
14974                                                NULL)) {
14975                         DRM_ERROR("failed to pin boot fb on pipe %d\n",
14976                                   to_intel_crtc(c)->pipe);
14977                         drm_framebuffer_unreference(c->primary->fb);
14978                         c->primary->fb = NULL;
14979                         update_state_fb(c->primary);
14980                 }
14981         }
14982         mutex_unlock(&dev->struct_mutex);
14983
14984         intel_backlight_register(dev);
14985 }
14986
14987 void intel_connector_unregister(struct intel_connector *intel_connector)
14988 {
14989         struct drm_connector *connector = &intel_connector->base;
14990
14991         intel_panel_destroy_backlight(connector);
14992         drm_connector_unregister(connector);
14993 }
14994
14995 void intel_modeset_cleanup(struct drm_device *dev)
14996 {
14997         struct drm_i915_private *dev_priv = dev->dev_private;
14998         struct drm_connector *connector;
14999
15000         intel_disable_gt_powersave(dev);
15001
15002         intel_backlight_unregister(dev);
15003
15004         /*
15005          * Interrupts and polling as the first thing to avoid creating havoc.
15006          * Too much stuff here (turning of connectors, ...) would
15007          * experience fancy races otherwise.
15008          */
15009         intel_irq_uninstall(dev_priv);
15010
15011         /*
15012          * Due to the hpd irq storm handling the hotplug work can re-arm the
15013          * poll handlers. Hence disable polling after hpd handling is shut down.
15014          */
15015         drm_kms_helper_poll_fini(dev);
15016
15017         mutex_lock(&dev->struct_mutex);
15018
15019         intel_unregister_dsm_handler();
15020
15021         intel_fbc_disable(dev);
15022
15023         mutex_unlock(&dev->struct_mutex);
15024
15025         /* flush any delayed tasks or pending work */
15026         flush_scheduled_work();
15027
15028         /* destroy the backlight and sysfs files before encoders/connectors */
15029         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
15030                 struct intel_connector *intel_connector;
15031
15032                 intel_connector = to_intel_connector(connector);
15033                 intel_connector->unregister(intel_connector);
15034         }
15035
15036         drm_mode_config_cleanup(dev);
15037
15038         intel_cleanup_overlay(dev);
15039
15040         mutex_lock(&dev->struct_mutex);
15041         intel_cleanup_gt_powersave(dev);
15042         mutex_unlock(&dev->struct_mutex);
15043 }
15044
15045 /*
15046  * Return which encoder is currently attached for connector.
15047  */
15048 struct drm_encoder *intel_best_encoder(struct drm_connector *connector)
15049 {
15050         return &intel_attached_encoder(connector)->base;
15051 }
15052
15053 void intel_connector_attach_encoder(struct intel_connector *connector,
15054                                     struct intel_encoder *encoder)
15055 {
15056         connector->encoder = encoder;
15057         drm_mode_connector_attach_encoder(&connector->base,
15058                                           &encoder->base);
15059 }
15060
15061 /*
15062  * set vga decode state - true == enable VGA decode
15063  */
15064 int intel_modeset_vga_set_state(struct drm_device *dev, bool state)
15065 {
15066         struct drm_i915_private *dev_priv = dev->dev_private;
15067         unsigned reg = INTEL_INFO(dev)->gen >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
15068         u16 gmch_ctrl;
15069
15070         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
15071                 DRM_ERROR("failed to read control word\n");
15072                 return -EIO;
15073         }
15074
15075         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
15076                 return 0;
15077
15078         if (state)
15079                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
15080         else
15081                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
15082
15083         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
15084                 DRM_ERROR("failed to write control word\n");
15085                 return -EIO;
15086         }
15087
15088         return 0;
15089 }
15090
15091 struct intel_display_error_state {
15092
15093         u32 power_well_driver;
15094
15095         int num_transcoders;
15096
15097         struct intel_cursor_error_state {
15098                 u32 control;
15099                 u32 position;
15100                 u32 base;
15101                 u32 size;
15102         } cursor[I915_MAX_PIPES];
15103
15104         struct intel_pipe_error_state {
15105                 bool power_domain_on;
15106                 u32 source;
15107                 u32 stat;
15108         } pipe[I915_MAX_PIPES];
15109
15110         struct intel_plane_error_state {
15111                 u32 control;
15112                 u32 stride;
15113                 u32 size;
15114                 u32 pos;
15115                 u32 addr;
15116                 u32 surface;
15117                 u32 tile_offset;
15118         } plane[I915_MAX_PIPES];
15119
15120         struct intel_transcoder_error_state {
15121                 bool power_domain_on;
15122                 enum transcoder cpu_transcoder;
15123
15124                 u32 conf;
15125
15126                 u32 htotal;
15127                 u32 hblank;
15128                 u32 hsync;
15129                 u32 vtotal;
15130                 u32 vblank;
15131                 u32 vsync;
15132         } transcoder[4];
15133 };
15134
15135 struct intel_display_error_state *
15136 intel_display_capture_error_state(struct drm_device *dev)
15137 {
15138         struct drm_i915_private *dev_priv = dev->dev_private;
15139         struct intel_display_error_state *error;
15140         int transcoders[] = {
15141                 TRANSCODER_A,
15142                 TRANSCODER_B,
15143                 TRANSCODER_C,
15144                 TRANSCODER_EDP,
15145         };
15146         int i;
15147
15148         if (INTEL_INFO(dev)->num_pipes == 0)
15149                 return NULL;
15150
15151         error = kzalloc(sizeof(*error), GFP_ATOMIC);
15152         if (error == NULL)
15153                 return NULL;
15154
15155         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
15156                 error->power_well_driver = I915_READ(HSW_PWR_WELL_DRIVER);
15157
15158         for_each_pipe(dev_priv, i) {
15159                 error->pipe[i].power_domain_on =
15160                         __intel_display_power_is_enabled(dev_priv,
15161                                                          POWER_DOMAIN_PIPE(i));
15162                 if (!error->pipe[i].power_domain_on)
15163                         continue;
15164
15165                 error->cursor[i].control = I915_READ(CURCNTR(i));
15166                 error->cursor[i].position = I915_READ(CURPOS(i));
15167                 error->cursor[i].base = I915_READ(CURBASE(i));
15168
15169                 error->plane[i].control = I915_READ(DSPCNTR(i));
15170                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
15171                 if (INTEL_INFO(dev)->gen <= 3) {
15172                         error->plane[i].size = I915_READ(DSPSIZE(i));
15173                         error->plane[i].pos = I915_READ(DSPPOS(i));
15174                 }
15175                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
15176                         error->plane[i].addr = I915_READ(DSPADDR(i));
15177                 if (INTEL_INFO(dev)->gen >= 4) {
15178                         error->plane[i].surface = I915_READ(DSPSURF(i));
15179                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
15180                 }
15181
15182                 error->pipe[i].source = I915_READ(PIPESRC(i));
15183
15184                 if (HAS_GMCH_DISPLAY(dev))
15185                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
15186         }
15187
15188         error->num_transcoders = INTEL_INFO(dev)->num_pipes;
15189         if (HAS_DDI(dev_priv->dev))
15190                 error->num_transcoders++; /* Account for eDP. */
15191
15192         for (i = 0; i < error->num_transcoders; i++) {
15193                 enum transcoder cpu_transcoder = transcoders[i];
15194
15195                 error->transcoder[i].power_domain_on =
15196                         __intel_display_power_is_enabled(dev_priv,
15197                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
15198                 if (!error->transcoder[i].power_domain_on)
15199                         continue;
15200
15201                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
15202
15203                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
15204                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
15205                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
15206                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
15207                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
15208                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
15209                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
15210         }
15211
15212         return error;
15213 }
15214
15215 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
15216
15217 void
15218 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
15219                                 struct drm_device *dev,
15220                                 struct intel_display_error_state *error)
15221 {
15222         struct drm_i915_private *dev_priv = dev->dev_private;
15223         int i;
15224
15225         if (!error)
15226                 return;
15227
15228         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev)->num_pipes);
15229         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
15230                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
15231                            error->power_well_driver);
15232         for_each_pipe(dev_priv, i) {
15233                 err_printf(m, "Pipe [%d]:\n", i);
15234                 err_printf(m, "  Power: %s\n",
15235                            error->pipe[i].power_domain_on ? "on" : "off");
15236                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
15237                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
15238
15239                 err_printf(m, "Plane [%d]:\n", i);
15240                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
15241                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
15242                 if (INTEL_INFO(dev)->gen <= 3) {
15243                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
15244                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
15245                 }
15246                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
15247                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
15248                 if (INTEL_INFO(dev)->gen >= 4) {
15249                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
15250                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
15251                 }
15252
15253                 err_printf(m, "Cursor [%d]:\n", i);
15254                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
15255                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
15256                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
15257         }
15258
15259         for (i = 0; i < error->num_transcoders; i++) {
15260                 err_printf(m, "CPU transcoder: %c\n",
15261                            transcoder_name(error->transcoder[i].cpu_transcoder));
15262                 err_printf(m, "  Power: %s\n",
15263                            error->transcoder[i].power_domain_on ? "on" : "off");
15264                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
15265                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
15266                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
15267                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
15268                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
15269                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
15270                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
15271         }
15272 }
15273
15274 void intel_modeset_preclose(struct drm_device *dev, struct drm_file *file)
15275 {
15276         struct intel_crtc *crtc;
15277
15278         for_each_intel_crtc(dev, crtc) {
15279                 struct intel_unpin_work *work;
15280
15281                 spin_lock_irq(&dev->event_lock);
15282
15283                 work = crtc->unpin_work;
15284
15285                 if (work && work->event &&
15286                     work->event->base.file_priv == file) {
15287                         kfree(work->event);
15288                         work->event = NULL;
15289                 }
15290
15291                 spin_unlock_irq(&dev->event_lock);
15292         }
15293 }